diff --git a/FEATURES.md b/FEATURES.md index f2f8c0e..d400e38 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1494,6 +1494,12 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - **憑證**:AnyBot 所有的 HTTP 連線(連接器、模型服務、Webhook、語音、下載)都信任同一份憑證:公開的加上這台電腦自己信任的。以前只有連帳號伺服器的那條會看這台電腦信任的,公司自己簽憑證的連接器或模型服務在別處會失敗。`clippy.toml` 擋下在 net.rs 以外自己建 HTTP 用戶端。 - **在聊天裡請 Bot 加**(設定畫面能做的,聊天也能做):有「管理 App」能力的 Bot 用 `manage_connectors` 列出、新增、修改(含開關)、重新連線、移除連接器。改的就是大腦上「設定 › 整合 › 連接器」那一份(Bot 的這一輪本來就在大腦上跑),所以每台螢幕電腦和手機都看得到,不會寫到手腳電腦(例如 nobledesktop 上的 ~/.local/share/AnyBot)那邊的檔案。新增、修改、移除先跳「允許…管理連接器嗎?」卡片,列出要執行的指令或網址、環境變數和標頭;名字像金鑰的(TOKEN、KEY、SECRET、PASS、AUTH…)和密碼顯示成「••••(已填)」。加好後等它連上(最多 90 秒)再回報「已連上,N 個工具」或連不上的原因;連上的工具同一輪的下一步就能用(例如「加上 GitLab,然後列出我的 MR」一次做完)。名稱重複、command 和 url 都給、網址不是 http(s)、還有「{…}」沒填、要改卻沒東西可改,都在問你之前就回給 Bot 說原因。 +### 長連線在慢的線上不再被切斷 + +- 2026-11-17:一台 Mac 經 Tailscale 香港中繼連伺服器(約 100 KB/s),大腦整份資料約 5 MB 要 45–55 秒,這台「45 秒沒收到一則完整訊息就算斷線」,把傳到一半的連線切掉,螢幕又從頭要整份,一直循環;帳號那欄寫已連線,大腦那欄寫「和帳號伺服器的連線斷了」。 +- 現在兩端(這台的 tunnel.rs、帳號伺服器的 relay)都以「有沒有收到資料」判斷連線還在;等回答時資料還在進來就繼續等(最多 10 分鐘);長連線一接回,螢幕馬上重新向大腦要資料(以前要等自己的重試時間,最多 20 秒)。 +- 設定 › 一般 › 帳戶 › 大腦:狀態下面分段寫「這台 ↔ 帳號伺服器」「帳號伺服器 ↔ 大腦(在線上或不在)」「上次同步的大小、秒數、速度」。帳號伺服器那端的修正要 make update-server 才生效。 + ### 用量(/usage) - 每一次模型呼叫(Bot 的每一步、快速模型、摘要、發布前檢查、目標檢查、支線…)都記一行在資料夾的 `usage/YYYY-MM.jsonl`:時間、供應商、模型、誰的、做什麼(從請求的 session 名稱看:anybot-bot-12 是 Bot 12 的回合)、輸入、輸出、快取讀寫的 token,供應商有回報花費(OpenRouter)時也記。 diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index 9a50467..58e0a94 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -7,6 +7,7 @@ - AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。 - 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 Bot 換成帳號裡最新的備份。 - 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效)。細節見 [computers](computers.md)。 +- 大腦那一欄(螢幕電腦上):狀態下面分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等。 - 帳號裡的電腦:同一個帳號的每台 AnyBot,在線或離線;那台打開「裝置連結」後,會出現在 Bot 可以用的電腦裡。 - 同一個網路直接連:先設手機密碼(至少 8 個字)才能打開;列出這台的網址(同一個 Wi-Fi,或都裝了 Tailscale)。區網用 https(這台自己做的憑證),Tailscale 的 100.x 用 http。同一台裝置密碼錯 5 次要等一分鐘。 - 直接連線的裝置:用手機密碼登入過的手機和瀏覽器、最近使用時間,可以逐台「登出」。 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 981aa55..281914b 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -87,7 +87,7 @@ - 做法:Linux 電腦上的指令用 Landlock:寫入只限工作資料夾和 /tmp,私密檔案(protected_dirs)讀寫都擋;核心不支援時照實說(「這台的指令沒有沙盒」),不假裝有。 - 做完:Linux 上的測試(CI 的 anybot-linux):寫工作資料夾外失敗、讀 ~/.ssh 失敗。 -### R7. 長連線:還在傳就不算斷線、斷線後馬上重連、看得出是哪一段 ⬜ +### R7. 長連線:還在傳就不算斷線、斷線後馬上重連、看得出是哪一段 ✅(帳號伺服器那端要 make update-server) - 2026-11-17 早上:這台走 Tailscale 香港中繼約 100 KB/s,大腦整份資料約 5 MB,45 秒沒收到「完整一則」就被這台切斷,切了又從頭要。 - 做法:tunnel 以「有沒有收到資料」判斷存活(兩端);等回覆時資料還在進來就繼續等;長連線接回時大腦馬上重新同步;大腦那一欄分段寫「這台↔帳號伺服器」「帳號伺服器↔大腦」和上次同步速度。 - 做完:測試:慢速傳 3 MB(超過 45 秒)不斷線。 diff --git a/relay/clippy.toml b/relay/clippy.toml new file mode 100644 index 0000000..53424cf --- /dev/null +++ b/relay/clippy.toml @@ -0,0 +1,2 @@ +# The account server (its own crate) has no net.rs: the main crate's rule about building HTTP +# clients (../clippy.toml) is not for it. Clippy reads the nearest clippy.toml, this one. diff --git a/relay/src/main.rs b/relay/src/main.rs index dda9b07..3958e6f 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -718,15 +718,22 @@ impl Relay { let _ = c.set_write_timeout(Some(Duration::from_secs(30))); // (A smaller read buffer than the default 128 KB: it is kept for every connected computer.) let cfg = tungstenite::protocol::WebSocketConfig::default().max_message_size(Some(httpd::MAX_BODY * 2)).max_frame_size(Some(httpd::MAX_BODY * 2)).read_buffer_size(32 << 10); - let mut ws = WebSocket::from_raw_socket(c, Role::Server, Some(cfg)); + let mut ws = WebSocket::from_raw_socket(Counted { inner: c, got: 0 }, Role::Server, Some(cfg)); let serial = SERIAL.fetch_add(1, Ordering::SeqCst); let (tx, rx) = channel::>(); self.sockets.lock().unwrap().insert(h.id.clone(), Sock { tx: tx.clone(), serial }); self.seen.lock().unwrap().insert(h.id.clone(), Instant::now()); let (mut heard, mut pinged, mut marked) = (Instant::now(), Instant::now(), Instant::now()); let mut pace = wire::Pace::new(); + let mut got = 0u64; 'live: loop { - pace.tune(ws.get_ref()); + pace.tune(&ws.get_ref().inner); + // Alive while anything comes in: a big upload over a slow line (a computer behind + // Tailscale's relay, 100 KB/s) used to be cut at WS_DEAD_SECS mid-message. + if ws.get_ref().got != got { + got = ws.get_ref().got; + heard = Instant::now(); + } match ws.read() { Ok(Message::Binary(b)) => { heard = Instant::now(); @@ -1849,6 +1856,30 @@ impl Relay { } } +/// A connection that counts what comes in (a lasting connection is alive while bytes arrive, +/// not only when a whole message has). +struct Counted { + inner: std::net::TcpStream, + got: u64, +} + +impl std::io::Read for Counted { + fn read(&mut self, b: &mut [u8]) -> std::io::Result { + let n = self.inner.read(b)?; + self.got += n as u64; + Ok(n) + } +} + +impl std::io::Write for Counted { + fn write(&mut self, b: &[u8]) -> std::io::Result { + self.inner.write(b) + } + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } +} + fn main() { let args: Vec = std::env::args().collect(); let arg = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned(); diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index 2559b2e..2f5f976 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -521,6 +521,19 @@ pub struct Mirror { pub(super) mcp_state: Value, /// When each bot's last turn ended, as last heard (a newer one ending well is read aloud). settled: HashMap, + /// The last answer from the brain: when (ms), how many bytes came over the lasting + /// connection for it, and how long it took (ms) — the 大腦 section says the line's speed. + pub(super) last_sync: Arc>>, +} + +/// The last sync in words: 「上次同步 10:31:05(1.2 MB,11 秒,約 110 KB/s)」. +pub(super) fn sync_words(at_ms: i64, bytes: u64, ms: u64) -> String { + let when = chrono::DateTime::from_timestamp_millis(at_ms).map(|t| t.with_timezone(&chrono::Local).format("%H:%M:%S").to_string()).unwrap_or_default(); + if bytes < 100_000 || ms == 0 { + return format!("上次同步 {when}"); + } + let size = if bytes >= 1_000_000 { format!("{:.1} MB", bytes as f64 / 1e6) } else { format!("{} KB", bytes / 1000) }; + format!("上次同步 {when}({size},{} 秒,約 {} KB/s)", ms.div_ceil(1000), bytes * 1000 / ms / 1000) } /// What a computer is, in a word a screen can show next to its name. @@ -977,18 +990,23 @@ impl App { let (tx, rx) = channel(); self.mir.rx = Some(rx); self.mir.tx = Some(tx.clone()); - let (g, version, client, s, resync) = (self.mir.gen.clone(), self.mir.version.clone(), self.mir.client.clone(), self.state.remote.clone(), self.mir.resync.clone()); + let (g, version, client, s, resync, last_sync) = (self.mir.gen.clone(), self.mir.version.clone(), self.mir.client.clone(), self.state.remote.clone(), self.mir.resync.clone(), self.mir.last_sync.clone()); let repaint = self.repaint_fn(); std::thread::spawn(move || { let mut backoff = 1u64; while g.load(Ordering::SeqCst) == gen { let since = if resync.swap(false, Ordering::SeqCst) { 0 } else { version.load(Ordering::SeqCst) }; + let (link_before, bytes_before, t0) = (crate::tunnel::link_serial(), crate::tunnel::bytes_in(), std::time::Instant::now()); match remote::sync_pull(&s, since, &client) { Ok(v) => { backoff = 1; if g.load(Ordering::SeqCst) != gen { break; } + // (A long poll that waited for news isn't the line's speed: only answers + // that came quickly or were big count.) + let (bytes, ms) = (crate::tunnel::bytes_in().saturating_sub(bytes_before), t0.elapsed().as_millis() as u64); + *last_sync.lock().unwrap_or_else(|e| e.into_inner()) = Some((crate::model::now_ms(), bytes, if bytes >= 100_000 { ms } else { 0 })); version.store(v["version"].as_u64().unwrap_or(0), Ordering::SeqCst); let _ = tx.send(Incoming::Pull(v)); } @@ -996,8 +1014,22 @@ impl App { let _ = tx.send(Incoming::Offline(e)); // Start over (with everything) once it is back. version.store(0, Ordering::SeqCst); - std::thread::sleep(std::time::Duration::from_secs(backoff)); - backoff = (backoff * 2).min(20); + // …and the moment the lasting connection is back, not after the wait: + // the account row said 已連線 while this one still waited up to 20 s. + let until = std::time::Instant::now() + std::time::Duration::from_secs(backoff); + let mut back = false; + while std::time::Instant::now() < until && g.load(Ordering::SeqCst) == gen { + let now = crate::tunnel::link_serial(); + if now != 0 && now != link_before { + back = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(200)); + } + backoff = if back { 1 } else { (backoff * 2).min(20) }; + if back { + let _ = tx.send(Incoming::Offline("已重新連上帳號伺服器,正在向大腦要資料…".into())); + } } } repaint(); diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index d016638..f6bc92b 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -873,6 +873,13 @@ impl App { ui.painter().circle_filled(r.center(), 4.0, if self.mir.online { p.up } else { p.text3 }); ui.label(RichText::new(status).size(FONT_SM).color(p.text2)); }); + // Which leg: this computer ↔ the account server, the account server ↔ the + // brain (as the account server last said), and the line's speed. + let brain_on = self.rm.peers.lock().unwrap().iter().find(|(id, _, _)| *id == s.brain_id).map(|x| x.2); + let legs = remote_legs(&remote::hub().relay_status(), brain_on, &s.brain_name, *self.mir.last_sync.lock().unwrap()); + for line in legs { + ui.add(egui::Label::new(RichText::new(line).size(FONT_XS).color(p.text3)).wrap()); + } ui.horizontal(|ui| { let busy = self.mir.moving.load(Ordering::SeqCst); if ui.add_enabled(self.mir.online && !busy, secondary_button("把這台的 Bot 搬過去")).on_hover_text(t("把這台電腦原本的 Bot(連同聊天)、模型金鑰、技能和連接器複製到大腦。這台的原始資料不會刪掉。")).clicked() { @@ -1115,6 +1122,25 @@ fn chats(model: &str) -> bool { !["imagine", "image", "video", "embed", "tts", "whisper", "audio", "moderation", "dall-e", "sora", "veo"].iter().any(|k| m.contains(k)) } +/// The 大腦 section's lines under its state: this computer ↔ the account server (the lasting +/// connection's own words), the account server ↔ the brain (online or not, as the account server +/// last said), and the last sync's size and speed. +pub(super) fn remote_legs(relay: &str, brain_online: Option, brain: &str, last: Option<(i64, u64, u64)>) -> Vec { + let mut out = vec![]; + if !relay.is_empty() { + out.push(format!("這台 ↔ 帳號伺服器:{relay}")); + } + match brain_online { + Some(true) => out.push(format!("帳號伺服器 ↔ 大腦「{brain}」:在線上")), + Some(false) => out.push(format!("帳號伺服器 ↔ 大腦「{brain}」:不在線上(大腦那台的 AnyBot 沒開、沒網路,或正在重新啟動)")), + None => {} + } + if let Some((at, bytes, ms)) = last { + out.push(super::mirror_ui::sync_words(at, bytes, ms)); + } + out +} + #[cfg(test)] mod phone_tests { #[test] diff --git a/src/tunnel.rs b/src/tunnel.rs index 239b9ba..3345187 100644 --- a/src/tunnel.rs +++ b/src/tunnel.rs @@ -18,6 +18,8 @@ use tungstenite::{Message, WebSocket}; const PING_SECS: u64 = 15; const DEAD_SECS: u64 = 45; +/// Silence after which the link is opened again (DEAD_SECS; a test makes it short). +static DEAD_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(DEAD_SECS * 1000); /// Bodies bigger than this are compressed. const ZIP_OVER: usize = 1024; const CUT: &str = "和帳號伺服器的連線斷了,正在重新連線"; @@ -95,13 +97,59 @@ impl Stream { impl Read for Stream { fn read(&mut self, b: &mut [u8]) -> std::io::Result { - match self { + let r = match self { Stream::Plain(t) => t.read(b), Stream::Tls(s) => s.read(b), + }; + if let Ok(n) = r { + if n > 0 { + came_in(n); + } } + r } } +// ---------- what is coming in ---------- +// 2026-11-17: over Tailscale's relay in Hong Kong (about 100 KB/s) a full sync of the brain (about +// 5 MB) took 45–55 s. The link counted as dead after 45 s without a *whole* message, so it was cut +// in the middle of the answer — and the screen asked for everything again, and again. Now bytes +// arriving are what keeps it alive, and a call still receiving its answer goes on waiting. + +static BYTES_IN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +/// When bytes last came in (ms since this process started; 0: never). +static LAST_IN_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +fn since_start_ms() -> u64 { + static START: OnceLock = OnceLock::new(); + START.get_or_init(Instant::now).elapsed().as_millis() as u64 + 1 +} + +fn came_in(n: usize) { + BYTES_IN.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed); + LAST_IN_MS.store(since_start_ms(), std::sync::atomic::Ordering::Relaxed); +} + +/// Bytes received on the lasting connection since this AnyBot started. +pub fn bytes_in() -> u64 { + BYTES_IN.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Whether bytes came in within the last `ms`. +pub fn receiving(ms: u64) -> bool { + let last = LAST_IN_MS.load(std::sync::atomic::Ordering::Relaxed); + last != 0 && since_start_ms().saturating_sub(last) <= ms +} + +/// The lasting connection's number (a new one each time it connects; 0 while it isn't up): a +/// screen of a brain asks again the moment it is back. +pub fn link_serial() -> u64 { + link().lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|l| l.serial).unwrap_or(0) +} + +/// How long a call keeps waiting past its own time while its answer is still coming in. +const LONGEST_WAIT: Duration = Duration::from_secs(600); + impl Write for Stream { fn write(&mut self, b: &[u8]) -> std::io::Result { match self { @@ -268,6 +316,7 @@ fn keep(mut ws: WebSocket, serial: u64, alive: &dyn Fn() -> bool) { let s = crate::remote::hub().settings(); let _ = tx.send(wire::pack(&json!({"t": "hello", "brain": s.brain_id, "hands": s.device_link}), &[])); let (mut heard, mut pinged) = (Instant::now(), Instant::now()); + let mut got = bytes_in(); 'live: while alive() { pace.tune(ws.get_ref().tcp()); match ws.read() { @@ -308,7 +357,13 @@ fn keep(mut ws: WebSocket, serial: u64, alive: &dyn Fn() -> bool) { Err(e) if !would_block(&e) => break, _ => {} } - if heard.elapsed().as_secs() >= DEAD_SECS { + // Alive while anything comes in, a big answer in the middle of arriving included. + let now_got = bytes_in(); + if now_got != got { + got = now_got; + heard = Instant::now(); + } + if heard.elapsed().as_millis() as u64 >= DEAD_MS.load(std::sync::atomic::Ordering::Relaxed) { break; } } @@ -491,11 +546,21 @@ pub fn call(to: &str, method: &str, path: &str, query: &[(&str, String)], body: calls.lock().unwrap().remove(&id); return None; } - Some(match rrx.recv_timeout(Duration::from_secs(secs)) { - Ok(r) => r, - Err(_) => { - calls.lock().unwrap().remove(&id); - Err("等太久沒有回應:網路很慢或斷斷續續".into()) + // Its own time, and longer while the link is still receiving (its answer may be what is + // arriving), up to LONGEST_WAIT. + let start = Instant::now(); + let due = start + Duration::from_secs(secs); + Some(loop { + match rrx.recv_timeout(Duration::from_millis(500)) { + Ok(r) => break r, + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break Err(CUT.into()), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + let now = Instant::now(); + if now >= due && (!receiving(3_000) || now - start >= LONGEST_WAIT) { + calls.lock().unwrap().remove(&id); + break Err("等太久沒有回應:網路很慢或斷斷續續".into()); + } + } } }) } @@ -526,6 +591,53 @@ mod own_certificate_live { #[cfg(test)] mod tests { + /// R7: one big answer coming in slowly (longer than the silence the link allows) keeps the + /// link up — it used to be cut at DEAD_SECS without a whole message, mid-answer, over and over. + /// Then real silence still ends it. + #[test] + fn a_big_answer_arriving_slowly_keeps_the_link() { + use std::io::Write as _; + use std::sync::atomic::{AtomicBool, Ordering}; + super::DEAD_MS.store(1_000, Ordering::Relaxed); + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + std::thread::spawn(move || { + let (s, _) = l.accept().unwrap(); + let mut ws = tungstenite::accept(s).unwrap(); + // One binary frame of 64 KB (a frame the client can read only once it is whole), + // written over 3 s — three times the allowed silence — then silence. + let body = super::wire::pack(&serde_json::json!({"t": "ret", "id": "nobody"}), &vec![b'x'; 64 * 1024]); + let mut frame = vec![0x82u8, 127]; + frame.extend_from_slice(&(body.len() as u64).to_be_bytes()); + frame.extend_from_slice(&body); + let raw = ws.get_mut(); + for chunk in frame.chunks(frame.len() / 12 + 1) { + let _ = raw.write_all(chunk); + let _ = raw.flush(); + std::thread::sleep(std::time::Duration::from_millis(250)); + } + std::thread::sleep(std::time::Duration::from_secs(10)); + }); + let said = std::sync::Arc::new(std::sync::Mutex::new(Vec::<(std::time::Instant, String)>::new())); + let (said2, stop) = (said.clone(), std::sync::Arc::new(AtomicBool::new(false))); + let stop2 = stop.clone(); + let t0 = std::time::Instant::now(); + let h = std::thread::spawn(move || { + super::run(&format!("http://127.0.0.1:{port}"), "token", &|| !stop2.load(Ordering::Relaxed), &|m| said2.lock().unwrap().push((std::time::Instant::now(), m.to_string()))); + }); + std::thread::sleep(std::time::Duration::from_millis(3_200)); + let early: Vec = said.lock().unwrap().iter().filter(|(t, _)| t.duration_since(t0).as_millis() < 3_200).map(|(_, m)| m.clone()).collect(); + assert_eq!(early, vec!["已連線".to_string()], "the link stayed up while the answer came in"); + assert!(super::receiving(1_000) && super::bytes_in() >= 64 * 1024); + // Real silence (the server stopped sending): the link is opened again. + std::thread::sleep(std::time::Duration::from_millis(2_000)); + assert!(said.lock().unwrap().iter().any(|(_, m)| m.contains("中斷")), "{:?}", said.lock().unwrap()); + stop.store(true, Ordering::Relaxed); + super::DEAD_MS.store(super::DEAD_SECS * 1000, Ordering::Relaxed); + // (Not joined: it may be waiting on a reconnect the fake server no longer answers.) + drop(h); + } + #[test] fn the_public_certificates_are_always_trusted() { // The system's list comes on top; a computer without one still reaches public servers.