AnyBot/src/doctor.rs

161 lines
7.9 KiB
Rust
Raw Normal View History

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>
2026-11-17 03:48:01 +00:00
//! 診斷 (/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
}
/// Whether commands on this computer run in a sandbox, and which.
pub fn sandbox_line() -> Line {
if cfg!(target_os = "macos") {
return if std::path::Path::new("/usr/bin/sandbox-exec").exists() { ok("指令沙盒:macOS 的 sandbox-exec") } else { bad("這台的指令沒有沙盒:找不到 /usr/bin/sandbox-exec") };
}
if cfg!(target_os = "linux") {
return match crate::landlock::abi() {
Some(v) => ok(format!("指令沙盒:Linux 的 Landlock(第 {v} 版)")),
None => bad(crate::landlock::NONE),
};
}
bad("這台的指令沒有沙盒(Windows 還沒有):指令讀得到 .ssh 這類私密資料夾,只靠安全規則擋")
}
feat: Hooks:自己的程式插在 Bot 做事的固定時間點(Claude Code 的格式),Bot 也能在聊天裡幫你設 - hooks.json 跟 Claude Code 一樣(matcher、type command/http、timeout),AnyBot 和 Claude Code 的工具名字都認;使用者的在資料夾 hooks/,管理員的(先跑、改不了)在系統位置,MDM 可推。 - SessionStart(對話第一輪)、UserPromptSubmit(補資訊或擋下這一輪)、PreToolUse(擋、改參數、ask 一定問、allow 省一次問但擋不過安全規則和每次問的)、PostToolUse(換掉或補 Bot 讀到的結果)、Stop(叫它接著做,一輪最多 3 次)、Notification(跟著通知跑)。 - hook 自己出錯(結束碼、逾時、JSON、設定檔)就當它不在,紀錄檔寫原因;/doctor 寫有幾個、檔案看不看得懂。 - manage_hooks(list/add/remove):加和移除每次都先問,一律放行也問;管理 App 的能力,外面的訊息不能用。 - 測試裡每一輪只拿測試給那個 Bot 的 hook,不讀檔(同時跑的測試不會互相影響)。 已驗證:cargo test 602 通過(hook 本身:擋 rm、改參數、ask、壞掉的 hook、逾時、prompt 補資訊、Stop 用 stop_hook_active 放行、PostToolUse 換結果、manage_hooks 改檔;真的一輪:rm 沒有執行、跑的是 hook 改過的指令、Stop 讓模型多回一次)、clippy -D warnings 乾淨。 未驗證:HTTP hook 打到真的伺服器、管理員檔案的位置在真的 Mac/Linux 上、Windows 的 cmd。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 04:59:21 +00:00
/// The hooks set here (None: none, and both files read fine).
pub fn hooks_line() -> Option<Line> {
let (mine, admin) = (crate::hooks::read_config(&crate::hooks::mine_path()), crate::hooks::read_config(&crate::hooks::admin_path()));
if let Some(e) = [&mine, &admin].into_iter().find_map(|r| r.as_ref().err()) {
return Some(bad(format!("hook 設定檔有問題,裡面的 hook 都沒有在跑:{e}")));
}
let count = |c: &crate::hooks::Config| c.hooks.values().flatten().map(|g| g.hooks.len()).sum::<usize>();
let (m, a) = (count(&mine.unwrap_or_default()), count(&admin.unwrap_or_default()));
(m + a > 0).then(|| ok(format!("hook:你的 {m} 個、管理員的 {a} 個({})", crate::hooks::mine_path().display())))
}
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>
2026-11-17 03:48:01 +00:00
/// 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_sandbox_is_said_as_it_is() {
let l = sandbox_line();
if cfg!(target_os = "macos") {
assert!(l.ok && l.text.contains("sandbox-exec"), "{l:?}");
} else if cfg!(target_os = "linux") {
assert_eq!(l.ok, crate::landlock::abi().is_some(), "{l:?}");
} else {
assert!(!l.ok && l.text.contains("沒有沙盒"), "{l:?}");
}
}
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>
2026-11-17 03:48:01 +00:00
#[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);
}
}