diff --git a/FEATURES.md b/FEATURES.md index 2c6bde3..91173a3 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1567,6 +1567,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 聊天打 /doctor:這台電腦的 AnyBot 一項一行 ✓ 或 ✗:版本、資料夾、今天的紀錄檔;這台 ↔ 帳號伺服器(長連線的狀態);帳號伺服器是 *.ts.net 時,Tailscale 是直連還是走它在哪裡的中繼(`tailscale ping`;走中繼會寫延遲和「多半是中間擋了 UDP 41641」);帳號伺服器 ↔ 大腦(帳號伺服器說在不在線上);螢幕連不連得到大腦和原因;上次同步的大小和速度(1 MB 以上、每秒不到 300 KB 算慢);每個 Bot 用到的模型服務連不連得到(列模型清單);Bot 的電腦;每個開著的連接器;磁碟剩多少(少於 2 GB 算 ✗);指令有沒有沙盒(macOS 的 sandbox-exec、Linux 的 Landlock 第幾版,沒有就 ✗);上次內部出錯。要上網的檢查在背景跑,好了一次留一行。 - 在連到大腦的螢幕電腦上檢查的是這台本身(大腦連不到時正是要用的時候),結果跳成提示;手機打的是大腦檢查自己。 +- **連線體檢**:每一段量真的數字。這台 ↔ 帳號伺服器:小請求連打四次,第一次含建立連線(和 TLS)另外寫,其餘取中位數當來回時間;再下載 256 KB(帳號伺服器的 `/api/speed`,給的是壓不小的亂數,Cloudflare、Caddy 都縮不了,量到的是真的線速)。螢幕電腦再量到大腦:大腦的 `/api/sync/ping` 由網路那條執行緒直接回、不經過視窗,三次取中位數,扣掉第一段就是帳號伺服器 ↔ 大腦。來回超過 400 ms、或每秒不到 300 KB 是 ✗,寫「每個動作都會等」「同步和檔案會等很久」或「問題在大腦那台的網路」。帳號伺服器或大腦是舊版(沒有這兩個網址)就說量不到、更新後就有,不算錯。沒有視窗的電腦用 `anybot --doctor`(只讀設定,AnyBot 開著也能跑;有 ✗ 結束碼 1)。 ### 自動審核的固定樣式規則 diff --git a/docs/feature-map/garden.md b/docs/feature-map/garden.md index f4dba3f..df5a773 100644 --- a/docs/feature-map/garden.md +++ b/docs/feature-map/garden.md @@ -5,7 +5,7 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「 ## 子功能 - `garden-issues` 待改進:一輪做完、自動整理做法時,AnyBot 本身的問題(工具回錯的結果、明明開著卻說找不到、一用就出錯、要繞路才做得到、Bot 一直誤用某個工具)另外記下來,不寫進技能。同一個工具的問題合併計次,最多留 50 條;出現 2 次以上的會標出來。 -- `garden-doctor` 診斷(/doctor):在聊天打 /doctor,一項一行 ✓/✗:版本和資料夾、紀錄檔在哪、這台 ↔ 帳號伺服器、Tailscale 是直連還是走它的中繼(走中繼很慢,多半是兩台之間擋了 UDP)、帳號伺服器 ↔ 大腦、上次同步的速度、每個 Bot 用的模型服務連不連得到、Bot 的電腦、每個連接器、磁碟、指令有沒有沙盒、上次內部出錯。在連到大腦的螢幕電腦上檢查的是這台(連不到大腦時也能用),結果跳成提示;手機打的檢查的是大腦。 +- `garden-doctor` 診斷(/doctor):在聊天打 /doctor,一項一行 ✓/✗:版本和資料夾、紀錄檔在哪、這台 ↔ 帳號伺服器、Tailscale 是直連還是走它的中繼(走中繼很慢,多半是兩台之間擋了 UDP)、帳號伺服器 ↔ 大腦、**每一段量出來的數字**(這台 ↔ 帳號伺服器的來回 ms 和第一次連上的 ms、下載 256 KB 每秒幾 KB;螢幕電腦再加帳號伺服器 ↔ 大腦約幾 ms——來回超過 400 ms 或每秒不到 300 KB 是 ✗,寫慢在哪一段;帳號伺服器或大腦是舊版就說量不到,不算錯)、上次同步的速度、每個 Bot 用的模型服務連不連得到、Bot 的電腦、每個連接器、磁碟、指令有沒有沙盒、上次內部出錯。在連到大腦的螢幕電腦上檢查的是這台(連不到大腦時也能用),結果跳成提示;手機打的檢查的是大腦。沒有視窗的電腦(手腳、伺服器)在終端機打 `anybot --doctor`,印出量連線的那幾行(有 ✗ 結束碼是 1)。 - `garden-logs` 紀錄檔: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 的變數值 → ••••);手機上的步驟細節也一樣遮。 - `garden-crash` 當掉報告:程式內部出錯(任何一條執行緒)時寫 `logs/crash-時間.txt`(版本、執行緒、位置、訊息、backtrace,一樣遮過);下次打開在主要 Bot 的聊天留一行「AnyBot 上次執行時內部出錯…」(連到大腦的螢幕電腦是跳一則提示),並記一條待改進。每份報告只說一次。 - `garden-daily` 園丁每日報告(平日 8:44 起)「園丁:過去一天有 N 件事值得看一下。」:過去一天失敗或被打斷的執行、走冤枉路的執行(10 步以上且 3 成以上沒成功)、被自動暫停的例行任務、重複出現的待改進。 @@ -33,8 +33,9 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「 - **待改進合併計次**(covers `garden-issues`):一輪做五步,整理做法時存一個技能、回報同一個工具的問題兩次。指令:`$CTL model-reply 整理經驗 '{"save":true,"name":"跑五步","description":"跑五步","instructions":"一步一行","replay":[],"tool_issues":["browser_fill_contact 填不進電話欄","browser_fill_contact 又填錯欄"]}' && $CTL phone send '[[call shell {"command":"sleep 4; echo 1"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 2' && $CTL phone send '[[call shell {"command":"sleep 4; echo 2"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 3' && $CTL phone send '[[call shell {"command":"sleep 4; echo 3"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 4' && $CTL phone send '[[call shell {"command":"sleep 4; echo 4"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 5' && $CTL phone send '[[call shell {"command":"echo 5"}]]' && $CTL phone wait-text '學會了新做法「跑五步」' --in '#msgs' 60 && $CTL state '{skill: (.skills[] | select(.name == "跑五步") | .instructions), issue: (.improvements[] | {text, count, bots})}'`。看到:技能照存,做法裡沒有那兩句;待改進一條「browser_fill_contact 填不進電話欄」count 2(同一個工具合併)、bots 是驗證小幫手。 - **版本**(covers `garden-update`):帳戶選單 › 設定 › 更新。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="updates"]' && $CTL phone wait-text 已是最新版 --in '#list' && $CTL api GET /api/settings --jq '{version, newer}'`。看到:版本(這個 checkout 的 HEAD)和建置時間、「已是最新版」。 - **電腦版 設定 › 更新**(covers `garden-issues`、`garden-update`、`garden-daily`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot garden-updates ANYBOT_SHOT_TAB=updates`(示範資料:真資料的截圖打不開 更新;有新版:加 `ANYBOT_SHOT_NEWER=0`)。看到:「自動更新」「園丁報告」開關、「重新啟動」;示範資料沒有待改進,「待改進」那一條的 ×2 和「全部清除」靠上面那一步的 state 和 `cargo test garden::`。 +- **量連線**(covers `garden-doctor`):前提:relay/ 建好、`$CTL up --no-serve`。指令:在 scratch 開一台 `relay/target/debug/anybot-relay --port <空的埠> --data /relay`,`/relay/signup`、`/relay/login` 拿登入、`/relay/pair` 拿配對碼,`scripts/scratch-env /target/debug/anybot setup <網址> <配對碼> --brain --no-service`,再 `scripts/scratch-env /target/debug/anybot --doctor`;換成只認 /api/hello 的舊伺服器、關掉伺服器各跑一次。看到:「✓ 這台 ↔ 帳號伺服器:來回 … ms(第一次連上 … ms)」「✓ 下載 256 KB 用了 … ms:每秒 … KB」;舊伺服器「下載速度:帳號伺服器是舊版,量不到」;關掉「✗ … 連不到」、結束碼 1。到大腦那一段要兩台(大腦+螢幕電腦):走不到,靠自動測試。 - **有事的報告、當掉**(covers `garden-daily`、`garden-weekly`、`garden-crash`):指令:走不到——scratch 一開就把今天那份看過(沒事不報),下一份要明天平日 8:44、每週要週一;「園丁報告」開關只在電腦版;當掉要程式真的出錯。看到:最接近的真路是自動測試(有失敗才報、一天一次、每週只列花太多的、當掉報告只說一次又遮過);關掉「園丁報告」兩種都不出現要在電腦版看。 -- 自動測試:`cargo test garden::`、`cargo test anybots_own_problems`(整理做法時另外記;一輪做完之後才回報的也記進清單)、`cargo test logfile::`、`cargo test doctor::`。 +- 自動測試:`cargo test garden::`、`cargo test anybots_own_problems`(整理做法時另外記;一輪做完之後才回報的也記進清單)、`cargo test logfile::`、`cargo test doctor::`、`cargo test the_connection_check`、`cargo test a_screen_pings_its_brain`、relay 的 `cargo test speed`。 ## 陷阱 diff --git a/docs/plan-2026-11-openbot.md b/docs/plan-2026-11-openbot.md index 6f841b3..c175711 100644 --- a/docs/plan-2026-11-openbot.md +++ b/docs/plan-2026-11-openbot.md @@ -30,7 +30,10 @@ | Mac mini | 原本卡在死掉的 `https://nobledesktop.tailbcc3a6.ts.net:8443` | **已換到 `http://100.64.0.5`**(`--move-to`,同一台登記),App 打開就同步到大腦 | | MacBook Pro | 11/21 01:00 用新網址重新登入,變成新的一台「王性驊的MacBook Pro (2)」 | 連得上;連線速度待量(見 A1) | | iPhone | 11/20 20:23、20:35 用新網址登入過 | 正常(最後一次 00:58) | -| ai(10.0.0.25,家裡另一套 AnyBot:帳號伺服器 anybot.30cm.net+「雲端大腦」+jenny 帳號) | 自己的;這台還在**舊的** Tailscale(ControlURL 還是 controlplane.tailscale.com) | 沒遷移。`~/AnyBot` 在 11/21 01:04 被整個重新 clone,`deploy/server/.env` **不見了**:現在跑的容器沒事,但下一次 `make update-server` 會沒有設定可用。另外「wang的MacBook Pro」在 11/20 23:58 登入了這台的 jenny 帳號(看起來是試錯留下的) | +| ai(10.0.0.25,家裡另一套 AnyBot:Jenny 帳號的帳號伺服器+wang 的「雲端大腦」) | **只剩 `https://anybot.30cm.net`**(使用者 11/21 要求:唯一能用的網址) | 11/21 10:24 換到 headscale(`100.64.0.6`),`tailscale serve` 拿掉;`deploy/server/.env`、`Caddyfile` 照跑著的容器補回(01:04 重新 clone 弄丟的,Caddy 一重開網站就會斷),`make update-server` 換成新版;Caddy 只回 anybot.30cm.net,打 IP、headscale 位址、ts.net 都拿不到帳號伺服器。這台自己的桌面 App 也改成 anybot.30cm.net(同一台登記)。「wang的MacBook Pro」在 11/20 23:58 登入了 jenny 帳號,之後沒再連(試錯留下的,等使用者決定要不要移除) | +| jenny-host(10.0.0.15,Jenny 的大腦「jenny-Host」,2 核虛擬機、沒有顯示卡、用 noVNC 看) | `https://anybot.30cm.net` | 11/21 10:24 換到 headscale(`100.64.0.7`)。「對話一直閃」:Bot 工作時每 5 秒在畫面執行緒整份重寫 90 MB 的聊天、動畫每秒 20–30 次全視窗 CPU 重畫、系統螢幕閱讀器(orca)00:00 被打開——修在 5bf4444(過去的對話另存、CPU 畫圖時動畫每秒 4 張),螢幕閱讀器已關 | +| 10.0.0.16(headscale 本身+子網路由「vpn」`100.64.0.3`) | — | 家裡網路從 tailnet 進來都經過它 | +| 10.0.0.3(cloudflared:anybot.30cm.net → `http://10.0.0.25`) | — | 還在**舊的** Tailscale(使用者沒要求搬;Jenny 的連線不經過 Tailscale) | --- @@ -46,14 +49,14 @@ - MacBook Pro(在家):從 nobledesktop 和 Mac mini 對它 `tailscale ping` 都逾時,但 TCP(SSH)通—— 它那端的路要它自己量(A1)。帳號伺服器上它的「最後出現」停在 22 分鐘前,但那個欄位只在部分請求更新,不能當在線判斷。 -**A1. 連線體檢(先量再改)** +**A1. 連線體檢(先量再改)**——11/21 做了:/doctor 每一段量真的數字(來回 ms、下載 256 KB 的速度、螢幕到大腦),`anybot --doctor` 給沒有視窗的電腦;帳號伺服器加 `/api/speed`、大腦加 `/api/sync/ping`。設定頁的按鈕沒做(account.md 篇幅已滿;/doctor 在聊天裡就能叫,手機也行)。三台實機的數字等伺服器和各台更新後補在下面。 - 做什麼:設定 › 手機與帳號 的大腦那一欄加「檢查連線」:分三段量——這台 ↔ 帳號伺服器(來回時間、下載 256 KB 的速度)、 帳號伺服器 ↔ 大腦(大腦回一個小請求的時間)、上一次同步(已有「上次同步 … KB/s」)——每段一行、慢的那段標出來, 並說是不是走中繼。CLI:`anybot doctor --net`。Bot 也要能叫(記憶:每個功能都能在聊天裡做)。 - 動哪裡:`src/remote.rs`(量測函式)、`src/app/remote_ui.rs`(大腦欄)、`src/doctor.rs`、relay 加一個回固定大小資料的端點。 - 做完:三段數字在三台實機(Mac mini、MacBook Pro、iPhone)各量一次寫進本檔。 -**A2. 帳號伺服器的多個網址+自動換網址** +**A2. 帳號伺服器的多個網址+自動換網址**(暫緩:使用者 11/21 定了「anybot.30cm.net 是唯一能用的網址」——一個穩定的公開網域就不會再搬家;要做也只當備援,不在畫面上多一串網址) - 做什麼:帳號伺服器在 `/api/hello` 公布自己所有的網址(`ANYBOT_RELAY_PUBLIC_URL` 加一串備用:tailnet IP、區網 IP、公開網域)。 電腦記住整串,連線時同時試、用最快的那個,掛了換下一個。伺服器搬家前先公布新網址,裝置就自己跟過去—— §0 這次就不用任何人動手。換網址照 §0 的規則:用金鑰確認是同一台才換。 @@ -72,9 +75,7 @@ - 做什麼:把「正在連到「…」…」整窗等待、按鈕轉圈、設定頁讀不到時的空白,全部列出來,各自改成先顯示本機副本。 - 做完:慢網路模式下打開 App、切 Bot、打開設定,都在 100 ms 內有畫面。 -**A5. ai 那台的 `.env`、遷移**(要你決定,見最後的問題) -- 從正在跑的容器把設定抄回 `deploy/server/.env`(容器裡都有),或確認那套已經不用了。 -- 要不要把 ai 也搬到 headscale。 +**A5. ai 那台的 `.env`、遷移**——11/21 做完(見 §0):`.env`、`Caddyfile` 照容器補回、ai 和 jenny-host 搬到 headscale、帳號伺服器只剩 anybot.30cm.net。 --- diff --git a/relay/src/main.rs b/relay/src/main.rs index b2c53fa..53fa54a 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -358,6 +358,24 @@ fn now() -> i64 { chrono::Utc::now().timestamp() } +/// 連線體檢's download: 256 KB unless asked, never more than 1 MB. +const SPEED_BYTES: usize = 256 * 1024; +const SPEED_MAX: usize = 1024 * 1024; + +/// `n` bytes nothing on the way can compress (xorshift; a different run each call). +fn noise(n: usize) -> Vec { + let mut x = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(1) | 1; + let mut out = Vec::with_capacity(n + 8); + while out.len() < n { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + out.extend_from_slice(&x.to_le_bytes()); + } + out.truncate(n); + out +} + impl Relay { fn load(dir: PathBuf) -> Relay { httpd::ensure_private_dir(&dir); @@ -1023,6 +1041,12 @@ impl Relay { ("GET", ["icon.svg"]) => Resp::bytes("image/svg+xml", ICON.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"), ("GET", [name]) if ICON_PNGS.iter().any(|(n, _)| n == name) => Resp::bytes("image/png", ICON_PNGS.iter().find(|(n, _)| n == name).map(|(_, b)| b.to_vec()).unwrap_or_default()).with_header("Cache-Control", "public, max-age=86400"), ("GET", ["api", "hello"]) => Resp::json(&json!({"app": "anybot-relay"})), + // 連線體檢 (/doctor): `bytes` of noise (256 KB, at most 1 MB) to time a download over the + // whole road — Cloudflare, Caddy, a tailnet relay. Noise: none of them can shrink it. + ("GET", ["api", "speed"]) => { + let n = req.query.get("bytes").and_then(|b| b.parse::().ok()).unwrap_or(SPEED_BYTES).clamp(1, SPEED_MAX); + Resp::bytes("application/octet-stream", noise(n)).with_header("Cache-Control", "no-store") + } ("GET", ["sw.js"]) => Resp::bytes("text/javascript; charset=utf-8", SW.as_bytes().to_vec()).with_header("Service-Worker-Allowed", "/"), ("GET", ["relay", "push", "key"]) => Resp::json(&json!({"key": self.vapid.public_b64})), ("POST", ["relay", "push", "subscribe"]) => { @@ -2032,6 +2056,36 @@ mod tests { String::from_utf8_lossy(&buf[..n]).split_whitespace().nth(1).and_then(|s| s.parse().ok()).unwrap_or(0) } + /// 連線體檢's download: the size asked (256 KB unless said, at most 1 MB), noise that doesn't + /// shrink (Cloudflare or Caddy compressing it would time a smaller download), never cached. + #[test] + fn the_speed_check_gets_noise_of_the_size_asked() { + use std::io::Write; + let dir = std::env::temp_dir().join(format!("anybot-relay-speed-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let relay = Relay::load(dir.clone()); + let ask = |q: &str| { + let mut req = Req { method: "GET".into(), path: "/api/speed".into(), ..Req::default() }; + if let Some((k, v)) = q.split_once('=') { + req.query.insert(k.into(), v.into()); + } + req.headers.insert("accept-encoding".into(), "gzip".into()); + relay.answer(req) + }; + let r = ask(""); + assert_eq!((r.status, r.body.len()), (200, SPEED_BYTES)); + assert!(r.headers.iter().any(|(k, v)| k == "Cache-Control" && v == "no-store")); + assert!(!r.headers.iter().any(|(k, _)| k == "Content-Encoding")); + let mut z = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + z.write_all(&r.body).unwrap(); + assert!(z.finish().unwrap().len() > SPEED_BYTES * 99 / 100, "noise doesn't shrink"); + assert_eq!(ask("bytes=1000").body.len(), 1000); + assert_eq!(ask("bytes=99999999").body.len(), SPEED_MAX); + assert_eq!(ask("bytes=0").body.len(), 1); + assert_ne!(ask("bytes=64").body, ask("bytes=64").body, "a different run each time"); + let _ = std::fs::remove_dir_all(&dir); + } + /// The page goes out gzipped to a browser that reads it — by this server itself, whatever /// stands in front (`tailscale serve` compresses nothing) — and whole to one that doesn't. /// The icons shown while connecting are kept by the browser. diff --git a/src/app/doctor_ui.rs b/src/app/doctor_ui.rs index 715ddaa..f493f78 100644 --- a/src/app/doctor_ui.rs +++ b/src/app/doctor_ui.rs @@ -1,6 +1,7 @@ // 診斷 (/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 +// leg of the road timed, 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. @@ -88,6 +89,7 @@ impl App { } } let ts_host = crate::doctor::tailscale_host(&s.relay_url); + let net = s.clone(); let out = self.doctor_out.clone(); let repaint = self.repaint_fn(); if self.mir.on { @@ -96,6 +98,8 @@ impl App { self.goal_note(bot_id, "診斷中:正在檢查連線和模型服務…"); } std::thread::spawn(move || { + // 連線體檢: each leg timed (this ↔ the account server, and on to the brain). + lines.extend(crate::remote::net_check(&net)); if let Some(host) = ts_host { if let Some(l) = crate::doctor::ping_tailscale(&host) { lines.push(l); diff --git a/src/main.rs b/src/main.rs index 2d1cc80..06dfaf9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -323,6 +323,7 @@ const USAGE: &str = "用法: anybot setup … 在沒有螢幕的機器上設定 anybot --install-skill 來源 安裝技能(GitHub 網址、owner/repo/path、SKILL.md 網址或本機資料夾) anybot --update-box 更新 Bot 的電腦(同 設定 › 電腦 › 更新;AnyBot 開著就請它做) + anybot --doctor 量連線:這台 ↔ 帳號伺服器、到大腦(同聊天裡的 /doctor 那幾行) anybot --screenshot 檔名 把視窗畫成一張圖 anybot --banner 標題 內文 送一則通知,看它怎麼送出(Mac:AnyBot.app 自己的通知) anybot --version 印出版本(v0.0.1-36bc2be · 建置時間) @@ -360,6 +361,21 @@ fn main() -> eframe::Result<()> { if args.get(1).map(String::as_str) == Some("--update-box") { std::process::exit(cloudbox::update_box_cli()); } + // `anybot --doctor`: 連線體檢 from a terminal (a computer without a window, hands, a server), + // the same timed legs /doctor puts in the chat. Only reads the settings (AnyBot may be open). + if args.get(1).map(String::as_str) == Some("--doctor") { + let st = model::State::load(); + if st.remote.relay_url.is_empty() { + println!("這台沒有登入帳號:沒有帳號伺服器可以量"); + std::process::exit(0); + } + println!("連線體檢:{}{}", st.remote.relay_url, if st.remote.brain_id.is_empty() { String::new() } else { format!("(大腦「{}」)", st.remote.brain_name) }); + let lines = remote::net_check(&st.remote); + for l in &lines { + println!("{} {}", if l.ok { "✓" } else { "✗" }, l.text); + } + std::process::exit(if lines.iter().all(|l| l.ok) { 0 } else { 1 }); + } // P7: install a skill package (a GitHub folder/URL, SKILL.md URL, or local folder/file). if let Some(i) = args.iter().position(|a| a == "--install-skill") { let src = args.get(i + 1).cloned().unwrap_or_default(); diff --git a/src/remote.rs b/src/remote.rs index ecfc562..98cec62 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -997,6 +997,9 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { ("GET", ["api", "screen", which]) => screen(which, &s), ("POST", ["api", "screen", which]) => screen_input(which, &req.json(), &s), ("POST", ["api", "device", "run"]) => device_run(&req.json(), &s, via_relay, req.header("x-anybot-from")), + // 連線體檢 (/doctor) from a screen: answered here, not by the window — the time is the + // road between the account server and this brain. + ("GET", ["api", "sync", "ping"]) => Resp::json(&json!({"ok": true})), ("GET", ["api", "sync"]) => { let since: u64 = req.query.get("since").and_then(|v| v.parse().ok()).unwrap_or(0); let client = req.query.get("client").cloned().unwrap_or_default(); @@ -3278,6 +3281,95 @@ pub fn check_server(url: &str) -> Result { /// this computer — asked with this computer's own key, and this computer is among the account's /// computers it lists. No password is sent and nothing is registered: another server (or this /// computer removed from the account) is a sign-out and a sign-in, as before. +/// 連線體檢 (/doctor, `anybot --doctor`): the road timed, leg by leg — this computer ↔ the account +/// server (a small request a few times; 256 KB of noise), and on a screen, on to its brain (a ping +/// the brain answers at once, without its window). One line a leg; a slow leg says so. +pub fn net_check(s: &Settings) -> Vec { + use crate::doctor::{bad, ok}; + let mut out = vec![]; + if s.relay_url.is_empty() { + return out; + } + let url = base(&s.relay_url); + if let Some(why) = relay_plain_problem(&url) { + out.push(bad(why)); + return out; + } + let timed = |path: &str, auth: bool, secs: u64| -> Result<(u16, Vec, u64), String> { + let t = Instant::now(); + let mut req = relay_agent(secs, &url).get(&format!("{url}{path}")); + if auth { + req = req.header("Authorization", &format!("Bearer {}", s.host_token)); + } + let mut r = req.call().map_err(|e| why_unreachable(&e))?; + let st = r.status().as_u16(); + let body = r.body_mut().with_config().limit(4 * 1024 * 1024).read_to_vec().map_err(|_| "回應到一半斷掉了".to_string())?; + Ok((st, body, t.elapsed().as_millis() as u64)) + }; + let median = |mut v: Vec| { + v.sort_unstable(); + v[v.len() / 2] + }; + // The first request opens the connection (and TLS); the next ones reuse it, as AnyBot does. + let mut times = vec![]; + for _ in 0..4 { + match timed("/api/hello", false, 15) { + Ok((_, _, ms)) => times.push(ms), + Err(e) => { + out.push(bad(format!("這台 → 帳號伺服器({url}):連不到({e})"))); + return out; + } + } + } + let rtt = median(times[1..].to_vec()); + let words = format!("這台 ↔ 帳號伺服器:來回 {rtt} ms(第一次連上 {} ms)", times[0]); + out.push(if rtt > NET_SLOW_RTT_MS { bad(format!("{words}:很慢,每個動作都會等")) } else { ok(words) }); + match timed(&format!("/api/speed?bytes={NET_SPEED_BYTES}"), false, 60) { + Ok((200, body, ms)) if !body.is_empty() => { + let n = body.len(); + let kbps = n as u64 * 1000 / ms.max(1) / 1024; + let words = format!("下載 {} KB 用了 {ms} ms:每秒 {kbps} KB", n / 1024); + out.push(if kbps < NET_SLOW_KBPS { bad(format!("{words}:線很慢,同步和檔案會等很久")) } else { ok(words) }); + } + Ok((404, _, _)) => out.push(ok("下載速度:帳號伺服器是舊版,量不到(更新帳號伺服器後就有)")), + Ok((st, _, _)) => out.push(bad(format!("下載速度:帳號伺服器回了 HTTP {st}"))), + Err(e) => out.push(bad(format!("下載速度:{e}"))), + } + // On to the brain (a screen): the whole road, minus the first leg. + if !s.brain_id.is_empty() && !s.host_token.is_empty() { + let name = if s.brain_name.trim().is_empty() { "大腦".to_string() } else { format!("大腦「{}」", s.brain_name.trim()) }; + let mut times = vec![]; + for _ in 0..3 { + match timed(&format!("/relay/hosts/{}/api/sync/ping", s.brain_id), true, 20) { + Ok((200, _, ms)) => times.push(ms), + Ok((404, body, _)) if serde_json::from_slice::(&body).is_ok_and(|v| v["error"] == NO_SUCH_PATH) => { + out.push(ok(format!("帳號伺服器 ↔ {name}:{name}的 AnyBot 是舊版,量不到(更新後就有)"))); + return out; + } + Ok((st, body, _)) => { + let v = serde_json::from_slice::(&body).unwrap_or(Value::Null); + out.push(bad(format!("帳號伺服器 ↔ {name}:{}", why_refused(st, &v, &name)))); + return out; + } + Err(e) => { + out.push(bad(format!("帳號伺服器 ↔ {name}:{e}"))); + return out; + } + } + } + let whole = median(times); + let leg = whole.saturating_sub(rtt); + let words = format!("帳號伺服器 ↔ {name}:約 {leg} ms(這台到{name}全程 {whole} ms)"); + out.push(if leg > NET_SLOW_RTT_MS { bad(format!("{words}:這一段慢,問題在{name}那台的網路")) } else { ok(words) }); + } + out +} + +/// 連線體檢: a leg slower than this (a round trip) is called slow; a download slower than this. +const NET_SLOW_RTT_MS: u64 = 400; +const NET_SLOW_KBPS: u64 = 300; +const NET_SPEED_BYTES: usize = 256 * 1024; + pub fn relay_move(s: &Settings, new_url: &str) -> Result { if s.host_token.is_empty() || s.host_id.is_empty() { return Err("這台還沒登入帳號:直接用新的網址登入".into()); @@ -3605,6 +3697,19 @@ mod tests { Req { method: "POST".into(), path: path.into(), query, headers, body: body.to_vec(), peer: String::new() } } + /// 連線體檢's last leg: a screen pings its brain and the answer comes from here at once (the + /// window isn't asked); it is the screens' road, not the phone's. + #[test] + fn a_screen_pings_its_brain_without_the_window() { + let ping = |role: &str| handle(Req { method: "GET".into(), ..voice_req("/api/sync/ping", role, b"") }, true); + let r = ping("mirror"); + assert_eq!(r.status, 200); + assert_eq!(serde_json::from_slice::(&r.body).unwrap()["ok"], true); + for role in ["owner", "device", "member", "none"] { + assert_eq!(ping(role).status, 403, "{role}"); + } + } + /// ChatGPT 方案: only the owner (the phone) and the owner's screens sign this brain in or out. #[test] fn only_the_owner_signs_the_brain_in_to_chatgpt() { @@ -3800,6 +3905,64 @@ mod tests { format!("http://127.0.0.1:{port}") } + /// 連線體檢 (/doctor): each leg timed and said — this ↔ the account server, its download, on to + /// the brain; an old server or brain says it can't be timed (not that it's broken); a brain + /// that's off, an account server that can't be reached, a slow leg: a ✗ that says where. + #[test] + fn the_connection_check_times_each_leg_and_says_which_is_slow() { + let s = Settings { relay_url: String::new(), host_id: "mac-1".into(), host_token: "key-1".into(), brain_id: "brain-9".into(), brain_name: "雲端大腦".into(), ..Default::default() }; + let at = |url: String| Settings { relay_url: url, ..s.clone() }; + let speed = |p: &str| p.starts_with("/api/speed?bytes="); + // The whole road. + let url = stand_in_relay(8, move |p, b| match p { + "/api/hello" => Resp::json(&json!({"app": "anybot-relay"})), + _ if speed(p) => Resp::bytes("application/octet-stream", vec![7u8; 256 * 1024]), + "/relay/hosts/brain-9/api/sync/ping" if b == "key-1" => Resp::json(&json!({"ok": true})), + _ => Resp::error(401, "這台電腦的金鑰無效"), + }); + let lines = net_check(&at(url)); + let texts: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect(); + assert_eq!(lines.len(), 3, "{texts:?}"); + assert!(lines.iter().all(|l| l.ok), "{texts:?}"); + assert!(texts[0].starts_with("這台 ↔ 帳號伺服器:來回 ") && texts[0].contains("第一次連上"), "{texts:?}"); + assert!(texts[1].starts_with("下載 256 KB 用了 ") && texts[1].contains("每秒"), "{texts:?}"); + assert!(texts[2].starts_with("帳號伺服器 ↔ 大腦「雲端大腦」:約 ") && texts[2].contains("全程"), "{texts:?}"); + // An old account server and an old brain: they can't be timed, which is no fault. + let url = stand_in_relay(8, move |p, _| match p { + "/api/hello" => Resp::json(&json!({"app": "anybot-relay"})), + _ => Resp::error(404, NO_SUCH_PATH), + }); + let lines = net_check(&at(url)); + assert!(lines.iter().all(|l| l.ok) && lines[1].text.contains("帳號伺服器是舊版") && lines[2].text.contains("是舊版"), "{lines:?}"); + // The brain is off: said, with the account server's words. + let url = stand_in_relay(8, move |p, _| match p { + "/api/hello" => Resp::json(&json!({"app": "anybot-relay"})), + _ if speed(p) => Resp::bytes("application/octet-stream", vec![7u8; 1024]), + _ => Resp::error(503, "那台 AnyBot 目前離線(電腦可能關機、睡眠、斷網,或 AnyBot 沒開)"), + }); + let last = net_check(&at(url)).pop().unwrap(); + assert!(!last.ok && last.text.contains("目前離線"), "{last:?}"); + // The account server can't be reached: one line, where. + let gone = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = gone.local_addr().unwrap().port(); + drop(gone); + let lines = net_check(&at(format!("http://127.0.0.1:{port}"))); + assert!(lines.len() == 1 && !lines[0].ok && lines[0].text.contains("連不到"), "{lines:?}"); + // A slow brain leg is called slow, and on whose side. + let url = stand_in_relay(8, move |p, _| match p { + "/api/hello" => Resp::json(&json!({"app": "anybot-relay"})), + _ if speed(p) => Resp::bytes("application/octet-stream", vec![7u8; 1024]), + _ => { + std::thread::sleep(Duration::from_millis(NET_SLOW_RTT_MS + 150)); + Resp::json(&json!({"ok": true})) + } + }); + let last = net_check(&at(url)).pop().unwrap(); + assert!(!last.ok && last.text.contains("這一段慢") && last.text.contains("大腦「雲端大腦」那台"), "{last:?}"); + // Not signed in: nothing to time. + assert!(net_check(&s).is_empty()); + } + /// 換網址 (the server moved, e.g. Tailscale → headscale killed every *.ts.net name): taken only /// when the server at the new address knows this computer's key and lists this computer — /// then only the address changes. Another server, a stranger, the same address: refused.