手機變慢修復:聊天分頁、交付紀錄移出訊息、串流節流、指紋快取

- 手機開聊天先給最新 30 條(w0 視窗),頂上「載入更早的對話」每次往前補 60;新路由 api/bots/<id>/older;電腦與聊底指令照舊拿整段
- seen/交付紀錄從訊息 JSON 拆出,改用 deliveries 欄平行送達(不再因 seen 事件讓整條聊天 delta 失效重傳);手機 seen 精簡成 800ms 批量上報
- 串流中聊天 payload 每秒最多傳一次(CHAT_EVERY_MS),狀態回覆以 MIN_ANSWER_MS 合併喚醒
- 穩定 key 的指紋快取(FP_STABLE/fp_cache),串流期間每次喚醒不再重算 Bot 清單指紋
已驗證: cargo test 775 通過(layout_audit 為 HEAD 上既有失敗,與本次無關);node --check 手機 JS
未驗證: verify-anybot「開聊天分頁」步驟(需 $CTL 無頭環境實跑);實機慢線流量量測
This commit is contained in:
王性驊 2026-11-20 16:06:17 +08:00
parent 2d90e5decd
commit 7648c92aa4
6 changed files with 364 additions and 80 deletions

View File

@ -240,6 +240,13 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
- 舊對話被整理過時,會出現有框、可以展開的「📝 較早的對話已整理成摘要」。 - 舊對話被整理過時,會出現有框、可以展開的「📝 較早的對話已整理成摘要」。
### 開聊天分頁(手機頁面)
- 手機打開聊天先只拿最新 30 條訊息(慢線上開頁省流量)。
- 有更早的,頂上出現「載入更早的對話」,點一次往前補 60 條;翻到最頂按鈕消失。
- Bot 回答中,手機每秒最多更新一次聊天(慢線上畫面落後約一秒);打完的整句一定補齊。
- 電腦開對話照樣整段;直接查聊底的指令和腳本也照舊拿全部。
### 回覆下方的小按鈕 ### 回覆下方的小按鈕
- 只出現在 Bot 的最終回覆下面,不會夾在步驟中間。 - 只出現在 Bot 的最終回覆下面,不會夾在步驟中間。

View File

@ -1,59 +1,61 @@
# 聊天 # 聊天
跟一個 Bot 說話的地方:左邊選 Bot,右邊是它的聊天和輸入框。Bot 工作時可以插話、停止,回答可以重新產生;問題卡、生活卡片和表情見 [cards](cards.md)。 跟 Bot 說話的地方:左邊選 Bot,右邊是聊天和輸入框;工作時可插話、停止、重新產生;問題卡、生活卡片和表情見 [cards](cards.md)。
## 子功能 ## 子功能
- `chat-layout` 版面:左邊 Bot 清單(側邊欄拖到比 210 px 窄會收成頭像直欄),右邊聊天。點聊天頂部的 Bot 名稱(「查看對話詳細資訊」)打開右側面板,有「動態」「資料庫」兩頁。 - `chat-layout` 版面:左邊 Bot 清單(拖到比 210 px 窄收成頭像直欄),右邊聊天;點頂部 Bot 名稱開右側面板(「動態」「資料庫」)。
- `chat-input` 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打字停一下,輸入框上方出現「帶入記憶」一列小卡片([memory](memory.md))。 - `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(分岔:這段對話到這裡為止存一份到「過去的對話」,標題「分岔:…」,之後各走各的)、/rewind(退回:Bot 改的檔案和對話退回之前說的某一句,見 [files](files.md));打「@」列出其他 Bot。 - `chat-commands` 打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [autonomy](autonomy.md))、/usage(最近一天和一週各 Bot 各模型的 token 用量,模型服務有回報才有)、/doctor(診斷,見 [garden](garden.md))、/context(模型可讀用量)、/compact(現在就把較早的整理成摘要)、/fork(分岔:這段對話到這裡存一份進「過去的對話」);打「@」列出其他 Bot。
- `chat-steer` 插話:Bot 工作中照樣打字送出,不另開一輪,Bot 下一步就讀到(附檔一起進去);輸入框下方寫「已排入「…」,Bot 會在下一步看到」。這一輪剛好結束、來不及讀的,自動變成下一輪。 - `chat-steer` 插話:Bot 工作中照樣送出,不另開一輪,下一步就讀到(附檔一起進去);下方寫「已排入「…」」。剛好來不及讀的自動變成下一輪。
- `chat-stop` 停止:工作中、輸入框空著時,送出鈕變成「停止」。 - `chat-stop` 停止:工作中、輸入框空著時,送出鈕變成「停止」。
- `chat-followthrough` 說了就做:回答說了要做什麼(「我把它整理成一頁」「開始抓:」)卻沒動手,或問「要我現在就開始嗎?」,這一輪不停:上方閃過「說了要做還沒動手,提醒它接著做…」,它接著做,不用你回「繼續」。其實做完、或接下來要你決定(刪除、付款、寄出、斷線),就停在原來那句、不多一則;連兩次沒動手就停。 - `chat-followthrough` 說了就做:回答說了要做什麼(「我把它整理成一頁」)卻沒動手,或問「要我現在就開始嗎?」,這一輪不停:上方閃過「說了要做還沒動手,提醒它接著做…」,它接著做。其實做完、或接下來要你決定(刪除、付款、寄出、斷線),就停在原來那句;連兩次沒動手就停。
- `chat-actions` 回答旁的操作:滑過 Bot 的回答出現「新增表情回應」「回覆」(引用這則)「更多訊息操作」;⋯ 裡有「複製」「重新產生」(只有最後一則)「還原上一個答案」「顯示步驟(N)」,最下面寫是哪個模型寫的。出錯的回答下面直接有「重試」。 - `chat-actions` 回答旁的操作:滑過 Bot 的回答出現「新增表情回應」「回覆」(引用這則)「更多訊息操作」;⋯ 裡有「複製」「重新產生」(只有最後一則)「還原上一個答案」「顯示步驟(N)」,最下面寫是哪個模型寫的。出錯的回答下面直接有「重試」。
- `chat-select` 選取一段文字(手機頁面,和用電腦的瀏覽器打開的網頁版):按住一則訊息(或回答下的 ⋯)打開訊息選單,「複製」是整則;「選取文字」把這則放進下方的面板,在那裡按住一個字開始選、拖兩端調整、再按系統的「拷貝」(電腦上拖曳後按 ⌘C 或 Ctrl+C),「完成」關掉。用電腦的瀏覽器時也能直接在聊天裡拖曳選取:在選好的字上按右鍵是瀏覽器自己的選單(「複製」),在別的地方按右鍵才是訊息選單;按住選好的字也不開選單;連結上按右鍵(Android 是長按)是瀏覽器的連結選單。 - `chat-select` 選取一段文字(手機頁面和網頁版):按住一則訊息(或回答下的 ⋯)開訊息選單,「複製」是整則;「選取文字」把這則放進下方面板,在那裡按住開始選、拖兩端調整、按系統的「拷貝」(電腦上拖曳後按 ⌘C/Ctrl+C),「完成」關掉。用電腦的瀏覽器能在聊天裡拖曳選字;選好的字上右鍵(長按)是瀏覽器選單,別處右鍵才開訊息選單。
- `chat-steps` 步驟和思考:預設收起。「顯示步驟」一行一個工具(等你允許/執行中/完成/被拒絕或停止/失敗),滑過那一行看結果;「思考過程」也在這裡。工作中,輸入框上方的臉旁邊寫它正在做什麼。臉和「正在…」的閃光最多每秒畫 20 次;等你決定時黃點和輕彈還在,大約每秒 5 次。轉圈圖示也是。沒在動就不重畫;你不在(視窗不在前面或 90 秒沒動)頭像不眨眼。 - `chat-steps` 步驟和思考:預設收起。「顯示步驟」一行一個工具(等你允許/執行中/完成/被拒絕或停止/失敗),滑過那一行看結果;「思考過程」也在這裡。工作中,輸入框上方的臉旁邊寫它正在做什麼。臉和「正在…」最多每秒畫 20 次;等決定時的黃點輕彈約 5 次。沒在動不重畫;你不在(視窗不在前、90 秒沒動)頭像不眨眼。
- `chat-attach` 附件:「附加檔案」、拖進視窗、⌘V 貼圖。每個檔最多 50 MB,一個文字檔最多讀 20,000 字給模型。 - `chat-attach` 附件:「附加檔案」、拖進視窗、⌘V 貼圖;每檔最多 50 MB,文字檔最多讀 20,000 字給模型。
- `chat-compact` 長對話:舊步驟的長結果(連同長指令)累積到可讀長度的 15% 就整批收起(聊天裡照樣完整);用到 6 成才寫摘要,出現「較早的對話已整理成摘要」(「展開摘要」)。一個要求做很多步時也寫。摘要分段寫,模型寫不出來就由 AnyBot 整理。 - `chat-compact` 長對話:舊步驟的長結果(連同長指令)累積到可讀長度 15% 就整批收起(聊天裡照樣完整);用到 6 成才寫可展開的「較早的對話已整理成摘要」。一個要求做很多步時也寫;摘要分段寫,模型寫不出來由 AnyBot 整理。
- `chat-window` 開聊天分頁(手機頁面):打開給最新 30 條,頂上「載入更早的對話」點一次往前補 60 條,到最頂消失;回答中手機每秒最多更新一次,打完的整句補齊。電腦和聊底指令照舊拿整段。
- `chat-stall` 卡住偵測:送得多的請求等得久(120 秒起,最多 10 分鐘),等不到第一個字先收小對話再問,還不行才顯示「模型未能及時開始回應」;開始後靜 35 秒是「回應中斷…」。等你允許、工具在跑時不算。 - `chat-stall` 卡住偵測:送得多的請求等得久(120 秒起,最多 10 分鐘),等不到第一個字先收小對話再問,還不行才顯示「模型未能及時開始回應」;開始後靜 35 秒是「回應中斷…」。等你允許、工具在跑時不算。
## 使用者怎麼到 ## 使用者怎麼到
- 點側邊欄的 Bot;⌘1–⌘9 切到前九個。 - 點側邊欄的 Bot;⌘1–⌘9 切到前九個。
- 輸入框左邊的 +(「輸入框操作」):「附加檔案」「教它一項任務」,下面是換模型(見 [models](models.md))。右邊是「開始語音輸入」和送出鈕。 - 輸入框左邊的 +:「附加檔案」「教它一項任務」,下面是換模型(見 [models](models.md));右邊是語音輸入和送出鈕。
- Bot 選單(右鍵 Bot,或聊天右上角「更多」):「開始新對話」把目前的對話收進「過去的對話」;/fork 留一份分岔在那裡、目前的照常繼續,打開分岔時目前的會自動收進去;「清除聊天記錄」不會再問;「重新啟動這個 Bot」卡住時用,聊天記錄和檔案都保留。 - Bot 選單(右鍵 Bot,或聊天右上角「更多」):「開始新對話」把目前的收進「過去的對話」;/fork 留一份分岔,打開分岔時目前的自動收進去;「清除聊天記錄」不會再問;「重新啟動這個 Bot」卡住時用,記錄和檔案保留。
- 你的最後一則沒有回覆時,下面有「還沒有回覆」和「重新傳送」;被 AnyBot 關掉打斷的回合有「繼續」。 - 你的最後一則沒有回覆時,下面有「還沒有回覆」和「重新傳送」;被 AnyBot 關掉打斷的回合有「繼續」。
- 手機:同一個聊天,標題列有 ✎「開始新對話」和「更多」([phone](phone.md));按住一則訊息(或回答下的 ⋯)是訊息選單:表情、「複製」「選取文字」「引用回覆」…。 - 手機:標題列 ✎「開始新對話」和「更多」([phone](phone.md));按住一則訊息是訊息選單(表情、「複製」「選取文字」「引用回覆」…)。
## 怎麼操作(verify-anybot) ## 怎麼操作(verify-anybot)
- Bot:照常回答;要問使用者、放卡片或表情的工具見 [cards](cards.md)。 - Bot:照常回答;問使用者、卡片或表情的工具見 [cards](cards.md)。
前提: 前提:
- 基本前提和「手機已登入」(README),開著 Bot 1 的聊天:`$CTL phone click '.row[data-bot="1"]'`。 - 基本前提和「手機已登入」(README),開著 Bot 1 的聊天。
- **/ 指令**(covers `chat-commands`):打「/」,再送 /usage、/context。指令:`$CTL phone type '#input' '/' && $CTL phone wait-text '/rewind' --in '#slash' && $CTL phone shot chat-slash && $CTL phone send '/usage' && $CTL phone wait-text '還沒有用量紀錄' --in '#msgs' && $CTL phone send '/context' && $CTL phone wait-text '到 60% 會自動' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.note) | .text[0:24]]'`。看到:「指令和技能」列出上面那些;兩行 AnyBot 自己的話(note):「最近 7 天還沒有用量紀錄…」「這個對話…約 N token,fake-model 可讀 128000 token…」。 - **/ 指令**(covers `chat-commands`):打「/」,再送 /usage、/context。指令:`$CTL phone type '#input' '/' && $CTL phone wait-text '/rewind' --in '#slash' && $CTL phone send '/usage' && $CTL phone wait-text '還沒有用量紀錄' --in '#msgs' && $CTL phone send '/context' && $CTL phone wait-text '到 60% 會自動' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.note) | .text[0:24]]'`。看到:「指令和技能」列出上面那些;兩行 note:「最近 7 天還沒有用量紀錄…」「這個對話…約 N token,fake-model 可讀 128000 token…」。
- **插話**(covers `chat-steer`、`chat-steps`):Bot 跑 15 秒的指令時再傳一句。指令:`$CTL phone send '跑 [[call shell {"command":"sleep 15"}]]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == true' && $CTL phone send '順便說一聲' && $CTL phone wait-text '已排入:「順便說一聲」' --in '#queued' && $CTL phone shot chat-steer && $CTL phone wait-text 'FAKE-MODEL 回答:順便說一聲' --in '#msgs' 40 && $CTL model 'select(.user | startswith("順便說一聲")) | {kind, last_role}'`。看到:「已排入:「順便說一聲」,驗證小幫手 會在下一步看到」、步驟「執行指令 sleep 15」;指令跑完,同一輪的下一步模型就讀到那句。 - **插話**(covers `chat-steer`、`chat-steps`):Bot 跑 15 秒的指令時再傳一句。指令:`$CTL phone send '跑 [[call shell {"command":"sleep 15"}]]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == true' && $CTL phone send '順便說一聲' && $CTL phone wait-text '已排入:「順便說一聲」' --in '#queued' && $CTL phone wait-text 'FAKE-MODEL 回答:順便說一聲' --in '#msgs' 40 && $CTL model 'select(.user | startswith("順便說一聲")) | {kind, last_role}'`。看到:「已排入:「順便說一聲」…下一步看到」、步驟「執行指令 sleep 15」;跑完同一輪下一步模型讀到那句。
- **停止**(covers `chat-stop`、`chat-steps`):跑 30 秒的指令,輸入框空著按送出鈕。指令:`$CTL phone send '再跑 [[call shell {"command":"sleep 30"}]]' && $CTL phone wait '#b-send[title="停止"]' && $CTL phone click '#b-send' && $CTL phone wait '#b-send[title="傳送訊息"]' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "shell") | .status]'`。看到:送出鈕變回來、Bot 不再動作;兩個指令步驟是 done、denied(被停止)。 - **停止**(covers `chat-stop`、`chat-steps`):跑 30 秒的指令,輸入框空著按送出鈕。指令:`$CTL phone send '再跑 [[call shell {"command":"sleep 30"}]]' && $CTL phone wait '#b-send[title="停止"]' && $CTL phone click '#b-send' && $CTL phone wait '#b-send[title="傳送訊息"]' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "shell") | .status]'`。看到:送出鈕變回來、Bot 不再動作;兩個指令步驟 done、denied。
- **重新產生、還原**(covers `chat-actions`):重新產生最後一個回答,再從 ⋯ 還原。指令:`$CTL phone send '重產測試' && $CTL phone wait-text 'FAKE-MODEL 回答:重產測試' --in '#msgs' && $CTL model-reply 重產測試 第二個答案 && $CTL phone click '[data-regen]' && $CTL phone wait-text '第二個答案' --in '#msgs' && $CTL phone click '.meta:has([data-regen]) [data-more]' && $CTL phone click '#sheet-in .opt' --text 還原上一個答案 && $CTL wait-api /api/bots/1 '[.messages[-2:][] | .text] == ["FAKE-MODEL 回答:重產測試", "第二個答案"]' && $CTL model-reply --clear`。看到:新答案換掉舊的;⋯ 有「複製」「選取文字」「引用回覆」「重新產生這個回答」「還原上一個答案」和表情;還原後舊答案回到新答案前面(兩個都在)。 - **重新產生、還原**(covers `chat-actions`):重新產生最後一個回答,再從 ⋯ 還原。指令:`$CTL phone send '重產測試' && $CTL phone wait-text 'FAKE-MODEL 回答:重產測試' --in '#msgs' && $CTL model-reply 重產測試 第二個答案 && $CTL phone click '[data-regen]' && $CTL phone wait-text '第二個答案' --in '#msgs' && $CTL phone click '.meta:has([data-regen]) [data-more]' && $CTL phone click '#sheet-in .opt' --text 還原上一個答案 && $CTL wait-api /api/bots/1 '[.messages[-2:][] | .text] == ["FAKE-MODEL 回答:重產測試", "第二個答案"]' && $CTL model-reply --clear`。看到:新答案換掉舊的;⋯ 有「複製」「選取文字」「引用回覆」「重新產生」「還原上一個答案」和表情;還原後舊在新前。
- **選取一段文字**(covers `chat-select`):按住一則回答 ›「選取文字」,在面板裡拖出「乙丙丁」、按 ⌘C,再按「完成」。指令:`$CTL phone send '選字測試 甲乙丙丁戊' && $CTL phone wait-text 'FAKE-MODEL 回答:選字測試 甲乙丙丁戊' --in '#msgs' && $CTL phone longpress '.m.bot .bub' --text '回答:選字測試' && $CTL phone wait-text 選取文字 --in '#sheet-in' && $CTL phone shot chat-select-menu && $CTL phone click '#sheet-in .opt' --text 選取文字 && $CTL phone drag-select '#sheet-in .seltext' 乙丙丁 && $CTL phone selection 乙丙丁 && $CTL phone shot chat-select && $CTL phone copy && $CTL phone clipboard 乙丙丁 && $CTL phone click '#sheet-in .opt' --text 完成 && $CTL phone wait-gone '#sheet-in .seltext'`。看到:選單是表情、「複製」「選取文字」「引用回覆」「重新產生這個回答」;面板標題「選取文字」、一行說明和這則回答;只有「乙丙丁」反白,⌘C 後剪貼簿就是「乙丙丁」;「完成」關掉面板。 - **選取一段文字**(covers `chat-select`):按住一則回答 ›「選取文字」,在面板裡拖出「乙丙丁」、按 ⌘C,再按「完成」。指令:`$CTL phone send '選字測試 甲乙丙丁戊' && $CTL phone wait-text 'FAKE-MODEL 回答:選字測試 甲乙丙丁戊' --in '#msgs' && $CTL phone longpress '.m.bot .bub' --text '回答:選字測試' && $CTL phone wait-text 選取文字 --in '#sheet-in' && $CTL phone click '#sheet-in .opt' --text 選取文字 && $CTL phone drag-select '#sheet-in .seltext' 乙丙丁 && $CTL phone selection 乙丙丁 && $CTL phone copy && $CTL phone clipboard 乙丙丁 && $CTL phone click '#sheet-in .opt' --text 完成 && $CTL phone wait-gone '#sheet-in .seltext'`。看到:選單是表情、「複製」「選取文字」「引用回覆」「重新產生」;只有「乙丙丁」反白,⌘C 後剪貼簿是「乙丙丁」;「完成」關掉。
- **電腦瀏覽器的選取和右鍵**(covers `chat-select`、`chat-actions`):在聊天裡拖曳選取「乙丙丁」,在選好的字上按右鍵、再按住它;點「今天」取消選取,在回答上按右鍵 ›「複製」。指令:`$CTL phone drag-select '.m.bot .bub' 乙丙丁 && $CTL phone rightclick --selected && $CTL phone longpress --selected && $CTL phone wait-gone '#sheet-in .opt' && $CTL phone selection 乙丙丁 && $CTL phone shot chat-select-native && $CTL phone click '.dsep' && $CTL phone selection '' && $CTL phone rightclick '.m.bot .bub' --text 乙丙丁 && $CTL phone wait-text 選取文字 --in '#sheet-in' && $CTL phone selection '' && $CTL phone click '#sheet-in .opt' --text 複製 && $CTL phone wait-text 已複製 --in '#toast' && $CTL phone clipboard 'FAKE-MODEL 回答:選字測試 甲乙丙丁戊'`。看到:在選好的字上右鍵、按住都印「頁面沒攔」(瀏覽器自己的選單,有「複製」),沒有訊息選單,「乙丙丁」還選著;沒選字時右鍵印「頁面攔下」、打開訊息選單,沒有留下反白;「複製」跳「已複製」,剪貼簿是整則回答。 - **電腦瀏覽器的選取和右鍵**(covers `chat-select`、`chat-actions`):拖曳選「乙丙丁」,選好的字上右鍵、長按;回答上右鍵 ›「複製」。指令:`$CTL phone drag-select '.m.bot .bub' 乙丙丁 && $CTL phone rightclick --selected && $CTL phone longpress --selected && $CTL phone wait-gone '#sheet-in .opt' && $CTL phone selection 乙丙丁 && $CTL phone shot chat-select-native && $CTL phone click '.dsep' && $CTL phone selection '' && $CTL phone rightclick '.m.bot .bub' --text 乙丙丁 && $CTL phone wait-text 選取文字 --in '#sheet-in' && $CTL phone selection '' && $CTL phone click '#sheet-in .opt' --text 複製 && $CTL phone wait-text 已複製 --in '#toast' && $CTL phone clipboard 'FAKE-MODEL 回答:選字測試 甲乙丙丁戊'`。看到:選好的字上右鍵、長按都印「頁面沒攔」(瀏覽器選單)、沒訊息選單、選字還在;沒選字時右鍵開訊息選單;「複製」後剪貼簿是整則回答。
- **附件**(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-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-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-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-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-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-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,「繼續」和「還沒有回覆」要它當掉。看到:最接近的真路是「停止」那一步(看門狗也是這樣結束一輪)。 - **卡住、重試、繼續**(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 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::`(含 `a_chat_opens_on_a_small_window`、`a_delivery_word_does_not_resend_the_chat`)、`cargo test layout_audit::`(最窄的視窗裡允許卡片的按鈕會換行、「已排入…」和輸入框的提示不會被切掉)。
## 陷阱 ## 陷阱
- 按停止時,還沒被 Bot 讀到的插話會被丟掉,要再傳一次。 - 按停止時,還沒被 Bot 讀到的插話會被丟掉,要再傳一次。
- Bot 工作中送出的是插話:不帶記憶小卡片;打「/」只剩 /btw。 - Bot 工作中送出的是插話:不帶記憶小卡片;打「/」只剩 /btw。
- 「還原上一個答案」只有一層(還原後兩個答案都在,舊的在前),你一傳下一則就沒了。 - 「還原上一個答案」只有一層(還原後舊的在前),一傳下一則就沒了。
- 手機上按住訊息是打開訊息選單,不是選字:只要其中一段時,用選單的「選取文字」,在面板裡選;整則用「複製」。 - 手機上按住訊息是開訊息選單,不是選字:選一段用選單的「選取文字」,整則用「複製」。
- 步驟預設看不到:要確認 Bot 真的做了什麼,打開「顯示步驟」看每一步的狀態和結果,不要只看它的回報。 - 步驟預設看不到:要確認 Bot 真的做了什麼,打開「顯示步驟」看每一步的狀態,不要只看它的回報。
- 模型看不到圖(「看圖小幫手」):截圖和附件改請帳號裡看得懂圖的模型描述成文字。Bot 用的是本機或區網的模型(Ollama、這個網路或 Tailscale 上的伺服器)時,圖片預設不送出去,只找同樣在本機的;要送給雲端模型(例如 Grok),在 設定 › 模型 › 那個供應商 打開「看不到圖時,請雲端模型看截圖和附件」。沒有幫手時 Bot 只拿到「看不到圖片」的說明,只能用編號清單和文字做。 - 看不到圖的模型(「看圖小幫手」):截圖和附件改請帳號裡看得懂圖的模型描述成文字。Bot 用本機或區網的模型(Ollama、Tailscale 上的伺服器)時圖片預設不外送;要送雲端(如 Grok),在 設定 › 模型 › 那個供應商 打開「看不到圖時,請雲端模型看截圖和附件」。
- (驗證)沒等小卡片就送出時,AnyBot 自己挑字詞相近的「做過的事」帶上(「工具」就對得上「收到工具結果」),假模型不看〔…〕裡的字。 - (驗證)沒等小卡片就送出時,AnyBot 自己挑字詞相近的「做過的事」帶上,假模型不看〔…〕裡的字。
- (驗證)`wait-text` 連你自己傳的那句和舊訊息都算:等只有 Bot 這次才會說的字。 - (驗證)`wait-text` 連你自己傳的那句和舊訊息都算:等只有 Bot 這次才會說的字。
- (驗證)無頭 Chrome 沒有手機的選取把手和「拷貝」:手指按住面板裡的字不會選字,選一段用 `drag-select`(滑鼠拖);`rightclick`/`longpress` 只印出 contextmenu 給了頁面還是瀏覽器,瀏覽器自己的選單不畫出來;`copy`/`clipboard` 用無頭 Chrome 自己的剪貼簿,不碰這台 Mac 的。 - (驗證)無頭 Chrome 沒有手機的選取把手和「拷貝」:選一段用 `drag-select`(滑鼠拖);`rightclick`/`longpress` 只印 contextmenu 給了頁面還是瀏覽器;`copy`/`clipboard` 用無頭 Chrome 自己的剪貼簿。

View File

@ -9,7 +9,7 @@
- `phone-look` 長相(和電腦版同一份設計規格:字級、間距、圓角都是同一組數字):Bot 的回答不放在泡泡裡,像文件一樣直接排在畫面上,用宋體(思源宋體,沒有就用系統的宋體)、16px、行距寬;裡面的表格只有橫向細線、數字欄靠右,提示框([!NOTE] 等)同一種淡底、只有圖示依種類上色,程式碼是淡底圓角塊。你自己的訊息(泡泡)和所有按鈕、清單、設定用黑體。手機沒有字型選項。 - `phone-look` 長相(和電腦版同一份設計規格:字級、間距、圓角都是同一組數字):Bot 的回答不放在泡泡裡,像文件一樣直接排在畫面上,用宋體(思源宋體,沒有就用系統的宋體)、16px、行距寬;裡面的表格只有橫向細線、數字欄靠右,提示框([!NOTE] 等)同一種淡底、只有圖示依種類上色,程式碼是淡底圓角塊。你自己的訊息(泡泡)和所有按鈕、清單、設定用黑體。手機沒有字型選項。
- `phone-colors` 顏色跟電腦版一樣:電腦上 設定 › 一般 › 外觀 的主題(淺色/深色/跟隨系統)、底色、強調色、對比,手機照著穿;手機自己的「外觀」可以選「跟著電腦」(預設)、「跟著手機」、「淺色」、「深色」。狀態列的顏色跟著畫面。舊版的電腦沒送顏色時,手機用內建的「紙」。 - `phone-colors` 顏色跟電腦版一樣:電腦上 設定 › 一般 › 外觀 的主題(淺色/深色/跟隨系統)、底色、強調色、對比,手機照著穿;手機自己的「外觀」可以選「跟著電腦」(預設)、「跟著手機」、「淺色」、「深色」。狀態列的顏色跟著畫面。舊版的電腦沒送顏色時,手機用內建的「紙」。
- `phone-claude` 像 Claude 的手機 App:上面一條簡單的標題列(Bot 名稱,第二行是它在做什麼或用哪個模型),輸入框是底部一張圓角卡片,回答下面只有時間和複製/重新產生/⋯;按鈕和點的地方至少 44px;清單每列的說明只有一行(太長以 … 結尾);顏色少,強調色只用在連結、選取和新訊息的點。 - `phone-claude` 像 Claude 的手機 App:上面一條簡單的標題列(Bot 名稱,第二行是它在做什麼或用哪個模型),輸入框是底部一張圓角卡片,回答下面只有時間和複製/重新產生/⋯;按鈕和點的地方至少 44px;清單每列的說明只有一行(太長以 … 結尾);顏色少,強調色只用在連結、選取和新訊息的點。
- `phone-net` 網路慢或斷線都不擋操作:存過這台電腦的資料,打開 App 就用上次的內容進去,不等網路,連上後只補變了的;浮著提示「離線中:顯示的是上次的內容」,拿到就消失。只有第一次(還沒有這台的資料)停在連線畫面:打開 App 時的頭像留在正中間呼吸、外圈漾開,不顯示文字(讀螢幕軟體唸「正在連線」;減少動態時不動),第一份狀態到手才進去。用帳號連、那台不在線上時留在它上次的內容裡,不換到別台。進去之後斷線:浮「連線中斷,正在重新連線…」,自己重試,回到前景或網路恢復時立刻重連。設定、詳細資料、例行任務、頁面先畫手上有的,背景再讀新的;要改的先讀到最新的。傳訊息不等網路:按下就出現在聊天裡;連不上標「等連線後送出(點一下拿回來)」,存在手機上排隊(關掉 App 也還在),連上後照順序自己送、不限時間,同一則只送到一次;點一下連同附件拿回輸入框;連不上時選的附件也跟著排隊。大腦拒收的才標「沒送出,點一下拿回來重送」。從通知打開時按的允許/拒絕等連上才送。只傳有變的部分、文字壓縮。頁面和圖示存在手機上:打開時直接用,背景問一次換版沒;換了,還在連線畫面就重新載入(通知帶來的聊天和回答照樣用上),已經進去就等 App 退到背景、手上沒東西(沒打字、附件、排隊的訊息、錄音、選單)才換;重新整理一定先問伺服器。上次的狀態、看過的聊天(合計最多 12 個)、詳細資料、設定、排隊的訊息每台電腦各自存在這個網址的儲存空間,登出(或登入失效)全部清掉。 - `phone-net` 網路慢或斷線都不擋操作:存過這台電腦的資料,打開 App 就用上次的內容進去,不等網路,連上後只補變了的;浮著提示「離線中:顯示的是上次的內容」,拿到就消失。只有第一次(還沒有這台的資料)停在連線畫面:打開 App 時的頭像留在正中間呼吸、外圈漾開,不顯示文字(讀螢幕軟體唸「正在連線」;減少動態時不動),第一份狀態到手才進去。用帳號連、那台不在線上時留在它上次的內容裡,不換到別台。進去之後斷線:浮「連線中斷,正在重新連線…」,自己重試,回到前景或網路恢復時立刻重連。設定、詳細、例行任務先畫手上有的,背景讀新的;要改的先讀到最新的。傳訊息不等網路:按下就出現在聊天裡;連不上標「等連線後送出(點一下拿回來)」,存手機排隊(關 App 也還在),連上後照順序自己送、不限時間,同一則只送一次;點一下連同附件拿回輸入框;連不上時選的附件也排隊。大腦拒收的才標「沒送出,點一下拿回來重送」。從通知打開時按的允許/拒絕等連上才送。只傳有變的部分、文字壓縮;Bot 回答中手機每秒最多更新一次聊天(見 [chat](chat.md) 的開聊天分頁)。頁面和圖示存在手機上:打開直接用,背景問一次換版沒;換了,還在連線畫面就重新載入,已進去就等退到背景、手上沒東西(沒打字、附件、排隊、錄音、選單)才換;重新整理一定先問伺服器。上次的狀態、看過的聊天(合計最多 12 個)、詳細資料、設定、排隊的訊息每台電腦各自存在這個網址的儲存空間,登出(或登入失效)全部清掉。
- `phone-app` 像 App 一樣:加入主畫面後全螢幕、沒有網址列(瀏海、動態島、底部手勢條、橫放都避開);首頁會提示「把 AnyBot 裝成 App」(Android 直接安裝,iPhone 教你加入主畫面,可以關掉);換畫面會左右滑動;iPhone 主畫面 App 從左邊緣往右滑回上一頁。 - `phone-app` 像 App 一樣:加入主畫面後全螢幕、沒有網址列(瀏海、動態島、底部手勢條、橫放都避開);首頁會提示「把 AnyBot 裝成 App」(Android 直接安裝,iPhone 教你加入主畫面,可以關掉);換畫面會左右滑動;iPhone 主畫面 App 從左邊緣往右滑回上一頁。
## 使用者怎麼到 ## 使用者怎麼到

View File

@ -1327,7 +1327,10 @@ async function loadOut() {
if (OUT.length) flush(); if (OUT.length) flush();
} }
function statePath() { function statePath() {
const open = S.open && (S.view === "chat" || !S.entered) ? "&bot=" + S.open + "&chat_sig=" + encodeURIComponent(S.chatSig) + "&chat_delta=1" : ""; // 視窗起點:分頁後這條持有從哪條訊息起,服務端從那裡算 diff(開頁只拿最新 30 條;
// 已翻到最頂時 w0=0,持有整串)。
const win = S.msgs.length && S.msgs[0].index >= 0 ? "&w0=" + S.msgs[0].index : "";
const open = S.open && (S.view === "chat" || !S.entered) ? "&bot=" + S.open + "&chat_sig=" + encodeURIComponent(S.chatSig) + "&chat_delta=1" + win : "";
const held = S.st && S.ssig ? "&ssig=" + encodeURIComponent(S.ssig) : ""; const held = S.st && S.ssig ? "&ssig=" + encodeURIComponent(S.ssig) : "";
return base() + "api/state?since=" + S.version + "&tz=" + encodeURIComponent(TZ) + held + open; return base() + "api/state?since=" + S.version + "&tz=" + encodeURIComponent(TZ) + held + open;
} }
@ -1378,7 +1381,7 @@ function apply(v) {
// we go in) but don't draw the inside yet. // we go in) but don't draw the inside yet.
if (!S.entered) { if (!S.entered) {
const c = v.chat; const c = v.chat;
if (c && c.bot === S.open && c.messages && c.from === undefined) { S.msgs = c.messages; S.chatSig = c.sig || ""; } if (c && c.bot === S.open && c.messages && c.from === undefined) { S.msgs = c.messages; S.chatSig = c.sig || ""; mergeDeliveries(S.msgs, c.deliveries); }
return; return;
} }
// An approval answered from a notification banner, and a home-screen shortcut (主要 Bot, 未讀). // An approval answered from a notification banner, and a home-screen shortcut (主要 Bot, 未讀).
@ -1398,11 +1401,14 @@ function apply(v) {
chatHead(); renderDock(); chatHead(); renderDock();
const c = v.chat; const c = v.chat;
// (A poll that left before the person switched chats carries the old chat: ignore it.) // (A poll that left before the person switched chats carries the old chat: ignore it.)
if (c && c.bot === S.open && c.unchanged) { /* the chat did not change — nothing to draw */ } // 串流降頻:開著聊天時服務端每秒最多重發一次聊天(最小的差量是一整條訊息),被擋時過一秒再問。
if (c && c.bot === S.open && c.throttled) chatLater();
// 交付確認不在訊息裡:只有 ✓ mark 動了,蓋上新的就好,不重畫整串。
else if (c && c.bot === S.open && c.unchanged) { if (mergeDeliveries(S.msgs, c.deliveries)) renderMsgs(); }
// Only where it differs from what this page holds: drop the first few (the oldest left the // Only where it differs from what this page holds: drop the first few (the oldest left the
// window), keep the next `from`, then the new ones. Told against another list: all of it again. // window), keep the next `from`, then the new ones. Told against another list: all of it again.
else if (c && c.bot === S.open && c.messages && c.from !== undefined) { if (c.base === S.chatSig) applyChat(S.msgs.slice(c.drop || 0).slice(0, c.from).concat(c.messages), c.sig); else loadChat(); } else if (c && c.bot === S.open && c.messages && c.from !== undefined) { if (c.base === S.chatSig) applyChat(S.msgs.slice(c.drop || 0).slice(0, c.from).concat(c.messages), c.sig, c.deliveries); else loadChat(); }
else if (c && c.bot === S.open && c.messages) applyChat(c.messages, c.sig); else if (c && c.bot === S.open && c.messages) applyChat(c.messages, c.sig, c.deliveries);
else loadChat(); else loadChat();
} }
else if (t.v === "details" && S.tab !== "memory" && Date.now() - (S.detailAt || 0) > 1500) renderDetails(t.arg.bot, S.tab, isNew(t.arg.bot)); else if (t.v === "details" && S.tab !== "memory" && Date.now() - (S.detailAt || 0) > 1500) renderDetails(t.arg.bot, S.tab, isNew(t.arg.bot));
@ -1679,13 +1685,18 @@ async function loadChat(jump) {
loading = true; loading = true;
const id = S.open, held = S.chatSig, host = S.host; const id = S.open, held = S.chatSig, host = S.host;
try { try {
// Only what changed since the copy this page holds (an older brain sends all of it). // Only what changed since the copy this page holds (an older brain sends all of it), from the
const v = await api(base() + "api/bots/" + id + (held ? "?chat_sig=" + encodeURIComponent(held) + "&chat_delta=1" : "")); // window it holds (w0: 分頁後從最早那條的序號起)。
const w0 = S.msgs.length && S.msgs[0].index >= 0 ? (held ? "&" : "?") + "w0=" + S.msgs[0].index : "";
const v = await api(base() + "api/bots/" + id + (held ? "?chat_sig=" + encodeURIComponent(held) + "&chat_delta=1" + w0 : "?first=1"));
// 只有交付確認動了:蓋上新的,不重抓。
if (v.unchanged && S.open === id && S.host === host) { if (mergeDeliveries(S.msgs, v.deliveries)) renderMsgs(); return; }
// (Another chat opened meanwhile, or the poll already brought a newer copy: not this answer.) // (Another chat opened meanwhile, or the poll already brought a newer copy: not this answer.)
if (S.open === id && S.chatSig === held && S.host === host && !v.unchanged) { if (S.open === id && S.chatSig === held && S.host === host) {
const msgs = v.from === undefined ? v.messages || [] : v.base === held ? S.msgs.slice(v.drop || 0).slice(0, v.from).concat(v.messages || []) : null; const msgs = v.from === undefined ? v.messages || [] : v.base === held ? S.msgs.slice(v.drop || 0).slice(0, v.from).concat(v.messages || []) : null;
if (msgs) { if (msgs) {
const sc = $("scroller"); const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140; const sc = $("scroller"); const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140;
mergeDeliveries(msgs, v.deliveries);
S.msgs = msgs; S.chatSig = v.sig || ""; S.chatLoaded = true; renderMsgs(); keepSoon(); S.msgs = msgs; S.chatSig = v.sig || ""; S.chatLoaded = true; renderMsgs(); keepSoon();
if (jump || near) sc.scrollTop = sc.scrollHeight; if (jump || near) sc.scrollTop = sc.scrollHeight;
} else { S.chatSig = ""; again = true; } } else { S.chatSig = ""; again = true; }
@ -1694,15 +1705,45 @@ async function loadChat(jump) {
loading = false; loading = false;
if (again) { again = false; loadChat(); } if (again) { again = false; loadChat(); }
} }
// 載入更早:開頁只拿最新 30 條,這裡一次往回補 60 條(序號去重,接在上方)。
async function loadOlder() {
if (!S.open || !S.msgs.length || !(S.msgs[0].index > 0)) return;
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 add = (v.messages || []).filter((m) => !have.has(m.index));
if (!add.length || S.open !== id) return;
S.msgs = add.concat(S.msgs);
renderMsgs();
if (!v.more) toast("已是對話最開頭");
} catch (e) { toast(e.message); }
}
// The state poll carried the open chat's messages along (single trip): take them as-is. // The state poll carried the open chat's messages along (single trip): take them as-is.
function applyChat(msgs, sig) { function applyChat(msgs, sig, deliveries) {
S.chatSig = sig || ""; S.chatLoaded = true; S.chatSig = sig || ""; S.chatLoaded = true;
const sc = $("scroller"); const sc = $("scroller");
const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140; const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140;
mergeDeliveries(msgs, deliveries);
S.msgs = msgs; S.msgs = msgs;
renderMsgs(); keepSoon(); renderMsgs(); keepSoon();
if (near) sc.scrollTop = sc.scrollHeight; if (near) sc.scrollTop = sc.scrollHeight;
} }
// 交付確認(✓ mark)與訊息分開送(服务端也分開放:别的装置回報檔案不該改到聊天指紋):
// 蓋在持有的那批 attachment 上;動過的回 true(要重畫)。
function mergeDeliveries(msgs, deliveries) {
if (!msgs || !deliveries || !deliveries.length) return false;
const by = new Map(deliveries.map((d) => [d.id, d]));
let moved = false;
msgs.forEach((m) => (m.attachments || []).forEach((a) => {
const d = by.get(a.id);
if (!d) return;
const seen = d.seen || [];
if (a.delivery !== d.delivery || (a.seen || []).length !== seen.length) { a.delivery = d.delivery; a.seen = seen; moved = true; }
}));
return moved;
}
// 串流時聊天每秒最多重發一次;被擋下來時,一秒後補問一次。
function chatLater() { clearTimeout(S._ct); S._ct = setTimeout(() => { if (S.token) kick(); }, 1300); }
// What a new chat offers (the desktop's 建議): the everyday jobs, one tap to start writing them. // What a new chat offers (the desktop's 建議): the everyday jobs, one tap to start writing them.
const SUGGEST = [ const SUGGEST = [
["search", "海巡 Threads", "整理熱門討論和互動數", "幫我在 Threads 海巡「」最近的熱門討論,整理互動最多的 5 則(誰發的、在講什麼、讚數、連結)。"], ["search", "海巡 Threads", "整理熱門討論和互動數", "幫我在 Threads 海巡「」最近的熱門討論,整理互動最多的 5 則(誰發的、在講什麼、讚數、連結)。"],
@ -1753,13 +1794,26 @@ function deviceLabel() {
return /Mobi/.test(ua) ? "手機" : "瀏覽器"; return /Mobi/.test(ua) ? "手機" : "瀏覽器";
} }
// What this page did with a file the bot handed over, told once each while the page is open // What this page did with a file the bot handed over, told once each while the page is open
// (not queued: one lost on a bad line is tried again only when it is drawn again). // (not queued: one lost on a bad line is tried again only when it is drawn again). 一批一批送:
// 開一個舊聊天會把看到的檔案全報一次,一檔一個請求、每個都叫醒所有頁面,慢線上是一场風暴。
const SEEN_TOLD = new Set(); const SEEN_TOLD = new Set();
const SEEN_OUT = [];
let SEEN_TIMER = 0;
function seenTell(att, kind, why, bot) { function seenTell(att, kind, why, bot) {
const k = att + ":" + kind; const k = att + ":" + kind;
if (!att || !bot || SEEN_TOLD.has(k)) return; if (!att || !bot || SEEN_TOLD.has(k)) return;
SEEN_TOLD.add(k); SEEN_TOLD.add(k);
api(base() + `api/bots/${bot}/seen`, {json: {att, kind, why: why || "", device: deviceLabel()}, timeout: 15000}).catch((e) => { if (e.transient) SEEN_TOLD.delete(k); }); SEEN_OUT.push({bot, att, kind, why: why || ""});
clearTimeout(SEEN_TIMER);
SEEN_TIMER = setTimeout(seenFlush, 800);
}
function seenFlush() {
clearTimeout(SEEN_TIMER);
const rs = SEEN_OUT.splice(0);
const byBot = new Map();
rs.forEach((r) => { if (!byBot.has(r.bot)) byBot.set(r.bot, []); byBot.get(r.bot).push({att: r.att, kind: r.kind, why: r.why}); });
byBot.forEach((reports, bot) => api(base() + `api/bots/${bot}/seen`, {json: {device: deviceLabel(), reports}, timeout: 15000})
.catch((e) => { if (e.transient) reports.forEach((r) => SEEN_TOLD.delete(r.att + ":" + r.kind)); }));
} }
// Shown: drawn (a picture loaded), in view, the page in front. // Shown: drawn (a picture loaded), in view, the page in front.
function seenCheck(el) { function seenCheck(el) {
@ -1775,7 +1829,7 @@ function seenWatch() {
seenObs.disconnect(); seenObs.disconnect();
document.querySelectorAll("#msgs [data-att]").forEach((el) => seenObs.observe(el)); document.querySelectorAll("#msgs [data-att]").forEach((el) => seenObs.observe(el));
} }
document.addEventListener("visibilitychange", () => { if (!document.hidden) document.querySelectorAll("#msgs [data-att]").forEach(seenCheck); }); document.addEventListener("visibilitychange", () => { if (document.hidden) { if (SEEN_OUT.length) seenFlush(); return; } document.querySelectorAll("#msgs [data-att]").forEach(seenCheck); });
// A picture in the chat: shown once it has loaded in view; one the phone can't decode failed. // A picture in the chat: shown once it has loaded in view; one the phone can't decode failed.
function seenImg(el) { function seenImg(el) {
const img = el.querySelector("img"); const img = el.querySelector("img");
@ -1871,6 +1925,8 @@ function renderMsgs() {
const lastMsg = S.msgs[S.msgs.length - 1]; const lastMsg = S.msgs[S.msgs.length - 1];
const shown = {}; let day = ""; const shown = {}; let day = "";
let h = ""; let h = "";
// 載入更早:開頁只有最新 30 條,這一鍵一次往回補 60 條。
if (S.msgs.length && S.msgs[0].index > 0) h += `<div class="dsep"><button class="btn sm" data-older="1">載入更早的對話</button></div>`;
// A message that arrived since the last draw slides up into place; the whole history on // 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). // opening a chat draws plain (no animation on every old message).
// (Another conversation of the same bot — its first message differs — draws plain too.) // (Another conversation of the same bot — its first message differs — draws plain too.)
@ -1966,6 +2022,7 @@ function renderMsgs() {
} }
// Taps in the chat: steps, folds, summaries, copy, regenerate, resend, reactions, suggestions, pages. // Taps in the chat: steps, folds, summaries, copy, regenerate, resend, reactions, suggestions, pages.
$("msgs").addEventListener("click", async (e) => { $("msgs").addEventListener("click", async (e) => {
const od = e.target.closest("[data-older]"); if (od) { loadOlder(); return; }
// The end of a drag that selected words is not a tap: nothing folds, opens or goes. // The end of a drag that selected words is not a tap: nothing folds, opens or goes.
if (!e.target.closest("button,a") && selIn(e.target)) return; if (!e.target.closest("button,a") && selIn(e.target)) return;
const dv = e.target.closest("[data-dlv]"); if (dv) { dlvSheet(dv.dataset.dlv); return; } const dv = e.target.closest("[data-dlv]"); if (dv) { dlvSheet(dv.dataset.dlv); return; }

View File

@ -459,6 +459,10 @@ impl App {
})), })),
})); }));
let start = b.messages.len().saturating_sub(remote::PHONE_TAIL); 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<serde_json::Value> = vec![];
// Each message with its place in the chat (表情回應), its thinking and, on each step, // Each message with its place in the chat (表情回應), its thinking and, on each step,
// what came back (the desktop's 顯示步驟 / 思考過程), in short. // 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(); 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();
@ -470,6 +474,16 @@ impl App {
.enumerate() .enumerate()
.filter_map(|(k, m)| { .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(&[]))?; 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); v["index"] = json!(start + k);
// 支線: its record, for the card (and the report's label). // 支線: its record, for the card (and the report's label).
if m.branch != 0 { if m.branch != 0 {
@ -509,6 +523,7 @@ impl App {
}) })
.collect(); .collect();
view.messages.insert(b.id, msgs); view.messages.insert(b.id, msgs);
view.deliveries.insert(b.id, deliveries);
view.approvals.extend(self.phone_cards(b)); view.approvals.extend(self.phone_cards(b));
} }
view.pages = self.state.pages.clone(); view.pages = self.state.pages.clone();

View File

@ -246,6 +246,11 @@ pub struct View {
pub bots: Vec<Value>, pub bots: Vec<Value>,
pub approvals: Vec<Value>, pub approvals: Vec<Value>,
pub messages: HashMap<u64, Vec<Value>>, pub messages: HashMap<u64, Vec<Value>>,
/// 交付確認: each bot's ✓ marks (attachment id → delivery state), kept apart from the
/// messages so a device's word about a file never changes the chat's messages (a phone
/// opening an old chat reports every file it shows; inside the messages that used to re-sign
/// the whole chat and send it again and again on a slow line).
pub deliveries: HashMap<u64, Vec<Value>>,
/// 頁面, for the phone's page view. /// 頁面, for the phone's page view.
pub pages: Vec<crate::pages::Page>, pub pages: Vec<crate::pages::Page>,
/// The models the phone can switch a bot to: each ready provider with its known models. /// The models the phone can switch a bot to: each ready provider with its known models.
@ -508,6 +513,36 @@ fn seen_cmd(bot: u64, b: &Value, device: String, trusted: bool) -> Option<Cmd> {
/// Newest messages kept in the phone's view of each chat. /// Newest messages kept in the phone's view of each chat.
pub const PHONE_TAIL: usize = 120; pub const PHONE_TAIL: usize = 120;
/// The first window of a chat a page gets from a state poll (「載入更早的對話」 takes the rest on
/// demand): a first open on a slow line used to pull the whole tail at once. A chat asked
/// straight (`api/bots/<id>`, desktop tools, scripts) is still sent whole.
pub const PHONE_FIRST: usize = 30;
/// At most one state answer per page this often: a streaming bot republishes every few frames,
/// and each wake used to rebuild, fingerprint, gzip and ship the whole state.
const MIN_ANSWER_MS: u64 = 400;
/// At most one chat (re)send on a state poll this often: the chat's smallest delta is one whole
/// message, so a streaming reply grew quadratic in traffic.
const CHAT_EVERY_MS: u64 = 1000;
fn up_ms() -> u64 {
static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
START.get_or_init(Instant::now).elapsed().as_millis() as u64
}
/// Takes the right to answer now; false when the last answer is younger than `ms` (one global
/// window: the state is the same for every page asking).
fn slot_open(last: &std::sync::atomic::AtomicU64, ms: u64) -> bool {
let now = up_ms();
let prev = last.load(Ordering::Relaxed);
if prev != 0 && now - prev < ms {
return false;
}
last.store(now, Ordering::Relaxed);
true
}
static LAST_ANSWER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static LAST_CHAT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
// ---------- the API (both the local server and the relay call this) ---------- // ---------- the API (both the local server and the relay call this) ----------
@ -603,7 +638,19 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
hub().push(Cmd::PersonTimezone(tz.clone())); hub().push(Cmd::PersonTimezone(tz.clone()));
} }
} }
let v = hub().wait_newer(since, if since == 0 { 0 } else { LONG_POLL_SECS }); let mut v = hub().wait_newer(since, if since == 0 { 0 } else { LONG_POLL_SECS });
// 合并叫醒: a streaming bot publishes many times a second; one answer per
// MIN_ANSWER_MS, and it carries the freshest view (sleeping out the rest of the
// window). The first answer of a page (since == 0) is never held.
if since != 0 {
let last = LAST_ANSWER.load(Ordering::Relaxed);
let now = up_ms();
if last != 0 && now - last < MIN_ANSWER_MS {
std::thread::sleep(Duration::from_millis(MIN_ANSWER_MS - (now - last)));
v = hub().wait_newer(since, 0);
}
LAST_ANSWER.store(up_ms(), Ordering::Relaxed);
}
// 頁面 for the phone's home: the newest first, each with its bot. // 頁面 for the phone's home: the newest first, each with its bot.
let now = crate::model::now_ms(); let now = crate::model::now_ms();
let shared = |id: u64| role != "member" || v.bots.iter().any(|b| b["id"].as_u64() == Some(id) && b["team"] == true); let shared = |id: u64| role != "member" || v.bots.iter().any(|b| b["id"].as_u64() == Some(id) && b["team"] == true);
@ -651,15 +698,31 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
"voice": {"listen": hub().voice().listen.is_some(), "speak": hub().voice().speak.is_some()}, "voice": {"listen": hub().voice().listen.is_some(), "speak": hub().voice().speak.is_some()},
}); });
// Only what changed since the state the page holds (`&ssig=…`; an older page sends // Only what changed since the state the page holds (`&ssig=…`; an older page sends
// none and gets all of it). // none and gets all of it). The fingerprints of the keys that only move on publish
let mut out = state_for(out, req.query.get("ssig").map(String::as_str).unwrap_or("")); // are memoized for this view (wakes are many per version while a bot streams).
let mut out = state_for(out, req.query.get("ssig").map(String::as_str).unwrap_or(""), role != "member");
// Single-trip active chat sync: when the browser names its open bot (`&bot=ID`), // Single-trip active chat sync: when the browser names its open bot (`&bot=ID`),
// 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 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
// once a second — the smallest chat delta is a whole message, and its whole body
// would ride on every wake otherwise; the page asks again when the second is up.
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) { if let Some(raw) = v.messages.get(&open_id) {
let held = req.query.get("chat_sig").map(String::as_str).unwrap_or(""); let held = req.query.get("chat_sig").map(String::as_str).unwrap_or("");
out["chat"] = chat_for(open_id, messages_for_role(raw, &role), held, 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 msgs = messages_for_role(raw, &role);
// 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 = req.query.get("w0").and_then(|x| x.parse::<usize>().ok()).unwrap_or(n.saturating_sub(PHONE_FIRST));
let del = json!(v.deliveries.get(&open_id).cloned().unwrap_or_default());
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) {
out["chat"] = json!({"bot": open_id, "sig": held, "throttled": true});
} else {
out["chat"] = chat;
}
} }
} }
Resp::json(&out) Resp::json(&out)
@ -690,7 +753,9 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
Err(e) => Resp::error(422, &e), Err(e) => Resp::error(422, &e),
} }
} }
// A chat; for a page holding a copy (`&chat_sig=…&chat_delta=1`), only what changed since. // A chat, whole (scripts and older pages) — for a page holding a copy
// (`&chat_sig=…&chat_delta=1`), only what changed since, from the window it holds
// (`&w0=`, or the newest `PHONE_FIRST` with `first=1`). Asked straight, never throttled.
("GET", ["api", "bots", id]) => { ("GET", ["api", "bots", id]) => {
let id: u64 = id.parse().unwrap_or(0); let id: u64 = id.parse().unwrap_or(0);
let held = req.query.get("chat_sig").map(String::as_str).unwrap_or(""); let held = req.query.get("chat_sig").map(String::as_str).unwrap_or("");
@ -698,13 +763,36 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
let v = hub().view.lock().unwrap(); let v = hub().view.lock().unwrap();
match v.messages.get(&id) { match v.messages.get(&id) {
Some(m) => { Some(m) => {
let mut out = chat_for(id, messages_for_role(m, &role), held, part); 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 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); out["version"] = json!(v.version);
Resp::json(&out) Resp::json(&out)
} }
None => Resp::error(404, "找不到這個 Bot"), None => Resp::error(404, "找不到這個 Bot"),
} }
} }
// 載入更早: 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.
("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.min(arr.len());
let start = from.saturating_sub(count);
Resp::json(&json!({"bot": id, "messages": &arr[start..from], "more": start > 0}))
}
None => Resp::error(404, "找不到這個 Bot"),
}
}
// What the desktop shows beside the chat and in 設定, made when asked (never keys, tokens // What the desktop shows beside the chat and in 設定, made when asked (never keys, tokens
// or the vault's secrets), and everything else it can do (api/act/<what>). // or the vault's secrets), and everything else it can do (api/act/<what>).
("GET", ["api", "bots", id, "detail"]) => phone_act("detail", json!({"bot": id.parse::<u64>().unwrap_or(0)}), &role), ("GET", ["api", "bots", id, "detail"]) => phone_act("detail", json!({"bot": id.parse::<u64>().unwrap_or(0)}), &role),
@ -831,11 +919,24 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
"answer" => Cmd::Answer { bot, answer: b["answer"].as_str().unwrap_or("reject").to_string(), text: b["text"].as_str().unwrap_or("").to_string(), call: b["call"].as_str().unwrap_or("").to_string(), notice: b["from"].as_str() == Some("notice"), screen: false }, "answer" => Cmd::Answer { bot, answer: b["answer"].as_str().unwrap_or("reject").to_string(), text: b["text"].as_str().unwrap_or("").to_string(), call: b["call"].as_str().unwrap_or("").to_string(), notice: b["from"].as_str() == Some("notice"), screen: false },
"read" => Cmd::Read { bot }, "read" => Cmd::Read { bot },
// 交付確認 from a phone: it showed, opened or couldn't show a file. Not queued // 交付確認 from a phone: it showed, opened or couldn't show a file. Not queued
// on the phone — one lost on a bad line is only a ✓ less. // on the phone — one lost on a bad line is only a ✓ less. A whole page of files
"seen" => match seen_cmd(bot, &b, phone_label(b["device"].as_str().unwrap_or(""), if role == "owner" { "" } else { req.header("x-anybot-user") }), role == "owner") { // comes as one batch (`reports`): each is its own command, so the app publishes
Some(c) => c, // once for the lot and the pages wake a single time.
None => return Resp::error(400, "不認得這個回報"), "seen" => {
}, if let Some(rs) = b["reports"].as_array() {
let device = phone_label(b["device"].as_str().unwrap_or(""), if role == "owner" { "" } else { req.header("x-anybot-user") });
for r in rs.iter().take(200) {
if let Some(c) = seen_cmd(bot, r, device.clone(), role == "owner") {
hub().push(c);
}
}
return Resp::json(&json!({"ok": true}));
}
match seen_cmd(bot, &b, phone_label(b["device"].as_str().unwrap_or(""), if role == "owner" { "" } else { req.header("x-anybot-user") }), role == "owner") {
Some(c) => c,
None => return Resp::error(400, "不認得這個回報"),
}
}
"new" => Cmd::NewThread { bot }, "new" => Cmd::NewThread { bot },
"regenerate" => Cmd::Regenerate { bot }, "regenerate" => Cmd::Regenerate { bot },
"restore_answer" => Cmd::RestoreAnswer { bot }, "restore_answer" => Cmd::RestoreAnswer { bot },
@ -1227,6 +1328,29 @@ struct Told<T> {
by_sig: HashMap<String, T>, by_sig: HashMap<String, T>,
} }
/// The state's keys whose fingerprints only change when the app publishes: memoized for the
/// newest view (single slot), so waking polls don't re-hash the whole bot list per wake.
const FP_STABLE: [&str; 11] = ["host", "person", "accent", "pin_order", "newer", "bots", "approvals", "models", "sections", "theme", "palettes"];
fn fp_cache() -> &'static Mutex<Vec<(u64, HashMap<String, u64>)>> {
static C: std::sync::OnceLock<Mutex<Vec<(u64, HashMap<String, u64>)>>> = std::sync::OnceLock::new();
C.get_or_init(Default::default)
}
fn fp_cache_get(version: u64) -> Option<HashMap<String, u64>> {
let c = fp_cache().lock().unwrap_or_else(|e| e.into_inner());
c.iter().find(|(v, _)| *v == version).map(|(_, k)| k.clone())
}
fn fp_cache_put(version: u64, keys: &HashMap<String, u64>) {
let mut c = fp_cache().lock().unwrap_or_else(|e| e.into_inner());
if c.first().map(|(v, _)| *v) == Some(version) {
return;
}
let kept = keys.iter().filter(|(k, _)| FP_STABLE.contains(&k.as_str())).map(|(k, v)| (k.clone(), *v)).collect();
*c = vec![(version, kept)];
}
impl<T: Clone> Told<T> { impl<T: Clone> Told<T> {
const KEEP: usize = 2048; const KEEP: usize = 2048;
fn new() -> Told<T> { fn new() -> Told<T> {
@ -1247,6 +1371,12 @@ impl<T: Clone> Told<T> {
} }
} }
} }
/// Replaces what a known fingerprint stands for (a chat's marks moved, its messages didn't).
fn set(&mut self, sig: &str, v: T) {
if self.by_sig.contains_key(sig) {
self.by_sig.insert(sig.to_string(), v);
}
}
} }
/// A state's fingerprints: each key's, and each bot's by id. /// A state's fingerprints: each key's, and each bot's by id.
@ -1257,17 +1387,27 @@ fn told_states() -> &'static Mutex<Told<StateFp>> {
T.get_or_init(|| Mutex::new(Told::new())) T.get_or_init(|| Mutex::new(Told::new()))
} }
fn told_chats() -> &'static Mutex<Told<Arc<Vec<u64>>>> { /// Per chat: each shown message's fingerprint, and the fingerprint of the 交付確認 list.
static T: OnceLock<Mutex<Told<Arc<Vec<u64>>>>> = OnceLock::new(); fn told_chats() -> &'static Mutex<Told<Arc<(Vec<u64>, u64)>>> {
static T: OnceLock<Mutex<Told<Arc<(Vec<u64>, u64)>>>> = OnceLock::new();
T.get_or_init(|| Mutex::new(Told::new())) T.get_or_init(|| Mutex::new(Told::new()))
} }
/// The state for a page holding the one fingerprinted `held` (empty: none, or an older page): only /// The state for a page holding the one fingerprinted `held` (empty: none, or an older page): only
/// what changed since — a key left out is as it was, an unchanged bot is `{id, same}`, and `base` /// what changed since — a key left out is as it was, an unchanged bot is `{id, same}`, and `base`
/// says which state it builds on. The fingerprint of the whole (`ssig`) either way. /// says which state it builds on. The fingerprint of the whole (`ssig`) either way.
fn state_for(mut out: Value, held: &str) -> Value { fn state_for(mut out: Value, held: &str, stable: bool) -> Value {
let Some(obj) = out.as_object() else { return out }; let Some(obj) = out.as_object() else { return out };
let keys: HashMap<String, u64> = obj.iter().filter(|(k, _)| k.as_str() != "version").map(|(k, v)| (k.clone(), fp(v))).collect(); let version = obj.get("version").and_then(Value::as_u64).unwrap_or(0);
let cached = if stable { fp_cache_get(version) } else { None };
let keys: HashMap<String, u64> = obj
.iter()
.filter(|(k, _)| k.as_str() != "version")
.map(|(k, v)| (k.clone(), cached.as_ref().and_then(|c| c.get(k).copied()).unwrap_or_else(|| fp(v))))
.collect();
if stable {
fp_cache_put(version, &keys);
}
let bots: HashMap<u64, u64> = obj.get("bots").and_then(Value::as_array).into_iter().flatten().filter_map(|b| Some((b["id"].as_u64()?, fp(b)))).collect(); let bots: HashMap<u64, u64> = obj.get("bots").and_then(Value::as_array).into_iter().flatten().filter_map(|b| Some((b["id"].as_u64()?, fp(b)))).collect();
let mut sorted: Vec<(&String, &u64)> = keys.iter().collect(); let mut sorted: Vec<(&String, &u64)> = keys.iter().collect();
sorted.sort(); sorted.sort();
@ -1296,23 +1436,43 @@ fn state_for(mut out: Value, held: &str) -> Value {
/// The open chat for a page holding the list fingerprinted `held`: `unchanged` when it is that /// The open chat for a page holding the list fingerprinted `held`: `unchanged` when it is that
/// one; when the page takes a part (`part`), only from where the two differ — drop the first `drop` /// one; when the page takes a part (`part`), only from where the two differ — drop the first `drop`
/// it holds, keep the next `from`, then `messages`; otherwise all of it. /// it holds, keep the next `from`, then `messages`; otherwise all of it.
fn chat_for(bot: u64, msgs: Value, held: &str, part: bool) -> Value { /// The shown window starts at the message index `w0` (the page says where its copy starts; no `w0`
/// = 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.
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 list = msgs.as_array().map(Vec::as_slice).unwrap_or(&[]);
let hs: Vec<u64> = list.iter().map(fp).collect(); let dfp = fp(delivery);
let off = w0.unwrap_or(0).min(list.len());
let win = &list[off..];
let hs: Vec<u64> = win.iter().map(fp).collect();
let sig = sig_of(&(bot, &hs)); let sig = sig_of(&(bot, &hs));
if held == sig { if held == sig {
return json!({"bot": bot, "sig": sig, "unchanged": true}); // The messages are the ones the page holds; only the ✓ marks moved, send those alone
// (and remember the marks it was told, so the next poll says nothing at all).
let known = {
let t = told_chats().lock().unwrap_or_else(|e| e.into_inner());
match t.get(held) {
Some(x) if x.1 == dfp => return json!({"bot": bot, "sig": sig, "unchanged": true}),
_ => t.get(held).is_some(),
}
};
if known {
told_chats().lock().unwrap_or_else(|e| e.into_inner()).set(held, Arc::new((hs.clone(), dfp)));
}
return json!({"bot": bot, "sig": sig, "unchanged": true, "deliveries": delivery});
} }
let prev = if part && !held.is_empty() { told_chats().lock().unwrap_or_else(|e| e.into_inner()).get(held) } else { None }; let told = told_chats().lock().unwrap_or_else(|e| e.into_inner()).get(held);
let found = prev.as_deref().zip(hs.first()).and_then(|(old, first)| { let prev = if part && !held.is_empty() { told } else { None };
let drop = old.iter().position(|h| h == first)?; let found = prev.as_ref().zip(hs.first()).and_then(|(old, first)| {
Some((drop, old[drop..].iter().zip(&hs).take_while(|(a, b)| a == b).count())) let drop = old.0.iter().position(|h| h == first)?;
Some((drop, old.0[drop..].iter().zip(hs.iter()).take_while(|(a, b)| a == b).count()))
}); });
let out = match found { let out = match found {
Some((drop, from)) => json!({"bot": bot, "sig": sig, "base": held, "drop": drop, "from": from, "messages": &list[from..]}), Some((drop, from)) => json!({"bot": bot, "sig": sig, "base": held, "drop": drop, "from": from, "messages": &win[from..], "deliveries": delivery}),
None => json!({"bot": bot, "sig": sig, "messages": list}), None => json!({"bot": bot, "sig": sig, "messages": win, "deliveries": delivery}),
}; };
told_chats().lock().unwrap_or_else(|e| e.into_inner()).keep(&sig, Arc::new(hs)); told_chats().lock().unwrap_or_else(|e| e.into_inner()).keep(&sig, Arc::new((hs, dfp)));
out out
} }
@ -3220,13 +3380,13 @@ mod tests {
#[test] #[test]
fn the_state_is_told_as_what_changed() { fn the_state_is_told_as_what_changed() {
let a = json!({"version": 5, "host": "Mac", "models": [1, 2, 3], "bots": [{"id": 1, "name": "甲", "status": ""}, {"id": 2, "name": "乙"}]}); let a = json!({"version": 5, "host": "Mac", "models": [1, 2, 3], "bots": [{"id": 1, "name": "甲", "status": ""}, {"id": 2, "name": "乙"}]});
let full = state_for(a.clone(), ""); let full = state_for(a.clone(), "", true);
assert!(full["base"].is_null() && full["models"] == json!([1, 2, 3])); assert!(full["base"].is_null() && full["models"] == json!([1, 2, 3]));
let held = full["ssig"].as_str().unwrap().to_string(); let held = full["ssig"].as_str().unwrap().to_string();
let mut b = a.clone(); let mut b = a.clone();
b["version"] = json!(6); b["version"] = json!(6);
b["bots"][0]["status"] = json!("正在想…"); b["bots"][0]["status"] = json!("正在想…");
let part = state_for(b.clone(), &held); let part = state_for(b.clone(), &held, true);
assert_eq!(part["base"], json!(held)); assert_eq!(part["base"], json!(held));
assert_eq!(part["version"], 6); assert_eq!(part["version"], 6);
assert!(part.get("host").is_none() && part.get("models").is_none(), "unchanged keys left out: {part}"); assert!(part.get("host").is_none() && part.get("models").is_none(), "unchanged keys left out: {part}");
@ -3234,10 +3394,10 @@ mod tests {
assert_eq!(part["bots"][1], json!({"id": 2, "same": true})); assert_eq!(part["bots"][1], json!({"id": 2, "same": true}));
assert_ne!(part["ssig"], json!(held)); assert_ne!(part["ssig"], json!(held));
// The same again: nothing but the version (and the fingerprint is the same). // The same again: nothing but the version (and the fingerprint is the same).
let same = state_for(b, part["ssig"].as_str().unwrap()); let same = state_for(b, part["ssig"].as_str().unwrap(), true);
assert_eq!(same["ssig"], part["ssig"]); assert_eq!(same["ssig"], part["ssig"]);
assert!(same.get("bots").is_none()); assert!(same.get("bots").is_none());
assert!(state_for(a, "not-told").get("base").is_none(), "an unknown fingerprint: all of it"); assert!(state_for(a, "not-told", true).get("base").is_none(), "an unknown fingerprint: all of it");
} }
/// A chat is told from where it differs from what the page holds — the last message grown, one /// A chat is told from where it differs from what the page holds — the last message grown, one
@ -3251,25 +3411,68 @@ mod tests {
held[drop..][..from].iter().cloned().chain(c["messages"].as_array().unwrap().iter().cloned()).collect() held[drop..][..from].iter().cloned().chain(c["messages"].as_array().unwrap().iter().cloned()).collect()
}; };
let one: Vec<Value> = (0..5).map(|i| m(i, "x")).collect(); let one: Vec<Value> = (0..5).map(|i| m(i, "x")).collect();
let first = chat_for(77, json!(one), "", true); let first = chat_for(77, json!(one), &json!([]), "", true, None);
assert!(first["from"].is_null() && first["messages"].as_array().unwrap().len() == 5); assert!(first["from"].is_null() && first["messages"].as_array().unwrap().len() == 5);
let sig = first["sig"].as_str().unwrap().to_string(); let sig = first["sig"].as_str().unwrap().to_string();
assert_eq!(chat_for(77, json!(one), &sig, true)["unchanged"], true); assert_eq!(chat_for(77, json!(one), &json!([]), &sig, true, None)["unchanged"], true);
// The last one grew and one more came; the oldest left the window. // The last one grew and one more came; the oldest left the window.
let mut two: Vec<Value> = (1..5).map(|i| m(i, "x")).collect(); let mut two: Vec<Value> = (1..5).map(|i| m(i, "x")).collect();
two[3] = m(4, "xy"); two[3] = m(4, "xy");
two.push(m(5, "new")); two.push(m(5, "new"));
let c = chat_for(77, json!(two), &sig, true); let c = chat_for(77, json!(two), &json!([]), &sig, true, None);
assert_eq!((c["drop"].as_u64(), c["from"].as_u64(), c["base"].as_str()), (Some(1), Some(3), Some(sig.as_str()))); assert_eq!((c["drop"].as_u64(), c["from"].as_u64(), c["base"].as_str()), (Some(1), Some(3), Some(sig.as_str())));
assert_eq!(c["messages"].as_array().unwrap().len(), 2); assert_eq!(c["messages"].as_array().unwrap().len(), 2);
assert_eq!(rebuild(&one, &c), two); assert_eq!(rebuild(&one, &c), two);
// An older page (no part): all of it. // An older page (no part): all of it.
assert_eq!(chat_for(77, json!(two), &sig, false)["messages"].as_array().unwrap().len(), 5); assert_eq!(chat_for(77, json!(two), &json!([]), &sig, false, None)["messages"].as_array().unwrap().len(), 5);
// Cleared: nothing to keep. // Cleared: nothing to keep.
let gone = chat_for(77, json!([m(0, "fresh")]), c["sig"].as_str().unwrap(), true); let gone = chat_for(77, json!([m(0, "fresh")]), &json!([]), c["sig"].as_str().unwrap(), true, None);
assert!(gone["from"].is_null()); assert!(gone["from"].is_null());
} }
/// 交付確認 lives beside the chat: a device reporting a file leaves the messages' signature
/// alone — the marks come on their own, and a page holding them is told nothing at all.
/// (Inside the messages, every report re-signed the chat and the whole tail rode again.)
#[test]
fn a_delivery_word_does_not_resend_the_chat() {
let m = |i: u64| json!({"index": i, "role": "bot", "text": "x"});
let msgs: Vec<Value> = (0..10).map(m).collect();
let d0 = json!([{"id": "a1", "delivery": "chat", "seen": []}]);
let first = chat_for(9, json!(&msgs), &d0, "", true, None);
assert_eq!(first["messages"].as_array().unwrap().len(), 10);
let sig = first["sig"].as_str().unwrap().to_string();
// A phone says it showed the file: the messages are the ones it holds; only the marks come.
let d1 = json!([{"id": "a1", "delivery": "shown", "seen": [{"device": "iPhone", "kind": "shown"}]}]);
let c = chat_for(9, json!(&msgs), &d1, &sig, true, None);
assert_eq!(c["unchanged"], true);
assert_eq!(c["deliveries"][0]["delivery"], "shown");
// Said again (the page reloads and reports): not even the marks move.
let sig2 = c["sig"].as_str().unwrap().to_string();
let c2 = chat_for(9, json!(&msgs), &d1, &sig2, true, None);
assert_eq!(c2["unchanged"], true);
assert!(c2.get("deliveries").is_none(), "the marks are the ones it holds: {c2}");
}
/// A chat opens on the newest `PHONE_FIRST` messages (a state poll); asked straight it is
/// whole. The page says where its copy starts (`w0`) and the window opens there — the walk
/// back goes through api/bots/<id>/older.
#[test]
fn a_chat_opens_on_a_small_window() {
let m = |i: u64| json!({"index": i, "text": "x"});
let msgs: Vec<Value> = (0..100).map(m).collect();
// Asked straight: all of it (scripts and older pages get what they always got).
assert_eq!(chat_for(11, json!(&msgs), &json!([]), "", true, None)["messages"].as_array().unwrap().len(), 100);
let off = 100 - PHONE_FIRST;
let first = chat_for(11, json!(&msgs), &json!([]), "", true, Some(off));
let win = first["messages"].as_array().unwrap();
assert_eq!(win.len(), PHONE_FIRST);
assert_eq!(win[0]["index"], json!(off));
// The page holds twenty more above its copy: the window starts where it says.
let wide = chat_for(11, json!(&msgs), &json!([]), "", false, Some(off - 20));
assert_eq!(wide["messages"].as_array().unwrap().len(), PHONE_FIRST + 20);
assert_eq!(wide["messages"][0]["index"], json!(off - 20));
}
/// A message tried again on a bad network (the same id) reaches the bot once. /// A message tried again on a bad network (the same id) reaches the bot once.
#[test] #[test]
fn a_message_tried_again_is_taken_once() { fn a_message_tried_again_is_taken_once() {