diff --git a/FEATURES.md b/FEATURES.md index 8458a33..99bb19a 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1491,9 +1491,10 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 設定 →「連接器」。接上 Model Context Protocol 伺服器,Bot 就能用它的工具(原版的 MCP 用戶端)。 - 本機伺服器填指令(例如 `npx -y @modelcontextprotocol/server-filesystem ~/Documents`)加環境變數;遠端伺服器填網址(Streamable HTTP,JSON 或 SSE 回應都可以)加標頭。 -- 每個連接器一張卡:狀態點(「已連上,N 個工具」/錯誤原因)、開啟、移除、「給 Bot 的使用說明」(原版的 MCP 自訂說明,會放進 Bot 的系統指示)。下面列出所有可以用的工具。 +- 清單+各自的頁(跟 Claude、ChatGPT 的設定一樣):「已加入」每個連接器一列(名稱、狀態點「已連上,N 個工具」/錯誤原因、開關、›);點一列進到它自己的頁:狀態、登入、重新連線、開關,「工具(N)」只列它自己的工具(多時可搜尋;大腦本機看得到全部,連到大腦的螢幕電腦每個連接器最多 80 個、說明最多 160 字),「設定」(各欄位和「給 Bot 的使用說明」——原版的 MCP 自訂說明,會放進 Bot 的系統指示),最下面「移除這個連接器」(再確認一次)。名稱打完按 Enter、離開欄位或離開這一頁才改(Esc 放回原來的;空白或同名不改);改名時登入、「一律允許」(每個 Bot 的 `mcp:<名稱>`)、金鑰、密碼、在清單裡的位置都留著——在螢幕電腦上改名是請大腦改它自己那一個(`/api/sync/mcp-rename`),本機不先改,新名字隨大腦的更新回來;不是讓大腦從網址猜。手機的 `/api/act/mcp` 不收改名(區網沒加密,改名會讓別的連接器接手「一律允許」)。「瀏覽市集」(連接器市集、公用市集)和「新增連接器」各是一頁。 +- 技能頁同樣是清單+各自的頁:「已加入(N)」每列名稱、一行說明、開關、›(超過 8 個可搜尋);點進去看完整說明、可重播步數、隨附檔案、內容和「刪除」;內建技能包、Anthropic 開源技能、從網址安裝都在「瀏覽市集」頁。 - 工具名稱給模型看時是 `mcp__<連接器>__<工具>`(最多 64 字;中文名稱的連接器用一段固定代碼)。 -- **帳號和密碼**:「新增連接器」表單和每張連接器卡片都有「帳號」「密碼」兩欄(給用帳號密碼登入的伺服器,例如公司內部系統)。卡片上改了就會用新的重新連線。 +- **帳號和密碼**:「新增連接器」頁和每個連接器自己的頁都有「帳號」「密碼」兩欄(給用帳號密碼登入的伺服器,例如公司內部系統)。在連接器的頁上改了就會用新的重新連線。 - 在指令、環境變數、網址或標頭裡寫「{username}」「{password}」,帳號密碼就填在那裡,例如環境變數 `SCC_USER={username} SCC_PASS={password}`。 - 都沒寫:本機伺服器收到環境變數 `MCP_USERNAME`、`MCP_PASSWORD`(自己設了同名變數的話用自己的);遠端伺服器收到 `Authorization: Basic …`(自己有 Authorization 標頭的話不加)。 - 密碼跟金鑰一樣:螢幕只看得到「已設定」,不會拿到內容;在螢幕上改指令或網址時,大腦會把密碼清掉(不然會被送到新的位址)。 @@ -2340,7 +2341,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - time; - playwright:瀏覽器自動化; - github:官方遠端伺服器。 -- 需要金鑰的(github)會把下面的「新增連接器」表單填好,補上 Token 再按「新增」。 +- 需要金鑰的(github)會打開填好的「新增連接器」頁,補上 Token 再按「新增」。 - 本機的連接器要先安裝 Node.js(npx)或 uv(uvx)。 - 驗證過的:不用金鑰的 7 個都實際下載、透過 AnyBot 的連接器程式連上。 - 工具數:files 14、memory 9、thinking 1、fetch 1、git 12、time 2、playwright 25。 @@ -2348,11 +2349,11 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 測試是 `cargo test --release -- --ignored marketplace`。 - **公用市集**:連接器市集下面有搜尋框,搜官方 MCP Registry(registry.modelcontextprotocol.io,公開、有 API)裡用網址連的連接器。 - 只列用網址連的(Streamable HTTP);要在大腦上跑套件的(npm/PyPI)不列,伺服器上的大腦不一定有 Node.js 或 uv。舊式 SSE 的標「還不支援」;下架的不列。 - - 電腦上按「加入」會把「新增連接器」表單填好、捲過去:名稱(重複就加「2」)、網址、標頭(例如「Authorization: Bearer {smithery_api_key}」)。還有「{…}」時標頭不遮起來、下面說要換成什麼(金鑰的說明、網址變數可以填的值),換好之前「新增」按不下去。 + - 電腦上按「加入」會打開填好的「新增連接器」頁:名稱(重複就加「2」)、網址、標頭(例如「Authorization: Bearer {smithery_api_key}」)。還有「{…}」時標頭不遮起來、下面說要換成什麼(金鑰的說明、網址變數可以填的值),換好之前「新增」按不下去。 - 手機:設定 › 整合 ›「從公用市集加入」,打關鍵字,大腦去搜(手機頁面只能連自己的伺服器);點一個,要金鑰的問金鑰、網址有變數的問變數,再請大腦加上。只有擁有者能用。 - 要登入帳號(OAuth)的連接器:連線時伺服器回 401(或要求登入的 403)、又沒填金鑰,狀態會說「這個連接器要先登入帳號(OAuth):在聊天裡請 Bot 幫你登入,或在 設定 › 整合 › 連接器 按「登入」」;有填金鑰的話說金鑰不對或過期了。 - **登入(MCP 的 OAuth,2025-06-18 版)**:AnyBot 先問連接器自己(401 的 WWW-Authenticate 指的 resource metadata,RFC 9728;沒有就找它的 /.well-known/oauth-protected-resource),再問它指的登入伺服器(RFC 8414 的 /.well-known/oauth-authorization-server,或 OpenID 的;都沒有就用 /authorize、/token、/register),自己註冊成一個 App(RFC 7591,名字 AnyBot),用 PKCE(S256)和 resource(RFC 8707,連接器的網址)帶你到登入頁。登入完瀏覽器回到大腦上的 http://127.0.0.1:臨時連接埠/callback,AnyBot 拿 code 換 token,連接器馬上重新連線(「已登入連接器「…」,正在連線。」)。 - - 從哪裡登入:設定 › 整合 › 連接器,遠端連接器那一列的「登入」(登入過的是「重新登入」),在大腦本機的瀏覽器打開;或在聊天請 Bot:「幫我登入 Notion」→ Bot 用 manage_connectors 的 login 拿到登入網址,用 open_for_person 開在你正在用的電腦上。瀏覽器不在大腦那台(大腦在伺服器上)時,登入後那一頁會打不開:把那頁的網址整個複製貼給 Bot,它用 login 加 callback 交給大腦完成。螢幕電腦和手機上沒有「登入」鍵,請 Bot 做。 + - 從哪裡登入:設定 › 整合 › 連接器,點遠端連接器進到它自己的頁按「登入」(登入過的是「重新登入」),在大腦本機的瀏覽器打開;或在聊天請 Bot:「幫我登入 Notion」→ Bot 用 manage_connectors 的 login 拿到登入網址,用 open_for_person 開在你正在用的電腦上。瀏覽器不在大腦那台(大腦在伺服器上)時,登入後那一頁會打不開:把那頁的網址整個複製貼給 Bot,它用 login 加 callback 交給大腦完成。螢幕電腦和手機上沒有「登入」鍵,請 Bot 做。 - Token 存在大腦的資料夾 connectors/oauth.json,用跟設定裡金鑰同一把鑰匙(鑰匙圈裡的)加密,檔案只有你能讀;不在連接器清單裡,所以不會同步到螢幕或手機。存取 token 快到期(剩 1 分鐘)或連接器回 401 時,用 refresh token 換新的再試一次;換不了就說「登入過期了:重新登入」。「logout」(會先問)刪掉 token。 - 登不進去時照實說:登入伺服器不讓 App 自己註冊(要先在它那邊建 OAuth App,AnyBot 還不支援填 client_id)、不支援 PKCE(S256)、登入伺服器回錯誤、10 分鐘沒有登入(取消)、登入網址用過一次或過期。 - mcpservers.org 這類網站是給人看的頁面,有瀏覽器檢查、沒有給程式讀的清單,所以用官方 Registry。 @@ -2532,7 +2533,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 群組標題按右鍵可以重新命名、刪除群組(裡面的 Bot 移到未分區);雙擊標題也能改名。 - 空的群組會留著,顯示「把 Bot 拖進來」;沒分群組的 Bot 在「未分區」。 - 每列 54 px、圓角 12、40 px 頭像、名字 15 px、最後一句 13 px;未讀是藍點,等你允許是強調色的點。 - - 最下面是你(縮寫頭像和名字,點了打開設定),右邊是「傳送到其他裝置」(↑,第 36 節)和連接器市集(打開 設定 › 整合,直接捲到市集)。這一列固定在側欄底部,不會被切到。 + - 最下面是你(縮寫頭像和名字,點了打開設定),右邊是「傳送到其他裝置」(↑,第 36 節)和連接器市集(打開 設定 › 整合 › 連接器 的「瀏覽市集」頁)。這一列固定在側欄底部,不會被切到。 - + 選單:新增 Bot、新增群組、群組聊天、從範本建立。 - 驗證過的:用模擬點擊確認帳號列、市集鈕、+ 選單、群組右鍵都有反應(`shots/sidebar-clicks.png`),也模擬了拖拉。 - **輸入框**: diff --git a/docs/feature-map/connectors.md b/docs/feature-map/connectors.md index fad51c4..68a889c 100644 --- a/docs/feature-map/connectors.md +++ b/docs/feature-map/connectors.md @@ -5,12 +5,12 @@ ## 子功能 - 本機伺服器:填指令(例如 `npx -y @modelcontextprotocol/server-filesystem ~/Documents`),可加環境變數。遠端伺服器:填網址(Streamable HTTP,回 JSON 或 SSE 都可以),可加標頭(例如 Authorization)。 -- 登入帳號(OAuth):遠端連接器回「要先登入」時,設定裡那一列按「登入」(只在大腦本機),或在聊天請 Bot 登入:瀏覽器打開登入頁,登入完自動接上;瀏覽器在別台電腦、登入後那頁打不開時,把那頁網址貼回聊天。Token 存在大腦、加密,不會同步到螢幕或手機;快到期自動換新,401 時換一次再試。 +- 登入帳號(OAuth):遠端連接器回「要先登入」時,到那個連接器自己的頁按「登入」(只在大腦本機),或在聊天請 Bot 登入:瀏覽器打開登入頁,登入完自動接上;瀏覽器在別台電腦、登入後那頁打不開時,把那頁網址貼回聊天。Token 存在大腦、加密,不會同步到螢幕或手機;快到期自動換新,401 時換一次再試。 - 帳號、密碼:給要用帳號密碼登入的伺服器。在指令、環境變數、網址或標頭寫「{username}」「{password}」,就填在那裡;都沒寫時,本機伺服器收到環境變數 `MCP_USERNAME`、`MCP_PASSWORD`,遠端伺服器收到 Basic 驗證。 - 「給 Bot 的使用說明」:寫進 Bot 的系統指示(例如「查詢客戶資料時先用 search_customers」)。 -- 「已加入」是一張清單,每個連接器一列:名稱、色點和狀態(「已連上,N 個工具」「連線中…」「未連線」「已關閉」或紅字錯誤原因)、「設定」和開關。按「設定」在那一列下面展開它的欄位(名稱、指令或網址、環境變數、標頭、帳號和密碼並排、給 Bot 的使用說明——每個欄位名稱都在輸入框上面),最下面左邊「移除」、右邊「重新連線」;再按「收起」收回。下面列「可以用的工具」。「新增連接器」表單也是同樣的欄位(名稱在上、框在下)。 -- 「連接器市集」:8 個常用的(files、memory、thinking、fetch、git、time、playwright、github),按「加入」就能用;要金鑰的(github)會把「新增連接器」表單填好,補上 Token 再按「新增」。 -- 「公用市集(官方 MCP Registry)」:搜尋用網址連的連接器,按「加入」會填好表單;還有「{…}」沒換成你的值時,按不下「新增」。 +- 頁面跟其他 App 的設定一樣是「清單+各自的頁」:最上面一張小卡「連接器(MCP)」和兩個按鈕「瀏覽市集」「新增連接器」;下面「已加入」每個連接器一列,只有名稱、色點和狀態(「已連上,N 個工具」「連線中…」「未連線」「已關閉」或紅字錯誤原因)、開關和 ›。按那一列(開關以外的地方)進到它自己的頁:最上面名稱、狀態、「登入」(遠端的)「重新連線」和開關(下面一行是登入或改名沒成功的原因);接著「工具(N)」列它自己的工具(名字和一行說明,滑過看全文;超過 8 個有「搜尋工具」;連上之後才有);再下面「設定」卡是它的欄位(名稱、指令或網址、環境變數、標頭、帳號和密碼並排、給 Bot 的使用說明——每個欄位名稱都在輸入框上面;名稱打完按 Enter、離開欄位或離開這一頁才改,Esc 放回原來的;空白或跟別的連接器同名不改並說原因;改名後登入、「一律允許」、金鑰、密碼和在清單裡的位置都留著;在螢幕電腦上改名是請大腦改它自己那一個,新名字等大腦更新回來才出現(等的時候寫「正在請大腦改名…」、欄位暫時不能改),連不到大腦時不改;移除連接器時它的「一律允許」也一起刪;手機和 Bot 的 `manage_connectors` 不能改名);最下面紅字「移除這個連接器」,再按「確定移除」才移除。左上「‹ 連接器」回清單。不再有把所有連接器的工具攤在一起的「可以用的工具」。「新增連接器」是它自己的頁(同樣的欄位,名稱在上、框在下),按「新增」後直接到新連接器的頁看它連線。 +- 「瀏覽市集」頁的「連接器市集」:8 個常用的(files、memory、thinking、fetch、git、time、playwright、github),按「加入」就能用;要金鑰的(github)會打開「新增連接器」頁並填好,補上 Token 再按「新增」。 +- 同一頁的「公用市集(官方 MCP Registry)」:搜尋用網址連的連接器,按「加入」會打開填好的「新增連接器」頁;還有「{…}」沒換成你的值時,按不下「新增」。 - 給 Bot 的方式:所有連接器加起來 20 個工具以內,每個工具直接給,名字是 `mcp__連接器__工具`;超過 20 個,只給 `find_connector_tool` 和 `use_connector_tool`。 - 工具回的文字和圖片都交給 Bot;一次最多等 120 秒。按停止,本機連接器的呼叫馬上結束(不用等它回);用網址連的照樣等它回或到 120 秒。 - 關掉、移除、重新連線或連不上時,連接器連同它帶起來的程式一起關(npx、uvx、sh 底下真正的伺服器以前會留著)。 @@ -19,7 +19,7 @@ ## 使用者怎麼到 -- 設定 ›「整合」›「連接器」分頁:上面「連接器(MCP)」列出已接上的,下面「連接器市集」「新增連接器」「公用市集(官方 MCP Registry)」。 +- 設定 ›「整合」›「連接器」分頁:「已加入」清單;「瀏覽市集」(連接器市集、公用市集)和「新增連接器」各是一頁。側邊欄的連接器市集圖示直接到「瀏覽市集」頁。 - 連接器在大腦上跑。在螢幕上看大腦時,開關就是大腦上的開關,錯誤前面會寫「在大腦上:」。 - 手機:設定 ›「整合」列出連接器(開關、重新連線、移除),還有「從公用市集加入」(只有擁有者能用)。 - 聊天:直接請 Bot「幫我加上 GitLab 的連接器」,給它網址或指令和 Token;它要「管理 App」能力。 @@ -29,7 +29,7 @@ - Bot:工具少時直接呼叫那個 `mcp__…` 工具。工具多時先 `find_connector_tool`:`query` 用功能的字找(英文比較準),或只給 `server` 列出那個連接器全部工具的名字;結果有完整名稱、說明和參數,再用 `use_connector_tool`(`tool` 是完整名稱,`arguments` 是參數)。名字給錯會叫你先找。 - Bot(管理):`manage_connectors`:`action` 是 list、add(name,加 command 或 url,env、headers、username、password、instructions)、update(只給要改的;換了指令或網址沒給新密碼,舊密碼清掉)、remove、reconnect、login(要登入的遠端連接器:回一個登入網址,用 `open_for_person` 開給使用者;登入後那頁打不開時,他把網址貼給你,再 login 加 callback)、logout(會先問)。加之前先在自己的電腦跑一次指令確認能動;秘密放 env、headers 或 password,不要寫進 instructions。 -- 驗證:在聊天請 Bot 加 time 連接器(`uvx mcp-server-time`):要先跳「新增連接器「time」」卡片,允許後 設定 › 整合 › 連接器 多一列「已連上,2 個工具」、Bot 同一輪就能查時間;在螢幕電腦和手機上也看得到這一列。請它關掉、再移除,各跳一次卡片。在「連接器市集」加入 time,卡片要變成「已連上,2 個工具」;請 Bot 查台北現在幾點:第一次要跳「使用連接器「time」的工具:…」,選一律允許後同一個連接器不再問。關掉開關後開新的一輪,Bot 不該再有它的工具。再加入 playwright(工具超過 20 個),Bot 拿到的要變成 `find_connector_tool` 和 `use_connector_tool`。自動測試:`cargo test mcp::`、`cargo test profile::`、`cargo test a_bot_adds_a_connector_from_chat`;實機(要網路、Node.js、uv):`cargo test --release -- --ignored marketplace`、`cargo test registry_search_live -- --ignored`。 +- 驗證:在聊天請 Bot 加 time 連接器(`uvx mcp-server-time`):要先跳「新增連接器「time」」卡片,允許後 設定 › 整合 › 連接器 多一列「已連上,2 個工具」、Bot 同一輪就能查時間;在螢幕電腦和手機上也看得到這一列。請它關掉、再移除,各跳一次卡片。在「連接器市集」加入 time,卡片要變成「已連上,2 個工具」;請 Bot 查台北現在幾點:第一次要跳「使用連接器「time」的工具:…」,選一律允許後同一個連接器不再問。關掉開關後開新的一輪,Bot 不該再有它的工具。再加入 playwright(工具超過 20 個),Bot 拿到的要變成 `find_connector_tool` 和 `use_connector_tool`。點進一個連接器改名稱:打字時游標不會跑掉,按 Enter 或離開欄位才改;改成別的連接器已有的名字要被拒絕並說原因。自動測試:`cargo test mcp::`、`cargo test profile::`、`cargo test a_bot_adds_a_connector_from_chat`、`cargo test a_connector_is_renamed_when_done`、`cargo test layout_audit::`;實機(要網路、Node.js、uv):`cargo test --release -- --ignored marketplace`、`cargo test registry_search_live -- --ignored`。 ## 陷阱 diff --git a/docs/feature-map/safety.md b/docs/feature-map/safety.md index 92860e5..ff3ff81 100644 --- a/docs/feature-map/safety.md +++ b/docs/feature-map/safety.md @@ -4,7 +4,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你 ## 子功能 -- 允許請求:黃色卡片停在輸入框上方,「允許 {Bot} {動作}嗎?」加細節框。按鈕:「允許」、「一律允許{類別}」(有能記住的類別才有)、「拒絕」。電腦工具沒開、或「在這台電腦上執行」沒開時,一律允許的按鈕就是「一律允許」,會打開什麼寫在滑過的說明裡。輸入框空著時 Enter 允許、Esc 拒絕。 +- 允許請求:黃色卡片停在輸入框上方,「允許 {Bot} {動作}嗎?」加細節框。按鈕:「允許」、「一律允許{類別}」(有能記住的類別才有)、「拒絕」。電腦工具沒開、或「在這台電腦上執行」沒開時,一律允許的按鈕就是「一律允許」,會打開什麼寫在滑過的說明裡。輸入框空著時 Enter 允許、Esc 拒絕——有任何對話框或選單開著(設定、Bot 設定、記憶、檔案或頁面、右鍵選單…)、或游標在別的輸入框時不算,那裡的 Enter/Esc 不會替你回答卡片(Esc 照樣關對話框和選單);這些都沒了之後要再等一下(約 0.6 秒)卡片才接按鍵;換了一張新卡片、剛切回這個聊天、輸入框有字或有檔案等著送、按住不放的 Enter,也都要重新等。 - 允許卡片:一句「它想在你的電腦上執行:」+指令,三個按鈕「允許」「一律允許」(滑過說明它會打開什麼)「拒絕」;下面一行灰字「之後都直接操作,不再一個個問」:允許這一筆並打開直接操作(還沒開、管理員沒鎖時才有)。等你的卡片(允許、問題、交給你處理)都是同一種黃:淡黃底、細黃框。 - 一律允許記在那個 Bot 身上(例如「修改檔案」、「npm install」、某個連接器),Bot 設定 ›「電腦操作」的「已設定「一律允許」」看得到,按 × 移除。 - 拒絕後停下:同一輪裡 Bot 再提一模一樣的操作(同一個工具、同樣的參數),直接替你拒絕、不再問,直到你再傳一則訊息(工作中插話也算)。按停止、關視窗不算拒絕。 diff --git a/docs/feature-map/settings.md b/docs/feature-map/settings.md index c83567b..ce19d55 100644 --- a/docs/feature-map/settings.md +++ b/docs/feature-map/settings.md @@ -15,8 +15,8 @@ - 「模型」:每家 AI 供應商的 API 金鑰、服務網址、新 Bot 預設模型、「測試連線並取得模型清單」([bots](bots.md));本機或區網的供應商多一個「看不到圖時,請雲端模型看截圖和附件」(預設關,[chat](chat.md))。「ChatGPT 方案」沒有金鑰和網址欄,改成「ChatGPT 帳號」:登入狀態、「使用 ChatGPT 繼續」「登出」「換帳號」「打開登入頁」「管理用量」;連到別台大腦時多一格貼回登入網址和「完成登入」([bots](bots.md))。 - 「整合」,三個小分頁: - 訊息管道:Slack、Discord、Telegram、Teams…([channels](channels.md))。 - - 連接器:「連接器(MCP)」清單、「可以用的工具」、「連接器市集」、「新增連接器」([connectors](connectors.md))。 - - 技能:所有 Bot 共用的「技能」庫、「技能市集」([skills](skills.md))。 + - 連接器:「連接器(MCP)」和「已加入」清單(每列進到那個連接器自己的頁:設定、它的工具、移除);「瀏覽市集」頁(「連接器市集」、公用市集)、「新增連接器」頁([connectors](connectors.md))。 + - 技能:所有 Bot 共用的「技能」庫清單(每列進到那個技能自己的頁)、「瀏覽市集」頁([skills](skills.md))。 - 「電腦」: - 你的電腦:「在這台電腦上執行」(一律允許/每次詢問/永不允許,[safety](safety.md))、經這台電腦轉送流量、其他電腦(帳號裡的、SSH)、讓帳號裡的其他電腦使用這台([computers](computers.md))。 - 訊息(只有 Mac):傳送訊息、無需詢問直接傳送([apps](apps.md))。 diff --git a/docs/feature-map/skills.md b/docs/feature-map/skills.md index 9d28af1..240ca93 100644 --- a/docs/feature-map/skills.md +++ b/docs/feature-map/skills.md @@ -17,7 +17,7 @@ ## 使用者怎麼到 -- 設定 › 整合 ›「技能」頁:「已加入」一張清單,每列是名稱、一行說明、「檢視」和開關(關掉的不列進任何 Bot 的說明)。按「檢視」在那一列下面展開:完整說明、「可重播 N 步」、隨附檔案、內容,最下面是紅字「刪除」。下面是市集:「內建技能包」按「加入」、「Anthropic 開源技能」(GitHub: anthropics/skills)按「安裝」,加過的寫灰字「已加入」;「從 GitHub、網址或資料夾安裝」貼網址或路徑按「安裝」。 +- 設定 › 整合 ›「技能」頁:最上面一張小卡「技能」和「瀏覽市集」按鈕;下面「已加入(N)」一張清單,每列是名稱、一行說明、開關和 ›(關掉的不列進任何 Bot 的說明);超過 8 個時清單上面有「搜尋技能」。按那一列進到它自己的頁:開關、完整說明、「可重播 N 步」、隨附檔案、內容,最下面是紅字「刪除」;左上「‹ 技能」回清單。「瀏覽市集」頁:「內建技能包」按「加入」、「Anthropic 開源技能」(GitHub: anthropics/skills)按「安裝」,加過的寫灰字「已加入」;「從 GitHub、網址或資料夾安裝」貼網址或路徑按「安裝」。 - Bot 設定 ›「技能」卡:勾這個 Bot 會的(「全選」「全不選」)。群組沒有這張卡。 - 輸入框打「/」再打字,列出這個 Bot 會的技能,選一個就指定它用(見 [chat](chat.md))。 - 手機:設定 › 整合(「從技能市集加入」「從 GitHub 或網址安裝技能」)、Bot 設定頁的「會的技能」、自己訊息的選單裡「教我做(學這一回合)」。 @@ -25,7 +25,7 @@ ## 怎麼操作 - Bot:開始做事前先看技能清單,符合就 `use_skill`(name;要讀附檔加 `file`,例如 scripts/audit_xlsx.py)。使用者教你一套做法或請你建技能時用 `save_skill`(name、description 寫什麼時候用、instructions,可附 files)。`delete_skill` 刪除(要有「管理 App」能力)。要做的事和標著「可重播」的技能一模一樣時用 `replay_skill`(name;有空格就用 values 給每一格這次的內容;computer 只在要換到別台時給),做完自己看結果再回答;還有別的不一樣,就 `use_skill` 讀了自己做。 -- 驗證:設定 › 整合 › 技能 從「內建技能包」加一個,Bot 設定 › 技能 要看得到它;請 Bot 用它,步驟要出現「正在讀技能:…」。請 Bot 在網頁上做一件 5 步以上的事,回覆下面要出現「(學會了新做法「…」…)」,技能頁那一列按「檢視」要看到「可重播 N 步」;再請它做同一件事,要看到「正在照技能重做:…」,重播的步驟標「(重播)」。技能帶參數:做一個 `allowed-tools: Read` 的技能,打「/名稱」後請它改檔案,那一步要被擋(「只准用」)。自動測試:`cargo test skills::`、`cargo test a_skills_allowed_tools`、`cargo test a_fork_skill`、`cargo test memory::`、`cargo test appctl::`、`cargo test agent::`、`cargo test profile::`。 +- 驗證:設定 › 整合 › 技能 按「瀏覽市集」,從「內建技能包」加一個,Bot 設定 › 技能 要看得到它;請 Bot 用它,步驟要出現「正在讀技能:…」。請 Bot 在網頁上做一件 5 步以上的事,回覆下面要出現「(學會了新做法「…」…)」,技能頁點那一列,它的頁要看到「可重播 N 步」;再請它做同一件事,要看到「正在照技能重做:…」,重播的步驟標「(重播)」。技能帶參數:做一個 `allowed-tools: Read` 的技能,打「/名稱」後請它改檔案,那一步要被擋(「只准用」)。自動測試:`cargo test skills::`、`cargo test a_skills_allowed_tools`、`cargo test a_fork_skill`、`cargo test memory::`、`cargo test appctl::`、`cargo test agent::`、`cargo test profile::`。 ## 陷阱 @@ -34,6 +34,6 @@ - `replay_skill` 屬於「看螢幕與操作」能力:沒有這個能力的 Bot、別人(訊息管道、團隊成員)傳來的那一輪都沒有它。技能沒存步驟就只能讀了自己做。 - 重播會停下來:空格沒給齊(會說要填哪幾格);畫面上找不到同一種、同名的東西時先自動截一次圖再找,還是沒有就停在第幾步交還給 Bot;任何一步失敗、被拒或重複,後面都不做。有風險的步驟照樣問使用者。 - 某一步點的東西說不出名字(只有編號),整份就不存步驟;「教我做」也會丟掉只看畫面的步驟和照編號點的步驟。 -- 設定 › 整合 › 技能 的「刪除」只在按「檢視」展開的那一格最下面(清單上沒有),按了要再按一次「確定刪除」才刪,連資料夾一起刪、救不回來。刪掉的內建技能不會自己回來,要再從市集加。 +- 設定 › 整合 › 技能 的「刪除」只在那個技能自己的頁最下面(清單上沒有),按了要再按一次「確定刪除」才刪,連資料夾一起刪、救不回來。刪掉的內建技能不會自己回來,要再從市集加。 - 技能放在大腦上:在連到大腦的螢幕上加入、安裝、刪除,都是請大腦做。 - `use_skill` 讀附檔最多 256 KB,太大的會給路徑,請在終端機直接讀。安裝的技能超過 6 MB 會失敗;檔案超過 48 個時,多的不會裝進來,也不會說。GitHub 達到速率限制時改貼 raw SKILL.md 網址。 diff --git a/src/app.rs b/src/app.rs index 9d4de3e..0f70012 100644 --- a/src/app.rs +++ b/src/app.rs @@ -984,7 +984,7 @@ impl App { app.shot_registry(&q); } app.state.channels.push(crate::channels::Channel { id: 1, kind: crate::channels::Kind::Slack, name: "客服群".into(), bot_id: 2, token: "xoxb-demo".into(), target: "C0123ABCD".into(), enabled: true, client_id: String::new(), tenant: String::new() }); - // Two added connectors (連接器 page); ANYBOT_SHOT_MCP_OPEN=n unfolds the n-th's fields. + // Two added connectors (連接器 page; ANYBOT_SHOT_MCP_PAGE below opens one's own page). for (name, cmd) in [("github", "https://api.githubcopilot.com/mcp/"), ("files", "npx -y @modelcontextprotocol/server-filesystem ~/Documents")] { let url = cmd.starts_with("https://"); let mut it = cmd.split_whitespace(); @@ -997,7 +997,25 @@ impl App { ..Default::default() }); } - app.ch.mcp_open = std::env::var("ANYBOT_SHOT_MCP_OPEN").ok().and_then(|v| v.parse().ok()); + // ANYBOT_SHOT_MCP_PAGE=market|add|: that page of 連接器 (n: the n-th connector's own); + // ANYBOT_SHOT_SKILL_PAGE=market|: that page of 技能. + let page = |v: &str, names: &[String]| match v { + "market" => channels_ui::Page::Market, + "add" => channels_ui::Page::Add, + n => n.parse::().ok().and_then(|i| names.get(i).cloned()).or_else(|| names.iter().find(|x| *x == n).cloned()).map(channels_ui::Page::Item).unwrap_or_default(), + }; + // ANYBOT_SHOT_MCP_TOOLS=n: every connector connected with n made-up tools. + if let Some(n) = std::env::var("ANYBOT_SHOT_MCP_TOOLS").ok().and_then(|v| v.parse::().ok()) { + app.mir.mcp_state = channels_ui::demo_mcp_state(&app.state.mcp_servers, n); + } + if let Ok(v) = std::env::var("ANYBOT_SHOT_MCP_PAGE") { + let names: Vec = app.state.mcp_servers.iter().map(|s| s.name.clone()).collect(); + app.ch.mcp_page = page(&v, &names); + } + if let Ok(v) = std::env::var("ANYBOT_SHOT_SKILL_PAGE") { + let names: Vec = app.state.skills.iter().map(|s| s.name.clone()).collect(); + app.ch.skill_page = page(&v, &names); + } } // 支線 (/btw): one done (its report below), one working, one waiting for the main line. Ok("btw") => { @@ -4094,7 +4112,39 @@ impl App { }); }); ui.add_space(6.0); - if answer.is_none() && draft_empty && !typing && shown > 0.6 && !egui::Popup::is_any_open(ctx) { + // Enter / Esc answer this card only while nothing else is being typed in: not with any + // dialog open over it (settings, Bot 設定, 記憶, a page or file…: a button pressed there + // leaves no caret, and Enter said yes behind it, Esc said no instead of closing it), nor + // with the caret in another field (a connector's name, a search). + // (Where the caret was as this frame began: a field that takes the Enter first lets go + // of the caret before this card looks, so the last frame's is what counts.) + // A menu too: one closed by this very Esc is already marked closed (egui doesn't use the key + // up), so whether one was open as the frame began counts as well — that Esc closed a menu, + // it didn't say no. + // What was kept is this card's, from the frame just before (not another bot's card, not + // from before the person came back to this chat): otherwise it counts as blocked. + let composer = egui::Id::unique(("composer", bot.id)); + // (Each bot's own; a card is told apart by its arrival key, its call id and its words — + // call ids repeat: a service that gives none gets call_0, call_1… every round.) + let seen = egui::Id::unique(("approval-dock-caret", bot.id)); + let card = self.approvals.get(&bot.id).map(|a| format!("{}|{}|{}", self.ask_keys.get(&bot.id).map(String::as_str).unwrap_or(""), a.call_id, a.reason)).unwrap_or_default(); + let pass = ctx.cumulative_pass_nr(); + let kept: Option<(Option, bool, u64, String)> = ctx.data(|d| d.get_temp(seen)); + let fresh = kept.as_ref().is_some_and(|k| k.2 + 1 == pass && k.3 == card); + let (caret_before, menu_before) = kept.map(|k| (k.0, k.1)).unwrap_or((None, false)); + let elsewhere = caret_before.or_else(|| ctx.memory(|m| m.focused())).is_some_and(|f| f != composer); + let dialog_open = self.show_settings || ctx.memory(|m| m.top_modal_layer()).is_some(); + let menu_now = egui::Popup::is_any_open(ctx); + // A key held down (its repeats), words in the box (Enter sends them; a second Enter right + // after was the yes), files waiting to go: none of them is a yes or a no either. + let repeated = ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: Key::Enter | Key::Escape, pressed: true, repeat: true, .. }))); + let blocked = !fresh || typing || elsewhere || dialog_open || menu_now || menu_before || repeated || !draft_empty || self.has_pending_attachments(bot.id); + // While anything else has the keys, the wait starts over: a card that comes into view + // (a dialog closed, a field let go) takes keys only after it has been there a moment. + if blocked { + self.ask_shown.insert(bot.id, Instant::now()); + } + if answer.is_none() && draft_empty && !blocked && shown > 0.6 { let (pressed, _) = ui.input_mut(chat_ui::take_enter); if enter || pressed { answer = Some(ApprovalAnswer::Once); @@ -4102,6 +4152,9 @@ impl App { answer = Some(ApprovalAnswer::Reject); } } + // (Read, then kept: one lock at a time — a ctx call inside another freezes the window.) + let now = (ctx.memory(|m| m.focused()), egui::Popup::is_any_open(ctx), pass, card); + ctx.data_mut(|d| d.insert_temp(seen, now)); if let Some(ans) = answer { self.ask_shown.remove(&bot.id); self.answer(ctx, bot.id, ans); @@ -4202,8 +4255,17 @@ impl App { // The field: the answer itself when there are no choices, 「自己回答」 beside them. let hint = if q.options.is_empty() { t("輸入回答") } else { t("自己回答") }; let field = Frame::new().fill(p.elevated).stroke(Stroke::new(1.0, p.border)).corner_radius(R_M).inner_margin(Margin::symmetric(12, 8)).show(ui, |ui| ui.add(egui::TextEdit::singleline(&mut form.typed[step]).id(typed_id).hint_text(hint).frame(Frame::NONE).font(egui::FontId::proportional(FONT_BASE)).desired_width(f32::INFINITY))).inner; - // A question with nothing to click starts with the caret in its field. - if q.options.is_empty() && self.ask_focus.as_ref() != Some(&(call_id.clone(), step)) { + // A question with nothing to click starts with the caret in its field — not while the + // settings are open over it (it took the caret from whatever was being typed there); + // it gets it once they close. + let dialog_open = self.show_settings || ui.ctx().memory(|m| m.top_modal_layer()).is_some(); + // (Nor while words are being typed in another field — the chat's input with something + // in it: they and their Enter would go into the answer. The chat's input keeps the caret + // after every send; empty, it lets the question have it.) + let composer = egui::Id::unique(("composer", bot.id)); + let draft_empty = self.drafts.get(&bot.id).is_none_or(|d| d.trim().is_empty()); + let typing_elsewhere = ui.ctx().memory(|m| m.focused()).is_some_and(|f| f != typed_id && (f != composer || !draft_empty)); + if q.options.is_empty() && !dialog_open && !typing_elsewhere && self.ask_focus.as_ref() != Some(&(call_id.clone(), step)) { self.ask_focus = Some((call_id.clone(), step)); field.request_focus(); } @@ -4395,6 +4457,8 @@ impl App { /// attention (the Dock icon bounces when AnyBot isn't in front, and the 提示音 rings). fn on_new_approval(&mut self, ctx: &egui::Context, bot_id: u64) { self.popup_hidden.remove(&bot_id); + // (A new card waits its own moment before it takes Enter / Esc.) + self.ask_shown.remove(&bot_id); let key = crate::httpd::random_hex(16); self.ask_keys.insert(bot_id, key.clone()); // (A brain on a server has nobody to hear it.) @@ -4561,9 +4625,11 @@ impl App { let approval_waits = self.approvals.get(&bot.id).is_some_and(|a| !matches!(a.kind, ApprovalKind::Question | ApprovalKind::Handoff)) && draft.trim().is_empty() && !self.has_pending_attachments(bot.id); let mut enter_for_approval = false; if had_focus && !composing { + let held = ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: Key::Enter, pressed: true, repeat: true, .. }))); let (enter, shift_enter) = ui.input_mut(chat_ui::take_enter); if approval_waits { - enter_for_approval = enter; + // (A held Enter's repeats are not a yes.) + enter_for_approval = enter && !held; } else { send_now |= enter; } @@ -6222,6 +6288,8 @@ impl App { self.compact_tick(); self.later_tick(); // A screen of another AnyBot's brain: its bots work there, not here. + // A connector's name left half-typed (its page closed): taken now, here or on a screen. + self.settle_mcp_name(); if self.mir.on { self.remote_tick(ctx); self.poll_fetches(); @@ -7990,6 +8058,209 @@ mod tests { assert!(!s.contains("使用者給你的指示")); } + /// An Enter typed somewhere else — in the settings over the chat, or in another field — is + /// not a yes to the step waiting in the chat (it used to approve it). + #[test] + fn enter_elsewhere_does_not_approve_the_waiting_step() { + let ctx = egui::Context::default(); + let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-enter-elsewhere.png"))); + let id = app.state.bots[0].id; + let (reply, got) = std::sync::mpsc::channel(); + app.approvals.insert(id, Approval { call_id: "c1".into(), tool: "shell".into(), reason: "執行:rm -rf build".into(), grant: String::new(), reply, kind: ApprovalKind::Action }); + app.ask_shown.insert(id, Instant::now() - std::time::Duration::from_secs(2)); + let bot = app.state.bot(id).unwrap().clone(); + let enter = egui::Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let mut other = String::from("github"); + // The caret in another field (drawn before the chat's input), then Enter. + let mut frame = |app: &mut super::App, events: Vec, focus_other: bool| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut other).id_salt("another-field")); + if focus_other { + r.request_focus(); + } + app.composer(ui, &ctx, &bot); + }); + out.textures_delta.clear(); + }; + frame(&mut app, vec![], true); + frame(&mut app, vec![], false); + frame(&mut app, vec![enter.clone()], false); + assert!(got.try_recv().is_err(), "an Enter in another field isn't a yes"); + // The settings open over the chat: nothing focused, still not a yes. + app.show_settings = true; + frame(&mut app, vec![], false); + frame(&mut app, vec![enter], false); + assert!(got.try_recv().is_err(), "an Enter with the settings open isn't a yes"); + // Another dialog over the chat (Bot 設定, 記憶…), nothing focused in it: no yes, no no. + app.show_settings = false; + let modal_frame = |app: &mut super::App, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + app.composer(ui, &ctx, &bot); + egui::Modal::new(egui::Id::unique("some-dialog")).show(ui.ctx(), |ui| ui.label("Bot 設定")); + }); + out.textures_delta.clear(); + }; + modal_frame(&mut app, vec![]); + modal_frame(&mut app, vec![egui::Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]); + modal_frame(&mut app, vec![egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]); + assert!(got.try_recv().is_err(), "keys in another dialog don't answer the card"); + } + + /// The card's keys are the card's, once it has been seen: a second Enter right after sending + /// words isn't a yes, nor is an Enter on the first frame of a new card (the last one answered + /// on the phone, the next one already there). + #[test] + fn a_new_card_or_a_second_enter_is_not_a_yes() { + let enter = egui::Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let setup = |name: &str| { + let ctx = egui::Context::default(); + let app = super::App::new(&ctx, Some(std::env::temp_dir().join(name))); + (ctx, app) + }; + let card = |app: &mut super::App, id: u64, call: &str| { + let (reply, got) = std::sync::mpsc::channel(); + app.approvals.insert(id, Approval { call_id: call.into(), tool: "shell".into(), reason: "執行:rm -rf build".into(), grant: String::new(), reply, kind: ApprovalKind::Action }); + got + }; + // Words typed in the box with the card up a while: Enter sends them to the running turn; + // the next Enter isn't the yes. + let (ctx, mut app) = setup("anybot-second-enter.png"); + let id = app.state.bots[0].id; + let bot = app.state.bot(id).unwrap().clone(); + let composer = egui::Id::unique(("composer", id)); + let frame = |app: &mut super::App, events: Vec, focus: bool| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + if focus { + ui.memory_mut(|m| m.request_focus(composer)); + } + app.composer(ui, &ctx, &bot); + }); + out.textures_delta.clear(); + }; + let got = card(&mut app, id, "c1"); + let steer = Arc::new(Mutex::new(vec![])); + app.streams.insert(id, Live { cancel: Arc::new(AtomicBool::new(false)), started: Instant::now(), last: Instant::now(), produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: steer.clone(), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 0 }); + app.drafts.insert(id, "不要刪".into()); + frame(&mut app, vec![], true); + frame(&mut app, vec![], false); + app.ask_shown.insert(id, Instant::now() - std::time::Duration::from_secs(2)); + frame(&mut app, vec![enter.clone()], false); + assert_eq!(steer.lock().unwrap().len(), 1, "the words went"); + // The same Enter held a moment (its repeat), let go, and a quick second press: neither is the yes. + frame(&mut app, vec![egui::Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: true, modifiers: egui::Modifiers::NONE }], false); + frame(&mut app, vec![egui::Event::Key { key: Key::Enter, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }], false); + frame(&mut app, vec![enter.clone()], false); + let r = got.try_recv(); + assert!(!matches!(r, Ok(ApprovalAnswer::Once)) && app.approvals.contains_key(&id), "the Enter right after sending isn't a yes"); + // A new card in the old one's place (the old one answered on the phone): its first frame + // doesn't take an Enter, however long the bot has been asking. + let (ctx2, mut app2) = setup("anybot-new-card.png"); + let id2 = app2.state.bots[0].id; + let bot2 = app2.state.bot(id2).unwrap().clone(); + let frame2 = |app: &mut super::App, events: Vec| { + let mut out = ctx2.run_ui(egui::RawInput { events, ..Default::default() }, |ui| app.composer(ui, &ctx2, &bot2)); + out.textures_delta.clear(); + }; + let _old = card(&mut app2, id2, "c1"); + frame2(&mut app2, vec![]); + frame2(&mut app2, vec![]); + app2.ask_shown.insert(id2, Instant::now() - std::time::Duration::from_secs(2)); + let got2 = card(&mut app2, id2, "c2"); + frame2(&mut app2, vec![enter.clone()]); + assert!(got2.try_recv().is_err(), "a card seen for no time isn't answered"); + // Two bots, each with a card called 「call_0」 (a service that gives no ids): looking at + // one a while, then back to the other — its first frame doesn't take an Enter. + let (ctx3, mut app3) = setup("anybot-same-call-id.png"); + let (a, b) = (app3.state.bots[0].id, app3.state.bots[1].id); + let (bot_a, bot_b) = (app3.state.bot(a).unwrap().clone(), app3.state.bot(b).unwrap().clone()); + let got_a = card(&mut app3, a, "call_0"); + let _got_b = card(&mut app3, b, "call_0"); + let show = |app: &mut super::App, bot: &crate::model::Bot, events: Vec| { + let mut out = ctx3.run_ui(egui::RawInput { events, ..Default::default() }, |ui| app.composer(ui, &ctx3, bot)); + out.textures_delta.clear(); + }; + show(&mut app3, &bot_a, vec![]); + show(&mut app3, &bot_b, vec![]); + show(&mut app3, &bot_b, vec![]); + app3.ask_shown.insert(a, Instant::now() - std::time::Duration::from_secs(2)); + show(&mut app3, &bot_a, vec![enter]); + assert!(got_a.try_recv().is_err(), "back on the chat: its card waits a moment again"); + } + + /// A question to type an answer to starts with the caret in its field — taken from the chat's + /// input when that is empty (it keeps the caret after every send), not from words being typed. + #[test] + fn a_question_to_type_takes_the_caret_unless_words_are_being_typed() { + for words in ["", "我想先問一下"] { + let ctx = egui::Context::default(); + let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-question-caret.png"))); + let id = app.state.bots[0].id; + let bot = app.state.bot(id).unwrap().clone(); + let composer = egui::Id::unique(("composer", id)); + app.drafts.insert(id, words.into()); + let (reply, _got) = std::sync::mpsc::channel(); + let qs = crate::ask::parse(&serde_json::json!({"questions": [{"question": "你的名字?"}]}).to_string()).unwrap_or_default(); + app.approvals.insert(id, Approval { call_id: "q1".into(), tool: crate::ask::TOOL.into(), reason: crate::ask::to_json(&qs), grant: String::new(), reply, kind: ApprovalKind::Question }); + let frame = |app: &mut super::App, focus: bool| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + if focus { + ui.memory_mut(|m| m.request_focus(composer)); + } + // (As the window draws them: the card in the chat, then the input.) + app.approval_card(ui, &ctx, &bot); + app.composer(ui, &ctx, &bot); + }); + out.textures_delta.clear(); + }; + frame(&mut app, true); + for _ in 0..3 { + frame(&mut app, false); + } + let on_composer = ctx.memory(|m| m.focused()) == Some(composer); + if words.is_empty() { + assert!(!on_composer && ctx.memory(|m| m.focused()).is_some(), "the empty input gives the caret to the question"); + } else { + assert!(on_composer, "words being typed keep the caret"); + } + } + } + + /// Esc that closes a menu closes the menu: it isn't a no to the step waiting in the chat. + /// And a card that comes into view (a field let go) takes keys only after a moment. + #[test] + fn esc_closing_a_menu_does_not_turn_down_the_waiting_step() { + let ctx = egui::Context::default(); + let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-esc-menu.png"))); + let id = app.state.bots[0].id; + let (reply, got) = std::sync::mpsc::channel(); + app.approvals.insert(id, Approval { call_id: "c1".into(), tool: "shell".into(), reason: "執行:ls".into(), grant: String::new(), reply, kind: ApprovalKind::Action }); + app.ask_shown.insert(id, Instant::now() - std::time::Duration::from_secs(2)); + let bot = app.state.bot(id).unwrap().clone(); + let esc = egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let menu = egui::Id::unique("a-menu"); + // A menu drawn before the chat's input, open; then Esc (which closes it first). + let frame = |app: &mut super::App, events: Vec, open: bool| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + let r = ui.button("⋯"); + if open { + egui::Popup::open_id(ui.ctx(), menu); + } + egui::Popup::menu(&r).id(menu).show(|ui| ui.label("釘選")); + app.composer(ui, &ctx, &bot); + }); + out.textures_delta.clear(); + }; + frame(&mut app, vec![], true); + frame(&mut app, vec![], false); + // (Even with the card up long enough by the clock: the menu's own Esc is the menu's.) + app.ask_shown.insert(id, Instant::now() - std::time::Duration::from_secs(2)); + frame(&mut app, vec![esc.clone()], false); + assert!(got.try_recv().is_err(), "the Esc closed the menu, it didn't say no"); + // Right after (the menu just gone): still a moment before the card takes keys. + frame(&mut app, vec![esc], false); + assert!(got.try_recv().is_err(), "not at once after the menu"); + } + /// Enter in an empty box with a step waiting for a yes is the yes. (The box took the Enter /// first, sent nothing — it was empty — and the waiting step never heard it.) #[test] @@ -8014,6 +8285,8 @@ mod tests { out.textures_delta.clear(); }; frame(&mut app, vec![], true); + frame(&mut app, vec![], false); + app.ask_shown.insert(id, Instant::now() - std::time::Duration::from_secs(2)); frame(&mut app, vec![enter.clone()], false); assert!(matches!(got.try_recv(), Ok(ApprovalAnswer::Once)), "Enter said yes"); // With words in the box, Enter sends them (to the running turn) and the step keeps waiting. diff --git a/src/app/channels_ui.rs b/src/app/channels_ui.rs index 0287271..532ee82 100644 --- a/src/app/channels_ui.rs +++ b/src/app/channels_ui.rs @@ -42,10 +42,22 @@ pub struct ChannelUi { new_mcp_hint: String, /// 新增連接器's 帳號 and 密碼. new_mcp_login: (String, String), - /// The form was just filled from the market: scroll it into view. - focus_form: bool, - /// 連接器: which added server's fields are unfolded (its place in the list). - pub(super) mcp_open: Option, + /// 連接器's page (the list, one connector, the market, the form). + pub(super) mcp_page: Page, + /// The connector whose 「移除」 was pressed once (it asks 「確定移除」). + mcp_confirm: Option, + /// What is typed in a connector's page to find one of its tools. + tool_q: String, + /// A connector's name as it is being typed (whose, the words): changed when done. + pub(super) mcp_name: Option<(String, String)>, + /// The name field of the connector page showing (the tests give it the keyboard directly). + pub(super) name_field: Option, + /// A rename asked of the brain from a screen (old, new, when): its page meanwhile. + pub(super) mcp_renaming: Option<(String, String, Instant)>, + /// What a connector's page says (a login that didn't start, a name not taken). + pub(super) mcp_note: Arc>, + /// The page shown last (a new one opens at its top). + page_key: Option<(u8, Page, Page)>, /// 公用市集 (the official MCP Registry): what is typed, a search on its way, what it found. reg_q: String, reg_busy: Arc, @@ -54,10 +66,11 @@ pub struct ChannelUi { pub sub: u8, /// The form for a new channel is open (a press on one of 新增管道's tiles). adding: bool, - /// 連接器市集 was asked for (scroll it into view once). - pub focus_market: bool, skill_src: String, - skill_open: Option, + /// 技能's page (the list, one skill, the market). + pub(super) skill_page: Page, + /// What is typed to find a skill in a long list. + skill_q: String, /// The skill whose 「刪除」 was pressed once: it asks 「確定刪除」 before it goes (with its folder). skill_confirm: Option, skill_busy: Arc, @@ -71,7 +84,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, focus_market: false, skill_src: String::new(), skill_open: None, 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(), focus_form: false, mcp_open: 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_name: None, name_field: None, mcp_renaming: None, mcp_note: Default::default(), page_key: None, reg_q: String::new(), reg_busy: Default::default(), reg_found: Default::default() } } } @@ -511,6 +524,7 @@ impl App { crate::mcp::Change::Remove(s) => { crate::mcp::forget(&s.name); let _ = crate::mcp_oauth::logout(&s.name); + self.forget_mcp_grants(&s.name); } // (Logged out: the link that still carries the token goes too.) crate::mcp::Change::Logout(n) => self.mcp_reconnect(n), @@ -555,7 +569,18 @@ impl App { /// The servers' state as 連接器 shows it: {servers: {name: {tools, error}}, busy, tools: /// [[server, tool, description]]}. A screen gets the brain's (its own would say 未連線). + #[cfg(test)] pub(super) fn mcp_state(&self) -> serde_json::Value { + self.mcp_state_capped(usize::MAX, usize::MAX) + } + + /// What a screen of this brain is sent (every sync): up to 80 tools of each connector, a + /// line of what each does — so a big one doesn't crowd the others out, and the sync stays small. + pub(super) fn mcp_state_for_screen(&self) -> serde_json::Value { + self.mcp_state_capped(80, 160) + } + + fn mcp_state_capped(&self, each: usize, words: usize) -> serde_json::Value { let status = crate::mcp::status(); let errors = self.ch.mcp_errors.lock().unwrap().clone(); let servers: serde_json::Map = self @@ -564,145 +589,454 @@ impl App { .iter() .map(|s| (s.name.clone(), serde_json::json!({"tools": status.get(&s.name), "error": errors.iter().find(|e| e.0 == s.name).map(|e| e.1.clone())}))) .collect(); - let tools: Vec = crate::mcp::tools().iter().take(60).map(|t| serde_json::json!([t.server, t.name, t.description.chars().take(300).collect::()])).collect(); + let mut per: std::collections::HashMap<&str, usize> = Default::default(); + let all = crate::mcp::tools(); + let tools: Vec = all + .iter() + .filter(|t| { + let n = per.entry(t.server.as_str()).or_default(); + *n += 1; + *n <= each + }) + .map(|t| serde_json::json!([t.server, t.name, t.description.chars().take(words).collect::()])) + .collect(); serde_json::json!({"servers": servers, "busy": self.ch.mcp_busy.load(Ordering::SeqCst), "tools": tools}) } - /// 連接器 (`part` 1: the servers, their tools, the markets, the form) and 技能 (`part` 2). + /// 連接器 (`part` 1) and 技能 (`part` 2), each the way other apps' settings do it: a short + /// list (a row each: name, its state, the switch, ›), and a page of its own for one item, + /// for the market, and (連接器) for the form — instead of everything on one long scroll. pub(super) fn connectors_page(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, part: u8) { - let p = self.pal; let before = serde_json::to_string(&self.state.mcp_servers).unwrap_or_default(); + // Another page (the list, one item, the market…): it opens at its top. + let key = (part, self.ch.mcp_page.clone(), self.ch.skill_page.clone()); + if self.ch.page_key.as_ref() != Some(&key) { + ui.scroll_to_cursor(Some(Align::TOP)); + self.ch.page_key = Some(key); + } + // A finished install: this computer's skill folder joins the list. (Not on a screen: its + // list is the brain's, and the brain installs there itself.) + if self.ch.skill_reload.swap(false, Ordering::SeqCst) && !self.mir.on { + crate::memory::merge_skill_files(&mut self.state.skills); + self.dirty = true; + } if part == 1 { - setting_card(ui, p, |ui| { - setting_title(ui, "連接器(MCP)", "接上 Model Context Protocol 伺服器,Bot 就能用它的工具(例如 GitHub、Notion、資料庫、你公司的內部系統)。每個連接器第一次被使用時會先問你。", p); - hint(ui, "本機伺服器填指令(例如 npx -y @modelcontextprotocol/server-filesystem ~/Documents);遠端伺服器填網址(Streamable HTTP),需要時加上 Authorization 標頭。", p); - }); - // On a screen the servers run at the brain: its state, not this computer's. - let st = if self.mir.on { self.mir.mcp_state.clone() } else { self.mcp_state() }; - let busy = st["busy"].as_bool().unwrap_or(false); + match self.ch.mcp_page.clone() { + Page::List => self.mcp_list(ui), + Page::Item(name) => self.mcp_item(ui, &name), + Page::Market => { + if back_link(ui, "連接器", self.pal) { + self.ch.mcp_page = Page::List; + } + ui.add_space(crate::theme::sp::S2); + self.mcp_market(ui, ctx); + } + Page::Add => { + if back_link(ui, "連接器", self.pal) { + self.ch.mcp_page = Page::List; + } + ui.add_space(crate::theme::sp::S2); + self.mcp_form(ui); + } + } + } else { + match self.ch.skill_page.clone() { + Page::Item(name) => self.skill_item(ui, &name), + Page::Market | Page::Add => { + if back_link(ui, "技能", self.pal) { + self.ch.skill_page = Page::List; + } + ui.add_space(crate::theme::sp::S2); + self.skill_market(ui, ctx); + } + Page::List => self.skill_list(ui), + } + } + if serde_json::to_string(&self.state.mcp_servers).unwrap_or_default() != before { + self.dirty = true; + } + } + + /// A connector's new name still being typed is taken (or refused, and said) as soon as its + /// field isn't on screen any more — another sub-tab or settings tab, the sidebar's market, + /// the window closed — never later, by surprise. + pub(super) fn settle_mcp_name(&mut self) { + let Some((whose, _)) = self.ch.mcp_name.as_ref() else { return }; + let showing = self.show_settings && self.settings_tab == SettingsTab::Channels && self.ch.sub == 1 && self.ch.mcp_page == Page::Item(whose.clone()); + if !showing { + self.commit_mcp_name(); + } + } + + /// Take the name being typed: it becomes the connector's when it is free (not empty, no other + /// connector's); otherwise the page says why. Its login and its page follow it. + fn commit_mcp_name(&mut self) { + let Some((whose, want)) = self.ch.mcp_name.take() else { return }; + let want = want.trim().to_string(); + if want == whose { + return; + } + // Why it wasn't changed: on its page, or (the page left) as a notice. + let on_page = self.ch.mcp_page == Page::Item(whose.clone()); + let say = |app: &mut App, why: String| { + if on_page { + *app.ch.mcp_note.lock().unwrap() = why; + } else { + app.notice = Some(why); + } + }; + let why = if want.is_empty() { + Some(t("名稱不能空白,沒有改。")) + } else if self.state.mcp_servers.iter().any(|s| s.name == want) { + Some(t("已經有叫「{n}」的連接器,名稱沒有改。").replace("{n}", &want)) + } else { + None + }; + if let Some(why) = why { + say(self, why); + return; + } + if !self.state.mcp_servers.iter().any(|s| s.name == whose) { + say(self, t("這個連接器已經被改名或移除了,名稱沒有改。")); + return; + } + // On a screen the connector is the brain's: the brain is asked to rename it — its own + // entry, with its keys, its place in the list, its sign-in and 「一律允許」 — and the new + // name comes back with the brain's next update. Nothing is renamed here first, so a + // rename the brain didn't make leaves both on the old name. Not guessed from addresses. + if self.mir.on { + if !self.mir.online { + say(self, t("連不到大腦,名稱沒有改。")); + return; + } + self.mirror_mcp_rename(&whose, &want); + self.ch.mcp_renaming = Some((whose.clone(), want.clone(), Instant::now())); + if on_page { + self.ch.mcp_page = Page::Item(want.clone()); + if let Some(k) = self.ch.page_key.as_mut() { + k.1 = Page::Item(want.clone()); + } + } + return; + } + // (Its sign-in and 「一律允許」 are kept under its name, here: they move with it.) + crate::mcp_oauth::rename(&whose, &want); + self.ch.mcp_errors.lock().unwrap().retain(|e| e.0 != whose); + self.move_mcp_grants(&whose, &want); + if let Some(s) = self.state.mcp_servers.iter_mut().find(|s| s.name == whose) { + s.name = want.clone(); + } + self.dirty = true; + self.ch.mcp_note.lock().unwrap().clear(); + if self.ch.mcp_page == Page::Item(whose.clone()) { + self.ch.mcp_page = Page::Item(want.clone()); + // (The same page under its new name: it doesn't jump to the top.) + if let Some(k) = self.ch.page_key.as_mut() { + k.1 = Page::Item(want.clone()); + } + } + if self.ch.mcp_confirm.as_deref() == Some(whose.as_str()) { + self.ch.mcp_confirm = Some(want); + } + } + + /// 「一律允許」 for a connector is kept by its name (`mcp:` in each bot's rules): a + /// renamed one keeps it, and a later one given the old name doesn't inherit it. + pub(super) fn move_mcp_grants(&mut self, old: &str, new: &str) { + let (from, to) = (format!("mcp:{old}"), format!("mcp:{new}")); + for b in &mut self.state.bots { + for r in b.allow_rules.iter_mut().filter(|r| **r == from) { + *r = to.clone(); + } + } + } + + /// A connector removed: its 「一律允許」 go too — a later one given its name doesn't get them. + pub(super) fn forget_mcp_grants(&mut self, name: &str) { + let grant = format!("mcp:{name}"); + for b in &mut self.state.bots { + b.allow_rules.retain(|r| *r != grant); + } + } + + /// The connectors' state as this window shows it (on a screen, the brain's; in a screenshot + /// or the layout audit, a made-up one marked `demo`). + fn mcp_view(&self, tools: bool) -> serde_json::Value { + if self.mir.on || self.mir.mcp_state["demo"] == true { + self.mir.mcp_state.clone() + } else { + self.mcp_state_capped(if tools { usize::MAX } else { 0 }, usize::MAX) + } + } +} + +/// A made-up connector state for screenshots and the layout audit: every added connector +/// connected, with `tools` tools each (names and descriptions like a real API's, some long). +pub(super) fn demo_mcp_state(servers: &[crate::mcp::Server], tools: usize) -> serde_json::Value { + let mut st = serde_json::json!({"demo": true, "busy": false, "servers": {}, "tools": []}); + for s in servers { + st["servers"][s.name.as_str()] = serde_json::json!({"tools": tools}); + for i in 0..tools { + let (name, about) = match i % 4 { + 0 => (format!("v1_dashboard_event_summary_get_{i}"), "Get BMC Event Severity Summary · [GET /v1/dashboard/eventSummary] · tags: Dashboard".to_string()), + 1 => (format!("v1_device_inventory_fru_physical_asset_get_{i}"), "List the physical assets (FRU) of every device in the inventory, with their serial numbers, part numbers and where each one sits in the rack".to_string()), + 2 => (format!("api_search_{i}"), "搜尋 API 端點".to_string()), + _ => (format!("an_extremely_long_tool_name_that_keeps_going_without_any_break_at_all_{i}"), String::new()), + }; + st["tools"].as_array_mut().unwrap().push(serde_json::json!([s.name, name, about])); + } + } + st +} + +impl App { + + /// A connector's state in a few words, and its dot's colour. + fn mcp_words(&self, s: &crate::mcp::Server, st: &serde_json::Value) -> (Color32, String) { + let p = self.pal; + let one = &st["servers"][s.name.as_str()]; // (「這台電腦沒有 Node.js」 from the brain means the brain, not the computer in front.) let at = if self.mir.on { "在大腦上:" } else { "" }; - let mut remove = None; - let mut reconnect = None; - let mut login: Option<(String, String)> = None; - // The servers as one list (a row each: name, its state, 設定, the switch); the one being - // set up unfolds its fields under its row — every name above its box, all boxes alike. - let open_now = self.ch.mcp_open; - let mut open_next = open_now; - if !self.state.mcp_servers.is_empty() { - section(ui, "已加入", p); - rows_card(ui, p, |ui| { - for (i, s) in self.state.mcp_servers.iter_mut().enumerate() { - let one = &st["servers"][s.name.as_str()]; - let (col, text) = match (s.enabled, one["tools"].as_u64(), one["error"].as_str()) { - (false, _, _) => (p.text3, "已關閉".to_string()), - (_, Some(n), _) => (p.up, format!("已連上,{n} 個工具")), - (_, _, Some(e)) => (p.danger, format!("{at}{e}")), - _ if busy => (p.text3, "連線中…".to_string()), - _ => (p.text3, "未連線".to_string()), - }; - let open = open_now == Some(i); - let name = s.name.clone(); - status_row(ui, p, &name, &text, col, |ui| { - ui.add(computers_ui::toggle(&mut s.enabled)).on_hover_text(t("開啟")); - if ui.add(secondary_button(if open { "收起" } else { "設定" })).clicked() { - open_next = if open { None } else { Some(i) }; - } - }); - if !open { - continue; - } - // 全部欄位都能改:改了就存(頁面尾端的簽名比對會標 dirty),mcp_poll 偵測到 - // 簽名變動會自動重連。 - let mut cmd_edit = if s.url.is_empty() { format!("{} {}", s.command, s.args.join(" ")).trim().to_string() } else { s.url.clone() }; - let mut env_edit: String = s.env.iter().map(|(k, v)| format!("{k}={v}")).collect::>().join(" "); - let mut hdr_edit: String = s.headers.iter().map(|(k, v)| format!("{k}: {v}")).collect::>().join(" "); - let hide_hdr = !hdr_edit.contains('{') && !hdr_edit.is_empty(); - let (mut cmd_changed, mut env_changed, mut hdr_changed) = (false, false, false); - form_row(ui, "名稱", p, |ui| { - ui.add(egui::TextEdit::singleline(&mut s.name).desired_width(ui.available_width())); - }); - form_row(ui, "指令或網址", p, |ui| { - cmd_changed = ui.add(egui::TextEdit::singleline(&mut cmd_edit).font(egui::TextStyle::Monospace).hint_text(t("npx -y … 或 https://…/mcp")).desired_width(ui.available_width())).changed(); - }); - form_row(ui, "環境變數", p, |ui| { - env_changed = ui.add(egui::TextEdit::singleline(&mut env_edit).font(egui::TextStyle::Monospace).password(true).hint_text(t("K=V K2=V2(本機用,選填)")).desired_width(ui.available_width())).changed(); - }); - form_row(ui, "標頭", p, |ui| { - hdr_changed = ui.add(egui::TextEdit::singleline(&mut hdr_edit).font(egui::TextStyle::Monospace).password(hide_hdr).hint_text(t("Authorization: Bearer …(遠端用,選填)")).desired_width(ui.available_width())).changed(); - }); - if cmd_changed { - let c = cmd_edit.trim().to_string(); - if c.starts_with("http://") || c.starts_with("https://") { - s.url = c; - s.command.clear(); - s.args.clear(); - } else { - let mut it = c.split_whitespace(); - s.command = it.next().unwrap_or_default().to_string(); - s.args = it.map(String::from).collect(); - s.url.clear(); - } - } - if env_changed { - s.env = env_edit.split_whitespace().filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect(); - } - if hdr_changed { - s.headers = hdr_edit.split_once(':').map(|(k, v)| std::iter::once((k.trim().to_string(), v.trim().to_string())).collect()).unwrap_or_default(); - } - if s.name != s.name.trim() { - s.name = s.name.trim().to_string(); - } - // 帳號 / 密碼: changed here, the server is connected again with the new ones. - let (user, pass) = (&mut s.username, &mut s.password); - form_pair( - ui, - p, - "帳號", - |ui| { - ui.add(egui::TextEdit::singleline(user).hint_text(t("選填")).desired_width(ui.available_width())); - }, - "密碼", - |ui| { - ui.add(egui::TextEdit::singleline(pass).password(true).hint_text(t("選填")).desired_width(ui.available_width())); - }, - ); - form_row(ui, "給 Bot 的使用說明(選填)", p, |ui| { - ui.add(egui::TextEdit::multiline(&mut s.instructions).desired_rows(1).desired_width(ui.available_width()).hint_text(t("例如:查詢客戶資料時先用 search_customers"))); - }); - // Its own actions, at the end of what they act on: 移除 on the left, away from the rest. - ui.add_space(crate::theme::sp::S3); - ui.horizontal(|ui| { - if ui.add(egui::Button::new(RichText::new(t("移除")).color(p.danger)).frame(false)).clicked() { - remove = Some(i); - } - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if s.enabled && ui.add(secondary_button("重新連線")).on_hover_text(t("再連一次,看連不連得上")).clicked() { - reconnect = Some(s.name.clone()); - } - // 連接器登入: a remote connector, on the brain itself (a screen: ask a bot). - if s.enabled && !s.url.trim().is_empty() && !self.mir.on { - let word = if crate::mcp_oauth::tokens(&s.name).is_some() { "重新登入" } else { "登入" }; - if ui.add(secondary_button(word)).on_hover_text(t("用帳號登入這個連接器(OAuth),在瀏覽器打開登入頁")).clicked() { - login = Some((s.name.clone(), s.url.clone())); - } - } - }); - }); - ui.add_space(crate::theme::sp::S3); + match (s.enabled, one["tools"].as_u64(), one["error"].as_str()) { + (false, _, _) => (p.text3, t("已關閉")), + (_, Some(n), _) => (p.up, t("已連上,{n} 個工具").replace("{n}", &n.to_string())), + (_, _, Some(e)) => (p.danger, format!("{at}{e}")), + _ if st["busy"].as_bool().unwrap_or(false) => (p.text3, t("連線中…")), + _ => (p.text3, t("未連線")), + } + } + + /// 連接器: what it is, 瀏覽市集 and 新增連接器, then the ones added — a row each. + fn mcp_list(&mut self, ui: &mut egui::Ui) { + let p = self.pal; + // (A 「確定移除」 left pressed once on a connector's page doesn't wait there for next time.) + self.ch.mcp_confirm = None; + setting_card(ui, p, |ui| { + setting_title(ui, "連接器(MCP)", "接上 Model Context Protocol 伺服器,Bot 就能用它的工具(例如 GitHub、Notion、資料庫、你公司的內部系統)。本機伺服器填指令(例如 npx -y @modelcontextprotocol/server-filesystem ~/Documents);遠端伺服器填網址(Streamable HTTP),需要時加上 Authorization 標頭。", p); + hint(ui, "讓 Bot 用外部服務的工具。每個連接器第一次被使用時會先問你。", p); + ui.add_space(crate::theme::sp::S2); + ui.horizontal(|ui| { + if ui.add(primary_button("瀏覽市集", p)).clicked() { + self.ch.mcp_page = Page::Market; + } + if ui.add(secondary_button("新增連接器")).on_hover_text(t("用指令或網址接你自己的伺服器")).clicked() { + self.ch.mcp_page = Page::Add; } }); + }); + if self.state.mcp_servers.is_empty() { + section(ui, "已加入", p); + hint(ui, "還沒有連接器。按「瀏覽市集」加一個常用的,或「新增連接器」接你自己的。", p); + return; } - if remove.is_some() { - open_next = None; + let st = self.mcp_view(false); + let words: Vec<(Color32, String)> = self.state.mcp_servers.iter().map(|s| self.mcp_words(s, &st)).collect(); + section(ui, "已加入", p); + let mut open = None; + rows_card(ui, p, |ui| { + for (s, (col, text)) in self.state.mcp_servers.iter_mut().zip(words) { + let name = s.name.clone(); + if nav_row(ui, p, &name, &text, Some(col), |ui| { + ui.add(computers_ui::toggle(&mut s.enabled)).on_hover_text(t("開啟")); + }) { + open = Some(name); + } + } + }); + if let Some(name) = open { + self.ch.mcp_page = Page::Item(name); + self.ch.tool_q.clear(); + self.ch.mcp_note.lock().unwrap().clear(); } - self.ch.mcp_open = open_next; - if let Some(i) = remove { + } + + /// One connector's own page: its state and switch, 重新連線/登入, its settings, its tools, + /// and 移除 at the end. + fn mcp_item(&mut self, ui: &mut egui::Ui, name: &str) { + let p = self.pal; + if back_link(ui, "連接器", p) { + // (A new name typed and not yet done: taken now, if it can be — said as a notice, the + // page being left.) + self.ch.mcp_note.lock().unwrap().clear(); + self.ch.tool_q.clear(); + self.ch.mcp_page = Page::List; + self.commit_mcp_name(); + return; + } + // (Renamed on a screen: until the brain's update brings the new name, it is the old one.) + let renaming = self.ch.mcp_renaming.as_ref().filter(|r| r.1 == name && r.2.elapsed() < std::time::Duration::from_secs(30)).map(|r| r.0.clone()); + let exact = self.state.mcp_servers.iter().position(|s| s.name == name); + // (Still under its old name: the brain hasn't sent the new one yet. Its fields wait — + // an edit now would name a connector the brain no longer has.) + let waiting = exact.is_none(); + let Some(i) = exact.or_else(|| renaming.and_then(|old| self.state.mcp_servers.iter().position(|s| s.name == old))) else { + self.ch.mcp_page = Page::List; + return; + }; + let st = self.mcp_view(true); + let (col, text) = self.mcp_words(&self.state.mcp_servers[i], &st); + let mut remove = false; + let mut reconnect = None; + let mut login: Option<(String, String)> = None; + ui.add_space(crate::theme::sp::S2); + rows_card(ui, p, |ui| { + let s = &mut self.state.mcp_servers[i]; + let shown = s.name.clone(); + status_row(ui, p, &shown, &text, col, |ui| { + ui.add(computers_ui::toggle(&mut s.enabled)).on_hover_text(t("開啟")); + if s.enabled && ui.add(secondary_button("重新連線")).on_hover_text(t("再連一次,看連不連得上")).clicked() { + reconnect = Some(s.name.clone()); + } + // 連接器登入: a remote connector, on the brain itself (a screen: ask a bot). + if s.enabled && !s.url.trim().is_empty() && !self.mir.on { + let word = if crate::mcp_oauth::tokens(&s.name).is_some() { "重新登入" } else { "登入" }; + if ui.add(secondary_button(word)).on_hover_text(t("用帳號登入這個連接器(OAuth),在瀏覽器打開登入頁")).clicked() { + login = Some((s.name.clone(), s.url.clone())); + } + } + }); + }); + let note = self.ch.mcp_note.lock().unwrap().clone(); + if !note.is_empty() { + hint(ui, note, p); + } + + // Its tools, its own (a search when there are many) — not every connector's on one card. + let tools: Vec = st["tools"].as_array().into_iter().flatten().filter(|t| t[0].as_str() == Some(name)).cloned().collect(); + if !tools.is_empty() { + let n = st["servers"][name]["tools"].as_u64().unwrap_or(tools.len() as u64); + section(ui, &t("工具({n})").replace("{n}", &n.to_string()), p); + if tools.len() > 8 { + ui.add(egui::TextEdit::singleline(&mut self.ch.tool_q).id_salt("mcp-tool-search").hint_text(t("搜尋工具")).desired_width(ui.available_width())); + ui.add_space(crate::theme::sp::S2); + } + // (The search counts only while its box shows.) + let q = if tools.len() > 8 { self.ch.tool_q.trim().to_lowercase() } else { String::new() }; + let shown: Vec<&serde_json::Value> = tools.iter().filter(|t| q.is_empty() || t[1].as_str().unwrap_or("").to_lowercase().contains(&q) || t[2].as_str().unwrap_or("").to_lowercase().contains(&q)).collect(); + if (tools.len() as u64) < n { + hint(ui, t("在這台螢幕電腦上只列出前 {k} 個。").replace("{k}", &tools.len().to_string()), p); + } + if shown.is_empty() { + hint(ui, "沒有符合的工具。", p); + } else { + rows_card(ui, p, |ui| { + for t in shown { + tool_row(ui, p, t[1].as_str().unwrap_or(""), t[2].as_str().unwrap_or("")); + } + }); + } + } + + // 設定: every field can be changed; it is kept as it changes (the page's fingerprint marks + // it dirty) and mcp_poll connects again when the fingerprint moves. Each field has an id of + // its own: the tools above come and go as it reconnects, and the one being typed in keeps + // its place. The name is changed when it is done (Enter, or leaving the field) — not on each + // letter, which passed through other connectors' names ("github" → "git") and empty. + let mut done = false; + let mut name_field = None; + section(ui, "設定", p); + if waiting { + hint(ui, "正在請大腦改名…", p); + } + ui.add_enabled_ui(!waiting, |ui| setting_card(ui, p, |ui| { + let s = &mut self.state.mcp_servers[i]; + let draft = self.ch.mcp_name.get_or_insert_with(|| (name.to_string(), name.to_string())); + if draft.0 != name { + *draft = (name.to_string(), name.to_string()); + } + let mut cmd_edit = if s.url.is_empty() { format!("{} {}", s.command, s.args.join(" ")).trim().to_string() } else { s.url.clone() }; + let mut env_edit: String = s.env.iter().map(|(k, v)| format!("{k}={v}")).collect::>().join(" "); + let mut hdr_edit: String = s.headers.iter().map(|(k, v)| format!("{k}: {v}")).collect::>().join(" "); + let hide_hdr = !hdr_edit.contains('{') && !hdr_edit.is_empty(); + let (mut cmd_changed, mut env_changed, mut hdr_changed) = (false, false, false); + form_row(ui, "名稱", p, |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut draft.1).id_salt(("mcp-field", "name")).desired_width(ui.available_width())); + name_field = Some(r.id); + // Esc: put back as it was. + if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) { + draft.1 = name.to_string(); + } else if r.lost_focus() { + done = true; + } + }); + form_row(ui, "指令或網址", p, |ui| { + cmd_changed = ui.add(egui::TextEdit::singleline(&mut cmd_edit).id_salt(("mcp-field", "cmd")).font(egui::TextStyle::Monospace).hint_text(t("npx -y … 或 https://…/mcp")).desired_width(ui.available_width())).changed(); + }); + form_row(ui, "環境變數", p, |ui| { + env_changed = ui.add(egui::TextEdit::singleline(&mut env_edit).id_salt(("mcp-field", "env")).font(egui::TextStyle::Monospace).password(true).hint_text(t("K=V K2=V2(本機用,選填)")).desired_width(ui.available_width())).changed(); + }); + form_row(ui, "標頭", p, |ui| { + hdr_changed = ui.add(egui::TextEdit::singleline(&mut hdr_edit).id_salt(("mcp-field", "headers")).font(egui::TextStyle::Monospace).password(hide_hdr).hint_text(t("Authorization: Bearer …(遠端用,選填)")).desired_width(ui.available_width())).changed(); + }); + if cmd_changed { + let c = cmd_edit.trim().to_string(); + if c.starts_with("http://") || c.starts_with("https://") { + s.url = c; + s.command.clear(); + s.args.clear(); + } else { + let mut it = c.split_whitespace(); + s.command = it.next().unwrap_or_default().to_string(); + s.args = it.map(String::from).collect(); + s.url.clear(); + } + } + if env_changed { + s.env = env_edit.split_whitespace().filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect(); + } + if hdr_changed { + s.headers = hdr_edit.split_once(':').map(|(k, v)| std::iter::once((k.trim().to_string(), v.trim().to_string())).collect()).unwrap_or_default(); + } + // 帳號 / 密碼: changed here, the server is connected again with the new ones. + let (user, pass) = (&mut s.username, &mut s.password); + form_pair( + ui, + p, + "帳號", + |ui| { + ui.add(egui::TextEdit::singleline(user).id_salt(("mcp-field", "user")).hint_text(t("選填")).desired_width(ui.available_width())); + }, + "密碼", + |ui| { + ui.add(egui::TextEdit::singleline(pass).id_salt(("mcp-field", "pass")).password(true).hint_text(t("選填")).desired_width(ui.available_width())); + }, + ); + form_row(ui, "給 Bot 的使用說明(選填)", p, |ui| { + ui.add(egui::TextEdit::multiline(&mut s.instructions).id_salt(("mcp-field", "instructions")).desired_rows(1).desired_width(ui.available_width()).hint_text(t("例如:查詢客戶資料時先用 search_customers"))); + }); + })); + // (Renamed: the page follows it.) + self.ch.name_field = name_field; + if done { + self.commit_mcp_name(); + } + + // 移除: at the end, away from the rest, asked once more. + ui.add_space(crate::theme::sp::S5); + ui.horizontal(|ui| { + if self.ch.mcp_confirm.as_deref() == Some(name) { + if ui.add(egui::Button::new(RichText::new(t("確定移除")).color(p.danger)).frame(false)).clicked() { + remove = true; + self.ch.mcp_confirm = None; + } + if ui.add(egui::Button::new(RichText::new(t("取消")).color(p.text2)).frame(false)).clicked() { + self.ch.mcp_confirm = None; + } + } else if ui.add(egui::Button::new(RichText::new(t("移除這個連接器")).color(p.danger)).frame(false)).clicked() { + self.ch.mcp_confirm = Some(name.to_string()); + } + }); + if remove { let gone = self.state.mcp_servers.remove(i); let _ = crate::mcp_oauth::logout(&gone.name); + self.forget_mcp_grants(&gone.name); + self.ch.mcp_note.lock().unwrap().clear(); + self.ch.mcp_name = None; + self.ch.mcp_page = Page::List; } if let Some((name, url)) = login { - let note = self.ch.note.clone(); + let note = self.ch.mcp_note.clone(); + note.lock().unwrap().clear(); std::thread::spawn(move || match crate::mcp_oauth::start(&name, &url) { // (Windows' `start` reads & in an address as the end of it: the address is shown instead.) Ok(u) if cfg!(windows) => *note.lock().unwrap() = format!("在瀏覽器打開這個網址登入「{name}」:{u}"), @@ -719,82 +1053,215 @@ impl App { self.mcp_reconnect(&name); } } - let tools: Vec<&serde_json::Value> = st["tools"].as_array().into_iter().flatten().collect(); - if !tools.is_empty() { - setting_card(ui, p, |ui| { - setting_title(ui, "可以用的工具", "", p); - for t in tools { - let s = |i: usize| t[i].as_str().unwrap_or(""); - ui.label(RichText::new(format!("{} · {}", s(0), s(1))).size(FONT_SM).color(p.text2)).on_hover_text(s(2)); - } - }); - } - } - // A finished install: this computer's skill folder joins the list. (Not on a screen: its - // list is the brain's, and the brain installs there itself.) - if self.ch.skill_reload.swap(false, Ordering::SeqCst) && !self.mir.on { - crate::memory::merge_skill_files(&mut self.state.skills); - self.dirty = true; - } - let skill_busy = self.ch.skill_busy.load(Ordering::SeqCst); + } - if part == 2 { + /// 瀏覽市集: the common connectors (one click), and the official MCP Registry's. + fn mcp_market(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + let p = self.pal; + setting_card(ui, p, |ui| { + setting_title(ui, "連接器市集", "常用的連接器,按「加入」就能用。需要金鑰的會打開「新增連接器」並填好,補上金鑰再按「新增」。本機的需要先裝 Node.js(npx)或 uv(uvx)。下面的「公用市集」搜尋官方 MCP Registry 裡用網址連的連接器。", p); + for (name, desc, cmd, needs) in crate::mcp::MARKET { + let added = self.state.mcp_servers.iter().any(|s| s.name == name); + listing_row( + ui, + |ui| { + if added { + ui.label(RichText::new(t("已加入")).size(FONT_XS).color(p.text3)); + } else if ui.add(secondary_button("加入")).clicked() { + if needs.is_empty() { + self.state.mcp_servers.push(crate::mcp::market_server(name, cmd)); + } else { + self.ch.new_mcp = (name.to_string(), cmd.to_string(), if cmd.starts_with("http") { String::new() } else { needs.to_string() }, if cmd.starts_with("http") { needs.to_string() } else { String::new() }); + self.ch.mcp_page = Page::Add; + } + } + }, + |ui| { + ui.label(RichText::new(name).strong().family(crate::bold()).size(FONT_SM)); + ui.add(egui::Label::new(RichText::new(desc).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(desc); + }, + ); + } + self.registry_market(ui, ctx); + }); + } + + /// 新增連接器: the form (filled already when it came from the market). + fn mcp_form(&mut self, ui: &mut egui::Ui) { + let p = self.pal; + setting_card(ui, p, |ui| { + setting_title(ui, "新增連接器", "", p); + let (name, cmd, env, headers) = &mut self.ch.new_mcp; + form_row(ui, "名稱", p, |ui| { + ui.add(egui::TextEdit::singleline(name).hint_text(t("例如 github")).desired_width(ui.available_width())); + }); + form_row(ui, "指令或網址", p, |ui| { + ui.add(egui::TextEdit::singleline(cmd).hint_text(t("npx -y @modelcontextprotocol/server-github 或 https://…/mcp")).desired_width(ui.available_width()).font(egui::TextStyle::Monospace)); + }); + form_row(ui, "環境變數", p, |ui| { + ui.add(egui::TextEdit::singleline(env).hint_text(t("GITHUB_TOKEN=…(多個用空白分開,本機伺服器用)")).password(true).desired_width(ui.available_width())); + }); + form_row(ui, "標頭", p, |ui| { + // Shown as typed while a 「{…}」 is still to be replaced; hidden once it's a key. + let hide = !headers.contains('{'); + ui.add(egui::TextEdit::singleline(headers).hint_text(t("Authorization: Bearer …(遠端伺服器用)")).password(hide).desired_width(ui.available_width())); + }); + let (user, pass) = &mut self.ch.new_mcp_login; + form_row(ui, "帳號", p, |ui| { + ui.add(egui::TextEdit::singleline(user).hint_text(t("要用帳號密碼登入的伺服器才填")).desired_width(ui.available_width())); + }); + form_row(ui, "密碼", p, |ui| { + ui.add(egui::TextEdit::singleline(pass).password(true).desired_width(ui.available_width())); + }); + hint(ui, "帳號密碼怎麼交給伺服器:在指令、環境變數、網址或標頭裡寫「{username}」「{password}」,就填在那裡(例如環境變數 SCC_USER={username} SCC_PASS={password});都沒寫的話,本機伺服器會收到環境變數 MCP_USERNAME、MCP_PASSWORD,遠端伺服器收到 Authorization: Basic。", p); + if !self.ch.new_mcp_hint.is_empty() { + ui.label(RichText::new(&self.ch.new_mcp_hint).size(FONT_SM).color(p.text2)); + } + // A 「{…}」 left in the address or the header can only fail (the 帳號/密碼 slots are filled when connecting). + let unfilled = crate::mcp::Server::unfilled(cmd) || crate::mcp::Server::unfilled(headers); + if unfilled { + ui.label(RichText::new(t("還有「{…}」沒換成你的值")).size(FONT_XS).color(p.danger)); + } + let ok = !unfilled && !name.trim().is_empty() && !cmd.trim().is_empty() && !self.state.mcp_servers.iter().any(|s| s.name == name.trim()); + ui.add_space(crate::theme::sp::S2); + if ui.add_enabled(ok, primary_button("新增", p)).clicked() { + let c = cmd.trim().to_string(); + let is_url = c.starts_with("http://") || c.starts_with("https://"); + let parts: Vec = c.split_whitespace().map(String::from).collect(); + let envs = env.split_whitespace().filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect(); + let hdrs = headers.split_once(':').map(|(k, v)| std::iter::once((k.trim().to_string(), v.trim().to_string())).collect()).unwrap_or_default(); + let added = name.trim().to_string(); + self.state.mcp_servers.push(crate::mcp::Server { + name: added.clone(), + command: if is_url { String::new() } else { parts.first().cloned().unwrap_or_default() }, + args: if is_url { vec![] } else { parts.into_iter().skip(1).collect() }, + env: envs, + url: if is_url { c } else { String::new() }, + headers: hdrs, + enabled: true, + instructions: String::new(), + username: user.trim().to_string(), + password: pass.clone(), + }); + self.ch.new_mcp_login = Default::default(); + self.ch.new_mcp = Default::default(); + self.ch.new_mcp_hint.clear(); + // Its own page: watch it connect. + self.ch.mcp_page = Page::Item(added); + self.ch.tool_q.clear(); + self.ch.mcp_note.lock().unwrap().clear(); + } + }); + } + + /// 技能: what they are and 瀏覽市集, then the ones added — a row each (a search when many). + fn skill_list(&mut self, ui: &mut egui::Ui) { + let p = self.pal; + let busy = self.ch.skill_busy.load(Ordering::SeqCst); setting_card(ui, p, |ui| { setting_title(ui, "技能", "所有 Bot 共用的專業指南與標準作業流程(相容 Agent Skills SKILL.md 規格,支援隨附 scripts/ 與 references/)。", p); hint(ui, "開著的技能會列在 Bot 的目錄裡,需要時自動載入。", p); + ui.add_space(crate::theme::sp::S2); + if ui.add(primary_button("瀏覽市集", p)).on_hover_text(t("內建技能包、Anthropic 開源技能,或從 GitHub、網址、資料夾安裝")).clicked() { + self.ch.skill_page = Page::Market; + } }); - // The skills as one list (a row each: name, one line of what it is, 檢視, the switch); the - // one being looked at unfolds under its row, with 刪除 at its end — not on every row. - section(ui, "已加入", p); - let mut remove = None; - if self.state.skills.is_empty() { - hint(ui, "還沒有技能。可從下方的內建技能包一鍵加入。", p); - } else { - let mut dirty_toggle = false; - rows_card(ui, p, |ui| { - for (i, k) in self.state.skills.iter_mut().enumerate() { - let open = self.ch.skill_open.as_deref() == Some(k.name.as_str()); - // (Unfolded, its whole description is under it: no cut-off copy in the row.) - let (name, about) = (k.name.clone(), if open { String::new() } else { k.description.replace('\n', " ") }); - card_row(ui, p, &name, &about, "", |ui| { - if ui.add(computers_ui::toggle(&mut k.enabled)).on_hover_text(t("開啟")).changed() { - dirty_toggle = true; - } - if ui.add(secondary_button(if open { "收起" } else { "檢視" })).clicked() { - self.ch.skill_open = if open { None } else { Some(name.clone()) }; - self.ch.skill_confirm = None; - } - }); - if open && skill_detail(ui, p, k, &mut self.ch.skill_confirm) { - remove = Some(i); + let n = self.state.skills.len(); + section(ui, &if n > 0 { t("已加入({n})").replace("{n}", &n.to_string()) } else { t("已加入") }, p); + if n == 0 { + hint(ui, "還沒有技能。按「瀏覽市集」從內建技能包加一個。", p); + if self.ch.skill_note_list { + skill_status(ui, &self.ch, busy, p); + } + return; + } + if n > 8 { + ui.add(egui::TextEdit::singleline(&mut self.ch.skill_q).id_salt("skill-search").hint_text(t("搜尋技能")).desired_width(ui.available_width())); + ui.add_space(crate::theme::sp::S2); + } + let q = if n > 8 { self.ch.skill_q.trim().to_lowercase() } else { String::new() }; + let mut open = None; + let mut toggled = false; + let mut any = false; + rows_card(ui, p, |ui| { + for k in self.state.skills.iter_mut().filter(|k| q.is_empty() || k.name.to_lowercase().contains(&q) || k.description.to_lowercase().contains(&q)) { + any = true; + let (name, about) = (k.name.clone(), k.description.replace('\n', " ")); + if nav_row(ui, p, &name, &about, None, |ui| { + if ui.add(computers_ui::toggle(&mut k.enabled)).on_hover_text(t("開啟")).changed() { + toggled = true; } + }) { + open = Some(name); + } + } + if !any { + ui.add_space(crate::theme::sp::S3); + ui.label(RichText::new(t("沒有符合的技能。")).size(FONT_SM).color(p.text3)); + ui.add_space(crate::theme::sp::S3); + } + }); + if toggled { + self.dirty = true; + } + if let Some(name) = open { + self.ch.skill_page = Page::Item(name); + self.ch.skill_confirm = None; + } + if self.ch.skill_note_list { + ui.add_space(crate::theme::sp::S2); + skill_status(ui, &self.ch, busy, p); + } + } + + /// One skill's own page: its switch, all of what it is, its files, its instructions, and 刪除. + fn skill_item(&mut self, ui: &mut egui::Ui, name: &str) { + let p = self.pal; + if back_link(ui, "技能", p) { + self.ch.skill_page = Page::List; + return; + } + let Some(i) = self.state.skills.iter().position(|k| k.name == name) else { + self.ch.skill_page = Page::List; + return; + }; + ui.add_space(crate::theme::sp::S2); + let mut toggled = false; + let mut remove = false; + rows_card(ui, p, |ui| { + let k = &mut self.state.skills[i]; + let words = if k.enabled { t("開著:列在 Bot 的目錄裡") } else { t("關著:不列進任何 Bot 的說明") }; + card_row(ui, p, name, &words, "", |ui| { + if ui.add(computers_ui::toggle(&mut k.enabled)).on_hover_text(t("開啟")).changed() { + toggled = true; } }); - if dirty_toggle { - self.dirty = true; - } + }); + setting_card(ui, p, |ui| { + remove = skill_detail(ui, p, &self.state.skills[i], &mut self.ch.skill_confirm); + }); + if toggled { + self.dirty = true; } - if let Some(i) = remove { + if remove { if self.mir.on { // The brain takes it off its list and its disk (a folder left there would // bring it back when the brain restarts); the list here follows. - let name = self.state.skills[i].name.clone(); self.ch.skill_note_list = true; self.mirror_skill(serde_json::json!({"name": name, "remove": true}), self.ch.skill_note.clone(), self.ch.skill_busy.clone()); } else { let gone = self.state.skills.remove(i); crate::memory::remove_skill_files(&gone.name); - if self.ch.skill_open.as_deref() == Some(gone.name.as_str()) { - self.ch.skill_open = None; - } self.dirty = true; } + self.ch.skill_page = Page::List; } - if self.ch.skill_note_list { - ui.add_space(crate::theme::sp::S2); - skill_status(ui, &self.ch, skill_busy, p); - } + } + /// 瀏覽市集 (技能): the built-in packs, Anthropic's open skills, and installing from an address. + fn skill_market(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + let p = self.pal; + let skill_busy = self.ch.skill_busy.load(Ordering::SeqCst); // 技能市集: the same quiet rows — 加入/安裝 until it is in, then a grey 「已加入」. section(ui, "內建技能包", p); let mut add_builtin = None; @@ -867,105 +1334,41 @@ impl App { if let Some(src) = install { self.skill_install(src, ctx); } - } - if part == 1 { - // 外掛市集: common connectors, one click away (ones needing a key fill the form below). - setting_card(ui, p, |ui| { - if std::mem::take(&mut self.ch.focus_market) { - ui.scroll_to_cursor(Some(Align::TOP)); - } - setting_title(ui, "連接器市集", "常用的連接器,按「加入」就能用。需要金鑰的會填好下面的表單,補上金鑰再按「新增」。本機的需要先裝 Node.js(npx)或 uv(uvx)。下面的「公用市集」搜尋官方 MCP Registry 裡用網址連的連接器。", p); - for (name, desc, cmd, needs) in crate::mcp::MARKET { - let added = self.state.mcp_servers.iter().any(|s| s.name == name); - listing_row( - ui, - |ui| { - if added { - ui.label(RichText::new(t("已加入")).size(FONT_XS).color(p.text3)); - } else if ui.add(secondary_button("加入")).clicked() { - if needs.is_empty() { - self.state.mcp_servers.push(crate::mcp::market_server(name, cmd)); - } else { - self.ch.new_mcp = (name.to_string(), cmd.to_string(), if cmd.starts_with("http") { String::new() } else { needs.to_string() }, if cmd.starts_with("http") { needs.to_string() } else { String::new() }); - } - } - }, - |ui| { - ui.label(RichText::new(name).strong().family(crate::bold()).size(FONT_SM)); - ui.add(egui::Label::new(RichText::new(desc).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(desc); - }, - ); - } - self.registry_market(ui, ctx); - }); - setting_card(ui, p, |ui| { - if std::mem::take(&mut self.ch.focus_form) { - ui.scroll_to_cursor(Some(Align::TOP)); - } - setting_title(ui, "新增連接器", "", p); - let (name, cmd, env, headers) = &mut self.ch.new_mcp; - form_row(ui, "名稱", p, |ui| { - ui.add(egui::TextEdit::singleline(name).hint_text(t("例如 github")).desired_width(ui.available_width())); - }); - form_row(ui, "指令或網址", p, |ui| { - ui.add(egui::TextEdit::singleline(cmd).hint_text(t("npx -y @modelcontextprotocol/server-github 或 https://…/mcp")).desired_width(ui.available_width()).font(egui::TextStyle::Monospace)); - }); - form_row(ui, "環境變數", p, |ui| { - ui.add(egui::TextEdit::singleline(env).hint_text(t("GITHUB_TOKEN=…(多個用空白分開,本機伺服器用)")).password(true).desired_width(ui.available_width())); - }); - form_row(ui, "標頭", p, |ui| { - // Shown as typed while a 「{…}」 is still to be replaced; hidden once it's a key. - let hide = !headers.contains('{'); - ui.add(egui::TextEdit::singleline(headers).hint_text(t("Authorization: Bearer …(遠端伺服器用)")).password(hide).desired_width(ui.available_width())); - }); - let (user, pass) = &mut self.ch.new_mcp_login; - form_row(ui, "帳號", p, |ui| { - ui.add(egui::TextEdit::singleline(user).hint_text(t("要用帳號密碼登入的伺服器才填")).desired_width(ui.available_width())); - }); - form_row(ui, "密碼", p, |ui| { - ui.add(egui::TextEdit::singleline(pass).password(true).desired_width(ui.available_width())); - }); - hint(ui, "帳號密碼怎麼交給伺服器:在指令、環境變數、網址或標頭裡寫「{username}」「{password}」,就填在那裡(例如環境變數 SCC_USER={username} SCC_PASS={password});都沒寫的話,本機伺服器會收到環境變數 MCP_USERNAME、MCP_PASSWORD,遠端伺服器收到 Authorization: Basic。", p); - if !self.ch.new_mcp_hint.is_empty() { - ui.label(RichText::new(&self.ch.new_mcp_hint).size(FONT_SM).color(p.text2)); - } - // A 「{…}」 left in the address or the header can only fail (the 帳號/密碼 slots are filled when connecting). - let unfilled = crate::mcp::Server::unfilled(cmd) || crate::mcp::Server::unfilled(headers); - if unfilled { - ui.label(RichText::new(t("還有「{…}」沒換成你的值")).size(FONT_XS).color(p.danger)); - } - let ok = !unfilled && !name.trim().is_empty() && !cmd.trim().is_empty() && !self.state.mcp_servers.iter().any(|s| s.name == name.trim()); - if ui.add_enabled(ok, primary_button("新增", p)).clicked() { - let c = cmd.trim().to_string(); - let is_url = c.starts_with("http://") || c.starts_with("https://"); - let parts: Vec = c.split_whitespace().map(String::from).collect(); - let envs = env.split_whitespace().filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect(); - let hdrs = headers.split_once(':').map(|(k, v)| std::iter::once((k.trim().to_string(), v.trim().to_string())).collect()).unwrap_or_default(); - self.state.mcp_servers.push(crate::mcp::Server { - name: name.trim().into(), - command: if is_url { String::new() } else { parts.first().cloned().unwrap_or_default() }, - args: if is_url { vec![] } else { parts.into_iter().skip(1).collect() }, - env: envs, - url: if is_url { c } else { String::new() }, - headers: hdrs, - enabled: true, - instructions: String::new(), - username: user.trim().to_string(), - password: pass.clone(), - }); - self.ch.new_mcp_login = Default::default(); - self.ch.new_mcp = Default::default(); - self.ch.new_mcp_hint.clear(); - } - }); - } - let _ = ctx; - if serde_json::to_string(&self.state.mcp_servers).unwrap_or_default() != before { - self.dirty = true; - } } } +/// A connector's tool in its page's list: the name, and one line of what it does (all of it +/// under the pointer). +fn tool_row(ui: &mut egui::Ui, p: Palette, name: &str, about: &str) { + let top = ui.cursor().top(); + if top > ui.max_rect().top() + 1.0 { + ui.painter().hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.border)); + } + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), if about.is_empty() { 36.0 } else { 48.0 }), egui::Sense::hover()); + let mut c = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(Layout::top_down(Align::Min))); + c.spacing_mut().item_spacing.y = 1.0; + c.add_space(if about.is_empty() { 9.0 } else { 7.0 }); + c.add(egui::Label::new(RichText::new(name).monospace().size(FONT_SM).color(p.text)).truncate().selectable(false)); + if !about.is_empty() { + c.add(egui::Label::new(RichText::new(about.replace('\n', " ")).size(FONT_XS).color(p.text3)).truncate().selectable(false)); + resp.on_hover_text(about); + } +} + +/// 連接器 and 技能: which page of the tab is showing. +#[derive(Clone, Debug, Default, PartialEq)] +pub enum Page { + /// The list of what is added. + #[default] + List, + /// One item's own page (by its name). + Item(String), + /// 瀏覽市集. + Market, + /// 新增連接器 (技能 has none: its market installs). + Add, +} + impl App { /// 公用市集: search the official MCP Registry (in the background) and list what it has that /// is reached by address; 加入 fills 新增連接器 with the address and the header to complete. @@ -1036,7 +1439,7 @@ impl App { let (name, url, header, hint) = crate::mcp::registry_form(e, &self.state.mcp_servers); self.ch.new_mcp = (name, url, String::new(), header); self.ch.new_mcp_hint = hint; - self.ch.focus_form = true; + self.ch.mcp_page = Page::Add; } } diff --git a/src/app/kit.rs b/src/app/kit.rs index ff95006..7dc0d13 100644 --- a/src/app/kit.rs +++ b/src/app/kit.rs @@ -289,6 +289,46 @@ pub(super) fn status_row(ui: &mut egui::Ui, p: Palette, label: &str, status: &st }); } +/// A row that opens a page of its own (a connector, a skill), as other apps' settings lists do: +/// the name and one line under it (with a coloured dot when it is a live state), its quick +/// control (a switch) and a › on the right. A press anywhere else on the row opens it: true. +pub(super) fn nav_row(ui: &mut egui::Ui, p: Palette, label: &str, sub: &str, dot: Option, control: impl FnOnce(&mut egui::Ui)) -> bool { + let top = ui.cursor().top(); + if top > ui.max_rect().top() + 1.0 { + ui.painter().hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.border)); + } + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 58.0), egui::Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect.shrink2(vec2(-8.0, 3.0)), R_M, p.hover); + } + let mut right = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(Layout::right_to_left(Align::Center))); + right.spacing_mut().item_spacing.x = sp::S2; + // (Not selectable: a press on it opens the row too.) + right.add(egui::Label::new(RichText::new("›").size(FONT_H3).color(p.text3)).selectable(false)); + control(&mut right); + let words = egui::Rect::from_min_max(rect.min, egui::pos2((right.min_rect().left() - 12.0).max(rect.left() + 80.0), rect.bottom())); + let mut left = ui.new_child(egui::UiBuilder::new().max_rect(words).layout(Layout::top_down(Align::Min))); + left.spacing_mut().item_spacing = vec2(6.0, 2.0); + left.add_space(if sub.is_empty() { 19.0 } else { 9.0 }); + left.add(egui::Label::new(RichText::new(label).size(FONT_BASE).color(p.text)).truncate().selectable(false)); + if !sub.is_empty() { + left.horizontal(|ui| { + if let Some(dot) = dot { + let (r, _) = ui.allocate_exact_size(vec2(8.0, 14.0), egui::Sense::hover()); + ui.painter().circle_filled(r.center(), 3.5, dot); + } + let col = if dot == Some(p.danger) { p.danger } else { p.text2 }; + ui.add(egui::Label::new(RichText::new(sub).size(FONT_SM).color(col)).truncate().selectable(false)); + }); + } + resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() +} + +/// 「‹ 連接器」: back from a page of its own to the list it came from. +pub(super) fn back_link(ui: &mut egui::Ui, text: &str, p: Palette) -> bool { + ui.add(egui::Button::new(RichText::new(format!("‹ {}", t(text))).size(FONT_SM).color(p.text2)).frame(false)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() +} + pub(super) fn field_label(ui: &mut egui::Ui, text: &str, p: Palette) { ui.add_space(sp::S2); ui.label(RichText::new(t(text)).size(FONT_SM).color(p.text2)); diff --git a/src/app/layout_audit.rs b/src/app/layout_audit.rs index 76268af..623c142 100644 --- a/src/app/layout_audit.rs +++ b/src/app/layout_audit.rs @@ -120,6 +120,54 @@ fn scenes() -> Vec<(&'static str, Open)> { a.ch.sub = 2; }), ), + // Each item's own page, the markets and the form (a list with pages, like other apps). + ( + "設定 › 整合 › 連接器 › 一個連接器", + Box::new(|a: &mut App| { + a.show_settings = true; + a.settings_tab = SettingsTab::Channels; + a.ch.sub = 1; + a.ch.mcp_page = channels_ui::Page::Item(a.state.mcp_servers.last().map(|s| s.name.clone()).unwrap_or_default()); + // Connected, with many tools (long names, long descriptions, none at all). + a.mir.mcp_state = channels_ui::demo_mcp_state(&a.state.mcp_servers, 24); + }), + ), + ( + "設定 › 整合 › 連接器 › 瀏覽市集", + Box::new(|a: &mut App| { + a.show_settings = true; + a.settings_tab = SettingsTab::Channels; + a.ch.sub = 1; + a.ch.mcp_page = channels_ui::Page::Market; + }), + ), + ( + "設定 › 整合 › 連接器 › 新增連接器", + Box::new(|a: &mut App| { + a.show_settings = true; + a.settings_tab = SettingsTab::Channels; + a.ch.sub = 1; + a.ch.mcp_page = channels_ui::Page::Add; + }), + ), + ( + "設定 › 整合 › 技能 › 一個技能", + Box::new(|a: &mut App| { + a.show_settings = true; + a.settings_tab = SettingsTab::Channels; + a.ch.sub = 2; + a.ch.skill_page = channels_ui::Page::Item(a.state.skills.first().map(|s| s.name.clone()).unwrap_or_default()); + }), + ), + ( + "設定 › 整合 › 技能 › 瀏覽市集", + Box::new(|a: &mut App| { + a.show_settings = true; + a.settings_tab = SettingsTab::Channels; + a.ch.sub = 2; + a.ch.skill_page = channels_ui::Page::Market; + }), + ), ("設定 › 電腦", tab(SettingsTab::Computers)), ("設定 › 權限", tab(SettingsTab::Review)), ("設定 › 保險庫", tab(SettingsTab::Vault)), @@ -380,3 +428,111 @@ fn the_check_sees_cut_and_overlapping_text() { assert!(found.iter().any(|p| p.starts_with("疊在一起") && p.contains("停止")), "{found:?}"); assert!(found.iter().any(|p| p.starts_with("被切掉") && p.contains("03:00")), "{found:?}"); } + +/// One frame with these events (a press, a key, typing). +fn step(app: &mut App, ctx: &egui::Context, size: egui::Vec2, events: Vec) -> Vec { + let mut frame = eframe::Frame::_new_kittest(); + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| app.ui(ui, &mut frame)); + out.textures_delta.clear(); + out.shapes +} + +fn key(k: egui::Key) -> egui::Event { + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() } +} + +/// 連接器's own page: the name field keeps the keyboard while the tools above come and go (a +/// reconnect), the name changes only when it is done (Enter), and a name another connector has +/// is refused — typing 「github」 down to 「git」 used to jump to the other connector and make two +/// of the same name. +#[test] +fn a_connector_is_renamed_when_done_and_its_field_keeps_the_keyboard() { + let ctx = egui::Context::default(); + crate::load_fonts(&ctx); + let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-rename-test.png"))); + app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id)); + let server = |n: &str| crate::mcp::Server { name: n.into(), url: format!("https://{n}.example/mcp"), enabled: true, ..Default::default() }; + app.state.mcp_servers = vec![server("git"), server("github")]; + app.mir.mcp_state = channels_ui::demo_mcp_state(&app.state.mcp_servers, 3); + app.show_settings = true; + app.settings_tab = SettingsTab::Channels; + app.ch.sub = 1; + app.ch.mcp_page = channels_ui::Page::Item("github".into()); + let size = vec2(1000.0, 1600.0); + draw(&mut app, &ctx, size); + // The name field, given the keyboard as a press would (by its id, not where it is drawn: + // other tests switch the language, and the page's layout with it, while this one runs). + let field = app.ch.name_field.expect("the name field"); + ctx.memory_mut(|m| m.request_focus(field)); + step(&mut app, &ctx, size, vec![]); + step(&mut app, &ctx, size, vec![key(egui::Key::End)]); + let typing = ctx.memory(|m| m.focused()).expect("the name field has the keyboard"); + for _ in 0..3 { + step(&mut app, &ctx, size, vec![key(egui::Key::Backspace)]); + } + assert_eq!(app.state.mcp_servers[1].name, "github", "not renamed while typing"); + assert_eq!(app.ch.mcp_page, channels_ui::Page::Item("github".into())); + // It reconnects (its tools go away for a moment): the field keeps the keyboard. + app.mir.mcp_state = channels_ui::demo_mcp_state(&[], 0); + step(&mut app, &ctx, size, vec![]); + assert_eq!(ctx.memory(|m| m.focused()), Some(typing), "the field kept the keyboard"); + // 「git」 is taken: not renamed, and the page says why. + step(&mut app, &ctx, size, vec![key(egui::Key::Enter)]); + let shapes = step(&mut app, &ctx, size, vec![]); + assert_eq!(app.state.mcp_servers.iter().map(|s| s.name.as_str()).collect::>(), ["git", "github"]); + // (Not by its words: other tests switch the language while this one runs, and the page + // translates what it shows. A line naming 「git」 is drawn, beyond the names themselves.) + let why = app.ch.mcp_note.lock().unwrap().clone(); + assert!(why.contains("git"), "says why: {why:?}"); + assert!(words(&shapes).iter().any(|w| w.text.contains("git") && w.text.chars().count() > 12 && !w.text.starts_with("http")), "the reason is drawn"); + // A free name: taken when done, and the page follows it. (The same field, given the + // keyboard directly: a second press read as a double press is timing, not what's tested.) + let _ = &shapes; + ctx.memory_mut(|m| m.request_focus(typing)); + step(&mut app, &ctx, size, vec![]); + step(&mut app, &ctx, size, vec![key(egui::Key::End)]); + step(&mut app, &ctx, size, vec![egui::Event::Text("-work".into())]); + step(&mut app, &ctx, size, vec![key(egui::Key::Enter)]); + step(&mut app, &ctx, size, vec![]); + assert_eq!(app.state.mcp_servers[1].name, "github-work"); + assert_eq!(app.ch.mcp_page, channels_ui::Page::Item("github-work".into())); + // Typing a name and going to another tab (the field isn't drawn again): taken at once, not + // left to come back later. (The same field, given the keyboard directly: two presses on one + // spot in frames without time read as a double press.) + ctx.memory_mut(|m| m.request_focus(typing)); + step(&mut app, &ctx, size, vec![]); + step(&mut app, &ctx, size, vec![key(egui::Key::End)]); + step(&mut app, &ctx, size, vec![egui::Event::Text("-x".into())]); + assert_eq!(ctx.memory(|m| m.focused()), Some(typing)); + app.ch.sub = 2; + step(&mut app, &ctx, size, vec![]); + assert_eq!(app.state.mcp_servers[1].name, "github-work-x", "taken on leaving"); + assert!(app.ch.mcp_name.is_none(), "nothing left to come back later"); + +} + +/// Esc while typing a connector's new name puts the old one back. +#[test] +fn esc_puts_a_connectors_name_back() { + let ctx = egui::Context::default(); + crate::load_fonts(&ctx); + let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-rename-esc-test.png"))); + app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id)); + app.state.mcp_servers = vec![crate::mcp::Server { name: "notion".into(), url: "https://notion.example/mcp".into(), enabled: true, ..Default::default() }]; + app.show_settings = true; + app.settings_tab = SettingsTab::Channels; + app.ch.sub = 1; + app.ch.mcp_page = channels_ui::Page::Item("notion".into()); + let size = vec2(1000.0, 1600.0); + draw(&mut app, &ctx, size); + ctx.memory_mut(|m| m.request_focus(app.ch.name_field.expect("the name field"))); + step(&mut app, &ctx, size, vec![]); + step(&mut app, &ctx, size, vec![key(egui::Key::End)]); + step(&mut app, &ctx, size, vec![egui::Event::Text("-work".into())]); + step(&mut app, &ctx, size, vec![key(egui::Key::Escape)]); + step(&mut app, &ctx, size, vec![]); + app.ch.sub = 2; + step(&mut app, &ctx, size, vec![]); + assert_eq!(app.state.mcp_servers[0].name, "notion"); +} diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index cba3f53..c496153 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -441,6 +441,8 @@ enum Out { Skill { body: Value, note: SkillNote, busy: Arc }, /// 連接器 › 重新連線 on a screen: the servers run at the brain. McpReconnect(String), + /// A connector renamed on a screen (old, new): the brain renames its own (see commit_mcp_name). + McpRename(String, String), } /// Where a skill request's answer is shown: (worked, words). @@ -692,7 +694,7 @@ impl App { }) .collect(); // The connectors run here too: whether each is connected, or why not. - out["mcp"] = self.mcp_state(); + out["mcp"] = self.mcp_state_for_screen(); // ChatGPT 方案: whether the brain's account can be used (never its tokens). out["chatgpt"] = crate::chatgpt::view(); // The bots' computer lives here; a screen shows its state, not its own computer's. @@ -1331,6 +1333,11 @@ impl App { *err.lock().unwrap() = format!("大腦沒有重新連線:{e}"); } } + Out::McpRename(old, new) => { + if let Err(e) = remote::sync_post(&s, "mcp-rename", &json!({"name": old, "rename": new})) { + *err.lock().unwrap() = format!("大腦沒有改連接器的名稱:{e}"); + } + } Out::Send { bot, text, atts, memories } => { let mut paths = vec![]; for a in &atts { @@ -1390,6 +1397,10 @@ impl App { /// 連接器 › 重新連線 on a screen: the brain connects it again; its line says 連線中… until /// the brain's next word on it. + pub(super) fn mirror_mcp_rename(&mut self, old: &str, new: &str) { + self.mirror_out(Out::McpRename(old.to_string(), new.to_string())); + } + pub(super) fn mirror_mcp_reconnect(&mut self, name: &str) { if !self.mir.online { *self.mir.error.lock().unwrap() = "連不到大腦,現在只能看。".into(); @@ -1516,6 +1527,32 @@ impl App { #[cfg(test)] mod tests { + /// A connector renamed on a screen is asked of the brain (queued for it, in order), not + /// renamed here — the brain's update brings the new name. Without the brain: not at all, + /// and the person is told. + #[test] + fn a_screen_asks_the_brain_to_rename_a_connector() { + let ctx = egui::Context::default(); + let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-rename.png"))); + app.state.mcp_servers = vec![crate::mcp::Server { name: "gh".into(), url: "https://gh.example/mcp".into(), enabled: true, ..Default::default() }]; + app.mir.on = true; + app.mir.online = false; + app.ch.mcp_name = Some(("gh".into(), "gh-work".into())); + app.settle_mcp_name(); + assert_eq!(app.state.mcp_servers[0].name, "gh"); + assert!(app.notice.as_deref().is_some_and(|n| n.contains("連不到大腦")), "{:?}", app.notice); + let (tx, rx) = channel(); + app.mir.outbox = Some(tx); + app.mir.online = true; + app.ch.mcp_name = Some(("gh".into(), "gh-work".into())); + app.settle_mcp_name(); + match rx.try_recv() { + Ok(Out::McpRename(a, b)) => assert_eq!((a.as_str(), b.as_str()), ("gh", "gh-work")), + _ => panic!("the brain wasn't asked"), + } + assert_eq!(app.state.mcp_servers[0].name, "gh", "renamed by the brain, not here first"); + } + use super::*; /// 每次更新強調色都變回橘色:外觀是這台自己的,連到大腦時、大腦的設定來時、存檔時都用這台的。 @@ -1604,6 +1641,12 @@ mod tests { let mut ch = v["channels"].clone(); unredact(&mut ch, &old["channels"]); assert_eq!(ch[0]["token"], "t"); + // Secrets are found by name only: a renamed item (the brain wasn't told) gets none — never + // another item's that happens to have the same address. + let servers = json!([{"name": "a", "url": "https://x.example/mcp", "password": "pa"}, {"name": "b", "url": "https://x.example/mcp", "password": "pb"}]); + let mut guessed = json!([{"name": "c", "url": "https://x.example/mcp", "password": REDACTED}]); + unredact(&mut guessed, &servers); + assert_eq!(guessed[0]["password"], ""); // Changing base_url while keeping REDACTED must NEVER send the brain's real key to the new server. let mut exfil = v["providers"].clone(); exfil["xai"]["base_url"] = json!("https://evil.example/v1"); diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 12a7c59..a24f46d 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -1593,9 +1593,24 @@ impl App { self.mcp_reconnect(&name); return done("重新連線中…"); } + // Renamed (from a screen): this entry keeps its keys, its place and its sign-in. + if let Some(new) = b["rename"].as_str().map(str::trim) { + if new.is_empty() || self.state.mcp_servers.iter().any(|m| m.name == new) { + return fail("名稱不能空白,也不能跟別的連接器一樣"); + } + if let Some(m) = self.state.mcp_servers.iter_mut().find(|m| m.name == name) { + m.name = new.to_string(); + } + crate::mcp_oauth::rename(&name, new); + self.ch.mcp_errors.lock().unwrap().retain(|e| e.0 != name); + self.move_mcp_grants(&name, new); + self.dirty = true; + return done("好了"); + } // (mcp_poll connects or drops it when the list changes.) if b["remove"].as_bool().unwrap_or(false) { self.state.mcp_servers.retain(|m| m.name != name); + self.forget_mcp_grants(&name); } else if let Some(m) = self.state.mcp_servers.iter_mut().find(|m| m.name == name) { m.enabled = b["enabled"].as_bool().unwrap_or(m.enabled); } @@ -1971,6 +1986,34 @@ mod phone_act_tests { assert!(app.phone_act(&ctx, "skill", &json!({"builtin": "pdf"}), "admin")["error"].is_string()); } + /// A connector renamed on a screen: the brain renames its own entry — its keys, its place in + /// the list and its sign-in stay — and refuses an empty or taken name. + #[test] + fn the_brain_renames_a_connector_for_a_screen() { + let (ctx, mut app) = demo(); + let tag = crate::httpd::random_hex(4); + let (gh, other) = (format!("gh-{tag}"), format!("x-{tag}")); + let server = |n: &str, url: &str| crate::mcp::Server { name: n.into(), url: url.into(), password: "pw".into(), enabled: true, ..Default::default() }; + app.state.mcp_servers = vec![server(&gh, "https://gh.example/mcp"), server(&other, "https://x.example/mcp")]; + crate::mcp_oauth::save_for_test(&gh, crate::mcp_oauth::Tokens { access: "tok".into(), url: "https://gh.example/mcp".into(), ..Default::default() }); + app.state.bots[0].allow_rules.push(format!("mcp:{gh}")); + let new = format!("{gh}-work"); + assert_eq!(app.phone_act(&ctx, "mcp", &json!({"name": gh, "rename": new}), "owner")["ok"], true); + let first = &app.state.mcp_servers[0]; + assert_eq!((first.name.as_str(), first.password.as_str()), (new.as_str(), "pw"), "same place, same keys"); + assert_eq!(crate::mcp_oauth::bearer(&new, "https://gh.example/mcp").as_deref(), Some("tok")); + assert!(crate::mcp_oauth::tokens(&gh).is_none()); + assert!(app.state.bots[0].allow_rules.contains(&format!("mcp:{new}")) && !app.state.bots[0].allow_rules.contains(&format!("mcp:{gh}")), "「一律允許」 follows it"); + for bad in [other.as_str(), " "] { + assert!(app.phone_act(&ctx, "mcp", &json!({"name": new, "rename": bad}), "owner")["error"].is_string(), "{bad:?}"); + } + assert!(app.phone_act(&ctx, "mcp", &json!({"name": new, "rename": "y"}), "admin")["error"].is_string(), "the owner's only"); + // Removed: its 「一律允許」 go with it (one given its name later starts from nothing). + assert_eq!(app.phone_act(&ctx, "mcp", &json!({"name": new, "remove": true}), "owner")["ok"], true); + assert!(!app.state.bots[0].allow_rules.iter().any(|r| r.starts_with("mcp:gh-"))); + let _ = crate::mcp_oauth::logout(&new); + } + /// The phone's 公用市集 adds a server reached by address, with its key; never one with a /// 「{…}」 left in it, never twice under one name, only the owner. #[test] diff --git a/src/app/sidebar_ui.rs b/src/app/sidebar_ui.rs index 7f1f241..b65fc58 100644 --- a/src/app/sidebar_ui.rs +++ b/src/app/sidebar_ui.rs @@ -229,7 +229,7 @@ impl App { if pill_icon(ui, crate::icons::Icon::Apps, p).on_hover_text(t("連接器市集")).clicked() { self.show_settings = true; self.settings_tab = SettingsTab::Channels; - self.ch.focus_market = true; + self.ch.mcp_page = super::channels_ui::Page::Market; self.ch.sub = 1; } }); diff --git a/src/i18n_table.rs b/src/i18n_table.rs index d89956e..ba18660 100644 --- a/src/i18n_table.rs +++ b/src/i18n_table.rs @@ -743,4 +743,31 @@ pub const ROWS: &[(&str, &str, &str)] = &[ ("未登入", "not signed in", "未ログイン"), ("已可使用", "Ready", "利用できます"), ("還沒設定金鑰", "No key yet", "キー未設定"), + // 設定 › 整合 › 連接器、技能 (a list, and a page of its own for each) + ("瀏覽市集", "Browse", "マーケットを見る"), + ("用指令或網址接你自己的伺服器", "Connect your own server by command or address", "コマンドまたはアドレスで自分のサーバーを接続"), + ("讓 Bot 用外部服務的工具。每個連接器第一次被使用時會先問你。", "Bots use tools from other services. Each connector asks you the first time it is used.", "Bot が外部サービスのツールを使います。各コネクタは初回使用時に確認します。"), + ("還沒有連接器。按「瀏覽市集」加一個常用的,或「新增連接器」接你自己的。", "No connectors yet. Add a common one from Browse, or your own with Add connector.", "コネクタはまだありません。「マーケットを見る」から追加するか、「コネクタを追加」で自分のものを接続します。"), + ("已連上,{n} 個工具", "Connected, {n} tools", "接続済み、ツール {n} 個"), + ("未連線", "Not connected", "未接続"), + ("工具({n})", "Tools ({n})", "ツール({n})"), + ("搜尋工具", "Search tools", "ツールを検索"), + ("沒有符合的工具。", "No tools match.", "一致するツールはありません。"), + ("移除這個連接器", "Remove this connector", "このコネクタを削除"), + ("確定移除", "Remove", "削除する"), + ("已加入({n})", "Added ({n})", "追加済み({n})"), + ("搜尋技能", "Search skills", "スキルを検索"), + ("沒有符合的技能。", "No skills match.", "一致するスキルはありません。"), + ("還沒有技能。按「瀏覽市集」從內建技能包加一個。", "No skills yet. Add one from the built-in packs under Browse.", "スキルはまだありません。「マーケットを見る」の内蔵パックから追加します。"), + ("內建技能包、Anthropic 開源技能,或從 GitHub、網址、資料夾安裝", "Built-in packs, Anthropic's open skills, or install from GitHub, an address or a folder", "内蔵パック、Anthropic のオープンスキル、または GitHub・アドレス・フォルダーからインストール"), + ("開著:列在 Bot 的目錄裡", "On: listed in the bots' catalog", "オン:Bot のカタログに表示"), + ("關著:不列進任何 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 のカタログに載り、必要なときに読み込まれます。"), + ("正在請大腦改名…", "Asking the brain to rename it…", "ブレインに名前の変更を依頼しています…"), + ("連不到大腦,名稱沒有改。", "Can't reach the brain; the name wasn't changed.", "ブレインに接続できないため、名前は変更していません。"), + ("這個連接器已經被改名或移除了,名稱沒有改。", "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 c68ae36..a3142c5 100644 --- a/src/mcp_oauth.rs +++ b/src/mcp_oauth.rs @@ -113,6 +113,30 @@ fn save(server: &str, t: Option) -> Result<(), String> { write_all(&all) } +/// A connector renamed: its sign-in goes with it (kept under its name). A login on its way +/// under the old name finishes under the new one. +pub fn rename(old: &str, new: &str) { + if old == new { + return; + } + if let Some(t) = tokens(old) { + if save(new, Some(t)).is_ok() { + let _ = save(old, None); + } + } + for p in pending().lock().unwrap_or_else(|e| e.into_inner()).values_mut() { + if p.server == old { + p.server = new.to_string(); + } + } +} + +/// 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) @@ -615,6 +639,16 @@ pub mod tests { let _ = logout(&name); } + #[test] + fn a_renamed_connector_keeps_its_sign_in() { + let (a, b) = (format!("oauth-old-{}", crate::httpd::random_hex(4)), format!("oauth-new-{}", crate::httpd::random_hex(4))); + save(&a, Some(Tokens { access: "tok".into(), url: "https://x.example/mcp".into(), ..Default::default() })).unwrap(); + rename(&a, &b); + assert!(tokens(&a).is_none()); + assert_eq!(bearer(&b, "https://x.example/mcp").as_deref(), Some("tok")); + let _ = logout(&b); + } + /// Against a test OAuth server: the login address is right, the browser's way back is caught, /// the code becomes tokens (PKCE checked by the server), and a token near its end is renewed. #[test] diff --git a/src/remote.rs b/src/remote.rs index f523c7d..969c86d 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -682,6 +682,12 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { // login. So what would let a bot act without asking — 直接操作, an 「一律允許」 // rule, a new connector — can't be switched on over it; on the computer itself, or // through the account (https), it can. + // 改名 is a screen's (/api/sync/mcp-rename): the phone has no use for it, and over the + // plain-http LAN one read login could rename connectors so that another one inherits a + // 「一律允許」 (they are kept by name). + if *action == "mcp" && !body["rename"].is_null() { + return Resp::error(403, "連接器的名稱只能在電腦上的 AnyBot 改"); + } if !via_relay && loosens_guard(action, &body) { return Resp::error(403, "這項設定會讓 Bot 不用問就動手,不能從區網連線(沒有加密)打開:請在電腦上的 AnyBot 改,或用帳號連線。"); } @@ -869,6 +875,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { ("POST", ["api", "sync", "skill"]) => phone_act_for("skill", req.json(), "owner", 55), // 連接器 › 重新連線 from a screen (the list itself changes through edits). ("POST", ["api", "sync", "mcp"]) => phone_act_for("mcp", json!({"name": req.json()["name"], "reconnect": true}), "owner", 10), + // A connector renamed on a screen: the brain renames its own (keys, place, sign-in stay). + ("POST", ["api", "sync", "mcp-rename"]) => phone_act_for("mcp", json!({"name": req.json()["name"], "rename": req.json()["rename"]}), "owner", 10), ("POST", ["api", "sync", "act"]) => { let b = req.json(); let bot = b["bot"].as_u64().unwrap_or(0); @@ -2525,6 +2533,14 @@ mod tests { } } + /// A connector's name is changed only from a screen (its own road): never through the phone's + /// actions, where a read login over the plain LAN could move a 「一律允許」 to another connector. + #[test] + fn a_connector_is_never_renamed_through_the_phones_road() { + let r = handle(voice_req("/api/act/mcp", "owner", br#"{"name":"github","rename":"x"}"#), true); + assert_eq!(r.status, 403); + } + /// 傳送 is the owner's: a team member or an admin can't send through this brain, and a /// computer takes parcels only from its own brain. #[test]