nekolas note

毎日書くことを目指しているけど全然達成できてないブログ

2.9 KB Raw
//! 通知ヘルパ(T030/T032)。
//! 参照: contracts/zed-ide-bridge.md
//!
//! 2 種類の通知を扱う:
//!  1. Zed への接続成否トースト: LSP `window/showMessage`(FR-028/029)。
//!     通常のコンテキスト送信(selection_changed 等)では通知しない。
//!  2. Claude への push: `selection_changed` / `at_mentioned`(MCP 側で送出, T030)。

use crate::protocol::rpc_notification;
use crate::state::{EditorContext, Selection};
use serde_json::{json, Value};
use tokio::sync::mpsc;

/// LSP stdout への送信ハンドル(writer タスクが drain する)。
pub type LspOut = mpsc::UnboundedSender<Value>;

/// LSP MessageType(1=Error, 2=Warning, 3=Info)。
const MSG_ERROR: i64 = 1;
const MSG_WARNING: i64 = 2;
const MSG_INFO: i64 = 3;

/// Zed へ接続成否トーストを出す(FR-028)。
#[derive(Clone)]
pub struct Notifier {
    out: LspOut,
}

impl Notifier {
    pub fn new(out: LspOut) -> Self {
        Notifier { out }
    }

    fn show_message(&self, typ: i64, message: &str) {
        let n = rpc_notification(
            "window/showMessage",
            json!({ "type": typ, "message": message }),
        );
        let _ = self.out.send(n);
    }

    /// 接続成功(Info)。
    pub fn connected(&self) {
        self.show_message(MSG_INFO, "Claude Code に接続しました");
    }

    /// 接続失敗(Error)。
    pub fn connect_failed(&self, detail: &str) {
        self.show_message(
            MSG_ERROR,
            &format!("Claude Code への接続に失敗しました: {detail}"),
        );
    }

    /// 切断(Warning)。
    pub fn disconnected(&self) {
        self.show_message(MSG_WARNING, "Claude Code との接続が切断されました");
    }
}

/// `selection_changed` 通知ペイロードを組み立てる(T030, FR-024)。
/// 診断は含めない(スコープ外)。filePath が無い(untitled)場合も安全に組む(FR-023)。
pub fn selection_changed_payload(ctx: &EditorContext) -> Value {
    let sel = ctx.selection.clone().unwrap_or_else(|| Selection {
        is_empty: true,
        ..Default::default()
    });
    json!({
        // Claude Code IDE プロトコルは text(選択テキスト本体)を必須に近い形で期待する。
        "text": ctx.text,
        "filePath": ctx.file_path,
        "fileUrl": ctx.file_url,
        "selection": {
            "start": { "line": sel.start.line, "character": sel.start.character },
            "end": { "line": sel.end.line, "character": sel.end.character },
            "isEmpty": sel.is_empty,
        }
    })
}

/// `at_mentioned` 通知ペイロード(ユーザー明示操作用, T030)。
pub fn at_mentioned_payload(file_path: &str, line_start: u32, line_end: u32) -> Value {
    json!({
        "filePath": file_path,
        "lineStart": line_start,
        "lineEnd": line_end,
    })
}