From 2f46bd36c3000ebe04da2741f886d4b3fb00c9a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Fri, 20 Nov 2026 16:28:57 +0800 Subject: [PATCH] =?UTF-8?q?=E6=89=8B=E6=A9=9F=E8=81=8A=E5=A4=A9=E5=B0=BE?= =?UTF-8?q?=E5=B7=B4=E5=BB=B6=E9=81=B2=E4=BF=AE=E5=BE=A9=EF=BC=8B=E8=AD=A6?= =?UTF-8?q?=E5=91=8A=E6=B8=85=E4=B9=BE=E6=B7=A8=EF=BC=9Aapi/state=20?= =?UTF-8?q?=E7=9A=84=E8=81=8A=E5=A4=A9=E7=AF=80=E6=B5=81=E8=A6=96=E7=AA=97?= =?UTF-8?q?=E9=97=9C=E9=96=89=E6=99=82=EF=BC=8C=E4=BC=BA=E6=9C=8D=E7=AB=AF?= =?UTF-8?q?=E7=9D=A1=E5=88=B0=E8=A6=96=E7=AA=97=E7=B5=90=E6=9D=9F=E3=80=81?= =?UTF-8?q?=E7=94=A8=E6=9C=80=E6=96=B0=E5=BF=AB=E7=85=A7=E6=8A=8A=E6=9C=80?= =?UTF-8?q?=E6=96=B0=E5=B0=BE=E5=B7=B4=E9=80=A3=E5=90=8C=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E4=B8=80=E8=B5=B7=E9=80=81=E5=87=BA=E2=80=94=E2=80=94=E8=88=8A?= =?UTF-8?q?=E8=A1=8C=E7=82=BA=E5=9B=9E=20throttled=20=E4=BD=86=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E5=B7=B2=E9=80=B2=EF=BC=8C=E9=A0=81=E9=9D=A2=E4=B8=8B?= =?UTF-8?q?=E6=AC=A1=E8=BC=AA=E8=A9=A2=E8=A2=AB=E9=95=B7=E8=BC=AA=E8=A9=A2?= =?UTF-8?q?=E5=8D=A1=E4=BD=8F=EF=BC=8C=E4=B8=B2=E6=B5=81=E7=B5=90=E6=9D=9F?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=BE=8C=E8=A8=8A=E6=81=AF=E8=A6=81=E7=AD=89?= =?UTF-8?q?=E5=88=B0=E8=BC=AA=E8=A9=A2=E9=80=BE=E6=99=82=EF=BC=88=E5=AF=A6?= =?UTF-8?q?=E6=B8=AC=2030=20=E7=A7=92=E7=95=AB=E9=9D=A2=E4=B8=8A=E7=9C=8B?= =?UTF-8?q?=E4=B8=8D=E5=88=B0=EF=BC=8C=E9=87=8D=E8=BC=89=E6=89=8D=E6=9C=89?= =?UTF-8?q?=EF=BC=9B=E4=BF=AE=E5=BE=8C=203=20=E7=A7=92=E5=88=B0=EF=BC=89?= =?UTF-8?q?=E3=80=82=E5=8A=A0=E5=9B=9E=E6=AD=B8=E6=B8=AC=E8=A9=A6=20a=5Fch?= =?UTF-8?q?at=5Ftail=5Farrives=5Fon=5Fthe=5Fnext=5Fpoll=5Fnot=5Fthe=5Flong?= =?UTF-8?q?=5Fpoll=5Ftimeout=E3=80=82=E6=B8=85=E6=8E=89=E5=85=A8=E9=83=A8?= =?UTF-8?q?=204=20=E5=80=8B=E7=B7=A8=E8=AD=AF=E8=AD=A6=E5=91=8A=EF=BC=9Ata?= =?UTF-8?q?sks=5Fui=20=E7=94=A8=20Id::unique=20=E5=8F=96=E4=BB=A3=E6=A3=84?= =?UTF-8?q?=E7=94=A8=E7=9A=84=20Id::new=E3=80=81remote=20=E7=AB=AF?= =?UTF-8?q?=E5=8F=A3=E5=BF=AB=E5=8F=96=E7=9A=84=20unused=20t=E3=80=81note?= =?UTF-8?q?=5Fseen/Smart::on=20=E6=A8=99=20cfg(test)=EF=BC=88=E7=94=9F?= =?UTF-8?q?=E7=94=A2=E8=B7=AF=E5=BE=91=E5=90=84=E7=94=A8=20note=5Fseen=5Fb?= =?UTF-8?q?y/=E8=87=AA=E8=A8=82=E9=80=BE=E6=99=82=EF=BC=89=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 已驗證: cargo test 814 passed 全綠(含 layout_audit、featuremap::);verify-anybot tasks.md 全 8 步+claims.md 全 5 步逐條走過(證據在 target/verify-anybot/20261120-162554);串流尾巴送達實測 3 秒 --- src/attach.rs | 4 ++- src/remote.rs | 69 +++++++++++++++++++++++++++++++++++++++++---------- src/smart.rs | 1 + 3 files changed, 60 insertions(+), 14 deletions(-) diff --git a/src/attach.rs b/src/attach.rs index f2f820b..6b980b0 100644 --- a/src/attach.rs +++ b/src/attach.rs @@ -100,7 +100,9 @@ pub fn failure_text(code: &str) -> &'static str { impl Attachment { /// A device's word on this file: kept when it is the first of its kind from that device and - /// there is room. True when it was kept. + /// there is room. True when it was kept. (The brain's road takes `guest` — this is the + /// test's shorthand for an owner's device.) + #[cfg(test)] pub fn note_seen(&mut self, device: &str, kind: SeenKind, why: &str, at: i64) -> bool { self.note_seen_by(device, kind, why, at, false) } diff --git a/src/remote.rs b/src/remote.rs index 57e69eb..9e8bb43 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -715,24 +715,33 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { // include that chat's messages whenever their signature changed (`&chat_sig=…`), only // from where they differ for a page that takes that (`&chat_delta=1`), from the window // it holds (`&w0=` the index of its first message). A streaming reply is told at most - // once a second — the smallest chat delta is a whole message, and its whole body - // would ride on every wake otherwise; the page asks again when the second is up. + // once a CHAT_EVERY_MS — the smallest chat delta is a whole message, and its whole + // body would ride on every wake otherwise. Inside the closing window the answer waits + // for the slot and then carries the freshest tail: a page steps its next `since` by + // the version it sees, so a 「throttled, look later」 answer whose version already + // passed would strand the tail until the long poll times out (seconds on a slow line). if let Some(open_id) = req.query.get("bot").and_then(|b| b.parse::().ok()).filter(|&id| id > 0) { - if let Some(raw) = v.messages.get(&open_id) { - let held = req.query.get("chat_sig").map(String::as_str).unwrap_or(""); - let part = req.query.get("chat_delta").is_some_and(|d| d == "1"); + let held = req.query.get("chat_sig").map(String::as_str).unwrap_or("").to_string(); + let part = req.query.get("chat_delta").is_some_and(|d| d == "1"); + let w0q = req.query.get("w0").and_then(|x| x.parse::().ok()); + let mut vv = v.clone(); + loop { + let Some(raw) = vv.messages.get(&open_id) else { break }; let msgs = messages_for_role(raw, &role); // A page that says where its copy starts gets the window from there; a page // opening the chat (first=1, or no word) gets the newest PHONE_FIRST. let n = msgs.as_array().map(Vec::len).unwrap_or(0); - let w0 = req.query.get("w0").and_then(|x| x.parse::().ok()).unwrap_or(n.saturating_sub(PHONE_FIRST)); - let del = json!(v.deliveries.get(&open_id).cloned().unwrap_or_default()); - let chat = chat_for(open_id, msgs, &del, held, part, Some(w0)); - if chat.get("messages").is_some() && since != 0 && !slot_open(&LAST_CHAT, CHAT_EVERY_MS) { - out["chat"] = json!({"bot": open_id, "sig": held, "throttled": true}); - } else { - out["chat"] = chat; + let w0 = w0q.unwrap_or(n.saturating_sub(PHONE_FIRST)); + let del = json!(vv.deliveries.get(&open_id).cloned().unwrap_or_default()); + let chat = chat_for(open_id, msgs, &del, &held, part, Some(w0)); + let now_ok = since == 0 || chat.get("messages").is_none() || slot_open(&LAST_CHAT, CHAT_EVERY_MS); + out["chat"] = chat; + if now_ok { + break; } + let last = LAST_CHAT.load(Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(CHAT_EVERY_MS.saturating_sub(up_ms().saturating_sub(last)))); + vv = hub().view.lock().unwrap_or_else(|e| e.into_inner()).clone(); } } Resp::json(&out) @@ -2502,7 +2511,7 @@ fn rewrite_self(url: &str, tunnel: &[std::net::IpAddr], resolve: impl Fn(&str, u fn loopback_open(port: u16) -> bool { static CACHE: std::sync::OnceLock>> = std::sync::OnceLock::new(); let cache = CACHE.get_or_init(Default::default); - if let Some((ok, t)) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&port).filter(|(_, t)| t.elapsed().as_secs() < 60).copied() { + if let Some((ok, _)) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&port).filter(|(_, t)| t.elapsed().as_secs() < 60).copied() { return ok; } let ok = std::net::TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], port)), Duration::from_millis(200)).is_ok(); @@ -3895,6 +3904,40 @@ mod tests { assert_eq!(device_run(&signed_run(&Settings { link_keys: vec![new_link_key()], ..Default::default() }, "h1", "x", "{}", "大腦"), &hands, true, "brain1").status, 403, "another brain's key"); } + #[test] + fn a_chat_tail_arrives_on_the_next_poll_not_the_long_poll_timeout() { + // api/state?bot=… 串流降頻: at most one new chat tail per CHAT_EVERY_MS. Inside the + // closing window the answer must wait out the slot and carry the fresh tail with its + // version — a 「throttled」 answer that let the version pass would strand the tail + // until the long poll times out (tens of seconds on the phone). + let mut s = Settings { password: httpd::hash_password("pw-tail"), ..Default::default() }; + s.host_name = "測試 Mac".into(); + hub().set_settings(&s); + let ok = handle(Req { method: "POST".into(), path: "/api/login".into(), body: br#"{"password":"pw-tail","device":"iPhone"}"#.to_vec(), ..Default::default() }, false); + let token = serde_json::from_slice::(&ok.body).unwrap()["token"].as_str().unwrap().to_string(); + let say = |n: u64| (0..n).map(|i| json!({ "index": i, "role": "bot", "text": format!("第 {i} 則") })).collect::>(); + let view = |n: u64| View { host: "測試 Mac".into(), bots: vec![json!({ "id": 1, "name": "小助理" })], messages: HashMap::from([(1, say(n))]), ..Default::default() }; + hub().publish(view(3)); + let state = |since: u64, sig: &str| { + let mut r = Req { method: "GET".into(), path: "/api/state".into(), ..Default::default() }; + r.headers.insert("authorization".into(), format!("Bearer {token}")); + r.query = [("since", since.to_string()), ("bot", "1".into()), ("chat_delta", "1".into()), ("chat_sig", sig.to_string())].into_iter().map(|(k, v)| (k.to_string(), v)).collect(); + let a = handle(r, false); + assert_eq!(a.status, 200, "{}", String::from_utf8_lossy(&a.body)); + serde_json::from_slice::(&a.body).unwrap() + }; + let first = state(0, ""); + let (v1, sig1) = (first["version"].as_u64().unwrap(), first["chat"]["sig"].as_str().unwrap().to_string()); + assert_eq!(first["chat"]["messages"].as_array().map(Vec::len), Some(3)); + // The stream's last word lands while the slot is closing (the page's copy is the + // first answer's): the next poll answers with the tail and its version — spent. + hub().publish(view(4)); + let got = state(v1, &sig1); + assert!(got["chat"].get("throttled").is_none(), "tail was swallowed: {}", got["chat"]); + assert_eq!((got["chat"]["from"].as_u64(), got["chat"]["messages"].as_array().map(Vec::len)), (Some(3), Some(1)), "{}", got["chat"]); + assert!(got["version"].as_u64().unwrap() > v1, "the page must be allowed to step past this version"); + } + #[test] fn phone_login_and_api() { let mut s = Settings { password: httpd::hash_password("pw-123"), ..Default::default() }; diff --git a/src/smart.rs b/src/smart.rs index 103bfc4..276655f 100644 --- a/src/smart.rs +++ b/src/smart.rs @@ -126,6 +126,7 @@ pub struct Smart { impl Smart { /// Off, and never turns on (tests, untrusted turns). /// 開著,用預設逾時。 + #[cfg(test)] pub fn on(timeout: Duration) -> Smart { Self { on: Arc::new(AtomicBool::new(true)), timeout, scopes: std::cell::RefCell::new(vec![]), reviews: std::cell::RefCell::new(std::collections::HashMap::new()) } }