`;
+ const atStart = S.olderEnd && S.olderEnd.bot === S.open && S.msgs.length && S.msgs[0].index <= S.olderEnd.at;
+ if (S.msgs.length && S.msgs[0].index > 0 && !atStart) h += ``;
// A message that arrived since the last draw slides up into place; the whole history on
// opening a chat draws plain (no animation on every old message).
// (Another conversation of the same bot — its first message differs — draws plain too.)
diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs
index 04901ce..f0679e8 100644
--- a/src/app/remote_ui.rs
+++ b/src/app/remote_ui.rs
@@ -493,70 +493,8 @@ impl App {
"line": if g.active() && self.goal_checking.contains(&b.id) { "目標 · 正在檢查有沒有達成…".to_string() } else { crate::goal::bar_text(g, crate::model::now_ms()) },
})),
}));
- let start = b.messages.len().saturating_sub(remote::PHONE_TAIL);
- // 交付確認: the ✓ marks go beside the chat, not inside the messages — a phone opening
- // an old chat reports every file it shows, and inside the messages that re-signed the
- // whole chat on every report (see remote::chat_for).
- let mut deliveries: Vec = vec![];
- // Each message with its place in the chat (表情回應), its thinking and, on each step,
- // what came back (the desktop's 顯示步驟 / 思考過程), in short.
- let results: HashMap<&str, &str> = b.messages[start..].iter().filter(|m| m.role == Role::Tool).map(|m| (m.tool_call_id.as_str(), m.text.as_str())).collect();
- // 頁面 cards: once a reply, under the step that saved the page last (over the whole chat,
- // so a reply cut by the tail still knows its later steps).
- let cards = crate::pages::cards_by_message(&b.messages);
- let msgs: Vec = b.messages[start..]
- .iter()
- .enumerate()
- .filter_map(|(k, m)| {
- let mut v = remote::message_json(m, &names, &self.state.pages, cards.get(start + k).map(Vec::as_slice).unwrap_or(&[]))?;
- if let Some(atts) = v["attachments"].as_array_mut() {
- for a in atts.iter_mut() {
- let Some(o) = a.as_object_mut() else { continue };
- let id = o.get("id").and_then(serde_json::Value::as_str).unwrap_or("").to_string();
- let (Some(d), has_seen) = (o.remove("delivery"), o.contains_key("seen")) else { continue };
- if id.is_empty() { continue; }
- let seen = if has_seen { o.remove("seen").unwrap_or(json!([])) } else { json!([]) };
- deliveries.push(json!({"id": id, "delivery": d, "seen": seen}));
- }
- }
- v["index"] = json!(start + k);
- // 支線: its record, for the card (and the report's label).
- if m.branch != 0 {
- if let Some(r) = b.branches.iter().find(|r| r.id == m.branch) {
- v["branch"] = json!({"id": r.id, "task": r.task, "state": r.state, "note": r.note, "doing": r.doing, "steps": r.steps, "log": r.log, "result": r.result});
- }
- }
- if !m.thinking.trim().is_empty() {
- v["thinking"] = json!(clip(m.thinking.trim(), 1500));
- }
- if let Some(tools) = v["tools"].as_array_mut() {
- for (t, c) in tools.iter_mut().zip(m.tool_calls.iter()) {
- if t["plan"].is_object() {
- let (state, live) = super::plan_ui::plan_card_state(b, c);
- t["plan"]["state"] = state;
- t["plan"]["live"] = live;
- continue;
- }
- if t.get("talk").is_some() {
- if let Some(r) = results.get(c.id.as_str()) {
- t["talk"]["answer"] = json!(clip(r.trim(), 2000));
- }
- continue;
- }
- if t.get("label").is_some() {
- t["name"] = json!(c.name);
- if let Some(r) = results.get(c.id.as_str()) {
- // (秘密遮罩: what a step printed may hold a key; the phone shows it masked.)
- // (Masked on a window a little past what is shown, not on the whole
- // output: a long command's output was scanned whole on every publish.)
- t["result"] = json!(clip(&crate::secrets::mask(&clip(r.trim(), 1200)), 600));
- }
- }
- }
- }
- Some(v)
- })
- .collect();
+ // (The newest PHONE_TAIL; 載入更早 asks for any stretch before it: phone_messages.)
+ let (msgs, deliveries) = self.phone_messages(b, &names, b.messages.len().saturating_sub(remote::PHONE_TAIL), b.messages.len());
view.messages.insert(b.id, msgs);
view.deliveries.insert(b.id, deliveries);
view.approvals.extend(self.phone_cards(b));
@@ -1324,6 +1262,49 @@ pub(super) fn remote_legs(relay: &str, brain_online: Option, brain: &str,
#[cfg(test)]
mod phone_tests {
+ use super::*;
+
+ /// 載入更早 walks back through the whole chat, not only the newest PHONE_TAIL the phone was
+ /// sent: from any place, the messages just before it (steps' results folded into their
+ /// steps, so a stretch of steps still gives `count` to show), and `more` until the start.
+ /// (A turn of 65 steps filled the newest 120 by itself; the button then did nothing: jenny-Host,
+ /// 2026-11-21.)
+ #[test]
+ fn loading_earlier_walks_the_whole_chat() {
+ let ctx = egui::Context::default();
+ let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-older.png")));
+ let id = app.state.bots[0].id;
+ {
+ let b = app.state.bot_mut(id).unwrap();
+ b.messages.clear();
+ b.messages.push(Message::user("開始"));
+ for i in 0..150 {
+ let call = crate::model::ToolCall { id: format!("c{i}"), name: "web_fetch".into(), args: format!(r#"{{"url":"https://example.com/{i}"}}"#), status: ToolStatus::Done };
+ b.messages.push(Message { tool_calls: vec![call], ..Message::assistant(&format!("第 {i} 步"), "") });
+ b.messages.push(Message::tool_result(&format!("c{i}"), "web_fetch", &format!("結果 {i}")));
+ }
+ }
+ let n = app.state.bot(id).unwrap().messages.len();
+ assert_eq!(n, 301);
+ // The phone holds the newest stretch; it asks for what is before index 241 (far past the
+ // newest 120's start, 181, and far before it too).
+ let ask = |app: &mut App, from: usize| app.phone_act(&ctx, "older", &json!({"bot": id, "from": from, "count": 60}), "owner");
+ let v = ask(&mut app, 181);
+ let msgs = v["messages"].as_array().unwrap();
+ assert_eq!(msgs.len(), 60, "{v}");
+ assert!(msgs.iter().all(|m| m["index"].as_u64().unwrap() < 181), "{v}");
+ assert_eq!(msgs.last().unwrap()["index"], json!(179));
+ assert_eq!(v["more"], json!(true));
+ // Each step shows with what it brought back.
+ assert!(msgs[0]["tools"][0]["result"].as_str().is_some_and(|r| r.starts_with("結果 ")), "{}", msgs[0]);
+ // Near the start: what is left, and no more.
+ let v = ask(&mut app, 9);
+ let msgs = v["messages"].as_array().unwrap();
+ assert_eq!((msgs.first().unwrap()["index"].as_u64(), msgs.last().unwrap()["index"].as_u64(), v["more"].as_bool()), (Some(0), Some(7), Some(false)), "{v}");
+ // A reader who isn't the owner may too (it only looks).
+ assert!(app.phone_act(&ctx, "older", &json!({"bot": id, "from": 50}), "admin").get("error").is_none());
+ }
+
#[test]
fn only_chat_models_are_offered() {
assert!(super::chats("grok-4.7") && super::chats("claude-opus-5-5") && super::chats("gpt-5-mini"));
@@ -1377,6 +1358,79 @@ fn clip(s: &str, n: usize) -> String {
}
impl App {
+ /// The phone's form of the messages `start..end` of this bot's chat — each with its place in
+ /// it, its thinking and what each step brought back, in short — and the ✓ marks of the files
+ /// among them. The published view is the newest PHONE_TAIL; 載入更早 (phone_act "older") asks
+ /// for the stretch before what the phone holds, from the whole chat.
+ fn phone_messages(&self, b: &Bot, names: &HashMap, start: usize, end: usize) -> (Vec, Vec) {
+ let end = end.min(b.messages.len());
+ let start = start.min(end);
+ // 交付確認: the ✓ marks go beside the chat, not inside the messages — a phone opening
+ // an old chat reports every file it shows, and inside the messages that re-signed the
+ // whole chat on every report (see remote::chat_for).
+ let mut deliveries: Vec = vec![];
+ // Each message with its place in the chat (表情回應), its thinking and, on each step,
+ // what came back (the desktop's 顯示步驟 / 思考過程), in short.
+ let results: HashMap<&str, &str> = b.messages[start..end].iter().filter(|m| m.role == Role::Tool).map(|m| (m.tool_call_id.as_str(), m.text.as_str())).collect();
+ // 頁面 cards: once a reply, under the step that saved the page last (over the whole chat,
+ // so a reply cut by the tail still knows its later steps).
+ let cards = crate::pages::cards_by_message(&b.messages);
+ let msgs: Vec = b.messages[start..end]
+ .iter()
+ .enumerate()
+ .filter_map(|(k, m)| {
+ let mut v = remote::message_json(m, names, &self.state.pages, cards.get(start + k).map(Vec::as_slice).unwrap_or(&[]))?;
+ if let Some(atts) = v["attachments"].as_array_mut() {
+ for a in atts.iter_mut() {
+ let Some(o) = a.as_object_mut() else { continue };
+ let id = o.get("id").and_then(serde_json::Value::as_str).unwrap_or("").to_string();
+ let (Some(d), has_seen) = (o.remove("delivery"), o.contains_key("seen")) else { continue };
+ if id.is_empty() { continue; }
+ let seen = if has_seen { o.remove("seen").unwrap_or(json!([])) } else { json!([]) };
+ deliveries.push(json!({"id": id, "delivery": d, "seen": seen}));
+ }
+ }
+ v["index"] = json!(start + k);
+ // 支線: its record, for the card (and the report's label).
+ if m.branch != 0 {
+ if let Some(r) = b.branches.iter().find(|r| r.id == m.branch) {
+ v["branch"] = json!({"id": r.id, "task": r.task, "state": r.state, "note": r.note, "doing": r.doing, "steps": r.steps, "log": r.log, "result": r.result});
+ }
+ }
+ if !m.thinking.trim().is_empty() {
+ v["thinking"] = json!(clip(m.thinking.trim(), 1500));
+ }
+ if let Some(tools) = v["tools"].as_array_mut() {
+ for (t, c) in tools.iter_mut().zip(m.tool_calls.iter()) {
+ if t["plan"].is_object() {
+ let (state, live) = super::plan_ui::plan_card_state(b, c);
+ t["plan"]["state"] = state;
+ t["plan"]["live"] = live;
+ continue;
+ }
+ if t.get("talk").is_some() {
+ if let Some(r) = results.get(c.id.as_str()) {
+ t["talk"]["answer"] = json!(clip(r.trim(), 2000));
+ }
+ continue;
+ }
+ if t.get("label").is_some() {
+ t["name"] = json!(c.name);
+ if let Some(r) = results.get(c.id.as_str()) {
+ // (秘密遮罩: what a step printed may hold a key; the phone shows it masked.)
+ // (Masked on a window a little past what is shown, not on the whole
+ // output: a long command's output was scanned whole on every publish.)
+ t["result"] = json!(clip(&crate::secrets::mask(&clip(r.trim(), 1200)), 600));
+ }
+ }
+ }
+ }
+ Some(v)
+ })
+ .collect();
+ (msgs, deliveries)
+ }
+
pub(super) fn phone_act(&mut self, ctx: &egui::Context, action: &str, b: &serde_json::Value, role: &str) -> serde_json::Value {
let owner = role == "owner";
let bot = b["bot"].as_u64().unwrap_or(0);
@@ -1391,7 +1445,7 @@ impl App {
// model and computer, a new chat, regenerate) plus looking and small chat things; making,
// changing or deleting bots, routines, memories, pages and settings stays the owner's.
let admin_ok = match action {
- "detail" | "settings" | "pages" | "search" | "export_bot" | "export_transcript" | "restart_bot" | "react" | "reply" | "resume" => true,
+ "detail" | "settings" | "pages" | "search" | "export_bot" | "export_transcript" | "restart_bot" | "react" | "reply" | "resume" | "older" => true,
"bot" => b["key"].as_str() == Some("unread"),
"box" => matches!(b["op"].as_str(), Some("wake" | "disk")),
_ => false,
@@ -1457,6 +1511,34 @@ impl App {
}
v
}
+ // 載入更早: the `count` (at most 120) messages before index `from`, from the whole chat
+ // (the published view holds only the newest PHONE_TAIL — the phone used to walk back
+ // through those alone, and the button then did nothing at all).
+ "older" => match self.state.bot(bot) {
+ Some(x) => {
+ let from = b["from"].as_u64().map(|f| f as usize).unwrap_or(x.messages.len()).min(x.messages.len());
+ let count = b["count"].as_u64().unwrap_or(60).clamp(1, 120) as usize;
+ let names: HashMap = self.state.bots.iter().map(|y| (y.id, y.name.clone())).collect();
+ // (Steps take room: walk back until `count` show, or the chat begins.)
+ let mut start = from.saturating_sub(count);
+ let (mut msgs, mut deliveries) = self.phone_messages(x, &names, start, from);
+ while msgs.len() < count && start > 0 {
+ let more_from = start;
+ start = start.saturating_sub(count);
+ let (m2, d2) = self.phone_messages(x, &names, start, more_from);
+ msgs.splice(0..0, m2);
+ deliveries.extend(d2);
+ }
+ // (The last stretch can bring more than asked: `count` at most, the rest next time.)
+ let mut more = start > 0;
+ if msgs.len() > count {
+ msgs.drain(..msgs.len() - count);
+ more = true;
+ }
+ json!({"bot": bot, "messages": msgs, "deliveries": deliveries, "more": more})
+ }
+ None => fail("找不到這個 Bot"),
+ },
"detail" => match self.state.bot(bot) {
Some(x) => self.phone_detail(x, owner),
None => fail("找不到這個 Bot"),
diff --git a/src/remote.rs b/src/remote.rs
index 1c8af81..378a18b 100644
--- a/src/remote.rs
+++ b/src/remote.rs
@@ -333,6 +333,10 @@ impl Hub {
pub fn version(&self) -> u64 {
self.view.lock().unwrap().version
}
+ /// An app is serving (it set its repaint at remote_start): asked things get answered.
+ fn has_app(&self) -> bool {
+ self.repaint.lock().unwrap().is_some()
+ }
pub fn take_cmds(&self) -> Vec {
std::mem::take(&mut *self.cmds.lock().unwrap())
}
@@ -804,20 +808,32 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
}
// 載入更早: the 60 (at most) messages before index `from` in this chat — a page opens on
// the newest `PHONE_FIRST` and walks back by asking here, so the first open stays small.
+ // (Asked of the app: the published view holds only the newest PHONE_TAIL, and walking back
+ // through that alone ran dry long before the chat began — the button then did nothing.)
("GET", ["api", "bots", id, "older"]) => {
let id: u64 = id.parse().unwrap_or(0);
- let from: usize = req.query.get("from").and_then(|v| v.parse().ok()).unwrap_or(usize::MAX);
- let count: usize = req.query.get("count").and_then(|v| v.parse().ok()).unwrap_or(60).clamp(1, 120);
- let v = hub().view.lock().unwrap();
- match v.messages.get(&id) {
- Some(m) => {
- let all = messages_for_role(m, &role);
- let arr = all.as_array().cloned().unwrap_or_default();
- let from = from_index(&arr, from);
- let start = from.saturating_sub(count);
- Resp::json(&json!({"bot": id, "messages": &arr[start..from], "more": start > 0}))
+ let from: u64 = req.query.get("from").and_then(|v| v.parse().ok()).unwrap_or(u64::MAX);
+ let count: u64 = req.query.get("count").and_then(|v| v.parse().ok()).unwrap_or(60).clamp(1, 120);
+ // (No app serving — a test of this server alone: the published list, as it was.)
+ if !hub().has_app() {
+ let v = hub().view.lock().unwrap();
+ let Some(m) = v.messages.get(&id) else { return Resp::error(404, "找不到這個 Bot") };
+ let arr = messages_for_role(m, &role).as_array().cloned().unwrap_or_default();
+ let from = from_index(&arr, from as usize);
+ let start = from.saturating_sub(count as usize);
+ return Resp::json(&json!({"bot": id, "messages": &arr[start..from], "more": start > 0}));
+ }
+ if !hub().view.lock().unwrap().messages.contains_key(&id) {
+ return Resp::error(404, "找不到這個 Bot");
+ }
+ match hub().ask_sync_for(SyncKind::Phone { action: "older".into(), body: json!({"bot": id, "from": from, "count": count}), role: role.clone() }, 20) {
+ Ok(v) if v.get("error").is_some() => Resp::error(400, v["error"].as_str().unwrap_or("做不到")),
+ Ok(mut v) => {
+ let msgs = v["messages"].as_array().cloned().unwrap_or_default();
+ v["messages"] = messages_for_role(&msgs, &role);
+ Resp::json(&v)
}
- None => Resp::error(404, "找不到這個 Bot"),
+ Err(e) => Resp::error(503, &e),
}
}
// What the desktop shows beside the chat and in 設定, made when asked (never keys, tokens