From 7eb2d79aa579a2f7701d98848c1ee2cd884491b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Mon, 23 Nov 2026 11:15:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=89=8B=E6=A9=9F=E3=80=8C=E8=BC=89=E5=85=A5?= =?UTF-8?q?=E6=9B=B4=E6=97=A9=E7=9A=84=E5=B0=8D=E8=A9=B1=E3=80=8D=E8=A3=9C?= =?UTF-8?q?=E4=B8=8A=E4=BE=86=E7=9A=84=E4=B8=8D=E6=9C=83=E5=86=8D=E4=B8=8D?= =?UTF-8?q?=E8=A6=8B=EF=BC=9A=E5=A4=A7=E8=85=A6=E6=AF=8F=E6=AC=A1=E9=80=81?= =?UTF-8?q?=E7=9A=84=E5=8F=AA=E6=98=AF=E5=AE=83=E7=99=BC=E5=B8=83=E7=9A=84?= =?UTF-8?q?=E9=82=A3=E4=B8=80=E6=AE=B5=EF=BC=88=E6=9C=80=E6=96=B0=20120=20?= =?UTF-8?q?=E5=89=87=E3=80=81=E4=B8=8D=E5=90=AB=E6=AD=A5=E9=A9=9F=E7=B5=90?= =?UTF-8?q?=E6=9E=9C=EF=BC=8C=E5=BE=9E=E6=89=8B=E6=A9=9F=E9=82=A3=E4=BB=BD?= =?UTF-8?q?=E7=9A=84=E9=96=8B=E9=A0=AD=E8=B5=B7=EF=BC=89=EF=BC=8C=E5=BE=80?= =?UTF-8?q?=E5=9B=9E=E8=A3=9C=E8=B6=85=E9=81=8E=E9=82=A3=E4=B8=80=E6=AE=B5?= =?UTF-8?q?=E7=9A=84=E9=96=8B=E9=A0=AD=E4=B9=8B=E5=BE=8C=EF=BC=8C=E4=B8=8B?= =?UTF-8?q?=E4=B8=80=E6=AC=A1=E6=9B=B4=E6=96=B0=EF=BC=88=E4=BE=8B=E5=A6=82?= =?UTF-8?q?=E4=BE=86=E4=B8=80=E5=89=87=E6=96=B0=E8=A8=8A=E6=81=AF=EF=BC=89?= =?UTF-8?q?=E5=B0=B1=E6=95=B4=E4=BB=BD=E6=8F=9B=E6=88=90=E9=82=A3=E4=B8=80?= =?UTF-8?q?=E6=AE=B5=EF=BC=8C=E5=89=9B=E8=A3=9C=E7=9A=84=E5=8F=88=E4=B8=8D?= =?UTF-8?q?=E8=A6=8B=E3=80=81=E6=8C=89=E9=88=95=E8=B7=91=E5=9B=9E=E4=BE=86?= =?UTF-8?q?=EF=BC=9B=E6=9C=89=E5=B7=A5=E5=85=B7=E6=AD=A5=E9=A9=9F=E7=9A=84?= =?UTF-8?q?=E8=81=8A=E5=A4=A9=E9=82=A3=E4=B8=80=E6=AE=B5=E5=BE=88=E7=9F=AD?= =?UTF-8?q?=EF=BC=8C=E6=8C=89=E4=B8=80=E6=AC=A1=E5=B0=B1=E6=9C=83=E3=80=82?= =?UTF-8?q?=E7=8F=BE=E5=9C=A8=E8=A3=9C=E4=B8=8A=E4=BE=86=E7=9A=84=E7=95=99?= =?UTF-8?q?=E5=9C=A8=E9=82=A3=E4=B8=80=E6=AE=B5=E5=89=8D=E9=9D=A2=EF=BC=88?= =?UTF-8?q?S.winAt=EF=BC=89=EF=BC=8C=E6=96=B0=E8=A8=8A=E6=81=AF=E6=8A=8A?= =?UTF-8?q?=E8=88=8A=E7=9A=84=E6=8E=A8=E5=87=BA=E9=82=A3=E4=B8=80=E6=AE=B5?= =?UTF-8?q?=E6=99=82=E4=B9=9F=E6=8E=A5=E5=88=B0=E5=89=8D=E9=9D=A2=EF=BC=8C?= =?UTF-8?q?=E5=AD=98=E8=B5=B7=E4=BE=86=E7=9A=84=E9=82=A3=E4=BB=BD=E4=B8=80?= =?UTF-8?q?=E8=B5=B7=E8=A8=98=E8=91=97=EF=BC=8C=E5=88=87=E5=88=B0=E5=88=A5?= =?UTF-8?q?=E7=9A=84=20Bot=20=E5=86=8D=E5=9B=9E=E4=BE=86=E3=80=81=E9=A0=81?= =?UTF-8?q?=E9=9D=A2=E9=87=8D=E9=96=8B=E4=B9=9F=E6=8E=A5=E5=BE=97=E5=B0=8D?= =?UTF-8?q?=EF=BC=88=E8=88=8A=E7=89=88=E9=A0=81=E9=9D=A2=E5=AD=98=E7=9A=84?= =?UTF-8?q?=E9=82=A3=E4=BB=BD=E7=AC=AC=E4=B8=80=E6=AC=A1=E5=8F=AA=E7=95=99?= =?UTF-8?q?=E5=A4=A7=E8=85=A6=E9=80=81=E4=BE=86=E7=9A=84=E9=82=A3=E6=AE=B5?= =?UTF-8?q?=EF=BC=8C=E8=A3=A1=E9=9D=A2=E5=8F=AF=E8=83=BD=E6=9C=89=E8=88=8A?= =?UTF-8?q?=E9=8C=AF=E8=AA=A4=E7=95=99=E4=B8=8B=E7=9A=84=E7=BC=BA=E5=8F=A3?= =?UTF-8?q?=EF=BC=89=EF=BC=9B=E7=AD=89=E3=80=8C=E8=BC=89=E5=85=A5=E6=9B=B4?= =?UTF-8?q?=E6=97=A9=E3=80=8D=E5=9B=9E=E4=BE=86=E6=99=82=E8=81=8A=E5=A4=A9?= =?UTF-8?q?=E9=96=8B=E9=A0=AD=E7=A7=BB=E4=BA=86=E5=B0=B1=E4=B8=8D=E6=8E=A5?= =?UTF-8?q?=E3=80=81=E5=BE=9E=E7=8F=BE=E5=9C=A8=E7=9A=84=E9=96=8B=E9=A0=AD?= =?UTF-8?q?=E5=86=8D=E5=95=8F=E4=B8=80=E6=AC=A1=EF=BC=9B=E5=B0=8D=E8=A3=9C?= =?UTF-8?q?=E4=B8=8A=E4=BE=86=E7=9A=84=E8=A8=8A=E6=81=AF=E6=8C=89=E8=A1=A8?= =?UTF-8?q?=E6=83=85=EF=BC=8C=E5=90=91=E5=A4=A7=E8=85=A6=E6=8B=BF=E9=82=A3?= =?UTF-8?q?=E5=89=87=E7=8F=BE=E5=9C=A8=E7=9A=84=E8=A1=A8=E6=83=85=E3=80=82?= =?UTF-8?q?=E5=9B=9E=E5=88=B0=E6=9C=80=E5=BA=95=E4=B8=8B=E6=9C=80=E5=A4=9A?= =?UTF-8?q?=E7=95=99=20300=20=E5=89=87=EF=BC=8C=E6=8D=B2=E5=9C=A8=E4=B8=8A?= =?UTF-8?q?=E9=9D=A2=E8=AE=80=E6=99=82=E8=B6=85=E9=81=8E=20600=20=E5=89=87?= =?UTF-8?q?=EF=BC=88=E8=83=8C=E6=99=AF=20300=E3=80=81=E6=80=8E=E6=A8=A3?= =?UTF-8?q?=E9=83=BD=E8=B6=85=E9=81=8E=201200=EF=BC=89=E5=BE=9E=E9=A0=82?= =?UTF-8?q?=E4=B8=8A=E6=94=B6=EF=BC=8C=E6=AD=A3=E5=9C=A8=E8=AE=80=E7=9A=84?= =?UTF-8?q?=E9=82=A3=E5=89=87=E7=95=99=E5=9C=A8=E7=95=AB=E9=9D=A2=E5=90=8C?= =?UTF-8?q?=E4=B8=80=E5=80=8B=E5=9C=B0=E6=96=B9=EF=BC=88=E5=88=87=E5=88=B0?= =?UTF-8?q?=E8=83=8C=E6=99=AF=E9=82=A3=E4=B8=80=E5=88=BB=E8=A8=98=E4=B8=8B?= =?UTF-8?q?=EF=BC=8C=E5=9B=9E=E5=88=B0=E5=89=8D=E6=99=AF=E7=95=AB=E5=A5=BD?= =?UTF-8?q?=E5=86=8D=E6=94=BE=E5=9B=9E=E5=8E=BB=EF=BC=89=E3=80=82=E9=A0=86?= =?UTF-8?q?=E6=89=8B=E4=BF=AE=EF=BC=9A=E9=BB=9E=E9=80=B2=E8=81=8A=E5=A4=A9?= =?UTF-8?q?=E3=80=81=E6=8C=89=E8=A1=A8=E6=83=85=E4=B9=8B=E5=BE=8C=E8=A6=81?= =?UTF-8?q?=E7=AD=89=2020=E2=80=9340=20=E7=A7=92=E6=89=8D=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E2=80=94=E2=80=9411/20=20=E8=B5=B7=20loadChat=20?= =?UTF-8?q?=E5=9C=A8=E5=A4=A7=E8=85=A6=E5=9B=9E=E3=80=8C=E6=B2=92=E8=AE=8A?= =?UTF-8?q?=E3=80=8D=E6=99=82=E7=9B=B4=E6=8E=A5=20return=EF=BC=8Cloading?= =?UTF-8?q?=20=E4=B8=80=E7=9B=B4=E5=8D=A1=E5=9C=A8=20true=EF=BC=8C?= =?UTF-8?q?=E4=B9=8B=E5=BE=8C=E5=8F=AA=E8=83=BD=E7=AD=89=E8=BC=AA=E8=A9=A2?= =?UTF-8?q?=E9=A0=86=E4=BE=BF=E5=B8=B6=E9=81=8E=E4=BE=86=E3=80=82=E6=89=8B?= =?UTF-8?q?=E6=A9=9F=E7=9A=84=E7=B7=A8=E8=99=9F=E6=B8=85=E5=96=AE=E7=85=A7?= =?UTF-8?q?=20Markdown=20=E7=9A=84=E8=AE=80=E6=B3=95=EF=BC=9A=E7=A9=BA?= =?UTF-8?q?=E4=B8=80=E8=A1=8C=E9=9A=94=E9=96=8B=E7=9A=84=E9=82=84=E6=98=AF?= =?UTF-8?q?=E5=90=8C=E4=B8=80=E5=80=8B=E6=B8=85=E5=96=AE=EF=BC=88=E4=BB=A5?= =?UTF-8?q?=E5=89=8D=E6=AF=8F=E4=B8=80=E9=BB=9E=E9=83=BD=E6=98=AF=E3=80=8C?= =?UTF-8?q?1.=E3=80=8D=EF=BC=89=EF=BC=8C=E7=B7=A8=E8=99=9F=E5=BE=9E?= =?UTF-8?q?=E7=AC=AC=E4=B8=80=E9=BB=9E=E5=AF=AB=E7=9A=84=E6=95=B8=E5=AD=97?= =?UTF-8?q?=E8=B5=B7=EF=BC=8C=E7=B8=AE=E6=8E=92=E5=9C=A8=E4=B8=80=E9=BB=9E?= =?UTF-8?q?=E5=BA=95=E4=B8=8B=E7=9A=84=E5=AD=90=E9=A0=85=E7=9B=AE=E3=80=81?= =?UTF-8?q?=E7=BA=8C=E8=A1=8C=E5=9C=A8=E9=82=A3=E4=B8=80=E9=BB=9E=E8=A3=A1?= =?UTF-8?q?=EF=BC=88=E4=BB=A5=E5=89=8D=E8=A2=AB=E6=94=A4=E5=B9=B3=E6=88=90?= =?UTF-8?q?=E5=90=8C=E4=B8=80=E5=B1=A4=E4=B8=80=E8=B5=B7=E7=B7=A8=E8=99=9F?= =?UTF-8?q?=EF=BC=89=E3=80=82=E5=A4=A7=E8=85=A6=E7=AE=A1=E7=90=86=E5=93=A1?= =?UTF-8?q?=EF=BC=9A=E6=A0=B8=E5=B0=8D=20Docker=20=E7=B6=B2=E8=B7=AF?= =?UTF-8?q?=E6=94=B9=E4=B8=8D=E6=88=90=E5=AF=AB=E9=80=B2=E7=B4=80=E9=8C=84?= =?UTF-8?q?=E3=80=81=E9=82=84=E4=B8=8D=E7=9F=A5=E9=81=93=E6=93=81=E6=9C=89?= =?UTF-8?q?=E8=80=85=E6=99=82=E5=85=88=E4=B8=8D=E5=8B=95=EF=BC=9B=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E6=99=82=20Caddyfile=20=E7=94=A8=20relay=20=E5=AE=B9?= =?UTF-8?q?=E5=99=A8=E7=9A=84=20IP=20=E6=88=96=20.env=20=E8=A3=A1=E7=9A=84?= =?UTF-8?q?=20{$=E8=AE=8A=E6=95=B8}=EF=BC=8F{$=E8=AE=8A=E6=95=B8:=E9=A0=90?= =?UTF-8?q?=E8=A8=AD}=20=E8=BD=89=E5=88=B0=20relay=20=E7=9A=84=E4=B9=9F?= =?UTF-8?q?=E8=AA=8D=E5=BE=97=E5=87=BA=E4=BE=86=E3=80=82=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E5=9C=B0=E5=9C=96=20chat=20=E5=92=8C=20FEATURES=20=E8=B7=9F?= =?UTF-8?q?=E8=91=97=E6=94=B9=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 已驗證: 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 Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm --- FEATURES.md | 5 +- deploy/server/setup.sh | 26 ++++- docs/feature-map/chat.md | 10 +- mobile/chatwindow.test.mjs | 212 +++++++++++++++++++++++++++++++++++ mobile/index.html | 219 ++++++++++++++++++++++++++++++------- mobile/markdown.test.mjs | 32 ++++++ src/brains.rs | 15 ++- src/remote.rs | 31 ++++++ 8 files changed, 493 insertions(+), 57 deletions(-) create mode 100644 mobile/chatwindow.test.mjs create mode 100644 mobile/markdown.test.mjs 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 += `
${x.text ? `
${esc(x.text)}
` : ""}${names}
${said}
`; }); - $("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() ? `
${QUICK.map((e) => ``).join("")}
` : ""; 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 ? `
  • ${task[1] === " " ? "☐" : "☑"} ${inl(task[2])}
  • ` : `
  • ${inl(it)}
  • `); + // 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; + } + 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) => "
    " + inl(x.trim())).join("") : pageMd(under.map((x) => x.slice(Math.min(cut, indent(x)))).join("\n"), id, rev); + items.push(`${words}${inner}`); } - out.push(ordered ? `
      ${items.join("")}
    ` : `
      ${items.join("")}
    `); continue; + out.push(ordered ? `${items.join("")}` : `
      ${items.join("")}
    `); 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(); }); diff --git a/mobile/markdown.test.mjs b/mobile/markdown.test.mjs new file mode 100644 index 0000000..9be813b --- /dev/null +++ b/mobile/markdown.test.mjs @@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[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. 丙"), "
    1. 甲
    2. 乙
    3. 丙
    "); +check("空行隔開的 1. 2. 3.:同一個清單", pageMd("1. 甲\n\n2. 乙\n\n3. 丙"), "
    1. 甲
    2. 乙
    3. 丙
    "); +check("緊接著的照舊", pageMd("1. 甲\n2. 乙"), "
    1. 甲
    2. 乙
    "); +check("從 3 開始", pageMd("3. 甲\n4. 乙"), '
    1. 甲
    2. 乙
    '); +check("子清單在那一點裡,不攤平", pageMd("1. **甲**\n - x\n - y\n2. 乙"), "
    1. **甲**
      • x
      • y
    2. 乙
    "); +check("空行後縮排的子清單也是那一點的", pageMd("1. 甲\n\n - x\n\n2. 乙"), "
    1. 甲
      • x
    2. 乙
    "); +check("縮排的續行是同一點的字", pageMd("- 甲\n 還有\n- 乙"), "
    • 甲
      還有
    • 乙
    "); +check("段落把清單隔開:後面那個照它寫的數字", pageMd("1. 甲\n\n中間一段\n\n2. 乙"), '
    1. 甲

    中間一段

    1. 乙
    '); +check("不同種類的項目:兩個清單", pageMd("- 甲\n1. 乙"), "
    • 甲
    1. 乙
    "); +check("待辦清單", pageMd("- [ ] 甲\n- [x] 乙"), '
    • ☐ 甲
    • ☑ 乙
    '); +check("清單後面空一行接段落:段落不算進去", pageMd("1. 甲\n2. 乙\n\n結論"), "
    1. 甲
    2. 乙

    結論

    "); +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) -> Vec log::info!("AnyBot 大腦管理員:{u} 的雲端大腦{}", if want { "接回 Docker" } else { "拿掉 Docker" }), + Err(err) => errors.push(format!("{u} 的雲端大腦{}失敗:{err}", if want { "接回 Docker " } else { "拿掉 Docker " })), } } } diff --git a/src/remote.rs b/src/remote.rs index 3e0ca8e..6f2cf42 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -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)