diff --git a/FEATURES.md b/FEATURES.md index 37d9a7e..8e89d00 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -262,6 +262,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 手機打開聊天先只拿最新 30 條訊息(慢線上開頁省流量)。 - 有更早的,頂上出現「載入更早的對話」,點一次往前補 60 條;翻到最頂按鈕消失。 +- 手機說它手上那份從哪一則開始(`w0`、載入更早的 `from`),用的是那則在整段聊天裡的位置(`index`,數到 Bot 每個工具步驟);大腦照這個位置找到清單裡對應的那則再開始。以前大腦把它當成「清單裡第幾則」——清單只是最新 120 則去掉工具步驟,短得多——有工具步驟的聊天就切到清單外、回一份空的,下一次手機手上沒東西、又拿到整段:點進去一次有聊天記錄、一次全空(jenny-Host 11/21,1133 則的聊天、清單 40 則左右)。 - Bot 回答中,手機每秒最多更新一次聊天(慢線上畫面落後約一秒);打完的整句一定補齊。 - 電腦開對話照樣整段;直接查聊底的指令和腳本也照舊拿全部。 diff --git a/src/httpd.rs b/src/httpd.rs index 1eda254..6f8ba9a 100644 --- a/src/httpd.rs +++ b/src/httpd.rs @@ -1053,12 +1053,12 @@ mod tests { } let each = t.elapsed() / 10 - Duration::from_millis(30); assert!(each < Duration::from_millis(15), "{each:?} an answer on a new connection"); - // Told to stop: it stops, and the port is free again. + // Told to stop: it stops. (Whether the port is free again isn't asked: with the other + // tests running, another listener may take a freed port at once.) on.store(false, std::sync::atomic::Ordering::SeqCst); let t = std::time::Instant::now(); done.join().unwrap(); assert!(t.elapsed() < Duration::from_secs(2), "stopped in {:?}", t.elapsed()); - assert!(TcpListener::bind(("127.0.0.1", port)).is_ok()); } #[test] diff --git a/src/remote.rs b/src/remote.rs index d413deb..1766f19 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -734,9 +734,12 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { // 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 = w0q.unwrap_or(n.saturating_sub(PHONE_FIRST)); + let off = match w0q { + Some(ix) => from_index(msgs.as_array().map(Vec::as_slice).unwrap_or(&[]), ix), + None => 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 chat = chat_for(open_id, msgs, &del, &held, part, Some(off)); let now_ok = since == 0 || chat.get("messages").is_none() || slot_open(&LAST_CHAT, CHAT_EVERY_MS); out["chat"] = chat; if now_ok { @@ -787,8 +790,10 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { Some(m) => { let msgs = messages_for_role(m, &role); let n = msgs.as_array().map(Vec::len).unwrap_or(0); - let w0 = req.query.get("w0").and_then(|x| x.parse::().ok()) - .or(req.query.get("first").map(|_| n.saturating_sub(PHONE_FIRST))); + let w0 = match req.query.get("w0").and_then(|x| x.parse::().ok()) { + Some(ix) => Some(from_index(msgs.as_array().map(Vec::as_slice).unwrap_or(&[]), ix)), + None => req.query.get("first").map(|_| n.saturating_sub(PHONE_FIRST)), + }; let del = json!(v.deliveries.get(&id).cloned().unwrap_or_default()); let mut out = chat_for(id, msgs, &del, held, part, w0); out["version"] = json!(v.version); @@ -808,7 +813,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { Some(m) => { let all = messages_for_role(m, &role); let arr = all.as_array().cloned().unwrap_or_default(); - let from = from.min(arr.len()); + let from = from_index(&arr, from); let start = from.saturating_sub(count); Resp::json(&json!({"bot": id, "messages": &arr[start..from], "more": start > 0})) } @@ -1465,6 +1470,16 @@ fn state_for(mut out: Value, held: &str, stable: bool) -> Value { /// = the whole chat, `first=1` on a poll = the newest `PHONE_FIRST`). 交付確認 rides beside the /// messages (`deliveries`), never inside them: a device reporting a file must not change the /// chat's fingerprint. +/// Where in the chat the phone sends (`w0`, an older page's `from`) — its first message's +/// `index`, the place in the bot's whole chat — as a place in the list it is sent from (the +/// newest PHONE_TAIL of the chat without the steps' results, so far shorter): the first message +/// at or after it. Read as a place in that list, it ran past its end on any chat with steps +/// (jenny-Host: index 1105 in a list of 40) and the window came back empty — the next ask, with +/// nothing held, got it all again: the chat was there one time and empty the next. +fn from_index(list: &[Value], index: usize) -> usize { + list.iter().position(|m| m["index"].as_u64().is_some_and(|i| i as usize >= index)).unwrap_or(list.len()) +} + fn chat_for(bot: u64, msgs: Value, delivery: &Value, held: &str, part: bool, w0: Option) -> Value { let list = msgs.as_array().map(Vec::as_slice).unwrap_or(&[]); let dfp = fp(delivery); @@ -3631,6 +3646,53 @@ mod tests { assert_eq!(wide["messages"][0]["index"], json!(off - 20)); } + /// A chat with steps, as the phone sees it: the list it is sent is the newest PHONE_TAIL of the + /// chat without the steps' results, each message carrying its place in the whole chat + /// (`index`, with gaps where the steps were). The page says where its copy starts with that + /// `index` — the chat comes back from there, every time (it came back empty every other time: + /// jenny-Host, 2026-11-21), and 載入更早 walks back from there. + #[test] + fn a_chat_with_steps_comes_back_every_time() { + let bot = 987_001u64; + // 40 messages shown, from the newest 120 of a chat of 1133 (two steps after each reply). + let list: Vec = (0..40).map(|i| json!({"index": 1013 + i * 3, "text": format!("第 {i} 則")})).collect(); + std::sync::Arc::make_mut(&mut *hub().view.lock().unwrap()).messages.insert(bot, list.clone()); + let ask = |q: &str| -> Value { + let (path, query) = q.split_once('?').unwrap_or((q, "")); + let query = query.split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect(); + let headers = [("x-anybot-role".to_string(), "owner".to_string())].into_iter().collect(); + let r = handle(Req { method: "GET".into(), path: path.into(), query, headers, body: vec![], peer: String::new() }, true); + assert_eq!(r.status, 200, "{q}"); + serde_json::from_slice(&r.body).unwrap() + }; + // Opened: the newest PHONE_FIRST. + let first = ask(&format!("/api/bots/{bot}?first=1")); + let win = first["messages"].as_array().unwrap().clone(); + assert_eq!(win.len(), PHONE_FIRST); + let (start, sig) = (win[0]["index"].as_u64().unwrap(), first["sig"].as_str().unwrap().to_string()); + assert_eq!(start, 1013 + 10 * 3); + // Opened again with what it holds (its first index, way past the list's length): the same + // window, not an empty one — said unchanged, or whole. + for _ in 0..3 { + let again = ask(&format!("/api/bots/{bot}?chat_sig={sig}&chat_delta=1&w0={start}")); + assert!(again["unchanged"] == true || again["messages"].as_array().is_some_and(|m| m.len() == PHONE_FIRST && m[0]["index"] == json!(start)), "{again}"); + } + // Something new: only that, onto the window it holds. + let mut more = list.clone(); + more.push(json!({"index": 1013 + 40 * 3, "text": "新的"})); + std::sync::Arc::make_mut(&mut *hub().view.lock().unwrap()).messages.insert(bot, more); + let delta = ask(&format!("/api/bots/{bot}?chat_sig={sig}&chat_delta=1&w0={start}")); + assert_eq!((delta["base"].as_str(), delta["from"].as_u64(), delta["messages"].as_array().map(Vec::len)), (Some(sig.as_str()), Some(PHONE_FIRST as u64), Some(1)), "{delta}"); + // 載入更早 from its first index: the messages just before it. + let older = ask(&format!("/api/bots/{bot}/older?from={start}&count=60")); + let o = older["messages"].as_array().unwrap(); + assert_eq!((o.len(), o[0]["index"].as_u64(), o[9]["index"].as_u64(), older["more"].as_bool()), (10, Some(1013), Some(start - 3), Some(false))); + // An index older than the list: all of it from the start. + assert_eq!(from_index(&list, 5), 0); + assert_eq!(from_index(&list, usize::MAX), list.len()); + std::sync::Arc::make_mut(&mut *hub().view.lock().unwrap()).messages.remove(&bot); + } + /// A message tried again on a bad network (the same id) reaches the bot once. #[test] fn a_message_tried_again_is_taken_once() {