手機「載入更早的對話」補上來的不會再不見:大腦每次送的只是它發布的那一段(最新 120 則、不含步驟結果,從手機那份的開頭起),往回補超過那一段的開頭之後,下一次更新(例如來一則新訊息)就整份換成那一段,剛補的又不見、按鈕跑回來;有工具步驟的聊天那一段很短,按一次就會。現在補上來的留在那一段前面(S.winAt),新訊息把舊的推出那一段時也接到前面,存起來的那份一起記著,切到別的 Bot 再回來、頁面重開也接得對(舊版頁面存的那份第一次只留大腦送來的那段,裡面可能有舊錯誤留下的缺口);等「載入更早」回來時聊天開頭移了就不接、從現在的開頭再問一次;對補上來的訊息按表情,向大腦拿那則現在的表情。回到最底下最多留 300 則,捲在上面讀時超過 600 則(背景 300、怎樣都超過 1200)從頂上收,正在讀的那則留在畫面同一個地方(切到背景那一刻記下,回到前景畫好再放回去)。順手修:點進聊天、按表情之後要等 20–40 秒才更新——11/20 起 loadChat 在大腦回「沒變」時直接 return,loading 一直卡在 true,之後只能等輪詢順便帶過來。手機的編號清單照 Markdown 的讀法:空一行隔開的還是同一個清單(以前每一點都是「1.」),編號從第一點寫的數字起,縮排在一點底下的子項目、續行在那一點裡(以前被攤平成同一層一起編號)。大腦管理員:核對 Docker 網路改不成寫進紀錄、還不知道擁有者時先不動;更新時 Caddyfile 用 relay 容器的 IP 或 .env 裡的 {$變數}/{$變數:預設} 轉到 relay 的也認得出來。功能地圖 chat 和 FEATURES 跟著改。

已驗證: cargo test(906,含 featuremap::、layout_audit::;新的 node 測試:手機聊天視窗 30 項、Markdown 清單 12 項,換回舊程式各自會失敗);verify-anybot 全新 scratch 照功能地圖 chat「開聊天分頁」一步步走(40 輪各一步、按兩下到最開頭、再傳一則「填充1」還在),另外:每輪跟大腦整段聊天逐則比對一模一樣、離開聊天來兩則再回來 0–1 秒內更新、整頁重開接得對、對補上來的第 4 則按 👍 畫面和大腦一致、捲在上面讀時來新訊息讀的那則不動、模擬切到背景來兩則再回前景(5 輪)讀的那則不動、空行隔開的「1. 1. 1.」畫成 1、2、3 並有子項目;Debian 10 和 Ubuntu 24.04 上 Caddyfile 轉到 relay 的各種寫法(含變數、預設值、IP)判斷正確;測試機兩台更新成功、Docker 網路核對照舊。四輪獨立審查找到的 P1(載入更早的競態、存起來的那份沒記前段、清單無上限、背景時對著舊畫面調捲動)都修了。
未驗證: 最後一輪獨立審查(切到背景那一刻記下位置之前的版本)還沒回來;真的 iPhone(無頭 Chrome 模擬觸控、用改 document.hidden 模擬切到背景);超過 300、600、1200 則的收法只有自動測試,沒在實機堆到那麼多則。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm
This commit is contained in:
王性驊 2026-11-23 11:15:51 +08:00
parent 1605b38354
commit 7eb2d79aa5
8 changed files with 493 additions and 57 deletions

File diff suppressed because one or more lines are too long

View File

@ -605,13 +605,31 @@ if [ -f .env ] && [ "$DRY" = 0 ]; then
# [[:space:]] and would match nothing.)
ws="[ $(printf '\t')]"
block="^$ws*reverse_proxy$ws+relay:8080$ws*[{]$ws*\$"
# The blocks the line goes in, and any other reverse_proxy or `to` naming the relay (one line,
# a matcher, http://relay:8080, the container's name, a comment after the {) — what else this
# Caddy forwards (a NAS, another site) doesn't count.
# The blocks the line goes in, and any other reverse_proxy or `to` going to the relay (one line,
# a matcher, http://relay:8080, the container's name, a comment after the {) — by its name, by
# the relay container's address, or through a {$VARIABLE} from .env saying either. What else
# this Caddy forwards (a NAS, another site) doesn't count.
blocks=0; others=0
if [ -f Caddyfile ]; then
blocks=$(grep -Ec "$block" Caddyfile || true)
others=$(grep -v "^$ws*#" Caddyfile | grep -E "^$ws*(reverse_proxy|to)$ws.*relay[:-]" | grep -Evc "$block" || true)
rid=$(docker compose ps -q relay 2>/dev/null | head -n 1)
relay_ips=""
[ -n "$rid" ] && relay_ips=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' "$rid" 2>/dev/null)
while IFS= read -r l; do
printf '%s\n' "$l" | grep -Eq "$block" && continue
# ({$VAR} or {$VAR:default}, as Caddy reads them: the value in .env, else the default.)
while IFS= read -r v; do
[ -n "$v" ] || continue
n=${v#?\$}; n=${n%\}}; dflt=""
case "$n" in *:*) dflt=${n#*:}; n=${n%%:*} ;; esac
val=$(sed -n "s/^$n=['\"]\{0,1\}\([^'\"]*\)['\"]\{0,1\}\$/\1/p" .env | tail -n 1)
l=${l//"$v"/"${val:-$dflt}"}
done <<<"$(printf '%s' "$l" | grep -oE '[{][$][A-Za-z_][A-Za-z0-9_]*(:[^}]*)?[}]' | sort -u)"
hit=0
printf '%s' "$l" | grep -Eq 'relay[:-]' && hit=1
for ip in $relay_ips; do printf '%s' "$l" | grep -Fq "$ip:" && hit=1; done
[ "$hit" = 1 ] && others=$((others + 1))
done < <(grep -v "^$ws*#" Caddyfile | grep -E "^$ws*(reverse_proxy|to)$ws" || true)
fi
if [ "$secret" = 1 ] && ! grep -q 'X-AnyBot-Proxy' Caddyfile; then
# Only where every way to the account server is a block the line can go in (any other would

View File

@ -15,7 +15,7 @@
- `chat-steps` 步驟和思考:預設收起。「顯示步驟」一行一個工具(等你允許/執行中/完成/被拒絕或停止/失敗),滑過那一行看結果;「思考過程」也在這裡。工作中,輸入框上方的臉旁邊寫它正在做什麼。臉和「正在…」最多每秒畫 20 次(CPU 畫圖 4 次),沒在動不重畫;你不在(視窗不在前、90 秒沒動)不眨眼。
- `chat-attach` 附件:「附加檔案」、拖進視窗、⌘V 貼圖;每檔最多 50 MB,文字檔最多讀 20,000 字給模型。
- `chat-compact` 長對話:舊步驟的長結果(連同長指令)累積到可讀長度 15% 就整批收起(聊天裡照樣完整);用到 6 成才寫可展開的「較早的對話已整理成摘要」。很多步時也寫。
- `chat-window` 開聊天分頁(手機頁面):打開給最新 30 條,頂上「載入更早的對話」點一次從大腦上整段聊天往前補 60 條,到最開頭說「已是對話最開頭」;回答中手機每秒最多更新一次,打完的整句補齊。電腦和聊底指令照舊拿整段。
- `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 輪各一步(超過手機那份),重新登入、開聊天。指令:`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-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]' && $CTL phone send 新一則 && $CTL phone wait-text 回答:新一則 --in '#msgs' && $CTL phone wait-text '填充1 ' --in '#msgs'`。看到:打開從「填充31」起;第一下補到「填充11」,第二下補到「填充1」、「已是對話最開頭」、按鈕消失;再傳一則,「填充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::`、`cargo test loading_earlier`、`cargo test layout_audit::`。
- **卡住、重試、繼續**(covers `chat-stall`):指令:走不到:假模型不會出錯,`ctl` 只會正常關 AnyBot(「繼續」「還沒有回覆」要它當掉)。看到:最接近的是「停止」那一步(看門狗也這樣結束一輪)。
- 自動測試:`cargo test agent::`(含 `agent::followthrough::`)、`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::`。
## 陷阱
@ -55,6 +55,6 @@
- 「還原上一個答案」只有一層(還原後舊的在前),一傳下一則就沒了。
- 手機上按住訊息是開訊息選單,不是選字:選一段用選單的「選取文字」,整則用「複製」。
- 步驟預設看不到:要確認 Bot 做了什麼,打開「顯示步驟」看每一步,不要只看它的回報。
- 看不到圖的模型(「看圖小幫手」):截圖和附件改請帳號裡看得懂圖的模型描述成文字。本機或區網的模型(Ollama、Tailscale 上的)圖片預設不外送;要送雲端,在 設定 › 模型 › 那個供應商 打開「看不到圖時,請雲端模型看截圖和附件」。
- 看不到圖的模型(「看圖小幫手」):截圖和附件改請看得懂圖的模型描述成文字;本機、區網模型(Ollama、Tailscale 上的)的圖預設不外送,設定 › 模型 › 那個供應商 打開「看不到圖時,請雲端模型看截圖和附件」才送。
- (驗證)沒等小卡片就送出時,AnyBot 自己挑字詞相近的「做過的事」帶上,假模型不看〔…〕裡的字。
- (驗證)`wait-text` 連你自己傳的那句和舊訊息都算:等只有 Bot 這次才會說的字。

212
mobile/chatwindow.test.mjs Normal file
View File

@ -0,0 +1,212 @@
// 手機聊天的視窗(mobile/index.html 的 takeWhole/takePart):大腦每次送的是它那一段(最新
// PHONE_TAIL,從手機說的 w0 起),「載入更早」拿到的、比那一段更早的訊息要留在前面——以前下一次
// 回答就把它們換掉,剛載入的又不見了(11/23)。在 node 裡跑頁面上的這兩個函式本身。
import { readFileSync } from "node:fs";
const page = readFileSync(new URL("./index.html", import.meta.url), "utf8");
const grab = (name) => {
const at = page.indexOf(`function ${name}(`);
if (at < 0) throw new Error(`index.html 裡沒有 ${name}`);
const i = page.slice(at - 6, at) === "async " ? at - 6 : at;
return page.slice(i, page.indexOf("\n}\n", i) + 2);
};
const hold = page.match(/\nconst HOLD = (\d+);/);
if (!hold) throw new Error("index.html 裡沒有 HOLD");
const S = { msgs: [], winAt: 0, chatSig: "" };
let loads = 0, draws = 0, answer = null;
const asked = [];
const { takeWhole, takePart, takeKept, trimFront, reacted } = new Function(
"S", "HOLD", "renderMsgs", "loadChat", "api", "base",
["takeWhole", "takePart", "takeKept", "trimFront", "reacted"].map(grab).join("\n") + "\nreturn { takeWhole, takePart, takeKept, trimFront, reacted };",
)(S, +hold[1], () => draws++, () => loads++, async (u) => { asked.push(u); return answer; }, () => "");
const m = (i, at = 1000 + i) => ({ index: i, role: i % 2 ? "assistant" : "user", at, text: `第 ${i} 則` });
const range = (a, b) => Array.from({ length: b - a }, (_, k) => m(a + k));
const ix = (list) => list.map((x) => x.index).join(",");
let failed = 0;
const check = (what, got, want) => {
if (got === want) console.log(`OK ${what}`);
else { failed++; console.log(`FAIL ${what}:得到 ${got},應該是 ${want}`); }
};
// 1. 只有大腦那一段:整段送來就是那一段,前面沒有多留。
S.msgs = range(10, 20); S.winAt = 0;
S.msgs = takeWhole(range(10, 20));
check("同一段整份送來", `${ix(S.msgs)}|${S.winAt}`, `${ix(range(10, 20))}|0`);
// 2. 載入更早補上 0..9(loadOlder 加的是 winAt),大腦的那一段還是從 10 開始:留著。
S.msgs = range(0, 10).concat(S.msgs); S.winAt += 10;
S.msgs = takeWhole(range(10, 21));
check("載入更早之後整份送來,前面的留著", `${ix(S.msgs)}|${S.winAt}`, `${ix(range(0, 21))}|10`);
// 3. 新訊息把那一段往後推(最舊的兩則離開那一段):離開的接到前面,不留空隙。
S.msgs = takePart({ drop: 2, from: 9, messages: [m(21), m(22)] });
check("差量:離開那一段的接到前面", `${ix(S.msgs)}|${S.winAt}`, `${ix(range(0, 23))}|12`);
// 4. 前面沒有多留時照舊:離開那一段的就不留(第一次打開保持小小的)。
S.msgs = range(10, 20); S.winAt = 0;
S.msgs = takePart({ drop: 2, from: 8, messages: [m(20), m(21)] });
check("沒載入更早:離開的照舊不留", `${ix(S.msgs)}|${S.winAt}`, `${ix(range(12, 22))}|0`);
// 5. 第一則不是手上有的(開了新對話、整段換掉):整份換掉,不留舊的。
S.msgs = range(0, 20); S.winAt = 5;
S.msgs = takeWhole([m(0, 99999), m(1, 99999)]);
check("新對話:整份換掉", `${ix(S.msgs)}|${S.winAt}|${S.msgs[0].at}`, "0,1|0|99999");
// 6. 手上沒有指紋(first=1,只拿最新幾則):手上更早的留著。
S.msgs = range(0, 20); S.winAt = 0;
S.msgs = takeWhole(range(15, 21));
check("只拿最新幾則:前面的留著", `${ix(S.msgs)}|${S.winAt}`, `${ix(range(0, 21))}|15`);
// 7. 空的一段:不出錯,什麼都不留。
S.msgs = range(0, 5); S.winAt = 2;
S.msgs = takeWhole([]);
check("空的一段", `${S.msgs.length}|${S.winAt}`, "0|0");
// 8. 存起來的那份連「前面多留幾則」一起回來:之後的差量接在對的地方(以前切走再回來,
// 新的直接接在補上來那段後面,最近的訊息不見)。
takeKept({ msgs: range(0, 20), sig: "abc", winAt: 10 });
S.msgs = takePart({ drop: 0, from: 10, messages: [m(20), m(21)] });
check("存起來的那份:差量接在對的地方", `${ix(S.msgs)}|${S.winAt}|${S.chatSig}`, `${ix(range(0, 22))}|10|abc`);
// 9. 舊格式(11/23 以前的頁面存的,沒記前面多留幾則;可能帶著舊錯誤留下的缺口):不用它的
// 指紋,下一次整份拿,前面的那次不留;之後照常。
takeKept({ msgs: range(0, 20), sig: "abc" });
check("舊格式的那份:不用指紋", `${S.winAt}|${S.chatSig}`, "0|");
S.msgs = takeWhole(range(15, 22));
check("舊格式之後第一次整份:前面的不留", `${ix(S.msgs)}|${S.winAt}`, `${ix(range(15, 22))}|0`);
S.msgs = range(0, 7).concat(S.msgs); S.winAt = 7;
S.msgs = takeWhole(range(15, 23));
check("再下一次:照常留著", `${ix(S.msgs)}|${S.winAt}`, `${ix(range(0, 7).concat(range(15, 23)))}|7`);
// 10. 不會無限長:回到最底下時,超過 HOLD 的、大腦那一段之前的從頂上拿掉;那一段本身不動。
const H = +hold[1];
S.msgs = range(0, H + 100); S.winAt = 150;
trimFront();
check("超過上限:從頂上拿掉前面多留的", `${S.msgs.length}|${S.msgs[0].index}|${S.winAt}`, `${H}|100|50`);
S.msgs = range(0, H + 100); S.winAt = 30;
trimFront();
check("前面多留的不夠拿:只拿那些", `${S.msgs.length}|${S.msgs[0].index}|${S.winAt}`, `${H + 70}|30|0`);
S.msgs = range(0, H + 100); S.winAt = 0;
trimFront();
check("沒有前面多留的:不拿", `${S.msgs.length}|${S.winAt}`, `${H + 100}|0`);
// 11. 對補上來的訊息按表情:大腦那一段沒有它,問大腦那一則現在的表情(別台也可能改過),照著畫。
S.msgs = range(0, 20); S.winAt = 10; loads = 0; draws = 0; asked.length = 0;
answer = { messages: [{ ...m(3), reactions: ["❤️", "👍"] }] };
await reacted({ text: "好了" }, 3);
check("前面多留的那則:照大腦的表情", `${(S.msgs[3].reactions || []).join("")}|${asked[0]}|${loads}`, "❤️👍|api/bots/undefined/older?from=4&count=1|1");
asked.length = 0;
await reacted({ text: "好了" }, 15);
check("那一段裡的:等大腦那一段", `${(S.msgs[15].reactions || []).length}|${asked.length}|${loads}`, "0|0|2");
await reacted(null, 4);
check("大腦沒做成:不問、不畫", `${(S.msgs[4].reactions || []).length}|${asked.length}`, "0|0");
// 12. 大腦回「沒有變」之後還會再去抓:以前那一下 return 跳過了 loading = false,之後每次打開
// 聊天、按表情都只排隊不抓,要等輪詢剛好帶過來(11/20–11/23)。
{
const T = { msgs: range(0, 5), winAt: 0, chatSig: "abc", open: 1, host: "h", chatLoaded: true, jumpAt: 0 };
let asked = 0;
const answers = [{ unchanged: true }, { unchanged: true }, { sig: "def", base: "abc", drop: 0, from: 5, messages: [m(5)] }];
const scroller = { scrollHeight: 100, scrollTop: 100, clientHeight: 0, getBoundingClientRect: () => ({ top: 0 }), querySelectorAll: () => [], querySelector: () => null };
const { loadChat, state } = new Function(
"S", "api", "base", "mergeDeliveries", "renderMsgs", "$", "keepSoon", "jumpTo", "toast", "HOLD", "document",
"let loading = false, again = false;\n" + ["takeWhole", "takePart", "trimFront", "anchorNow", "place", "loadChat"].map(grab).join("\n") + "\nreturn { loadChat, state: () => ({ loading, again }) };",
)(T, async () => answers[asked++], () => "", () => false, () => {}, () => scroller, () => {}, () => true, () => {}, +hold[1], { hidden: false });
await loadChat();
await loadChat();
check("沒有變之後:下一次還會去抓", `${asked}|${state().loading}`, "2|false");
await loadChat();
check("再下一次拿到新的", `${asked}|${ix(T.msgs)}|${T.chatSig}`, `3|${ix(range(0, 6))}|def`);
}
// 13. 「載入更早」等回應時聊天開頭往後移了(Bot 做步驟,舊的離開那一段;開了新對話):回來的
// 那批不接上去(會留下一直在的缺口),從現在的開頭再問一次。
{
const T = { msgs: range(40, 60), winAt: 0, open: 1, host: "h", olderBusy: false };
const calls = [];
const scroller = { scrollHeight: 100, scrollTop: 0 };
const { loadOlder } = new Function(
"S", "api", "base", "renderMsgs", "mergeDeliveries", "toast", "$",
grab("loadOlder") + "\nreturn { loadOlder };",
)(T, (u) => new Promise((done) => calls.push({ u, done })), () => "", () => {}, () => false, () => {}, () => scroller);
const first = loadOlder();
T.msgs = range(42, 61); // two left the window meanwhile
calls[0].done({ messages: range(0, 40), more: false });
await first; await new Promise((r) => setTimeout(r, 0));
check("開頭移了:那批不接", `${T.msgs[0].index}|${calls.length}|${calls[1] && calls[1].u}`, "42|2|api/bots/1/older?from=42&count=60");
calls[1].done({ messages: range(0, 42), more: false });
await new Promise((r) => setTimeout(r, 0));
check("再問一次:從現在的開頭接上,沒有缺口", `${ix(T.msgs)}|${T.winAt}|${T.olderBusy}`, `${ix(range(0, 61))}|42|false`);
// (Only once: moved again, it waits for the next press rather than chasing a working bot.)
T.msgs = range(50, 70); T.winAt = 0; calls.length = 0;
const p = loadOlder();
T.msgs = range(52, 71); calls[0].done({ messages: range(10, 50), more: true });
await p; await new Promise((r) => setTimeout(r, 0));
T.msgs = range(54, 72); calls[1].done({ messages: range(12, 52), more: true });
await new Promise((r) => setTimeout(r, 0));
check("又移了:只重問一次", `${calls.length}|${T.msgs[0].index}|${T.olderBusy}`, "2|54|false");
}
// 14. 換上新的一串時,正在讀的那則留在畫面上同一個地方;收掉頂上最多收到它上面 20 則(捲在上面
// 超過 HOLD×2、頁面不在前景超過 HOLD 才收;超過 HOLD×4 不管讀到哪都收);在最底下就跟著最底下。
// 假的畫面照真的來:每則高度不同,頁面不在前景時不重畫,回到前景(backInView)才畫。
{
const Hh = +hold[1];
const T = { msgs: [], winAt: 0, view: "chat", msgsStale: false };
const doc = { hidden: false };
let drawn = [], tops = [];
const height = (m) => 30 + ((m.index * 7919) % 271); // (no pattern a cut could line up with)
const sc = { scrollTop: 0, scrollHeight: 0, clientHeight: 800, getBoundingClientRect: () => ({ top: 0 }) };
const el = (p) => ({ dataset: { msg: String(p) }, getBoundingClientRect: () => ({ top: tops[p] - sc.scrollTop, bottom: tops[p] + height(drawn[p]) - sc.scrollTop }) });
const list = { querySelectorAll: () => drawn.map((_, p) => el(p)), querySelector: (q) => { const p = +q.match(/\d+/)[0]; return p < drawn.length ? el(p) : null; } };
const renderMsgs = () => {
if (doc.hidden) { T.msgsStale = true; return; }
T.msgsStale = false; drawn = T.msgs.slice(); T.drawn = T.msgs;
let y = 0; tops = drawn.map((m) => { const t = y; y += height(m); return t; }); sc.scrollHeight = y;
};
T.open = 1;
const { place, backInView, outOfView } = new Function(
"S", "HOLD", "$", "renderMsgs", "document",
["trimFront", "anchorNow", "holdRead", "outOfView", "backInView", "place"].map(grab).join("\n") + "\nreturn { place, backInView, outOfView };",
)(T, Hh, (id) => (id === "scroller" ? sc : list), renderMsgs, doc);
const at = (index, off) => { T.msgs = T.msgs; renderMsgs(); const p = drawn.findIndex((m) => m.index === index); sc.scrollTop = tops[p] - off; };
const top = () => { const p = drawn.findIndex((_, q) => tops[q] + height(drawn[q]) > sc.scrollTop); return `${drawn[p].index}@${tops[p] - sc.scrollTop}`; };
// 捲在上面讀第 350 則(往下 30px),清單長過 HOLD×2:頂上收掉,第 350 則還在原處。
T.msgs = range(0, 2 * Hh); T.winAt = 2 * Hh - 100; at(350, -30);
place(range(0, 2 * Hh + 2), false);
check("捲在上面、超過上限:收掉頂上,讀的那則不動", `${T.msgs.length}|${T.msgs[0].index}|${top()}`, `${Hh}|${Hh + 2}|350@-30`);
// 沒超過上限:不收,讀的那則一樣不動(下面多了新的)。
T.msgs = range(0, 400); T.winAt = 100; at(121, 0);
place(range(0, 403), false);
check("捲在上面、沒超過:不收、不動", `${T.msgs.length}|${top()}`, "403|121@0");
// 讀的那則離頂上很近:最多收到它上面 20 則。
T.msgs = range(0, 2 * Hh); T.winAt = 2 * Hh - 100; at(31, 0);
place(range(0, 2 * Hh + 2), false);
check("讀的那則離頂上近:只收到它上面 20 則", `${T.msgs[0].index}|${top()}`, "11|31@0");
// 頁面不在前景:不畫;超過 HOLD 就收;回到前景畫好,讀的那則還在原處。
T.msgs = range(0, Hh + 50); T.winAt = 100; at(80, -12);
doc.hidden = true; outOfView();
// (While away the layout moves — the bar under the chat grows as a bot starts: not measured again.)
sc.scrollTop -= 298; sc.clientHeight = 587;
place(range(0, Hh + 52), false);
T.winAt += 2; place(T.msgs.concat([m(Hh + 52), m(Hh + 53)]), false);
check("在背景:不畫", `${drawn.length}|${T.msgsStale}`, `${Hh + 50}|true`);
sc.clientHeight = 800; doc.hidden = false; backInView();
check("回到前景:收過了、讀的那則不動", `${T.msgs[0].index}|${top()}|${T.keepRead}`, "54|80@-12|null");
// 在背景時在最底下:回到前景還在最底下。
T.msgs = range(0, 100); T.winAt = 0; renderMsgs(); sc.scrollTop = sc.scrollHeight - sc.clientHeight;
doc.hidden = true; outOfView(); sc.scrollTop -= 298; place(range(0, 103), false); doc.hidden = false; backInView();
check("在背景時在最底下:回來還在最底下", `${sc.scrollTop === sc.scrollHeight}`, "true");
// 一直捲在最頂上讀、Bot 一直寫:超過 HOLD×4 就收,清單有上限。
T.msgs = range(0, 4 * Hh); T.winAt = 4 * Hh - 100; at(0, 0);
// (Each time: three new at the bottom, three leaving the window into the front — takePart's way.)
for (let k = 0, next = 4 * Hh; k < 200; k++, next += 3) { T.winAt += 3; place(T.msgs.concat([m(next), m(next + 1), m(next + 2)]), false); }
check("一直讀最頂上:清單不超過 HOLD×4", `${T.msgs.length}`, `${4 * Hh}`);
// 在最底下:跟著最底下,前面多留的收到 HOLD。
T.msgs = range(0, Hh + 50); T.winAt = 100; renderMsgs(); sc.scrollTop = sc.scrollHeight - sc.clientHeight;
place(range(0, Hh + 52), true);
check("在最底下:收到 HOLD、跟著最底下", `${T.msgs.length}|${sc.scrollTop === sc.scrollHeight}`, `${Hh}|true`);
}
if (failed) process.exitCode = 1;

View File

@ -158,6 +158,7 @@ details.dt>.dt-in{padding-left:var(--sp-4);margin-top:var(--sp-2)}
:is(.bub,.page,.tk-a) :is(ul,ol){margin:0 0 .75em;padding-left:1.4em}
:is(.bub,.page,.tk-a) li{margin:0 0 6px}
:is(.bub,.page,.tk-a) li:last-child{margin-bottom:0}
:is(.bub,.page,.tk-a) li>:is(ul,ol,p,blockquote,pre,.tw){margin:.35em 0 0}
:is(.bub,.page,.tk-a) li.task{list-style:none;margin-left:-1.2em}
:is(.bub,.page) :is(h2,h3,h4){font-family:var(--font-read);font-weight:600;line-height:1.35;color:var(--text)}
.bub h2{font-size:var(--fs-h3);margin:1.2em 0 .4em}
@ -1298,7 +1299,7 @@ function signOut(expired) {
S.token = ""; localStorage.removeItem("anybot.token"); S.version = 0; S.entered = false; NAV.length = 0; CHATS.clear(); callOffEarly(); EARLY.me = null; show("login");
// Nothing of this account stays on the phone: last states, chats, details, unsent messages.
clearTimeout(keepTimer); keepTimer = 0; OUT.length = 0; S.st = null; S.ssig = ""; S.stHost = ""; S.stale = false; S.detail = {}; S.detailNew = {}; S.settings = null;
S.open = 0; S.msgs = []; S.chatSig = ""; KEEP.clear();
S.open = 0; S.msgs = []; S.winAt = 0; S.oldCopy = false; S.chatSig = ""; KEEP.clear();
if (expired) $("login-err").textContent = "登入已失效,請重新登入" + (lost ? `(還沒送出的 ${lost} 則訊息已清掉)` : "");
}
// 登出這支手機, from the 帳戶選單 or 設定 › 手機與帳號: the same question both ways (the menu's
@ -1446,7 +1447,7 @@ async function restore() {
S.relay = known === "1";
S.st = st; S.ssig = st.ssig || ""; S.stHost = host; S.version = 0; S.stale = true;
const c = S.open && CHATS.get(chatKey(S.open));
if (c) { S.msgs = c.msgs; S.chatSig = c.sig; S.chatLoaded = true; }
if (c) { takeKept(c); S.chatLoaded = true; }
apply(st);
enter();
}
@ -1522,7 +1523,7 @@ function apply(v) {
// we go in) but don't draw the inside yet.
if (!S.entered) {
const c = v.chat;
if (c && c.bot === S.open && c.messages && c.from === undefined) { S.msgs = c.messages; S.chatSig = c.sig || ""; mergeDeliveries(S.msgs, c.deliveries); }
if (c && c.bot === S.open && c.messages && c.from === undefined) { S.msgs = takeWhole(c.messages); S.chatSig = c.sig || ""; mergeDeliveries(S.msgs, c.deliveries); }
return;
}
// An approval answered from a notification banner, and a home-screen shortcut (主要 Bot, 未讀).
@ -1553,8 +1554,8 @@ function apply(v) {
}
// 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.
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, c.deliveries);
else if (c && c.bot === S.open && c.messages && c.from !== undefined) { if (c.base === S.chatSig) applyChat(takePart(c), c.sig, c.deliveries); else loadChat(); }
else if (c && c.bot === S.open && c.messages) applyChat(takeWhole(c.messages), c.sig, c.deliveries);
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));
@ -1853,7 +1854,7 @@ function keepNow() {
if (!S.token || !S.st || S.stale || S.stHost !== S.host) return;
const st = Object.assign({}, S.st); delete st.chat;
KEEP.put("st:" + S.stHost, st);
if (S.open && S.chatSig) keepChat(S.open, S.msgs, S.chatSig);
if (S.open && S.chatSig) keepChat(S.open, S.msgs, S.chatSig, S.winAt);
}
// 看過的聊天(最多 12 份,每台電腦各自記):回到它先畫上次看到的,再只拿有變的部分。
const CHATS = new Map();
@ -1861,8 +1862,8 @@ const chatKey = (id) => S.host + ":" + id;
function toHost(h) {
if (h === S.host) return;
keepNow();
if (S.chatSig) keepChat(S.open, S.msgs, S.chatSig);
S.open = 0; S.msgs = []; S.chatSig = "";
if (S.chatSig) keepChat(S.open, S.msgs, S.chatSig, S.winAt);
S.open = 0; S.msgs = []; S.winAt = 0; S.oldCopy = false; S.chatSig = "";
S.host = h; if (h) localStorage.setItem("anybot.host", h); else localStorage.removeItem("anybot.host");
// Nothing of the other computer stays on screen or goes to this one (a message typed to one of
// its bots would reach this one's bot with the same number): its list, state, details and
@ -1880,12 +1881,15 @@ function toHost(h) {
apply(st); enter();
});
}
function keepChat(id, msgs, sig) {
function keepChat(id, msgs, sig, winAt) {
if (!id || !sig) return;
// (Each kept with its own name and when it was last seen: found again by its prefix.)
const k = chatKey(id), was = CHATS.get(k), c = {k, msgs, sig, t: Date.now()};
if (!was || was.sig !== sig || Date.now() - (was.t || 0) > 3600000) KEEP.put("chat:" + k, c);
CHATS.delete(k); CHATS.set(k, was && was.sig === sig && Date.now() - (was.t || 0) <= 3600000 ? was : c);
// (Each kept with its own name and when it was last seen: found again by its prefix. With how
// many of its messages are from before the brain's window — 載入更早 — or the next answer,
// told against that window, lands in the wrong place.)
const k = chatKey(id), was = CHATS.get(k), c = {k, msgs, sig, winAt: winAt || 0, t: Date.now()};
const same = was && was.sig === sig && was.winAt === c.winAt && (was.msgs || []).length === msgs.length && Date.now() - (was.t || 0) <= 3600000;
if (!same) KEEP.put("chat:" + k, c);
CHATS.delete(k); CHATS.set(k, same ? was : c);
while (CHATS.size > 12) { const old = CHATS.keys().next().value; CHATS.delete(old); KEEP.del("chat:" + old); }
}
// What was typed and not sent stays with its bot, as on the computer: switching bots, or closing
@ -1908,11 +1912,11 @@ function openChat(id, at) {
box.value = drafts()[id] || ""; box.style.height = "auto"; setTimeout(() => box.dispatchEvent(new Event("input")), 0);
}
if (S.open !== id) {
keepChat(S.open, S.msgs, S.chatSig);
S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; S.prevFirst = ""; MODE_OPEN = ""; $("msgs").innerHTML = "";
keepChat(S.open, S.msgs, S.chatSig, S.winAt);
S.msgs = []; S.winAt = 0; S.oldCopy = false; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; S.prevFirst = ""; MODE_OPEN = ""; $("msgs").innerHTML = "";
const kept = CHATS.get(chatKey(id));
S.chatLoaded = !!kept;
if (kept) { S.msgs = kept.msgs; S.chatSig = kept.sig; }
if (kept) takeKept(kept);
}
S.open = id;
// Your bubbles as 聊天的顏色 on the computer says (ob.bubble): "quiet" a light grey with the
@ -1939,16 +1943,17 @@ async function loadChat(jump) {
// 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; }
// 只有交付確認動了:蓋上新的,不重抓。(Not a return: it left `loading` set for good — from then
// on every chat opened, 表情 and the like only asked again later, and a chat showed what this
// phone kept until the next poll happened to carry it, 20–40 s on a quiet line; 11/20–11/23.)
if (v.unchanged && S.open === id && S.host === host) { if (mergeDeliveries(S.msgs, v.deliveries)) renderMsgs(); }
// (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) {
const msgs = v.from === undefined ? v.messages || [] : v.base === held ? S.msgs.slice(v.drop || 0).slice(0, v.from).concat(v.messages || []) : null;
else if (S.open === id && S.chatSig === held && S.host === host) {
const msgs = v.from === undefined ? takeWhole(v.messages || []) : v.base === held ? takePart(v) : null;
if (msgs) {
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();
if (jump || near) sc.scrollTop = sc.scrollHeight;
S.chatSig = v.sig || ""; S.chatLoaded = true; place(msgs, jump || near); keepSoon();
jumpTo();
} else { S.chatSig = ""; again = true; }
}
@ -1960,36 +1965,148 @@ async function loadChat(jump) {
}
// 載入更早:開頁只拿最新 30 條,這裡一次往回補 60 條(序號去重,接在上方)——從大腦上整段聊天拿,
// 不只手機那份最新的。按了一定有回應:載入中、補上了、或「已是對話最開頭」(按鈕收起來)。
async function loadOlder() {
async function loadOlder(again) {
if (!S.open || !S.msgs.length || !(S.msgs[0].index > 0) || S.olderBusy) return;
const id = S.open;
const id = S.open, host = S.host, from = S.msgs[0].index, fromAt = S.msgs[0].at;
let moved = false;
S.olderBusy = true; renderMsgs();
try {
const v = await api(base() + `api/bots/${id}/older?from=${S.msgs[0].index}&count=60`);
if (S.open !== id) return;
const v = await api(base() + `api/bots/${id}/older?from=${from}&count=60`);
if (S.open !== id || S.host !== host) return;
// (The chat's start moved while it was asked — an older message left the window as a bot
// worked, a new conversation: these are from before another start, and on top they would
// leave a hole that stays. Asked again from where it starts now, once.)
if (!S.msgs.length || S.msgs[0].index !== from || S.msgs[0].at !== fromAt) { moved = true; return; }
const have = new Set(S.msgs.map((m) => m.index));
const add = (v.messages || []).filter((m) => !have.has(m.index));
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.msgs = add.concat(S.msgs); S.winAt = (S.winAt || 0) + add.length;
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(); } }
finally {
if (S.olderBusy) { S.olderBusy = false; if (S.open === id) renderMsgs(); }
if (moved && !again) loadOlder(true);
}
// The state poll carried the open chat's messages along (single trip): take them as-is.
}
// What the brain sends is its window of the chat: the newest it publishes (PHONE_TAIL, steps'
// results left out), from where this page says its copy starts (w0). 載入更早 brings messages
// from before that window — S.winAt of them, held in front of it as long as the window still
// begins on a message this page has; the next answer used to put the window alone in their
// place, and what was just loaded went away again (11/23: one new message, and the chat was
// back to 120 with 「載入更早的對話」 on top).
function takeWhole(msgs) {
const f = msgs[0];
// (A copy kept by a page from before 11/23 may hold a hole the old way left — what it had loaded
// and the newest, with the middle gone: none of its front is kept, once.)
const old = S.oldCopy; S.oldCopy = false;
const j = f && !old ? S.msgs.findIndex((m) => m.index === f.index && m.role === f.role && (m.at || 0) === (f.at || 0)) : -1;
S.winAt = j > 0 ? j : 0;
return j > 0 ? S.msgs.slice(0, j).concat(msgs) : msgs;
}
// Only where the window differs: drop its first `drop` (the oldest left it), keep the next `from`,
// then the new ones — the ones held in front stay, and with them the ones that left the window
// (no gap between); with none in front, those leave as before (the first open stays small).
function takePart(c) {
const at = S.winAt || 0, win = S.msgs.slice(at), drop = c.drop || 0;
const pre = at ? S.msgs.slice(0, at).concat(win.slice(0, drop)) : [];
S.winAt = pre.length;
return pre.concat(win.slice(drop).slice(0, c.from), c.messages || []);
}
// A kept copy, as it was: one kept before it said how many were from before the window has no
// fingerprint to be told against — the next answer is whole, and placed by its first message.
function takeKept(c) {
S.msgs = c.msgs; S.winAt = c.winAt || 0; S.oldCopy = c.winAt === undefined; S.chatSig = S.oldCopy ? "" : c.sig;
}
// What 載入更早 brought stays — but not without end: once the person is back at the bottom (or
// the page isn't in view), more than HOLD held and some from before the window, those go from the
// top (the button comes back). A phone left open for days would otherwise draw thousands, every
// second while a bot works.
const HOLD = 300;
function trimFront(most) {
const cut = Math.min(S.winAt || 0, S.msgs.length - HOLD, most === undefined ? Infinity : most);
if (cut > 0) { S.msgs = S.msgs.slice(cut); S.winAt -= cut; }
}
// What the person is reading: the first message on screen (its place in the whole chat) and how
// far down it sits — read off what is drawn (S.drawn: a page not in view isn't drawn again, and
// S.msgs may have moved on since).
function anchorNow() {
const top = $("scroller").getBoundingClientRect().top, drawn = S.drawn || S.msgs;
for (const el of $("msgs").querySelectorAll("[data-msg]")) {
const r = el.getBoundingClientRect(), m = drawn[+el.dataset.msg];
if (m && r.bottom > top) return {index: m.index, off: r.top - top};
}
return null;
}
// Back to it once drawn: the end, or that message where it was.
function holdRead(a) {
const sc = $("scroller");
if (!a) return;
if (a.end) { sc.scrollTop = sc.scrollHeight; return; }
const p = S.msgs.findIndex((m) => m.index === a.index), el = p < 0 ? null : $("msgs").querySelector(`[data-msg="${p}"]`);
if (el) sc.scrollTop += el.getBoundingClientRect().top - sc.getBoundingClientRect().top - a.off;
}
// Out of view: where the person was, taken now — while it is away the page isn't drawn, and what
// moves meanwhile (the bar under the chat growing as a bot starts, the list changing) is no
// place to measure it from (it drifted, 11/23).
function outOfView() {
if (S.view !== "chat" || !S.open) { S.keepRead = null; return; }
const sc = $("scroller");
S.keepRead = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140 ? {end: true} : anchorNow();
}
// In view again: drawn as it is now, and held where the person was (or at the end).
function backInView() {
if (S.msgsStale) { renderMsgs(); holdRead(S.keepRead); }
S.keepRead = null;
}
// A new list in place. Back at the bottom it follows the end, and what 載入更早 brought past HOLD
// goes. Further up, the message being read stays where it is on screen, whatever changes above it
// — and above HOLD×2 (HOLD while the page isn't in view: a phone in a pocket, a bot at work) the
// top goes too, up to 20 above that message. Past HOLD×4 the top goes regardless — read at the very
// top while a bot writes for hours, the list still has an end (what is read may then go with it).
// Not in view, nothing is drawn: where to be is kept, and taken back when it is (backInView).
function place(msgs, follow) {
// (Out of view: where it was when it went — not measured again on a page that isn't drawn.)
const away = document.hidden && S.keepRead;
const a = away ? S.keepRead : follow ? {end: true} : anchorNow();
if (away) follow = !!a.end;
S.msgs = msgs;
const n = S.msgs.length, most = (a && !a.end ? S.msgs.findIndex((m) => m.index === a.index) : -1) - 20;
if (follow) trimFront();
else if (n > 4 * HOLD) trimFront(Math.max(most, n - 4 * HOLD));
else if (n > (document.hidden ? HOLD : 2 * HOLD)) trimFront(most);
renderMsgs();
if (document.hidden) { S.keepRead = a; return; }
holdRead(a);
}
// 表情 on a message from before the brain's window: the brain has it, but no answer will say so —
// that message isn't in the window. Its reactions as the brain now has them (asked, not guessed:
// another device may have changed them too).
async function reacted(v, index) {
const i = v ? S.msgs.findIndex((m) => m.index === index) : -1;
if (i >= 0 && i < (S.winAt || 0)) {
const id = S.open;
try {
const o = await api(base() + `api/bots/${id}/older?from=${index + 1}&count=1`);
// (Only one still in front of the window: one the window took meanwhile comes with it.)
const got = (o.messages || []).find((m) => m.index === index), k = S.open === id ? S.msgs.findIndex((m) => m.index === index) : -1;
if (got && k >= 0 && k < (S.winAt || 0)) { S.msgs[k].reactions = got.reactions || []; renderMsgs(); }
} catch (_) {}
}
loadChat();
}
// The state poll carried the open chat's messages along (single trip): take them as they come.
function applyChat(msgs, sig, deliveries) {
S.chatSig = sig || ""; S.chatLoaded = true;
const sc = $("scroller");
const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140;
mergeDeliveries(msgs, deliveries);
S.msgs = msgs;
renderMsgs(); keepSoon();
if (near) sc.scrollTop = sc.scrollHeight;
place(msgs, near); keepSoon();
jumpTo();
}
// 交付確認(✓ mark)與訊息分開送(服务端也分開放:别的装置回報檔案不該改到聊天指紋):
@ -2319,7 +2436,7 @@ function renderMsgs() {
const said = x.failed ? "沒送出,點一下拿回來重送" : x.sentAt ? (busy ? "已排入,它下一步會看到" : "已送出") : x.going ? "傳送中…" : "等連線後送出(點一下拿回來)";
h += `<div class="m user sending${x.failed ? " failed" : ""}${held ? " held" : ""}" data-unsent="${esc(x.id)}">${x.text ? `<div class="bub">${esc(x.text)}</div>` : ""}${names}<div class="sn">${said}</div></div>`;
});
$("msgs").innerHTML = h;
$("msgs").innerHTML = h; S.drawn = S.msgs;
// (Diagrams in the answers: drawn by the brain once they are on the page.)
if ($("msgs").querySelector(".chart[data-mermaid]")) loadCharts();
renderSendBtn();
@ -2358,7 +2475,7 @@ $("msgs").addEventListener("click", async (e) => {
if (e.target.closest("[data-resend]")) { act("reply", {bot: S.open}); return; }
if (e.target.closest("[data-resume]")) { act("resume", {bot: S.open}, "繼續中…"); return; }
const mo = e.target.closest("[data-more]"); if (mo) { msgMenu(+mo.dataset.more); return; }
const r = e.target.closest("[data-react]"); if (r) { act("react", {bot: S.open, index: +r.dataset.i, emoji: r.dataset.react}, false).then(() => loadChat()); return; }
const r = e.target.closest("[data-react]"); if (r) { act("react", {bot: S.open, index: +r.dataset.i, emoji: r.dataset.react}, false).then((v) => reacted(v, +r.dataset.i)); return; }
const sg = e.target.closest("[data-sugg]");
if (sg) {
const text = SUGGEST[+sg.dataset.sugg][3];
@ -2436,7 +2553,7 @@ function msgMenu(i) {
}});
const emojis = m.index != null && owner() ? `<div class="emojis">${QUICK.map((e) => `<button data-e="${e}">${e}</button>`).join("")}</div>` : "";
const el = sheet("", items, emojis);
el.querySelectorAll("[data-e]").forEach((b) => b.onclick = () => { closeSheet(); act("react", {bot: S.open, index: m.index, emoji: b.dataset.e}, false).then(() => loadChat()); });
el.querySelectorAll("[data-e]").forEach((b) => b.onclick = () => { closeSheet(); act("react", {bot: S.open, index: m.index, emoji: b.dataset.e}, false).then((v) => reacted(v, m.index)); });
}
async function regen() { try { await api(base() + `api/bots/${S.open}/regenerate`, {json: {}}); toast("重新產生中…"); } catch (e) { toast(e.message); } }
// The dock: what needs the person (允許 / 需要處理), what is queued, then the composer.
@ -4639,13 +4756,31 @@ function pageMd(text, id, rev) {
continue;
}
if (/^([-*+•]|\d+[.)])\s+/.test(t)) {
const ordered = /^\d/.test(t); const items = [];
while (i < L.length && /^\s*([-*+•]|\d+[.)])\s+/.test(L[i])) {
const it = L[i++].trim().replace(/^([-*+•]|\d+[.)])\s+/, "");
const task = it.match(/^\[( |x|X)\]\s+(.*)$/);
items.push(task ? `<li class="task">${task[1] === " " ? "☐" : "☑"} ${inl(task[2])}</li>` : `<li>${inl(it)}</li>`);
// One list, the way Markdown reads it: items of one kind at this depth, with blank lines
// between them or not — a spaced-out 「1. … 2. … 3.」 was three lists of one, and every point
// read 1. — numbered from the first one's number. What is indented under an item is that
// item's: more of its words, or a list (or quote, code…) inside it — sub-points were flattened
// into the numbered ones.
const ordered = /^\d/.test(t), start = ordered ? parseInt(t, 10) : 1, items = [];
const kind = ordered ? /^\d+[.)]\s+/ : /^[-*+•]\s+/;
const indent = (x) => x.length - x.trimStart().length, base = indent(l);
const same = (x) => x.trim() && indent(x) < base + 2 && kind.test(x.trim());
while (i < L.length && same(L[i])) {
const head = L[i++].trim().replace(kind, ""), under = [];
for (;;) {
let j = i; while (j < L.length && !L[j].trim()) j++;
if (j < L.length && indent(L[j]) >= base + 2) { while (i <= j) under.push(L[i++]); } else break;
}
out.push(ordered ? `<ol>${items.join("")}</ol>` : `<ul>${items.join("")}</ul>`); continue;
let j = i; while (j < L.length && !L[j].trim()) j++;
if (j > i && j < L.length && same(L[j])) i = j;
const task = head.match(/^\[( |x|X)\]\s+(.*)$/);
const words = task ? `${task[1] === " " ? "☐" : "☑"} ${inl(task[2])}` : inl(head);
const lines = under.filter((x) => x.trim()), cut = Math.min(...lines.map(indent));
const plain = lines.length === under.length && lines.every((x) => !/^(#{1,6}\s|```|>|\||([-*+•]|\d+[.)])\s)/.test(x.trim()));
const inner = !lines.length ? "" : plain ? lines.map((x) => "<br>" + inl(x.trim())).join("") : pageMd(under.map((x) => x.slice(Math.min(cut, indent(x)))).join("\n"), id, rev);
items.push(`<li${task ? ' class="task"' : ""}>${words}${inner}</li>`);
}
out.push(ordered ? `<ol${start !== 1 ? ` start="${start}"` : ""}>${items.join("")}</ol>` : `<ul>${items.join("")}</ul>`); continue;
}
const para = [];
while (i < L.length && L[i].trim() && !/^(#{1,6}\s|```|>|\||([-*+•]|\d+[.)])\s)/.test(L[i].trim())) para.push(L[i++].trim());
@ -5317,7 +5452,7 @@ if (window.visualViewport) {
visualViewport.addEventListener("resize", kb);
visualViewport.addEventListener("scroll", kb);
}
document.addEventListener("visibilitychange", () => { if (document.hidden) { keepNow(); swapWhenAway(); return; } setTimeout(() => { picking = false; }, 1000); if (S.msgsStale) renderMsgs(); kick(); if (S.view === "screen") startFrames(); });
document.addEventListener("visibilitychange", () => { if (document.hidden) { outOfView(); keepNow(); swapWhenAway(); return; } setTimeout(() => { picking = false; }, 1000); backInView(); kick(); if (S.view === "screen") startFrames(); });
addEventListener("online", kick);
addEventListener("offline", () => { if (S.token) netDown(true); });
addEventListener("pageshow", (e) => { if (e.persisted) kick(); });

32
mobile/markdown.test.mjs Normal file
View File

@ -0,0 +1,32 @@
// 手機的 Markdown 清單(mobile/index.html 的 pageMd,聊天和頁面都用它):照 Markdown 的讀法——
// 空一行再接同一種項目還是同一個清單(以前每一點各自成一個清單,每一點都是「1.」,11/23),編號從
// 第一點寫的數字起,縮排在項目底下的是那一點的(續行或子清單,以前子項目被攤平成同一層、一起編號)。
import { readFileSync } from "node:fs";
const page = readFileSync(new URL("./index.html", import.meta.url), "utf8");
const at = page.indexOf("function pageMd(");
if (at < 0) throw new Error("index.html 裡沒有 pageMd");
const src = page.slice(at, page.indexOf("\n}\n", at) + 2);
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
const pageMd = new Function("inl", "esc", `${src}\nreturn pageMd;`)(esc, esc);
let failed = 0;
const check = (what, got, want) => {
if (got === want) console.log(`OK ${what}`);
else { failed++; console.log(`FAIL ${what}:\n 得到 ${got}\n 應該 ${want}`); }
};
check("空行隔開、每點都寫 1.:同一個清單", pageMd("1. 甲\n\n1. 乙\n\n1. 丙"), "<ol><li>甲</li><li>乙</li><li>丙</li></ol>");
check("空行隔開的 1. 2. 3.:同一個清單", pageMd("1. 甲\n\n2. 乙\n\n3. 丙"), "<ol><li>甲</li><li>乙</li><li>丙</li></ol>");
check("緊接著的照舊", pageMd("1. 甲\n2. 乙"), "<ol><li>甲</li><li>乙</li></ol>");
check("從 3 開始", pageMd("3. 甲\n4. 乙"), '<ol start="3"><li>甲</li><li>乙</li></ol>');
check("子清單在那一點裡,不攤平", pageMd("1. **甲**\n - x\n - y\n2. 乙"), "<ol><li>**甲**<ul><li>x</li><li>y</li></ul></li><li>乙</li></ol>");
check("空行後縮排的子清單也是那一點的", pageMd("1. 甲\n\n - x\n\n2. 乙"), "<ol><li>甲<ul><li>x</li></ul></li><li>乙</li></ol>");
check("縮排的續行是同一點的字", pageMd("- 甲\n 還有\n- 乙"), "<ul><li>甲<br>還有</li><li>乙</li></ul>");
check("段落把清單隔開:後面那個照它寫的數字", pageMd("1. 甲\n\n中間一段\n\n2. 乙"), '<ol><li>甲</li></ol><p>中間一段</p><ol start="2"><li>乙</li></ol>');
check("不同種類的項目:兩個清單", pageMd("- 甲\n1. 乙"), "<ul><li>甲</li></ul><ol><li>乙</li></ol>");
check("待辦清單", pageMd("- [ ] 甲\n- [x] 乙"), '<ul><li class="task">☐ 甲</li><li class="task">☑ 乙</li></ul>');
check("清單後面空一行接段落:段落不算進去", pageMd("1. 甲\n2. 乙\n\n結論"), "<ol><li>甲</li><li>乙</li></ol><p>結論</p>");
check("一般段落不受影響", pageMd("第一行\n第二行\n\n第二段"), "<p>第一行<br>第二行</p><p>第二段</p>");
if (failed) process.exitCode = 1;

View File

@ -295,11 +295,18 @@ fn tick(cfg: &Config, resting: &mut HashMap<String, (Instant, u32)>) -> Vec<Stri
// and was made with it — taken away at once (not when it is made again, which can keep
// failing), given back when it was lost, never given to one made without it (one put back or
// woken after a failed remake).
if let Some(n) = &cfg.docker_network {
// (Not while the owner isn't known — no account yet and none kept: whose Docker it is can't be
// told, and the owner's own would be taken away until the accounts come back. A change that
// fails is said, and tried again next tick.)
if let (Some(n), Some(o)) = (&cfg.docker_network, owner.as_deref()) {
for (u, e) in &existing {
let want = e.docker && gets_docker(u, owner.as_deref(), &cfg.docker_users);
if want != on_network(e, n) && docker(&["network", if want { "connect" } else { "disconnect" }, n, &e.name]).is_ok() {
log::info!("AnyBot 大腦管理員:{u} 的雲端大腦{}", if want { "接回 Docker" } else { "拿掉 Docker" });
let want = e.docker && gets_docker(u, Some(o), &cfg.docker_users);
if want == on_network(e, n) {
continue;
}
match docker(&["network", if want { "connect" } else { "disconnect" }, n, &e.name]) {
Ok(_) => log::info!("AnyBot 大腦管理員:{u} 的雲端大腦{}", if want { "接回 Docker" } else { "拿掉 Docker" }),
Err(err) => errors.push(format!("{u} 的雲端大腦{}失敗:{err}", if want { "接回 Docker " } else { "拿掉 Docker " })),
}
}
}

View File

@ -3725,6 +3725,37 @@ mod tests {
assert!(text.matches("OK").count() >= 13, "{text}");
}
/// 載入更早 stays loaded: the brain sends its window of the chat (the newest it publishes,
/// from where the page's copy starts), and the messages loaded from before it stay in front of
/// it — the next answer used to put the window alone in their place (11/23). The page's own
/// takeWhole/takePart, run in node when it is there.
#[test]
fn messages_loaded_from_before_the_window_stay() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("mobile");
let Ok(out) = std::process::Command::new("node").arg("chatwindow.test.mjs").current_dir(&dir).output() else {
eprintln!("(沒有 node:略過手機聊天視窗的測試)");
return;
};
let text = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success() && !text.contains("FAIL"), "{text}{}", String::from_utf8_lossy(&out.stderr));
assert!(text.matches("OK").count() >= 30, "{text}");
}
/// The phone reads a list the way Markdown does: one list across blank lines (every point of a
/// spaced-out list read 「1.」), numbered from its first number, sub-points inside their point.
/// The page's own pageMd, run in node when it is there.
#[test]
fn a_numbered_list_counts_on_the_phone() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("mobile");
let Ok(out) = std::process::Command::new("node").arg("markdown.test.mjs").current_dir(&dir).output() else {
eprintln!("(沒有 node:略過手機 Markdown 清單的測試)");
return;
};
let text = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success() && !text.contains("FAIL"), "{text}{}", String::from_utf8_lossy(&out.stderr));
assert!(text.matches("OK").count() >= 12, "{text}");
}
use super::*;
/// A chart goes to the phone only as shapes and words: whatever a bot (or a page it read)