diff --git a/FEATURES.md b/FEATURES.md index 7f9db3b..29c11f1 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -228,6 +228,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 支援簡單排版: - 標題(# / ## / ###):17 px 粗體,行高 24 px。 - 項目符號(- 或 *):依縮排往內縮。 + - 編號清單照 Markdown 的讀法(電腦和手機一樣):項目之間空一行還是同一個清單,編號從第一點寫的數字起(模型每點都寫「1.」也排成 1、2、3);縮排在一點底下的是那一點的——續行或子清單。以前手機頁面遇到空行就把清單切斷,空一行寫的清單每一點都是「1.」,子項目也被攤平成同一層一起編號(11/23 修)。 - 整行粗體(**…**)。 - 程式碼區塊(```):灰底,圓角 8 px,等寬字 13 px,行高 18 px。 - 其他行內的 ** 和 ` 符號會被拿掉。 @@ -263,7 +264,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 開聊天分頁(手機頁面) - 手機打開聊天先只拿最新 30 條訊息(慢線上開頁省流量)。 -- 有更早的,頂上出現「載入更早的對話」,點一次往前補 60 條;翻到最頂說「已是對話最開頭」、按鈕消失。補的是大腦上整段聊天(App 自己組,跟發布的那份同一套:步驟帶結果、檔案的 ✓),不只發布給手機的最新 120 則——以前只在那 120 則裡往回找,有工具步驟的聊天(Jenny 一輪 65 步,120 則還裝不下這一輪)很快就找完,按鈕還在卻按了沒反應(拿到的都是手上已有的,頁面什麼也不說)。補的時候按鈕寫「載入中…」、不能連按,補完畫面停在原本看的地方;沒有 App 在跑時(只測伺服器)照舊從發布的那份找。 +- 有更早的,頂上出現「載入更早的對話」,點一次往前補 60 條;翻到最頂說「已是對話最開頭」、按鈕消失。補的是大腦上整段聊天(App 自己組,跟發布的那份同一套:步驟帶結果、檔案的 ✓),不只發布給手機的最新 120 則——以前只在那 120 則裡往回找,有工具步驟的聊天(Jenny 一輪 65 步,120 則還裝不下這一輪)很快就找完,按鈕還在卻按了沒反應(拿到的都是手上已有的,頁面什麼也不說)。補的時候按鈕寫「載入中…」、不能連按,補完畫面停在原本看的地方;補上來的一直留著:大腦之後送來的仍是它那一段(最新 120 則,從手機手上那份的開頭起),手機把它接在補上來的那些後面,新訊息把那一段往後推時,離開那一段的也接在前面(以前下一次更新、例如來一則新訊息,就整份換成那 120 則,剛補的又不見、按鈕跑回來);手機存起來的那份記著其中幾則是補上來的,切到別的 Bot 再回來、頁面重開也接得對;對補上來的訊息按表情,手機向大腦拿那則現在的表情畫上(大腦送來的那一段沒有它);等「載入更早」回來時聊天開頭移了(Bot 做步驟、舊的離開那一段,或開了新對話),那批不接、從現在的開頭再問一次(接上去會留下一直在的缺口);回到最底下時手機最多留 300 則,多的從頂上收掉、按鈕回來;捲在上面讀時超過 600 則(頁面不在前景時 300 則)也收,最多收到正在讀的那則上面 20 則,正在讀的那則留在畫面同一個地方(頁面不在前景時不重畫,回到前景畫好再放回那裡);一直停在最頂上讀、Bot 又寫了上千則時,超過 1200 則就照樣從頂上收(一直開著不會越積越多);11/23 以前的頁面存的那份,第一次只留大腦送來的那段(舊的錯誤可能在裡面留了缺口);點進聊天立刻拿新的(以前大腦回「沒變」一次之後,手機就再也不自己去拿,點進聊天要等輪詢順便帶過來,20–40 秒);沒有 App 在跑時(只測伺服器)照舊從發布的那份找。 - 手機說它手上那份從哪一則開始(`w0`、載入更早的 `from`),用的是那則在整段聊天裡的位置(`index`,數到 Bot 每個工具步驟);大腦照這個位置找到清單裡對應的那則再開始。以前大腦把它當成「清單裡第幾則」——清單只是最新 120 則去掉工具步驟,短得多——有工具步驟的聊天就切到清單外、回一份空的,下一次手機手上沒東西、又拿到整段:點進去一次有聊天記錄、一次全空(jenny-Host 11/21,1133 則的聊天、清單 40 則左右)。 - Bot 回答中,手機每秒最多更新一次聊天(慢線上畫面落後約一秒);打完的整句一定補齊。 - 電腦開對話照樣整段;直接查聊底的指令和腳本也照舊拿全部。 @@ -2391,7 +2392,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - **一行裝好、每個帳號自己的雲端大腦**(2026-11-23,`docs/plan-2026-11-install.md`): - 在 Linux 上貼 `curl … install.sh | sh -s -- server`,**不問任何問題**:沒有 Docker 就裝好並設成開機自動跑(rootless 也打開 linger)、裝系統套件(含 `make`)、建置、啟動;最後只印網址和**邀請碼**。剛加進 docker 群組的人用 `sg` 跑設定(不再用 sudo:以前 `.env`、`Caddyfile`、`~/.docker` 變成 root 的,之後的更新全部「Permission denied」);之前留下的 root 檔案會自己改回來。 - 網址自己找:`ANYBOT_SETUP_DOMAIN` 給了就用;Tailscale 有發憑證用 `https://名字`;tailnet 不發憑證(headscale)用 `http://tailnet 位址`(WireGuard 加密,AnyBot 只在 tailnet 上收 http;任何指到這台的名字也通,`https://位址` 也在,手機通知用);都沒有用 `https://區網 IP`(自簽,每台裝置先信任一次);公開的位址(VPS)又沒給網域就停下來,請你給網域或裝 Tailscale。以前 headscale 會被給一個永遠連不上的 `https://名字`。綁在某個位址時設 `net.ipv4.ip_nonlocal_bind=1`:重開機時 tailnet 比 Docker 晚起來,caddy 也綁得到。 - - 帳號在 App 或手機上註冊(要邀請碼,第一個人也要)。**大腦管理員**(compose 的 `brains`,`anybot --brains`)看到新帳號就替它開一個雲端大腦 `anybot-brain-帳號`:自己的資料卷,用帳號伺服器發的登入憑證(`/relay/manager/brain`,伺服器上不存密碼);停了會叫醒,重開機自己回來,映像檔換了(更新後)用同一份資料和登入換成新版,不刪任何大腦。**只有擁有者(第一個帳號,管理員第一次看到就記住;完成畫面提醒先自己註冊)和 `ANYBOT_BRAINS_DOCKER` 列的帳號有 Docker**(自己的 Bot 電腦和家目錄卷):大腦上可以跑 hook 和連接器,能動 Docker 就能讀別人的大腦、拿到整台主機;其他帳號的大腦用自己的電腦當手腳。**拿到邀請碼的人,雲端大腦能在這台伺服器的網路裡跑程式**(連得到它的區網、tailnet、主機上的服務):使用者選擇每個帳號都開、只把邀請碼給信任的人,完成畫面寫著。每個大腦都 `--cap-drop NET_RAW`、`no-new-privileges`,有記憶體(`ANYBOT_BRAIN_MEMORY`,預設 4g,不准用 swap 多拿)、CPU(`ANYBOT_BRAIN_CPUS`,預設 2、不超過主機的核心數;Docker 不能限 CPU 時——沒有 CFS 配額,例如沒交出 cpu controller 的 rootless——不設,否則 Docker 拒絕建立)和程序數上限,最多 `ANYBOT_BRAINS_MAX`(預設 20)個,新帳號的大腦排在重建前面;帳號伺服器只相信帶著 `ANYBOT_PROXY_SECRET` 的 Caddy 說的請求來源(大腦直接連進去自己寫 X-Forwarded-For 不算,繞不過註冊、登入、配對的次數限制)——只在 Caddy 是唯一入口時:舊的 Caddyfile(手改的也是)更新時在每個 `reverse_proxy relay:8080 {` 區塊補上送暗號的那行(註解掉的不算),Caddy 檢查過才換上,並重開 caddy;還有別的轉到 relay 的寫法的(一行的、`http://relay:8080`、容器名、帶 matcher、`to`、`{` 後面接註解;同一台 Caddy 代理別的服務不算)、補不了或是 Tailscale serve 模式就不用暗號、照舊(不然走那條路的請求沒有暗號,大家共用一個次數上限),因為 Caddyfile 補不上的每次更新都寫出來、說怎麼自己補,已經有那行的 Caddyfile 還有沒帶暗號、轉到 relay 的路也寫出來;從 `.env` 拿掉的設定(暗號、語音)這次啟動就不再算;要停掉某個帳號的大腦,把它加進 `.env` 的 `ANYBOT_BRAINS_SKIP` 再 `docker stop`。不能在跟帳號伺服器共用的網路上偽造或偷聽封包;管理員跟帳號伺服器講話走只有它們兩個的 `manager` 網路(`relay-manager`),金鑰不經過大腦們的網路。重建前先 `docker stop` 讓它收尾,新的先在舊的旁邊建好(Docker 建立時就檢查所有參數,拒絕的話舊的照常在跑、完全不動),才停舊的、換名字、啟動,新的跑起來才刪舊的,換不成就放回舊的;換不成時原本的停著(上次換到一半管理員被停掉)也叫醒它,放回或叫醒的舊大腦先拿掉現在不該有的 Docker;管理員每一輪核對每個大腦接著的網路:現在設定給 Docker、而且建立時就有 Docker 的才接到 Docker,拿掉立刻生效(不等換成新版),掉了的接回來;新的換上去還沒啟動管理員就被停掉的,下次放回舊的再換一次;要新登入的先拿到登入再動舊的,讀不到原本的登入(Docker 一時沒回答)就先不換,不另外領新的(會把跑著的那個登出);舊的停不下來(或 Docker 沒說它停了)就不換;同一個帳號一直失敗時,隔 1、2、4…分鐘再試,最多隔半小時(不會一直停掉跑得好好的大腦);管理員中途被停掉的下次接回來;更新時先建置,成功了才停管理員(建置失敗它照常在跑;啟動失敗或被 Ctrl-C 中斷也會把它開回來),它收到停止是做完手上那件才結束(最多兩分鐘);問不到 Docker 能不能限 CPU 就重啟再問;停掉(skip)的大腦不算進上限;看的是映像檔裡裝了什麼(各層內容的雜湊,建立時記在標籤上——每次建置映像檔 ID 都不同,舊的那個重建後在 containerd 的儲存裡也查不到),只改 `.env` 或重建出一樣的東西不會重開大腦;開法變了(標籤裡記著雜湊)也重建;`.dockerignore` 不讓 `deploy/server/.env`、`Caddyfile` 進建置;帳號伺服器不再認得它的登入(`/relay/manager/users` 的 `brains`)時發新的。管理員第一次啟動以前就有的帳號不開(`ANYBOT_BRAINS_ALL=1` 才開);它不取代帳號裡不是它開的同名電腦(409),登入的電腦也不能取代它開的大腦(409)。管理員的 API 只認 `ANYBOT_RELAY_MANAGER_TOKEN`、只收伺服器內部直接來的請求(經 Caddy 的一律 404,Caddy 也擋 `/relay/manager/`);`/api/hello` 只在管理員最近一分鐘來過時說 `brains: true`。 + - 帳號在 App 或手機上註冊(要邀請碼,第一個人也要)。**大腦管理員**(compose 的 `brains`,`anybot --brains`)看到新帳號就替它開一個雲端大腦 `anybot-brain-帳號`:自己的資料卷,用帳號伺服器發的登入憑證(`/relay/manager/brain`,伺服器上不存密碼);停了會叫醒,重開機自己回來,映像檔換了(更新後)用同一份資料和登入換成新版,不刪任何大腦。**只有擁有者(第一個帳號,管理員第一次看到就記住;完成畫面提醒先自己註冊)和 `ANYBOT_BRAINS_DOCKER` 列的帳號有 Docker**(自己的 Bot 電腦和家目錄卷):大腦上可以跑 hook 和連接器,能動 Docker 就能讀別人的大腦、拿到整台主機;其他帳號的大腦用自己的電腦當手腳。**拿到邀請碼的人,雲端大腦能在這台伺服器的網路裡跑程式**(連得到它的區網、tailnet、主機上的服務):使用者選擇每個帳號都開、只把邀請碼給信任的人,完成畫面寫著。每個大腦都 `--cap-drop NET_RAW`、`no-new-privileges`,有記憶體(`ANYBOT_BRAIN_MEMORY`,預設 4g,不准用 swap 多拿)、CPU(`ANYBOT_BRAIN_CPUS`,預設 2、不超過主機的核心數;Docker 不能限 CPU 時——沒有 CFS 配額,例如沒交出 cpu controller 的 rootless——不設,否則 Docker 拒絕建立)和程序數上限,最多 `ANYBOT_BRAINS_MAX`(預設 20)個,新帳號的大腦排在重建前面;帳號伺服器只相信帶著 `ANYBOT_PROXY_SECRET` 的 Caddy 說的請求來源(大腦直接連進去自己寫 X-Forwarded-For 不算,繞不過註冊、登入、配對的次數限制)——只在 Caddy 是唯一入口時:舊的 Caddyfile(手改的也是)更新時在每個 `reverse_proxy relay:8080 {` 區塊補上送暗號的那行(註解掉的不算),Caddy 檢查過才換上,並重開 caddy;還有別的轉到 relay 的寫法的(一行的、`http://relay:8080`、容器名、relay 容器的 IP、`.env` 裡(或 `{$變數:預設}` 的預設)指到 relay 的 `{$變數}`、帶 matcher、`to`、`{` 後面接註解;同一台 Caddy 代理別的服務不算)、補不了或是 Tailscale serve 模式就不用暗號、照舊(不然走那條路的請求沒有暗號,大家共用一個次數上限),因為 Caddyfile 補不上的每次更新都寫出來、說怎麼自己補,已經有那行的 Caddyfile 還有沒帶暗號、轉到 relay 的路也寫出來;從 `.env` 拿掉的設定(暗號、語音)這次啟動就不再算;要停掉某個帳號的大腦,把它加進 `.env` 的 `ANYBOT_BRAINS_SKIP` 再 `docker stop`。不能在跟帳號伺服器共用的網路上偽造或偷聽封包;管理員跟帳號伺服器講話走只有它們兩個的 `manager` 網路(`relay-manager`),金鑰不經過大腦們的網路。重建前先 `docker stop` 讓它收尾,新的先在舊的旁邊建好(Docker 建立時就檢查所有參數,拒絕的話舊的照常在跑、完全不動),才停舊的、換名字、啟動,新的跑起來才刪舊的,換不成就放回舊的;換不成時原本的停著(上次換到一半管理員被停掉)也叫醒它,放回或叫醒的舊大腦先拿掉現在不該有的 Docker;管理員每一輪核對每個大腦接著的網路:現在設定給 Docker、而且建立時就有 Docker 的才接到 Docker,拿掉立刻生效(不等換成新版),掉了的接回來(改不成寫進紀錄、下一輪再試;還不知道擁有者是誰時先不動);新的換上去還沒啟動管理員就被停掉的,下次放回舊的再換一次;要新登入的先拿到登入再動舊的,讀不到原本的登入(Docker 一時沒回答)就先不換,不另外領新的(會把跑著的那個登出);舊的停不下來(或 Docker 沒說它停了)就不換;同一個帳號一直失敗時,隔 1、2、4…分鐘再試,最多隔半小時(不會一直停掉跑得好好的大腦);管理員中途被停掉的下次接回來;更新時先建置,成功了才停管理員(建置失敗它照常在跑;啟動失敗或被 Ctrl-C 中斷也會把它開回來),它收到停止是做完手上那件才結束(最多兩分鐘);問不到 Docker 能不能限 CPU 就重啟再問;停掉(skip)的大腦不算進上限;看的是映像檔裡裝了什麼(各層內容的雜湊,建立時記在標籤上——每次建置映像檔 ID 都不同,舊的那個重建後在 containerd 的儲存裡也查不到),只改 `.env` 或重建出一樣的東西不會重開大腦;開法變了(標籤裡記著雜湊)也重建;`.dockerignore` 不讓 `deploy/server/.env`、`Caddyfile` 進建置;帳號伺服器不再認得它的登入(`/relay/manager/users` 的 `brains`)時發新的。管理員第一次啟動以前就有的帳號不開(`ANYBOT_BRAINS_ALL=1` 才開);它不取代帳號裡不是它開的同名電腦(409),登入的電腦也不能取代它開的大腦(409)。管理員的 API 只認 `ANYBOT_RELAY_MANAGER_TOKEN`、只收伺服器內部直接來的請求(經 Caddy 的一律 404,Caddy 也擋 `/relay/manager/`);`/api/hello` 只在管理員最近一分鐘來過時說 `brains: true`。 - 電腦註冊或登入這種伺服器(`/api/hello` 有 `brains: true`)時,等那個雲端大腦上線再當它的螢幕(「正在等你的雲端大腦開好…」,最多約一分半),不會先把自己當成大腦。 - 舊的單一帳號伺服器(`.env` 有 `ANYBOT_USER`):原本的大腦照舊(compose 的 `owner-brain` 設定檔,更新時自動打開),管理員不替那個帳號再開;更新時補上管理員的金鑰。舊的問答流程:`setup.sh --ask`。 - 實測:全新 Ubuntu 24.04(有 systemd、沒有 Docker)一行裝好約 14 分鐘;註冊兩個帳號,各自的雲端大腦 5 秒內出現、只看得到自己的;`make update-server`、重開機都自己回來。 diff --git a/deploy/server/setup.sh b/deploy/server/setup.sh index 4428729..059b75b 100755 --- a/deploy/server/setup.sh +++ b/deploy/server/setup.sh @@ -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 diff --git a/docs/feature-map/chat.md b/docs/feature-map/chat.md index 5a88952..478ce41 100644 --- a/docs/feature-map/chat.md +++ b/docs/feature-map/chat.md @@ -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 這次才會說的字。 diff --git a/mobile/chatwindow.test.mjs b/mobile/chatwindow.test.mjs new file mode 100644 index 0000000..bc874ba --- /dev/null +++ b/mobile/chatwindow.test.mjs @@ -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; diff --git a/mobile/index.html b/mobile/index.html index 1bd607d..c9d208e 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -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 += `
中間一段
結論
"); +check("一般段落不受影響", pageMd("第一行\n第二行\n\n第二段"), "第一行
第二行
第二段
"); + +if (failed) process.exitCode = 1; diff --git a/src/brains.rs b/src/brains.rs index 006f880..c377150 100644 --- a/src/brains.rs +++ b/src/brains.rs @@ -295,11 +295,18 @@ fn tick(cfg: &Config, resting: &mut HashMap