feat: /doctor 診斷這台電腦:連線、Tailscale 直連還是中繼、大腦、模型服務、Bot 的電腦、連接器、磁碟、上次出錯

工程基礎計畫 E11(grok-build 的 /doctor)。早上「連不到大腦」花了半小時用指令查出是 Tailscale 走香港中繼,現在打一句就看得到。

- doctor.rs:報告的樣子(一項一行 ✓/✗,最後數有幾項要看);帳號伺服器網址是 *.ts.net 時跑 tailscale ping,讀出是直連還是走哪個中繼(走中繼寫延遲和「多半是中間擋了 UDP 41641」);df 看磁碟;找最新的當掉報告。
- app/doctor_ui.rs:當下就知道的(版本、資料夾、紀錄檔、這台 ↔ 帳號伺服器、帳號伺服器 ↔ 大腦、螢幕連不連得到大腦和原因、上次同步的大小和速度、Bot 的電腦、每個開著的連接器、磁碟少於 2 GB、上次出錯),要上網的在背景跑(Tailscale、每個 Bot 用到的模型服務列模型清單),好了在聊天留一行。
- 在連到大腦的螢幕電腦上:/doctor 在連不到大腦的檢查之前就處理,檢查的是這台本身,結果跳成提示(那個聊天是大腦的)。手機打的是大腦檢查自己。
- / 清單、手機的指令清單多一個 doctor;功能地圖 garden.md、chat.md,FEATURES.md。

已驗證:cargo test 全過、clippy -D warnings 過。新測試:報告的格式和計數;tailscale ping 的直連和中繼兩種輸出(用今天早上這台真的輸出「via DERP(hkg) in 63ms」);最新的當掉報告、磁碟;從聊天打 /doctor 先說「診斷中」、再一份報告(模型服務指向測試用的假模型)。
未驗證:螢幕電腦上真的跑一次(要更新這台 App)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-17 11:48:01 +08:00
parent ed879c5005
commit 6ab56c9ad3
11 changed files with 307 additions and 8 deletions

View File

@ -487,7 +487,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
### 「/」清單只放指令
- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。
- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。
- 「/」後面打字,才會再找**這個 Bot 自己會的**技能(名稱開頭符合的先,最多 6 個),想指定它用某個技能時還是可以。手機一樣。
### 上線前補上的防護(安全和資源)
@ -1505,6 +1505,11 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 指令輸出、連接器的回答太長時,給模型的只留開頭和結尾各 6000 字,中間寫「…(中間省略 N 個字;完整內容用 read_result 讀:id=r…)…」;完整的存在資料夾的 `outputs/`(一份最多 20 MB、留 7 天,同樣的內容同一個 id)。較早的結果為了騰出空間被收起時也一樣寫 id。
- 每個 Bot 都有 `read_result`(id、從第幾個字、一次最多兩萬字),只是看,計畫模式也能用。以前叫 Bot「再做一次這一步」看完整的:會改東西的步驟重做很危險,答案也可能不一樣,長紀錄的中間就這樣不見了。
### 診斷(/doctor)
- 聊天打 /doctor:這台電腦的 AnyBot 一項一行 ✓ 或 ✗:版本、資料夾、今天的紀錄檔;這台 ↔ 帳號伺服器(長連線的狀態);帳號伺服器是 *.ts.net 時,Tailscale 是直連還是走它在哪裡的中繼(`tailscale ping`;走中繼會寫延遲和「多半是中間擋了 UDP 41641」);帳號伺服器 ↔ 大腦(帳號伺服器說在不在線上);螢幕連不連得到大腦和原因;上次同步的大小和速度(1 MB 以上、每秒不到 300 KB 算慢);每個 Bot 用到的模型服務連不連得到(列模型清單);Bot 的電腦;每個開著的連接器;磁碟剩多少(少於 2 GB 算 ✗);上次內部出錯。要上網的檢查在背景跑,好了一次留一行。
- 在連到大腦的螢幕電腦上檢查的是這台本身(大腦連不到時正是要用的時候),結果跳成提示;手機打的是大腦檢查自己。
### 用量(/usage)
- 每一次模型呼叫(Bot 的每一步、快速模型、摘要、發布前檢查、目標檢查、支線…)都記一行在資料夾的 `usage/YYYY-MM.jsonl`:時間、供應商、模型、誰的、做什麼(從請求的 session 名稱看:anybot-bot-12 是 Bot 12 的回合)、輸入、輸出、快取讀寫的 token,供應商有回報花費(OpenRouter)時也記。

View File

@ -5,7 +5,7 @@
## 子功能
- 版面:左邊 Bot 清單(側邊欄拖到比 210 px 窄會收成頭像直欄),右邊聊天。點聊天頂部的 Bot 名稱(「查看對話詳細資訊」)打開右側面板,有「動態」「資料庫」兩頁。
- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費),打「@」列出其他 Bot。
- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費)、/doctor(診斷,見 [garden](garden.md)),打「@」列出其他 Bot。
- 記憶小卡片:打字停一下,輸入框上方出現「帶入記憶」一列,見 [memory](memory.md)。
- 插話:Bot 工作中照樣打字送出,不另開一輪,Bot 下一步就讀到(附檔一起進去);輸入框下方寫「已排入「…」,Bot 會在下一步看到」。這一輪剛好結束、來不及讀的,自動變成下一輪。
- 停止:工作中、輸入框空著時,送出鈕變成「停止」。

View File

@ -5,6 +5,7 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「
## 子功能
- 待改進:一輪做完、自動整理做法時,AnyBot 本身的問題(工具回錯的結果、明明開著卻說找不到、一用就出錯、要繞路才做得到、Bot 一直誤用某個工具)另外記下來,不寫進技能。同一個工具的問題合併計次,最多留 50 條;出現 2 次以上的會標出來。
- 診斷(/doctor):在聊天打 /doctor,一項一行 ✓/✗:版本和資料夾、紀錄檔在哪、這台 ↔ 帳號伺服器、Tailscale 是直連還是走它的中繼(走中繼很慢,多半是兩台之間擋了 UDP)、帳號伺服器 ↔ 大腦、上次同步的速度、每個 Bot 用的模型服務連不連得到、Bot 的電腦、每個連接器、磁碟、上次內部出錯。在連到大腦的螢幕電腦上檢查的是這台(連不到大腦時也能用),結果跳成提示;手機打的檢查的是大腦。
- 紀錄檔:AnyBot 自己的訊息寫在資料夾的 `logs/anybot-日期.log`(一天一個、留 7 天、一天最多 20 MB),同時照舊印在終端機(伺服器的 `make server-logs` 看得到)。等級用環境變數 ANYBOT_LOG(error、warn、info 預設、debug)。寫進去前先遮掉金鑰、Token、密碼(glpat-、ghp_、sk-、xai-、AKIA、Bearer、JWT、私鑰、名字像 TOKEN/SECRET/PASSWORD 的變數值 → ••••);手機上的步驟細節也一樣遮。
- 當掉報告:程式內部出錯(任何一條執行緒)時寫 `logs/crash-時間.txt`(版本、執行緒、位置、訊息、backtrace,一樣遮過);下次打開在主要 Bot 的聊天留一行「AnyBot 上次執行時內部出錯…」(連到大腦的螢幕電腦是跳一則提示),並記一條待改進。每份報告只說一次。
- 園丁每日報告(平日 8:44 起):過去一天失敗或被打斷的執行、走冤枉路的執行(10 步以上且 3 成以上沒成功)、被自動暫停的例行任務、重複出現的待改進。

View File

@ -54,7 +54,7 @@
- 做法:`anybot --ask` 加 `--json`(每個事件一行 JSON)、`--bot 名稱`、`--data-dir`、`--approve once|reject`;結束碼 0 成功、1 失敗、130 被中斷。
- 做完:`anybot --ask --json …` 的輸出能被 `jq` 讀;測試涵蓋結束碼。
### E11. `/doctor` 診斷 ⬜
### E11. `/doctor` 診斷 ✅
- 做法:聊天打 `/doctor`(或 設定 › 更新):版本、資料夾、這台↔帳號伺服器(延遲、走 Tailscale 中繼還是直連、下載速度)、帳號伺服器↔大腦(在不在線)、模型供應商(金鑰、連得到)、Bot 的電腦、連接器、磁碟、上次當掉。一條一條 ✓/✗ 加原因。
- 做完:每一項都有測試;把「連不到大腦」那天的情況跑一次要說得出是哪一段。

View File

@ -1656,7 +1656,7 @@ input.addEventListener("keydown", (e) => {
input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && matchMedia("(pointer:fine)").matches) { e.preventDefault(); send(); } });
const SL = {hits: [], lit: 0, q: null, moved: false, closed: false, loading: false, fresh: false, at: false};
/** AnyBot's own / commands (goal.rs on the brain). */
const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}];
const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}];
const GOAL_TAG = "[目標]";
/** The skills a draft like 「/pp」 asks for, as the brain ranks them: name starts with it, name
* contains it, then description. None once a space ends the name, or while the bot works. */
@ -1754,7 +1754,7 @@ async function send() {
const memories = b.busy ? undefined : memPicks();
memReset();
input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash();
const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/usage\s*$/i.test(text);
const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/(usage|doctor)\s*$/i.test(text);
if (!b.busy && !quiet) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; }
// 先顯示: while it works the words aren't in the chat yet — shown at once all the same.
const sent = b.busy && text ? {bot: S.open, text, at: Date.now(), failed: false} : null;

View File

@ -43,6 +43,7 @@ mod voice_ui;
mod drops_ui;
mod memory_ui;
mod goal_ui;
mod doctor_ui;
mod plan_ui;
mod mood_ui;
mod profile_ui;
@ -208,6 +209,8 @@ pub struct App {
popup_hidden: std::collections::HashSet<u64>,
/// "全部允許,之後直接操作" was clicked in a request.
want_direct: std::cell::Cell<bool>,
/// 診斷 (/doctor) reports finished on their thread: (the chat it was asked in, the report).
doctor_out: Arc<Mutex<Vec<(u64, String)>>>,
/// Bots whose running turn came from someone else's message (a channel, a teammate):
/// 一律放行 doesn't answer for them.
strangers: std::collections::HashSet<u64>,
@ -486,6 +489,7 @@ impl App {
popup_hidden: Default::default(),
want_direct: Default::default(),
strangers: Default::default(),
doctor_out: Default::default(),
managed: if demo { policy::Managed::default() } else { policy::read() },
settings_was_open: false,
exe_built: crate::version::exe_modified(),
@ -1402,6 +1406,13 @@ impl App {
if text.trim().is_empty() && !self.has_pending_attachments(bot_id) {
return;
}
// 診斷: 「/doctor」 checks this computer — here even on a screen of a brain, and above
// all when the brain can't be reached.
if crate::doctor::command(&text) {
self.drafts.insert(bot_id, String::new());
self.doctor_start(bot_id);
return;
}
// A screen that can't reach its brain: say so, and keep the quote, the files and the
// memories picked (they used to be used up, leaving only the words to send again).
if self.mir.on && !self.mir.online {
@ -5958,6 +5969,8 @@ impl App {
if !self.demo {
self.tell_crashes();
}
// 診斷: a 「/doctor」 that finished.
self.doctor_tick();
// A screen of another AnyBot's brain: its bots work there, not here.
if self.mir.on {
self.remote_tick(ctx);
@ -7948,6 +7961,34 @@ mod tests {
assert_eq!(app.state.bot(id).unwrap().name, name);
}
/// 診斷: 「/doctor」 says it is checking, then one report: each finding ✓ or ✗ (the model
/// services are this test's fake one; no account, no bots' computer in a test).
#[test]
fn doctor_reports_each_finding() {
let ctx = egui::Context::default();
let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-doctor.png")));
let fake = crate::testkit::Fake::openai(vec![]);
app.state.provider_mut(crate::providers::ProviderKind::Custom).base_url = fake.base();
for b in app.state.bots.iter_mut() {
b.provider = crate::providers::ProviderKind::Custom;
}
let id = app.state.bots[0].id;
app.drafts.insert(id, "/doctor".into());
app.send(&ctx, id);
assert!(app.state.bot(id).unwrap().messages.last().is_some_and(|m| m.note && m.text.starts_with("診斷中")));
let mut report = String::new();
for _ in 0..200 {
app.doctor_tick();
if let Some(m) = app.state.bot(id).unwrap().messages.last().filter(|m| m.text.starts_with("診斷(/doctor)")) {
report = m.text.clone();
break;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(report.contains("✓ AnyBot ") && report.contains("✓ 沒有登入帳號") && report.contains("模型服務 ") && report.contains("Bot 的電腦:"), "{report}");
assert!(report.lines().last().is_some_and(|l| l == "全部正常。" || l.starts_with("有 ")), "{report}");
}
/// 一律放行: before it, a command on this computer waits for 允許; after 「/always-approve」 the
/// person's own turn runs it with no card at all; a stranger's message still waits; 「off」
/// puts asking back (and 直接操作 off again, as it was before).
@ -8328,7 +8369,7 @@ mod tests {
let mut bot = app.state.bots[0].clone();
bot.skills = Some(vec!["週報".into()]);
let names = |l: Vec<(String, String)>| l.into_iter().map(|x| x.0).collect::<Vec<_>>();
assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage"]);
assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage", "doctor"]);
assert_eq!(names(app.slash_list("/週", &bot)), vec!["週報"], "its own, by the word");
assert_eq!(names(app.slash_list("/b", &bot)), vec!["btw"]);
}

View File

@ -1134,7 +1134,7 @@ fn jump_shows(from_bottom: f32, jumping: bool) -> bool {
}
/// AnyBot's own / commands: (name, what it does). The brain acts on them itself (goal.rs).
pub const SLASH_COMMANDS: [(&str, &str); 5] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token")];
pub const SLASH_COMMANDS: [(&str, &str); 6] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟")];
/// What the bot is doing, in the one line beside its face (and on a colleague's card, the phone).
/// A status of several lines — a retry: the error, what it means, when it tries again — used to

123
src/app/doctor_ui.rs Normal file
View File

@ -0,0 +1,123 @@
// 診斷 (/doctor) in the window: what this computer can tell about itself, gathered now (the
// settings and states the window has) and on a thread (the checks that go over the network: each
// model service the bots use, how Tailscale reaches the account server), then said in one line of
// AnyBot's in the chat — on a screen of a brain, whose chats are the brain's, as a notice. What
// each line says and how: doctor.rs.
use super::*;
use crate::doctor::{bad, ok, Line};
impl App {
/// 「/doctor」: gather, check on a thread, tell (doctor_tick).
pub(super) fn doctor_start(&mut self, bot_id: u64) {
let mut lines: Vec<Line> = vec![];
let data = State::path().parent().map(|p| p.to_path_buf()).unwrap_or_default();
lines.push(ok(format!("AnyBot {};資料夾 {}", crate::version::full(crate::version::exe_modified()), data.display())));
lines.push(ok(format!("紀錄檔 {}", crate::logfile::dir().join(format!("anybot-{}.log", chrono::Local::now().format("%Y-%m-%d"))).display())));
// The account server and the brain.
let s = self.state.remote.clone();
if s.relay_url.is_empty() {
lines.push(ok("沒有登入帳號(只在這台用)"));
} else {
let status = crate::remote::hub().relay_status();
if status == "已連線" {
lines.push(ok(format!("這台 ↔ 帳號伺服器({}):已連線", s.relay_url)));
} else {
lines.push(bad(format!("這台 ↔ 帳號伺服器({}):{}", s.relay_url, if status.is_empty() { "沒有連線" } else { status.as_str() })));
}
}
if !s.brain_id.is_empty() {
match self.rm.peers.lock().unwrap().iter().find(|(id, _, _)| *id == s.brain_id).map(|x| x.2) {
Some(true) => lines.push(ok(format!("帳號伺服器 ↔ 大腦「{}」:在線上", s.brain_name))),
Some(false) => lines.push(bad(format!("帳號伺服器 ↔ 大腦「{}」:不在線上(大腦那台的 AnyBot 沒開、沒網路,或正在重新啟動)", s.brain_name))),
None => {}
}
if self.mir.on {
if self.mir.online {
lines.push(ok(format!("大腦「{}」:連得到", s.brain_name)));
} else {
lines.push(bad(format!("大腦「{}」:{}", s.brain_name, self.mir.reason)));
}
}
if let Some((at, bytes, ms)) = *self.mir.last_sync.lock().unwrap() {
let slow = bytes >= 1_000_000 && ms > 0 && bytes * 1000 / ms < 300_000;
let words = super::mirror_ui::sync_words(at, bytes, ms);
lines.push(if slow { bad(format!("{words}:線很慢")) } else { ok(words) });
}
}
// The bots' computer and the connectors (a screen's are the brain's).
if self.mir.on {
lines.push(ok("Bot 的電腦、連接器、模型服務在大腦上(到大腦那台打 /doctor 看)"));
} else {
let run = crate::cloudbox::run_state();
if crate::cloudbox::available() {
lines.push(ok(format!("Bot 的電腦:{}", run.label())));
} else {
lines.push(bad(format!("Bot 的電腦:{}(指令改在封閉的資料夾裡跑,沒有桌面)", run.label())));
}
let status = crate::mcp::status();
let errors = self.ch.mcp_errors.lock().unwrap().clone();
for m in self.state.mcp_servers.iter().filter(|m| m.enabled) {
match (status.get(&m.name), errors.iter().find(|e| e.0 == m.name)) {
(Some(n), _) => lines.push(ok(format!("連接器「{}」:已連上,{n} 個工具", m.name))),
(None, Some((_, e))) => lines.push(bad(format!("連接器「{}」:{e}", m.name))),
(None, None) => lines.push(bad(format!("連接器「{}」:還沒連上", m.name))),
}
}
}
match crate::doctor::free_mb(&data) {
Some(mb) if mb < 2048 => lines.push(bad(format!("磁碟只剩 {mb} MB(快照、模型和 Bot 的電腦都要空間)"))),
Some(mb) => lines.push(ok(format!("磁碟還有 {:.1} GB", mb as f64 / 1024.0))),
None => {}
}
if let Some((when, at)) = crate::doctor::last_crash(&crate::logfile::dir()) {
lines.push(bad(format!("上次內部出錯:{when},在 {at}(報告在紀錄檔資料夾)")));
}
// Over the network, on a thread: the model services the bots use (here, not on a screen),
// and how Tailscale reaches the account server.
let mut services: Vec<(String, crate::providers::ProviderKind, String, String)> = vec![];
if !self.mir.on {
for kind in ALL_PROVIDERS.into_iter().filter(|k| self.state.bots.iter().any(|b| b.provider == *k)) {
let ps = self.state.provider(kind);
services.push((kind.label().to_string(), kind, providers::resolve_base(kind, &ps.base_url), providers::resolve_key_for(kind, &ps.api_key, &ps.base_url)));
}
}
let ts_host = crate::doctor::tailscale_host(&s.relay_url);
let out = self.doctor_out.clone();
let repaint = self.repaint_fn();
if self.mir.on {
self.notice = Some("診斷中:正在檢查連線…".into());
} else {
self.goal_note(bot_id, "診斷中:正在檢查連線和模型服務…");
}
std::thread::spawn(move || {
if let Some(host) = ts_host {
if let Some(l) = crate::doctor::ping_tailscale(&host) {
lines.push(l);
}
}
for (name, kind, base, key) in services {
match providers::list_models(kind, &base, &key) {
Ok(m) => lines.push(ok(format!("模型服務 {name}:連得到({} 個模型)", m.len()))),
Err(e) => lines.push(bad(format!("模型服務 {name}:{}", e.chars().take(160).collect::<String>()))),
}
}
out.lock().unwrap().push((bot_id, crate::doctor::report(&lines)));
repaint();
});
self.dirty = true;
}
/// A finished 「/doctor」: its report in the chat it was asked in (a notice on a screen).
pub(super) fn doctor_tick(&mut self) {
let done: Vec<(u64, String)> = std::mem::take(&mut *self.doctor_out.lock().unwrap());
for (bot_id, text) in done {
if self.mir.on {
self.notice = Some(text);
} else {
self.goal_note(bot_id, &text);
}
self.dirty = true;
}
}
}

View File

@ -32,7 +32,7 @@ pub struct RemoteUi {
join_rx: Option<Receiver<Result<(Settings, remote::AccountFind), String>>>,
restore_rx: Option<Receiver<Result<Vec<u8>, String>>>,
busy: Arc<AtomicBool>,
peers: Arc<Mutex<Vec<(String, String, bool)>>>,
pub(super) peers: Arc<Mutex<Vec<(String, String, bool)>>>,
last_seen_mark: Option<Instant>,
peers_at: Option<Instant>,
/// 團隊: (user, role) shared with, loaded from the relay; the form to add one.
@ -557,6 +557,11 @@ impl App {
self.usage_note(bot);
return;
}
// (From the phone or a screen: the brain checks itself.)
if crate::doctor::command(&text) {
self.doctor_start(bot);
return;
}
self.goal_heard(bot);
}
if self.streams.contains_key(&bot) {

123
src/doctor.rs Normal file
View File

@ -0,0 +1,123 @@
//! 診斷 (/doctor): what this computer's AnyBot can find out about itself, one line each, ✓ or ✗
//! with the reason — the version and folders, this computer ↔ the account server (and whether
//! Tailscale goes direct or through one of its relays), the account server ↔ the brain, the last
//! sync's speed, each model service the bots use, the bots' computer, the connectors, the disk,
//! the last crash. On a screen of a brain it is this computer that is checked (where a problem
//! usually is). The checks that go over the network run on a thread of their own. Like
//! grok-build's /doctor; `make doctor` checks the build tools instead.
use std::path::Path;
/// 「/doctor」 (nothing after it).
pub fn command(text: &str) -> bool {
text.trim() == "/doctor"
}
/// One finding: fine or not, and what it says.
#[derive(Clone, Debug, PartialEq)]
pub struct Line {
pub ok: bool,
pub text: String,
}
pub fn ok(t: impl Into<String>) -> Line {
Line { ok: true, text: t.into() }
}
pub fn bad(t: impl Into<String>) -> Line {
Line { ok: false, text: t.into() }
}
/// The report: a title line, then each finding with ✓ or ✗, and a last line counting the ✗.
pub fn report(lines: &[Line]) -> String {
let bad = lines.iter().filter(|l| !l.ok).count();
let mut s = String::from("診斷(/doctor):這台電腦的 AnyBot");
for l in lines {
s.push_str(&format!("\n{} {}", if l.ok { "✓" } else { "✗" }, l.text));
}
s.push_str(&if bad == 0 { "\n全部正常。".to_string() } else { format!("\n有 {bad} 項要看一下(✗)。") });
s
}
/// The Tailscale name in an account server's address (…​.ts.net), if it is one.
pub fn tailscale_host(url: &str) -> Option<String> {
let host = url.split("://").nth(1)?.split(['/', ':']).next()?.to_string();
host.ends_with(".ts.net").then_some(host)
}
/// What `tailscale ping` said, in words: direct, or through which relay (much slower).
pub fn tailscale_path(ping: &str) -> Option<Line> {
let line = ping.lines().find(|l| l.contains("pong from"))?;
if let Some(relay) = line.split("via DERP(").nth(1).and_then(|r| r.split(')').next()) {
let ms = line.split(" in ").nth(1).unwrap_or("").trim().to_string();
return Some(bad(format!("Tailscale 沒有直連,走它在「{relay}」的中繼({ms}):大份資料會很慢。兩台通常在同一個網路卻連不直,多半是中間擋了 UDP(Tailscale 直連用 41641)")));
}
Some(ok(format!("Tailscale 直連({})", line.split("pong from").nth(1).unwrap_or("").trim())))
}
/// Ask Tailscale how it reaches `host` (None when Tailscale isn't here).
pub fn ping_tailscale(host: &str) -> Option<Line> {
for bin in ["tailscale", "/Applications/Tailscale.app/Contents/MacOS/Tailscale"] {
let out = std::process::Command::new(bin).args(["ping", "-c", "1", "--timeout", "5s", host]).output();
if let Ok(o) = out {
let text = format!("{}{}", String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
return tailscale_path(&text).or_else(|| Some(bad(format!("Tailscale 找不到 {host}:{}", text.lines().next().unwrap_or("沒有回應")))));
}
}
None
}
/// Free space where the data folder is, in MB (None where `df` can't say).
pub fn free_mb(dir: &Path) -> Option<u64> {
let out = std::process::Command::new("df").args(["-Pk"]).arg(dir).output().ok()?;
let text = String::from_utf8_lossy(&out.stdout);
text.lines().nth(1)?.split_whitespace().nth(3)?.parse::<u64>().ok().map(|kb| kb / 1024)
}
/// The newest crash report in `logs`: (when, where) from its file.
pub fn last_crash(logs: &Path) -> Option<(String, String)> {
let mut reports: Vec<std::path::PathBuf> = std::fs::read_dir(logs).ok()?.flatten().map(|e| e.path()).filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("crash-"))).collect();
reports.sort();
let text = std::fs::read_to_string(reports.last()?).ok()?;
let field = |k: &str| text.lines().find_map(|l| l.strip_prefix(k)).unwrap_or("").trim().to_string();
Some((field("時間:"), field("位置:")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_report_counts_what_is_wrong() {
let r = report(&[ok("版本 v1"), bad("模型服務 xAI:金鑰不對")]);
assert!(r.contains("✓ 版本 v1\n✗ 模型服務 xAI:金鑰不對") && r.ends_with("有 1 項要看一下(✗)。"), "{r}");
assert!(report(&[ok("a")]).ends_with("全部正常。"));
assert!(command(" /doctor ") && !command("/doctor x"));
}
#[test]
fn tailscale_says_direct_or_through_which_relay() {
assert_eq!(tailscale_host("https://nobledesktop.tailbcc3a6.ts.net:8443").as_deref(), Some("nobledesktop.tailbcc3a6.ts.net"));
assert_eq!(tailscale_host("https://example.com"), None);
let relayed = tailscale_path("pong from nobledesktop (100.82.106.34) via DERP(hkg) in 63ms\n").unwrap();
assert!(!relayed.ok && relayed.text.contains("「hkg」") && relayed.text.contains("63ms") && relayed.text.contains("41641"), "{relayed:?}");
let direct = tailscale_path("pong from nobledesktop (100.82.106.34) via 10.184.27.181:41641 in 4ms").unwrap();
assert!(direct.ok && direct.text.contains("10.184.27.181:41641"), "{direct:?}");
assert_eq!(tailscale_path("no reply"), None);
}
#[test]
fn the_last_crash_and_the_disk() {
let d = std::env::temp_dir().join(format!("anybot-doctor-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
assert_eq!(last_crash(&d), None);
std::fs::write(d.join("crash-20261101-000000.000.seen.txt"), "時間:舊的\n位置:a.rs:1\n").unwrap();
std::fs::write(d.join("crash-20261117-104200.000.txt"), "時間:2026-11-17 10:42:00\n位置:src/app.rs:12\n").unwrap();
assert_eq!(last_crash(&d), Some(("2026-11-17 10:42:00".into(), "src/app.rs:12".into())));
if cfg!(unix) {
assert!(free_mb(&d).is_some_and(|mb| mb > 0));
}
let _ = std::fs::remove_dir_all(&d);
}
}

View File

@ -75,6 +75,7 @@ mod always;
mod secrets;
mod logfile;
mod net;
mod doctor;
mod outputs;
mod gate;
mod usage;