手機聊天尾巴延遲修復+警告清乾淨:api/state 的聊天節流視窗關閉時,伺服端睡到視窗結束、用最新快照把最新尾巴連同版本一起送出——舊行為回 throttled 但版本已進,頁面下次輪詢被長輪詢卡住,串流結束的最後訊息要等到輪詢逾時(實測 30 秒畫面上看不到,重載才有;修後 3 秒到)。加回歸測試 a_chat_tail_arrives_on_the_next_poll_not_the_long_poll_timeout。清掉全部 4 個編譯警告:tasks_ui 用 Id::unique 取代棄用的 Id::new、remote 端口快取的 unused t、note_seen/Smart::on 標 cfg(test)(生產路徑各用 note_seen_by/自訂逾時)。

已驗證: cargo test 814 passed 全綠(含 layout_audit、featuremap::);verify-anybot tasks.md 全 8 步+claims.md 全 5 步逐條走過(證據在 target/verify-anybot/20261120-162554);串流尾巴送達實測 3 秒
This commit is contained in:
王性驊 2026-11-20 16:28:57 +08:00
parent 21e87ee2c6
commit 2f46bd36c3
3 changed files with 60 additions and 14 deletions

View File

@ -100,7 +100,9 @@ pub fn failure_text(code: &str) -> &'static str {
impl Attachment { impl Attachment {
/// A device's word on this file: kept when it is the first of its kind from that device and /// 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 { pub fn note_seen(&mut self, device: &str, kind: SeenKind, why: &str, at: i64) -> bool {
self.note_seen_by(device, kind, why, at, false) self.note_seen_by(device, kind, why, at, false)
} }

View File

@ -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 // 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 // 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 // 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 // once a CHAT_EVERY_MS — the smallest chat delta is a whole message, and its whole
// would ride on every wake otherwise; the page asks again when the second is up. // 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::<u64>().ok()).filter(|&id| id > 0) { if let Some(open_id) = req.query.get("bot").and_then(|b| b.parse::<u64>().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("").to_string();
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 part = req.query.get("chat_delta").is_some_and(|d| d == "1");
let w0q = req.query.get("w0").and_then(|x| x.parse::<usize>().ok());
let mut vv = v.clone();
loop {
let Some(raw) = vv.messages.get(&open_id) else { break };
let msgs = messages_for_role(raw, &role); let msgs = messages_for_role(raw, &role);
// A page that says where its copy starts gets the window from there; a page // 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. // 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 n = msgs.as_array().map(Vec::len).unwrap_or(0);
let w0 = req.query.get("w0").and_then(|x| x.parse::<usize>().ok()).unwrap_or(n.saturating_sub(PHONE_FIRST)); let w0 = w0q.unwrap_or(n.saturating_sub(PHONE_FIRST));
let del = json!(v.deliveries.get(&open_id).cloned().unwrap_or_default()); 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 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) { let now_ok = since == 0 || chat.get("messages").is_none() || slot_open(&LAST_CHAT, CHAT_EVERY_MS);
out["chat"] = json!({"bot": open_id, "sig": held, "throttled": true});
} else {
out["chat"] = chat; 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) 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 { fn loopback_open(port: u16) -> bool {
static CACHE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<u16, (bool, std::time::Instant)>>> = std::sync::OnceLock::new(); static CACHE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<u16, (bool, std::time::Instant)>>> = std::sync::OnceLock::new();
let cache = CACHE.get_or_init(Default::default); 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; return ok;
} }
let ok = std::net::TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], port)), Duration::from_millis(200)).is_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"); 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::<Value>(&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::<Vec<_>>();
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::<Value>(&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] #[test]
fn phone_login_and_api() { fn phone_login_and_api() {
let mut s = Settings { password: httpd::hash_password("pw-123"), ..Default::default() }; let mut s = Settings { password: httpd::hash_password("pw-123"), ..Default::default() };

View File

@ -126,6 +126,7 @@ pub struct Smart {
impl Smart { impl Smart {
/// Off, and never turns on (tests, untrusted turns). /// Off, and never turns on (tests, untrusted turns).
/// 開著,用預設逾時。 /// 開著,用預設逾時。
#[cfg(test)]
pub fn on(timeout: Duration) -> Smart { 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()) } Self { on: Arc::new(AtomicBool::new(true)), timeout, scopes: std::cell::RefCell::new(vec![]), reviews: std::cell::RefCell::new(std::collections::HashMap::new()) }
} }