手機點進聊天一次有記錄、一次全空:手機說它那份從哪一則開始(w0,載入更早的 from)用的是那則在整段聊天裡的位置(index,數到 Bot 每個工具步驟),大腦卻當成「發布清單裡第幾則」——清單只是最新 PHONE_TAIL(120)則去掉工具步驟,短得多。有工具步驟的聊天就切到清單外,回一份空的;下一次手機手上沒東西、不帶 w0,又拿到整段——一次有一次空,一直交替(jenny-Host 11/21:1133 則的聊天、index 1105,清單 40 則左右)。11/20 7648c92「聊天分頁」帶進來的,Jenny 半夜升級正好升到它。假模型不叫工具(index 等於清單位置),所以 scratch 重現不出來,原本的測試 index 也是 0..100。

現在 from_index 把 index 換成清單裡第一則 ≥ 它的位置,三個地方都用:api/state 的開著的聊天、api/bots/<id>、api/bots/<id>/older。手機頁面不用改(舊頁面送的也是 index)。另外 httpd 那個測試拿掉「停下後埠可以再綁」那一行:整套測試一起跑時,別的測試會立刻拿走剛放掉的埠(第二次整套跑失敗過一次),要驗的是它停下來,那一行還在。FEATURES.md 補一行。

已驗證: cargo test 全綠(826,連跑兩次);新測試 a_chat_with_steps_comes_back_every_time(40 則、index 從 1013 起每則隔 3:打開拿最新 30、再拿三次都是同一個窗不會空、有新的一則只送那一則、載入更早從那則往前、index 太舊從頭)——把換算拿掉它會失敗;clippy 錯誤數跟之前一樣(12)。
未驗證: Jenny 的手機實機(大腦換新版之後請她點幾次)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm
This commit is contained in:
王性驊 2026-11-21 11:52:10 +08:00
parent 60e4e81f4f
commit 430d3f0367
3 changed files with 70 additions and 7 deletions

View File

@ -262,6 +262,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
- 手機打開聊天先只拿最新 30 條訊息(慢線上開頁省流量)。
- 有更早的,頂上出現「載入更早的對話」,點一次往前補 60 條;翻到最頂按鈕消失。
- 手機說它手上那份從哪一則開始(`w0`、載入更早的 `from`),用的是那則在整段聊天裡的位置(`index`,數到 Bot 每個工具步驟);大腦照這個位置找到清單裡對應的那則再開始。以前大腦把它當成「清單裡第幾則」——清單只是最新 120 則去掉工具步驟,短得多——有工具步驟的聊天就切到清單外、回一份空的,下一次手機手上沒東西、又拿到整段:點進去一次有聊天記錄、一次全空(jenny-Host 11/21,1133 則的聊天、清單 40 則左右)。
- Bot 回答中,手機每秒最多更新一次聊天(慢線上畫面落後約一秒);打完的整句一定補齊。
- 電腦開對話照樣整段;直接查聊底的指令和腳本也照舊拿全部。

View File

@ -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]

View File

@ -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::<usize>().ok())
.or(req.query.get("first").map(|_| n.saturating_sub(PHONE_FIRST)));
let w0 = match req.query.get("w0").and_then(|x| x.parse::<usize>().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<usize>) -> 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<Value> = (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() {