From 406ca12dac303edcbd87302536166febbe26951c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 17 Nov 2026 18:17:01 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E8=9E=A2=E5=B9=95=E9=9B=BB=E8=85=A6?= =?UTF-8?q?=E4=B8=8A=E6=94=B9=E9=80=A3=E6=8E=A5=E5=99=A8=E5=90=8D=E7=A8=B1?= =?UTF-8?q?=EF=BC=8C=E5=A4=A7=E8=85=A6=E4=B9=9F=E6=8A=8A=E7=99=BB=E5=85=A5?= =?UTF-8?q?=E6=90=AC=E9=81=8E=E5=8E=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 改名的登入搬移改由大腦自己偵測(follow_renames,在 mcp_poll 重新連線之前):舊名字不見、 同一個網址或指令換了新名字,就把 OAuth 登入和錯誤狀態搬過去。這台、螢幕電腦、Bot 的 manage_connectors 改名都一樣(以前螢幕電腦上改名,搬的是螢幕電腦自己的檔案,大腦上等於登出)。 - 兩個同網址的連接器一起改名時,各自拿回自己的密鑰(每個舊的只配對一次)。 - 打好的名稱碰到連接器已經在別處被改名或移除時,說明沒有改。 已驗證: cargo test 全綠;新測試 the_brain_moves_a_renamed_connectors_sign_in、mirror_ui 的同網址兩個改名。 未驗證: 螢幕電腦連真的大腦實際改名(要兩台機器)。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha3KhvSzysuKUobKUTR --- docs/feature-map/connectors.md | 2 +- src/app/channels_ui.rs | 63 +++++++++++++++++++++++++++++++--- src/app/mirror_ui.rs | 11 +++++- src/i18n_table.rs | 1 + src/mcp_oauth.rs | 6 ++++ 5 files changed, 76 insertions(+), 7 deletions(-) diff --git a/docs/feature-map/connectors.md b/docs/feature-map/connectors.md index 216ff3e..647a76b 100644 --- a/docs/feature-map/connectors.md +++ b/docs/feature-map/connectors.md @@ -8,7 +8,7 @@ - 登入帳號(OAuth):遠端連接器回「要先登入」時,到那個連接器自己的頁按「登入」(只在大腦本機),或在聊天請 Bot 登入:瀏覽器打開登入頁,登入完自動接上;瀏覽器在別台電腦、登入後那頁打不開時,把那頁網址貼回聊天。Token 存在大腦、加密,不會同步到螢幕或手機;快到期自動換新,401 時換一次再試。 - 帳號、密碼:給要用帳號密碼登入的伺服器。在指令、環境變數、網址或標頭寫「{username}」「{password}」,就填在那裡;都沒寫時,本機伺服器收到環境變數 `MCP_USERNAME`、`MCP_PASSWORD`,遠端伺服器收到 Basic 驗證。 - 「給 Bot 的使用說明」:寫進 Bot 的系統指示(例如「查詢客戶資料時先用 search_customers」)。 -- 頁面跟其他 App 的設定一樣是「清單+各自的頁」:最上面一張小卡「連接器(MCP)」和兩個按鈕「瀏覽市集」「新增連接器」;下面「已加入」每個連接器一列,只有名稱、色點和狀態(「已連上,N 個工具」「連線中…」「未連線」「已關閉」或紅字錯誤原因)、開關和 ›。按那一列(開關以外的地方)進到它自己的頁:最上面名稱、狀態、「登入」(遠端的)「重新連線」和開關(下面一行是登入或改名沒成功的原因);接著「工具(N)」列它自己的工具(名字和一行說明,滑過看全文;超過 8 個有「搜尋工具」;連上之後才有);再下面「設定」卡是它的欄位(名稱、指令或網址、環境變數、標頭、帳號和密碼並排、給 Bot 的使用說明——每個欄位名稱都在輸入框上面;名稱打完按 Enter、離開欄位或離開這一頁才改,Esc 放回原來的;空白或跟別的連接器同名不改並說原因;改名後登入跟著新名字,在螢幕電腦上改名,大腦照網址或指令找回它的金鑰和密碼);最下面紅字「移除這個連接器」,再按「確定移除」才移除。左上「‹ 連接器」回清單。不再有把所有連接器的工具攤在一起的「可以用的工具」。「新增連接器」是它自己的頁(同樣的欄位,名稱在上、框在下),按「新增」後直接到新連接器的頁看它連線。 +- 頁面跟其他 App 的設定一樣是「清單+各自的頁」:最上面一張小卡「連接器(MCP)」和兩個按鈕「瀏覽市集」「新增連接器」;下面「已加入」每個連接器一列,只有名稱、色點和狀態(「已連上,N 個工具」「連線中…」「未連線」「已關閉」或紅字錯誤原因)、開關和 ›。按那一列(開關以外的地方)進到它自己的頁:最上面名稱、狀態、「登入」(遠端的)「重新連線」和開關(下面一行是登入或改名沒成功的原因);接著「工具(N)」列它自己的工具(名字和一行說明,滑過看全文;超過 8 個有「搜尋工具」;連上之後才有);再下面「設定」卡是它的欄位(名稱、指令或網址、環境變數、標頭、帳號和密碼並排、給 Bot 的使用說明——每個欄位名稱都在輸入框上面;名稱打完按 Enter、離開欄位或離開這一頁才改,Esc 放回原來的;空白或跟別的連接器同名不改並說原因;改名後登入跟著新名字(在大腦上:不管是這台、螢幕電腦還是 Bot 改的);在螢幕電腦上改名,大腦照網址或指令找回它的金鑰和密碼);最下面紅字「移除這個連接器」,再按「確定移除」才移除。左上「‹ 連接器」回清單。不再有把所有連接器的工具攤在一起的「可以用的工具」。「新增連接器」是它自己的頁(同樣的欄位,名稱在上、框在下),按「新增」後直接到新連接器的頁看它連線。 - 「瀏覽市集」頁的「連接器市集」:8 個常用的(files、memory、thinking、fetch、git、time、playwright、github),按「加入」就能用;要金鑰的(github)會打開「新增連接器」頁並填好,補上 Token 再按「新增」。 - 同一頁的「公用市集(官方 MCP Registry)」:搜尋用網址連的連接器,按「加入」會打開填好的「新增連接器」頁;還有「{…}」沒換成你的值時,按不下「新增」。 - 給 Bot 的方式:所有連接器加起來 20 個工具以內,每個工具直接給,名字是 `mcp__連接器__工具`;超過 20 個,只給 `find_connector_tool` 和 `use_connector_tool`。 diff --git a/src/app/channels_ui.rs b/src/app/channels_ui.rs index 1bfe7e8..ec16e73 100644 --- a/src/app/channels_ui.rs +++ b/src/app/channels_ui.rs @@ -48,6 +48,8 @@ pub struct ChannelUi { mcp_confirm: Option, /// What is typed in a connector's page to find one of its tools. tool_q: String, + /// The connectors (name, where each connects) as last seen: to tell a rename (follow_renames). + mcp_prev: Option>, /// A connector's name as it is being typed (whose, the words): changed when done. pub(super) mcp_name: Option<(String, String)>, /// What a connector's page says (a login that didn't start, a name not taken). @@ -80,7 +82,7 @@ impl Default for ChannelUi { fn default() -> Self { let (tx, rx) = channel(); let (trig_tx, trig_rx) = channel(); - ChannelUi { tx, rx, replies: HashMap::new(), waiting: VecDeque::new(), new_kind: Kind::Telegram, new_name: String::new(), new_token: String::new(), new_target: String::new(), new_bot: 0, note: Default::default(), started: false, trig_tx, trig_rx, trig_sig: String::new(), new_client: String::new(), new_tenant: String::new(), ms_login: Default::default(), mcp_sig: String::new(), mcp_errors: Default::default(), mcp_busy: Default::default(), mcp_tried: None, new_mcp: Default::default(), sub: 0, adding: false, skill_src: String::new(), skill_page: Page::List, skill_q: String::new(), skill_confirm: None, skill_busy: Default::default(), skill_reload: Default::default(), skill_note: Default::default(), skill_note_list: false, new_mcp_hint: String::new(), new_mcp_login: Default::default(), mcp_page: Page::List, mcp_confirm: None, tool_q: String::new(), mcp_name: None, mcp_note: Default::default(), page_key: None, reg_q: String::new(), reg_busy: Default::default(), reg_found: Default::default() } + ChannelUi { tx, rx, replies: HashMap::new(), waiting: VecDeque::new(), new_kind: Kind::Telegram, new_name: String::new(), new_token: String::new(), new_target: String::new(), new_bot: 0, note: Default::default(), started: false, trig_tx, trig_rx, trig_sig: String::new(), new_client: String::new(), new_tenant: String::new(), ms_login: Default::default(), mcp_sig: String::new(), mcp_errors: Default::default(), mcp_busy: Default::default(), mcp_tried: None, new_mcp: Default::default(), sub: 0, adding: false, skill_src: String::new(), skill_page: Page::List, skill_q: String::new(), skill_confirm: None, skill_busy: Default::default(), skill_reload: Default::default(), skill_note: Default::default(), skill_note_list: false, new_mcp_hint: String::new(), new_mcp_login: Default::default(), mcp_page: Page::List, mcp_confirm: None, tool_q: String::new(), mcp_prev: None, mcp_name: None, mcp_note: Default::default(), page_key: None, reg_q: String::new(), reg_busy: Default::default(), reg_found: Default::default() } } } @@ -445,6 +447,7 @@ impl App { Err(e) => self.notice = Some(format!("連接器「{name}」沒有登入成功:{e}")), } } + self.follow_renames(); if self.ch.mcp_busy.load(Ordering::SeqCst) { return; } @@ -464,6 +467,30 @@ impl App { }); } + /// Connectors renamed since the last look — here, from a screen of this brain, or by a bot: + /// the same address or command under a new name. Their sign-in (kept by name, here on the + /// brain) and their error follow, before they are connected again. + pub(super) fn follow_renames(&mut self) { + let endpoint = |s: &crate::mcp::Server| format!("{}\n{}\n{}", s.url.trim(), s.command.trim(), s.args.join(" ")); + let now: Vec<(String, String)> = self.state.mcp_servers.iter().map(|s| (s.name.clone(), endpoint(s))).collect(); + let Some(before) = self.ch.mcp_prev.replace(now.clone()) else { return }; + if before == now { + return; + } + let mut taken: Vec<&str> = vec![]; + for (old, ep) in &before { + if ep.trim().is_empty() || now.iter().any(|(n, _)| n == old) { + continue; + } + // (A name that is new, with the same address or command — each new one once.) + if let Some((new, _)) = now.iter().find(|(n, e)| e == ep && !before.iter().any(|(b, _)| b == n) && !taken.contains(&n.as_str())) { + taken.push(new); + crate::mcp_oauth::rename(old, new); + self.ch.mcp_errors.lock().unwrap().retain(|e| &e.0 != old); + } + } + } + /// 管理連接器 (a bot asked; the person already said yes to a change): the brain's own list /// changes, as 新增連接器 / 設定 / 移除 would, and the answer waits until the connector has /// connected or said why not (at most CONNECT_WAIT; a first `npx` may download for a while). @@ -671,12 +698,13 @@ impl App { *self.ch.mcp_note.lock().unwrap() = why; return; } - let Some(s) = self.state.mcp_servers.iter_mut().find(|s| s.name == whose) else { return }; + let Some(s) = self.state.mcp_servers.iter_mut().find(|s| s.name == whose) else { + *self.ch.mcp_note.lock().unwrap() = t("這個連接器已經被改名或移除了,名稱沒有改。"); + return; + }; s.name = want.clone(); self.dirty = true; - // (Its sign-in is kept under its name: it moves with it.) - crate::mcp_oauth::rename(&whose, &want); - self.ch.mcp_errors.lock().unwrap().retain(|e| e.0 != whose); + // (Its sign-in and error follow it on the brain: follow_renames, there.) self.ch.mcp_note.lock().unwrap().clear(); if self.ch.mcp_page == Page::Item(whose.clone()) { self.ch.mcp_page = Page::Item(want.clone()); @@ -1490,6 +1518,31 @@ fn listing_row(ui: &mut egui::Ui, buttons: impl FnOnce(&mut egui::Ui), words: im mod tests { use super::*; + /// A connector renamed — here, from a screen, by a bot — keeps its sign-in on the brain: the + /// brain sees the same address under a new name. One that also moved elsewhere doesn't. + #[test] + fn the_brain_moves_a_renamed_connectors_sign_in() { + let ctx = egui::Context::default(); + let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-follow-renames.png"))); + let tag = crate::httpd::random_hex(4); + let (a, b) = (format!("gh-{tag}"), format!("notion-{tag}")); + let server = |n: &str, url: &str| crate::mcp::Server { name: n.into(), url: url.into(), enabled: true, ..Default::default() }; + app.state.mcp_servers = vec![server(&a, "https://gh.example/mcp"), server(&b, "https://notion.example/mcp")]; + for (n, url) in [(&a, "https://gh.example/mcp"), (&b, "https://notion.example/mcp")] { + crate::mcp_oauth::save_for_test(n, crate::mcp_oauth::Tokens { access: format!("tok-{n}"), url: url.into(), ..Default::default() }); + } + app.follow_renames(); + // As a screen's edit leaves it: one renamed, one renamed and pointed elsewhere. + app.state.mcp_servers = vec![server(&format!("{a}-work"), "https://gh.example/mcp"), server(&format!("{b}-2"), "https://other.example/mcp")]; + app.follow_renames(); + assert_eq!(crate::mcp_oauth::bearer(&format!("{a}-work"), "https://gh.example/mcp"), Some(format!("tok-{a}"))); + assert!(crate::mcp_oauth::tokens(&a).is_none()); + assert!(crate::mcp_oauth::tokens(&format!("{b}-2")).is_none(), "moved elsewhere: not its sign-in"); + for n in [format!("{a}-work"), b.clone()] { + let _ = crate::mcp_oauth::logout(&n); + } + } + /// A message from a channel never joins a turn that is running: it waits for its own. #[test] fn a_channel_message_waits_for_a_turn_of_its_own() { diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index e9e6cdf..8b08b47 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -165,6 +165,7 @@ fn unredact(new: &mut Value, old: &Value) { Value::Array(a) => { let key_of = |x: &Value| x.get("id").cloned().filter(|x| !x.is_null()).or_else(|| x.get("name").cloned().filter(|s| s.as_str().is_some_and(|t| !t.is_empty()))); let new_names: Vec = a.iter().filter_map(key_of).collect(); + let mut used: Vec = vec![]; for (i, v) in a.iter_mut().enumerate() { let key = |x: &Value| x.get("id").cloned().filter(|x| !x.is_null()).or_else(|| x.get("name").cloned().filter(|s| s.as_str().is_some_and(|t| !t.is_empty()))); // (One renamed on a screen — a connector — is found by where it connects instead: @@ -174,7 +175,11 @@ fn unredact(new: &mut Value, old: &Value) { let reaches = |x: &Value| ["url", "command"].iter().any(|k| x.get(*k).and_then(Value::as_str).is_some_and(|s| !s.is_empty())); let twin = old.as_array().and_then(|olds| match key(v) { Some(k) => olds.iter().find(|o| key(o).as_ref() == Some(&k)).or_else(|| { - olds.iter().find(|o| reaches(o) && reaches(v) && endpoint(o) == endpoint(v) && key(o).is_some_and(|n| !new_names.contains(&n))) + // (Each old one found this way once: two renamed copies of one address + // don't both get the first one's secrets.) + let j = olds.iter().enumerate().position(|(j, o)| !used.contains(&j) && reaches(o) && reaches(v) && endpoint(o) == endpoint(v) && key(o).is_some_and(|n| !new_names.contains(&n)))?; + used.push(j); + olds.get(j) }), None => olds.get(i), }); @@ -1617,6 +1622,10 @@ mod tests { let mut moved = json!([{"name": "gh-work", "url": "https://evil.example/mcp", "headers": {"Authorization": REDACTED}, "password": REDACTED}]); unredact(&mut moved, &servers); assert_eq!((moved[0]["headers"]["Authorization"].clone(), moved[0]["password"].clone()), (json!(""), json!(""))); + let two = json!([{"name": "a", "url": "https://x.example/mcp", "password": "pa"}, {"name": "b", "url": "https://x.example/mcp", "password": "pb"}]); + let mut both = json!([{"name": "a2", "url": "https://x.example/mcp", "password": REDACTED}, {"name": "b2", "url": "https://x.example/mcp", "password": REDACTED}]); + unredact(&mut both, &two); + assert_eq!((both[0]["password"].clone(), both[1]["password"].clone()), (json!("pa"), json!("pb")), "each its own"); let mut copy = json!([{"name": "gh", "url": "https://x.example/mcp", "password": REDACTED}, {"name": "gh-2", "url": "https://x.example/mcp", "password": REDACTED}]); unredact(&mut copy, &servers); assert_eq!((copy[0]["password"].clone(), copy[1]["password"].clone()), (json!("pw"), json!(""))); diff --git a/src/i18n_table.rs b/src/i18n_table.rs index bed8950..8deb511 100644 --- a/src/i18n_table.rs +++ b/src/i18n_table.rs @@ -749,6 +749,7 @@ pub const ROWS: &[(&str, &str, &str)] = &[ ("關著:不列進任何 Bot 的說明", "Off: not given to any bot", "オフ:どの Bot にも渡されません"), ("接上 Model Context Protocol 伺服器,Bot 就能用它的工具(例如 GitHub、Notion、資料庫、你公司的內部系統)。本機伺服器填指令(例如 npx -y @modelcontextprotocol/server-filesystem ~/Documents);遠端伺服器填網址(Streamable HTTP),需要時加上 Authorization 標頭。", "Connect Model Context Protocol servers and bots can use their tools (GitHub, Notion, databases, your company's own systems). A local server takes a command (e.g. npx -y @modelcontextprotocol/server-filesystem ~/Documents); a remote one an address (Streamable HTTP), with an Authorization header if needed.", "Model Context Protocol サーバーを接続すると、Bot がそのツールを使えます(GitHub、Notion、データベース、社内システムなど)。ローカルのサーバーはコマンド(例:npx -y @modelcontextprotocol/server-filesystem ~/Documents)、リモートのサーバーはアドレス(Streamable HTTP)を入力し、必要なら Authorization ヘッダーを付けます。"), ("開著的技能會列在 Bot 的目錄裡,需要時自動載入。", "Skills that are on are listed in the bots' catalog and loaded when needed.", "オンのスキルは Bot のカタログに載り、必要なときに読み込まれます。"), + ("這個連接器已經被改名或移除了,名稱沒有改。", "This connector was renamed or removed meanwhile; the name wasn't changed.", "このコネクタは別の場所で名前変更または削除されたため、名前は変更していません。"), ("名稱不能空白,沒有改。", "A name can't be empty; it wasn't changed.", "名前は空にできません。変更していません。"), ("已經有叫「{n}」的連接器,名稱沒有改。", "There is already a connector called “{n}”; the name wasn't changed.", "「{n}」というコネクタがすでにあります。名前は変更していません。"), ("常用的連接器,按「加入」就能用。需要金鑰的會打開「新增連接器」並填好,補上金鑰再按「新增」。本機的需要先裝 Node.js(npx)或 uv(uvx)。下面的「公用市集」搜尋官方 MCP Registry 裡用網址連的連接器。", "Common connectors, ready with Add. One that needs a key opens Add connector filled in: add the key and press Add. Local ones need Node.js (npx) or uv (uvx). The public market below searches the official MCP Registry for connectors reached by address.", "よく使うコネクタは「追加」ですぐ使えます。キーが必要なものは「コネクタを追加」を入力済みで開きます。キーを入れて「追加」を押してください。ローカルのものは Node.js(npx)か uv(uvx)が必要です。下の「公開マーケット」は公式 MCP Registry からアドレスで接続するコネクタを検索します。"), diff --git a/src/mcp_oauth.rs b/src/mcp_oauth.rs index 71f7efe..92e28bc 100644 --- a/src/mcp_oauth.rs +++ b/src/mcp_oauth.rs @@ -131,6 +131,12 @@ pub fn rename(old: &str, new: &str) { } } +/// Keep tokens for a connector (other modules' tests). +#[cfg(test)] +pub fn save_for_test(server: &str, t: Tokens) { + save(server, Some(t)).unwrap(); +} + /// Log a connector out (its tokens go). pub fn logout(server: &str) -> Result<(), String> { save(server, None)