diff --git a/FEATURES.md b/FEATURES.md index ce314f3..277c92e 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -261,7 +261,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 開聊天分頁(手機頁面) - 手機打開聊天先只拿最新 30 條訊息(慢線上開頁省流量)。 -- 有更早的,頂上出現「載入更早的對話」,點一次往前補 60 條;翻到最頂按鈕消失。 +- 有更早的,頂上出現「載入更早的對話」,點一次往前補 60 條;翻到最頂說「已是對話最開頭」、按鈕消失。補的是大腦上整段聊天(App 自己組,跟發布的那份同一套:步驟帶結果、檔案的 ✓),不只發布給手機的最新 120 則——以前只在那 120 則裡往回找,有工具步驟的聊天(Jenny 一輪 65 步,120 則還裝不下這一輪)很快就找完,按鈕還在卻按了沒反應(拿到的都是手上已有的,頁面什麼也不說)。補的時候按鈕寫「載入中…」、不能連按,補完畫面停在原本看的地方;沒有 App 在跑時(只測伺服器)照舊從發布的那份找。 - 手機說它手上那份從哪一則開始(`w0`、載入更早的 `from`),用的是那則在整段聊天裡的位置(`index`,數到 Bot 每個工具步驟);大腦照這個位置找到清單裡對應的那則再開始。以前大腦把它當成「清單裡第幾則」——清單只是最新 120 則去掉工具步驟,短得多——有工具步驟的聊天就切到清單外、回一份空的,下一次手機手上沒東西、又拿到整段:點進去一次有聊天記錄、一次全空(jenny-Host 11/21,1133 則的聊天、清單 40 則左右)。 - Bot 回答中,手機每秒最多更新一次聊天(慢線上畫面落後約一秒);打完的整句一定補齊。 - 電腦開對話照樣整段;直接查聊底的指令和腳本也照舊拿全部。 diff --git a/docs/feature-map/chat.md b/docs/feature-map/chat.md index 2498561..887f999 100644 --- a/docs/feature-map/chat.md +++ b/docs/feature-map/chat.md @@ -6,16 +6,16 @@ - `chat-layout` 版面:左邊 Bot 清單(拖到比 210 px 窄收成頭像直欄),右邊聊天;點頂部 Bot 名稱開右側面板(「動態」「資料庫」)。 - `chat-input` 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」清單裡自動接下一項);↑ 找回上一則;草稿每個 Bot 各存一份;打字停一下,上方出現「帶入記憶」小卡片([memory](memory.md))。 -- `chat-commands` 打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [autonomy](autonomy.md))、/usage(最近一天和一週各 Bot 各模型的 token 用量,模型服務有回報才有)、/doctor(診斷,見 [garden](garden.md))、/context(模型可讀用量)、/compact(現在就把較早的整理成摘要)、/fork(分岔:這段對話到這裡存一份進「過去的對話」);打「@」列出其他 Bot。 +- `chat-commands` 打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [autonomy](autonomy.md))、/usage(最近一天、一週的 token 用量)、/doctor(診斷,見 [garden](garden.md))、/context(模型可讀用量)、/compact(現在就把較早的整理成摘要)、/fork(分岔:這段對話到這裡存一份進「過去的對話」);打「@」列出其他 Bot。 - `chat-steer` 插話:Bot 工作中照樣送出,不另開一輪,下一步就讀到(附檔一起進去);下方寫「已排入「…」」。剛好來不及讀的自動變成下一輪。 - `chat-stop` 停止:工作中、輸入框空著時,送出鈕變成「停止」。 - `chat-followthrough` 說了就做:回答說了要做什麼(「我把它整理成一頁」)卻沒動手,或問「要我現在就開始嗎?」,這一輪不停:上方閃過「說了要做還沒動手,提醒它接著做…」,它接著做。其實做完、或接下來要你決定(刪除、付款、寄出、斷線),就停在原來那句;連兩次沒動手就停。 - `chat-actions` 回答旁的操作:滑過 Bot 的回答出現「新增表情回應」「回覆」(引用這則)「更多訊息操作」;⋯ 裡有「複製」「重新產生」(只有最後一則)「還原上一個答案」「顯示步驟(N)」,最下面寫是哪個模型寫的。出錯的回答下面直接有「重試」。 - `chat-select` 選取一段文字(手機頁面和網頁版):按住一則訊息(或回答下的 ⋯)開訊息選單,「複製」是整則;「選取文字」把這則放進下方面板,在那裡按住開始選、拖兩端調整、按系統的「拷貝」(電腦上拖曳後按 ⌘C/Ctrl+C),「完成」關掉。用電腦的瀏覽器能在聊天裡拖曳選字;選好的字上右鍵(長按)是瀏覽器選單,別處右鍵才開訊息選單。 -- `chat-steps` 步驟和思考:預設收起。「顯示步驟」一行一個工具(等你允許/執行中/完成/被拒絕或停止/失敗),滑過那一行看結果;「思考過程」也在這裡。工作中,輸入框上方的臉旁邊寫它正在做什麼。臉和「正在…」最多每秒畫 20 次(CPU 畫圖 4 次);等決定時的黃點輕彈約 5 次。沒在動不重畫;你不在(視窗不在前、90 秒沒動)頭像不眨眼。 +- `chat-steps` 步驟和思考:預設收起。「顯示步驟」一行一個工具(等你允許/執行中/完成/被拒絕或停止/失敗),滑過那一行看結果;「思考過程」也在這裡。工作中,輸入框上方的臉旁邊寫它正在做什麼。臉和「正在…」最多每秒畫 20 次(CPU 畫圖 4 次),沒在動不重畫;你不在(視窗不在前、90 秒沒動)頭像不眨眼。 - `chat-attach` 附件:「附加檔案」、拖進視窗、⌘V 貼圖;每檔最多 50 MB,文字檔最多讀 20,000 字給模型。 -- `chat-compact` 長對話:舊步驟的長結果(連同長指令)累積到可讀長度 15% 就整批收起(聊天裡照樣完整);用到 6 成才寫可展開的「較早的對話已整理成摘要」。一個要求做很多步時也寫;摘要分段寫,模型寫不出來由 AnyBot 整理。 -- `chat-window` 開聊天分頁(手機頁面):打開給最新 30 條,頂上「載入更早的對話」點一次往前補 60 條,到最頂消失;回答中手機每秒最多更新一次,打完的整句補齊。電腦和聊底指令照舊拿整段。 +- `chat-compact` 長對話:舊步驟的長結果(連同長指令)累積到可讀長度 15% 就整批收起(聊天裡照樣完整);用到 6 成才寫可展開的「較早的對話已整理成摘要」。一個要求做很多步時也寫。 +- `chat-window` 開聊天分頁(手機頁面):打開給最新 30 條,頂上「載入更早的對話」點一次從大腦上整段聊天往前補 60 條,到最開頭說「已是對話最開頭」;回答中手機每秒最多更新一次,打完的整句補齊。電腦和聊底指令照舊拿整段。 - `chat-stall` 卡住偵測:送得多的請求等得久(120 秒起,最多 10 分鐘),等不到第一個字先收小對話再問,還不行才顯示「模型未能及時開始回應」;開始後靜 35 秒是「回應中斷…」。等你允許、工具在跑時不算。 ## 使用者怎麼到 @@ -43,10 +43,10 @@ - **附件**(covers `chat-attach`):「照片與檔案」是系統選檔,無頭 Chrome 選不了,改走同一個上傳 API。指令:`$CTL api POST /api/bots/1/send "{\"text\":\"看附件\",\"attachments\":[$($CTL api POST '/api/bots/1/upload?name=note.txt' '附件裡的字 ABC123' --jq .path)]}" && $CTL phone wait-text 'FAKE-MODEL 回答:看附件' --in '#msgs' && $CTL phone wait-text 'note.txt' --in '#msgs' && $CTL model 'select(.user | startswith("看附件")) | .user'`。看到:你的訊息下有 note.txt 的檔案卡;模型收到「[附件「note.txt」(22 B)…]」和檔案裡的字。 - **說了就做**(covers `chat-followthrough`):Bot 只說「我把它整理成一頁做法文件。」;被提醒後跑一個指令。指令:`$CTL model-reply 說了就做測試 '資料齊了,我把它整理成一頁做法文件。' && $CTL model-reply 什麼都還沒做 '[[call shell {"command":"echo ft-done"}]] 寫好了。' && $CTL phone send '說了就做測試' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.name == "shell")] | length >= 1' 30 && $CTL phone wait-text '整理成一頁做法文件' --in '#msgs' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' 30 && $CTL model 'select(.user | test("什麼都還沒做")) | .user[0:40]' && $CTL model-reply --clear`。看到:同一輪接著「執行指令 echo ft-done」;模型多收到「【AnyBot:你剛才說了…」。 - **整理、分岔、新對話**(covers `chat-compact`、`chat-commands`):送 /compact、/fork,再按 ✎。指令:`$CTL phone send '/compact' && $CTL phone wait-text '較早的對話已整理成摘要' --in '#msgs' && $CTL phone send '/fork' && $CTL phone wait-text '已分岔' --in '#msgs' && $CTL phone click '#b-newchat' && $CTL phone click '#sheet-in .opt' --text 開始新對話 && $CTL wait-api '/api/state?since=0' '.bots[0].threads | length == 2' && $CTL api GET '/api/state?since=0' --jq '[.bots[0].threads[].title]'`。看到:「已整理:較早的 N 則訊息換成一段摘要…」和摺起來的摘要;「已分岔:…」;新對話是空的,過去的對話有兩段。 -- **開聊天分頁**(covers `chat-window`):填 40 個來回後登出再登入(清cache),重開聊天。指令:`(for i in $(seq 1 40); do $CTL api POST /api/bots/1/send "{\"text\":\"填充$i\"}" >/dev/null || exit 1; done) && $CTL wait-api /api/bots/1 '.messages | length >= 80' 60 && $CTL phone click '#b-me' && $CTL phone click '[data-s="out"]' && $CTL phone click '#sheet-in .opt' --text 登出 && $CTL phone wait '#f-pass' && $CTL phone login && $CTL phone click '.row[data-bot="1"]' && $CTL phone wait '[data-older]' && $CTL phone click '[data-older]' && $CTL phone wait-text '填充1' --in '#msgs' && $CTL phone wait-gone '[data-older]'`。看到:打開從「填充51」起、按鈕在頂上;點一下補到最頂就消失。 +- **開聊天分頁**(covers `chat-window`):填 40 輪各一步(超過手機那份),重新登入、開聊天。指令:`for i in $(seq 1 40); do $CTL api POST /api/bots/1/send "{\"text\":\"填充$i [[call list_dir {}]]\"}" && $CTL wait-api /api/bots/1 "(.messages[-3].text|test(\"填充$i \")) and (.messages[-1].text|test(\"收到工具\"))" 60 || break; done >/dev/null && $CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 登出這支手機 && $CTL phone click '#sheet-in .opt' --text 登出 && $CTL phone wait '#f-pass' && $CTL phone login && $CTL phone wait '.row[data-bot="1"]' 30 && $CTL phone click '.row[data-bot="1"]' && $CTL phone click '[data-older]' && $CTL phone wait-text '填充11 ' --in '#msgs' && $CTL phone click '[data-older]' && $CTL phone wait-text '填充1 ' --in '#msgs' && $CTL phone wait-text 已是對話最開頭 && $CTL phone wait-gone '[data-older]'`。看到:打開從「填充31」起;第一下補到「填充11」,第二下補到「填充1」、「已是對話最開頭」、按鈕消失。 - **桌面**(covers `chat-layout`、`chat-input`、`chat-actions`、`chat-steps`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot chat-rail ANYBOT_SHOT_VIEW=rail ANYBOT_SHOT_PANEL=1`。看到:頭像直欄、右面板「動態」「資料庫」;回答上懸停三個按鈕、「顯示步驟」、Enter/Shift+Enter/↑、草稿靠自動測試。 - **卡住、重試、繼續**(covers `chat-stall`):指令:走不到——假模型立刻回答、不會出錯;`ctl` 只會正常關 AnyBot,「繼續」和「還沒有回覆」要它當掉。看到:最接近的真路是「停止」那一步(看門狗也是這樣結束一輪)。 -- 自動測試:`cargo test agent::`(含 `mid_turn_message_steers_the_same_turn`、`agent::followthrough::`、`an_announced_step_is_carried_out_without_the_person`、`a_nudge_answered_with_the_marker_shows_nothing_more`)、`cargo test app::chat_ui::`、`cargo test attach::`、`cargo test app::commands::`、`cargo test app::tests::`(含 `regenerate_keeps_a_stopped_turn_to_put_back`、`context_and_compact_from_the_chat`)、`cargo test remote::`(含 `a_chat_opens_on_a_small_window`、`a_delivery_word_does_not_resend_the_chat`)、`cargo test layout_audit::`(最窄的視窗裡允許卡片的按鈕會換行、「已排入…」和輸入框的提示不會被切掉)。 +- 自動測試:`cargo test agent::`(含 `mid_turn_message_steers_the_same_turn`、`agent::followthrough::`、`an_announced_step_is_carried_out_without_the_person`、`a_nudge_answered_with_the_marker_shows_nothing_more`)、`cargo test app::chat_ui::`、`cargo test attach::`、`cargo test app::commands::`、`cargo test app::tests::`(含 `regenerate_keeps_a_stopped_turn_to_put_back`、`context_and_compact_from_the_chat`)、`cargo test remote::`、`cargo test loading_earlier`、`cargo test layout_audit::`。 ## 陷阱 @@ -54,8 +54,7 @@ - Bot 工作中送出的是插話:不帶記憶小卡片;打「/」只剩 /btw。 - 「還原上一個答案」只有一層(還原後舊的在前),一傳下一則就沒了。 - 手機上按住訊息是開訊息選單,不是選字:選一段用選單的「選取文字」,整則用「複製」。 -- 步驟預設看不到:要確認 Bot 真的做了什麼,打開「顯示步驟」看每一步的狀態,不要只看它的回報。 -- 看不到圖的模型(「看圖小幫手」):截圖和附件改請帳號裡看得懂圖的模型描述成文字。Bot 用本機或區網的模型(Ollama、Tailscale 上的伺服器)時圖片預設不外送;要送雲端(如 Grok),在 設定 › 模型 › 那個供應商 打開「看不到圖時,請雲端模型看截圖和附件」。 +- 步驟預設看不到:要確認 Bot 做了什麼,打開「顯示步驟」看每一步,不要只看它的回報。 +- 看不到圖的模型(「看圖小幫手」):截圖和附件改請帳號裡看得懂圖的模型描述成文字。本機或區網的模型(Ollama、Tailscale 上的)圖片預設不外送;要送雲端,在 設定 › 模型 › 那個供應商 打開「看不到圖時,請雲端模型看截圖和附件」。 - (驗證)沒等小卡片就送出時,AnyBot 自己挑字詞相近的「做過的事」帶上,假模型不看〔…〕裡的字。 - (驗證)`wait-text` 連你自己傳的那句和舊訊息都算:等只有 Bot 這次才會說的字。 -- (驗證)無頭 Chrome 沒有手機的選取把手和「拷貝」:選一段用 `drag-select`(滑鼠拖);`rightclick`/`longpress` 只印 contextmenu 給了頁面還是瀏覽器;`copy`/`clipboard` 用無頭 Chrome 自己的剪貼簿。 diff --git a/mobile/index.html b/mobile/index.html index b4ed2c9..b7143a8 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1747,18 +1747,28 @@ async function loadChat(jump) { // 任務 → a message older than what the phone keeps of the chat: the chat stays at its end. else if (S.jumpAt && S.chatLoaded && S.open === id && !jumpTo()) { S.jumpAt = 0; toast("那件事開頭的訊息太早了,手機上只留最近的訊息"); } } -// 載入更早:開頁只拿最新 30 條,這裡一次往回補 60 條(序號去重,接在上方)。 +// 載入更早:開頁只拿最新 30 條,這裡一次往回補 60 條(序號去重,接在上方)——從大腦上整段聊天拿, +// 不只手機那份最新的。按了一定有回應:載入中、補上了、或「已是對話最開頭」(按鈕收起來)。 async function loadOlder() { - if (!S.open || !S.msgs.length || !(S.msgs[0].index > 0)) return; + if (!S.open || !S.msgs.length || !(S.msgs[0].index > 0) || S.olderBusy) return; + const id = S.open; + S.olderBusy = true; renderMsgs(); try { - const v = await api(base() + `api/bots/${S.open}/older?from=${S.msgs[0].index}&count=60`); - const id = S.open, have = new Set(S.msgs.map((m) => m.index)); + const v = await api(base() + `api/bots/${id}/older?from=${S.msgs[0].index}&count=60`); + if (S.open !== id) return; + const have = new Set(S.msgs.map((m) => m.index)); const add = (v.messages || []).filter((m) => !have.has(m.index)); - if (!add.length || S.open !== id) return; - S.msgs = add.concat(S.msgs); - renderMsgs(); + mergeDeliveries(add, v.deliveries); + if (!v.more) S.olderEnd = {bot: id, at: add.length ? add[0].index : S.msgs[0].index}; + if (add.length) { + const sc = $("scroller"), keep = sc.scrollHeight - sc.scrollTop; + S.msgs = add.concat(S.msgs); + S.olderBusy = false; renderMsgs(); + sc.scrollTop = sc.scrollHeight - keep; + } if (!v.more) toast("已是對話最開頭"); } catch (e) { toast(e.message); } + finally { if (S.olderBusy) { S.olderBusy = false; if (S.open === id) renderMsgs(); } } } // The state poll carried the open chat's messages along (single trip): take them as-is. function applyChat(msgs, sig, deliveries) { @@ -1987,7 +1997,8 @@ function renderMsgs() { const shown = {}; let day = ""; let h = ""; // 載入更早:開頁只有最新 30 條,這一鍵一次往回補 60 條。 - if (S.msgs.length && S.msgs[0].index > 0) h += `
`; + 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