From fe361c5b7646251a54507374a39c819fcbf17c3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Fri, 20 Nov 2026 08:05:23 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E6=89=8B=E6=A9=9F=E9=A0=81=E9=9D=A2?= =?UTF-8?q?=E5=AD=98=E5=9C=A8=E6=89=8B=E6=A9=9F=E4=B8=8A=E3=80=81=E7=9C=8B?= =?UTF-8?q?=E9=81=8E=E7=9A=84=E8=81=8A=E5=A4=A9=E5=8F=AA=E6=8B=BF=E5=B7=AE?= =?UTF-8?q?=E7=95=B0=E3=80=81=E9=80=A3=E7=B7=9A=E7=95=AB=E9=9D=A2=E6=94=B9?= =?UTF-8?q?=E6=88=90=E9=A0=AD=E5=83=8F=E5=8B=95=E7=95=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 正式站這條線只有約 25–50 KB/s,每次打開都重抓頁面和圖示、換聊天就整份重拿。 - Service Worker(mobile/sw.js,帳號伺服器和直接連線都送、一律註冊)把頁面、圖示、 manifest 存在手機上,打開時直接用;背景帶版本標記問一次換版沒。換了:還在連線畫面就 重新載入(通知帶來的聊天和回答照樣用上);已經進去的話,App 退到背景、手上沒東西 (沒打字、附件、送到一半的請求、錄音、選單、選照片)才換,回到同一個聊天。重新整理一定 先問伺服器。只碰那幾個固定的檔,API、發布的網站、下載、看畫面(novnc.js)都不經過它。 - 看過的聊天記在頁面裡(最多 12 個,每台電腦各自記,還沒送到的那句不記,登出清掉); 回到它先顯示上次的,再用 api/bots/?chat_sig=…&chat_delta=1 只拿有變的(大腦這條 路徑現在支援,舊頁面不帶參數照舊整份)。 - 登入過的手機打開時,api/hello、relay/me、第一份狀態同時出發(還是拿到狀態才進去); 網路切換時那個先出發的請求會被叫停重問。 - 連線畫面不再是兩行字:打開 App 時的頭像留在正中間呼吸、外圈漾開;讀螢幕軟體唸 「正在連線」,減少動態時不動。 - FEATURES.md、docs/feature-map/phone.md 同步,phone.md 多兩條 verify-anybot 步驟。 已驗證: cargo test(主程式 756,含聊天差異與 sw.js 的新斷言;帳號伺服器 24); verify-anybot 手機區:還沒連上就在外面、清單和選單、聊天、頁面存在手機上、回到看過的 聊天(兩個 Bot 切換)、只傳有變的、斷線又回來;另用 DevTools 實測:擋住狀態時發現新版 會在連線畫面重新載入且保留 #bot=1、進去後有字不換/清空後退到背景換上同一個聊天、 選檔案時不換、連線畫面淺色深色截圖無文字、減少動態時不動;兩輪獨立審查,P1 與 P2 都已修。 未驗證: 真的 iPhone/Android(主畫面 App 的退到背景、Safari 的 Cache Storage)——要實機; 正式站的實際秒數——部署後再量。帳號伺服器的兩步驗證測試偶爾在 30 秒邊界失敗(原本就有, 單跑四次都過)。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha5JgTkqJjkgMtrEXrn --- FEATURES.md | 4 +- docs/feature-map/phone.md | 6 +- mobile/index.html | 135 ++++++++++++++++++++++++++++++++------ mobile/sw.js | 83 ++++++++++++++++++++++- src/remote.rs | 31 ++++++++- 5 files changed, 231 insertions(+), 28 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 6773312..3acb4d4 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -2198,8 +2198,8 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 畫面更新:手機問「有沒有新東西」會等最多 20 秒,有變化就立刻回來,所以不用一直刷新。 - **單趟同步**:開著對話時,狀態檢查順帶把那個對話的訊息帶回來(手機附上簽名,沒變不重傳):Bot 串流輸出時每趟少一個請求,訊息和側欄狀態永遠同一刻。 - **只傳有變的**:手機附上它手上那份狀態的指紋,大腦只回改了的部分(沒變的欄位不送、沒變的 Bot 只寫代號);對話也只送從不一樣的地方開始的訊息(最舊的滑出視窗、最後一則長大、多了新的,都不必整段重送)。大腦記得最近幾千份給過的指紋,慢的網路隔很多次更新再問也對得上;對不上就整份重送。舊版頁面不帶指紋,照舊拿整份。 -- **網路不穩**:每個請求有期限(等新東西 45 秒、其他 60 秒,上傳不限),連線無聲斷掉也會發現;連不上時頂端顯示「連線中斷,正在重新連線…」,重試間隔 1 秒起倍增到 15 秒,回到前景、網路恢復時立刻重連。傳出的訊息帶一個代號自動重送(約一分鐘內),大腦 10 分鐘內同一代號只收一次。還沒連上之前停在最外面的「正在連線…」,第一份狀態到手才進去(進去時清單已經在)。已經進去之後斷線留在裡面重連。 -- **傳輸**:直接連線的連線留著給下一個請求(30 秒沒用才關,手機不用每次重做 TCP 和 TLS 握手)、文字回答用 gzip 壓縮、手機頁面帶版本標記(沒換版只回「沒有變」);帳號連線時,電腦回給手機的資料壓縮著上傳到帳號伺服器,在那裡打開、再由帳號伺服器自己用 gzip 壓縮給手機(頁面、狀態、聊天都是;不靠前面的 Caddy 或 `tailscale serve`)。連線時畫面上的圖示瀏覽器留一天,不用每次打開都重新下載。 +- **網路不穩**:每個請求有期限(等新東西 45 秒、其他 60 秒,上傳不限),連線無聲斷掉也會發現;連不上時頂端顯示「連線中斷,正在重新連線…」,重試間隔 1 秒起倍增到 15 秒,回到前景、網路恢復時立刻重連。傳出的訊息帶一個代號自動重送(約一分鐘內),大腦 10 分鐘內同一代號只收一次。還沒連上之前停在最外面的連線畫面(打開 App 時的頭像留在正中間呼吸、外圈漾開,不顯示文字;讀螢幕軟體唸「正在連線」,減少動態時不動),第一份狀態到手才進去(進去時清單已經在)。已經進去之後斷線留在裡面重連。 +- **傳輸**:直接連線的連線留著給下一個請求(30 秒沒用才關,手機不用每次重做 TCP 和 TLS 握手)、文字回答用 gzip 壓縮、手機頁面帶版本標記(沒換版只回「沒有變」);帳號連線時,電腦回給手機的資料壓縮著上傳到帳號伺服器,在那裡打開、再由帳號伺服器自己用 gzip 壓縮給手機(頁面、狀態、聊天都是;不靠前面的 Caddy 或 `tailscale serve`)。連線時畫面上的圖示瀏覽器留一天,不用每次打開都重新下載。頁面和圖示由 Service Worker(`mobile/sw.js`,帳號伺服器和直接連線都送)存在手機上:打開時直接用,背景用版本標記問一次換版沒,換了就存新的(還在連線畫面時頁面自己重新載入一次,通知帶來的聊天和回答照樣用上;已經進去的話,App 退到背景、手上沒東西——沒打字、沒附件、沒有改東西的請求在路上、沒在錄音、沒開選單、沒在選照片或拍照——才換,回到同一個聊天);重新整理一定先問伺服器,連不上才用存的。它只碰這幾個每個人都一樣的檔,API、發布的網站、下載、看畫面(含 `novnc.js`)都不經過它。看過的聊天記在頁面裡(最多 12 個,每台電腦各自記,還沒送到的話不記,登出清掉),回到那個聊天先顯示上次的,再用 `api/bots/?chat_sig=…&chat_delta=1` 只拿有變的部分(沒變只回 `unchanged`)。登入過的手機打開時,`api/hello`、`relay/me`、第一份狀態同時出發。 ### 設定 › 手機與帳號 diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index f48ba9b..87b9133 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -9,7 +9,7 @@ - `phone-look` 長相(和電腦版同一份設計規格:字級、間距、圓角都是同一組數字):Bot 的回答不放在泡泡裡,像文件一樣直接排在畫面上,用宋體(思源宋體,沒有就用系統的宋體)、16px、行距寬;裡面的表格只有橫向細線、數字欄靠右,提示框([!NOTE] 等)同一種淡底、只有圖示依種類上色,程式碼是淡底圓角塊。你自己的訊息(泡泡)和所有按鈕、清單、設定用黑體。手機沒有字型選項。 - `phone-colors` 顏色跟電腦版一樣:電腦上 設定 › 一般 › 外觀 的主題(淺色/深色/跟隨系統)、底色、強調色、對比,手機照著穿;手機自己的「外觀」可以選「跟著電腦」(預設)、「跟著手機」、「淺色」、「深色」。狀態列的顏色跟著畫面。舊版的電腦沒送顏色時,手機用內建的「紙」。 - `phone-claude` 像 Claude 的手機 App:上面一條簡單的標題列(Bot 名稱,第二行是它在做什麼或用哪個模型),輸入框是底部一張圓角卡片,回答下面只有時間和複製/重新產生/⋯;按鈕和點的地方至少 44px;清單每列的說明只有一行(太長以 … 結尾);顏色少,強調色只用在連結、選取和新訊息的點。 -- `phone-net` 網路不穩也能用:還沒連上之前停在最外面的「正在連線…」(登入表單和 Bot 清單都還沒出現),連上、第一份狀態到手才進去,進去時清單已經在,可以直接點。已經進去之後斷線才留在裡面:上面出現「連線中斷,正在重新連線…」,自己重試(間隔越來越長,最長 15 秒),回到前景或網路恢復時立刻重連,不用重新整理;一個請求太久沒回音(連線斷了不會自己報錯)就放棄重來。傳出去的訊息沒送到會自己重送,同一則只會送到一次;Bot 工作中插的話重送時寫「網路不穩,重新傳送中…」,真的送不出去才標「沒送出,點一下拿回來重送」(Bot 沒在工作時,字放回輸入框)。只傳有變的部分:狀態只送改了的、打開的聊天只送從不一樣的地方開始的訊息;直接連線的連線留著給下一個請求用;兩種連線文字都壓縮(帳號伺服器自己壓,不靠前面的代理),頁面沒換版就不重新下載,圖示留一天。 +- `phone-net` 網路不穩也能用:還沒連上之前停在最外面的連線畫面:只有打開 App 時那個頭像留在正中間輕輕呼吸、外圈一圈圈漾開,不顯示文字(讀螢幕軟體唸「正在連線」;系統設成減少動態時頭像不動),登入表單和 Bot 清單都還沒出現,連上、第一份狀態到手才進去,進去時清單已經在,可以直接點。已經進去之後斷線才留在裡面:上面出現「連線中斷,正在重新連線…」,自己重試(間隔越來越長,最長 15 秒),回到前景或網路恢復時立刻重連,不用重新整理;一個請求太久沒回音(連線斷了不會自己報錯)就放棄重來。傳出去的訊息沒送到會自己重送,同一則只會送到一次;Bot 工作中插的話重送時寫「網路不穩,重新傳送中…」,真的送不出去才標「沒送出,點一下拿回來重送」(Bot 沒在工作時,字放回輸入框)。只傳有變的部分:狀態只送改了的、打開的聊天只送從不一樣的地方開始的訊息;直接連線的連線留著給下一個請求用;兩種連線文字都壓縮(帳號伺服器自己壓,不靠前面的代理)。存在手機上的:頁面和圖示(打開時直接用,背景問一次換版沒;換了,還在連線畫面就自己重新載入,通知帶來的聊天和回答照樣用上;已經進去的話,App 退到背景、手上沒東西(沒打字、沒附件、沒有送到一半的訊息、沒在錄音、沒開選單、沒在選照片或拍照)時才換,回來還在同一個聊天;重新整理一定先問伺服器,連不上才用存的)、這次看過的聊天(最多 12 個,每台電腦各自記;回到那個聊天先顯示上次的,再只拿有變的部分;還沒送到的話不記;登出就清掉);聊天和帳號資料不會留在手機的儲存空間。登入過的手機打開時,確認連線、帳號裡的電腦和第一份狀態同時問,不一個等一個(還是拿到狀態才進去)。 - `phone-app` 像 App 一樣:加入主畫面後全螢幕、沒有網址列(瀏海、動態島、底部手勢條、橫放都避開);首頁會提示「把 AnyBot 裝成 App」(Android 直接安裝,iPhone 教你加入主畫面,可以關掉);換畫面會左右滑動;iPhone 主畫面 App 從左邊緣往右滑回上一頁。 ## 使用者怎麼到 @@ -36,6 +36,8 @@ - **裝成 App 的提示**(covers `phone-app`):回首頁,看「把 AnyBot 裝成 App」,按 ✕ 關掉。指令:`$CTL phone open --listed && $CTL phone wait-text '把 AnyBot 裝成 App' && $CTL phone shot phone-install && $CTL phone click '#install-no' && $CTL phone wait-gone '#install-go' && $CTL api --no-auth GET /manifest.webmanifest --jq '.display'`。看到:提示和「安裝」(Chrome 給了安裝提示;iPhone 是「怎麼做」);按 ✕ 就不見了;manifest 的 display 是 standalone。 - **斷線又回來**(covers `phone-net`):打開 Bot,把大腦關掉,看提示;斷線時傳一句,再把大腦開回來。指令:`$CTL phone click '.row[data-bot="1"]' && $CTL stop && $CTL phone wait '#net.on' 30 && $CTL phone send '斷線時傳的' && $CTL phone wait-text '網路不穩,重新傳送中' --in '#msgs' 20 && $CTL phone shot phone-offline && $CTL serve && $CTL phone wait-gone '#net.on' 40 && $CTL phone wait-text 'FAKE-MODEL 回答:斷線時傳的' --in '#msgs' 60 && $CTL phone shot phone-back && $CTL model 'select(.tools > 0 and ((.user // "") | startswith("斷線時傳的"))) | .t' | grep -c '^"20'`。看到:標題列下方「連線中斷,正在重新連線…」,沒有另外跳「連不上」的提示,標題沒被蓋住;那句下面寫「網路不穩,重新傳送中…」(不是「重新傳送」按鈕);大腦回來後提示自己消失(沒有重新整理),斷線時傳的那句自己送到、有回答;最後印 `1`:重送了幾次,Bot 都只收到一次。 - **只傳有變的**(covers `phone-net`):拿著同一份狀態的指紋再問一次。指令:`S=$($CTL api GET '/api/state?since=0' --jq .ssig | tr -d '"') && $CTL api GET "/api/state?since=0&ssig=$S" --jq '[has("base"), has("bots"), has("host"), has("version")]'`。看到:`[true,false,false,true]`:只回版本,Bot 清單和主機名稱沒有重送。 +- **頁面存在手機上**(covers `phone-net`):打開過一次之後再打開,頁面和圖示從手機拿。指令:`$CTL phone open --listed && $CTL phone wait '.row[data-bot="1"]' && $CTL phone js 'navigator.serviceWorker.controller !== null' && $CTL phone js 'caches.open("anybot-shell-v1").then((c) => c.keys()).then((k) => k.map((r) => new URL(r.url).pathname).join(" "))'`。看到:`true`,和存著的 `/ /manifest.webmanifest /icon.svg /icon-180.png /icon-192.png`;`api/`、`h/`、`s/` 開頭的都不在裡面。 +- **回到看過的聊天**(covers `phone-net`):打開 Bot、回首頁、再打開。指令:`$CTL phone click '.row[data-bot="1"]' && $CTL phone wait-text 'FAKE-MODEL 回答' --in '#msgs' && $CTL phone click '[data-back]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone wait-text 'FAKE-MODEL 回答' --in '#msgs' 2 && S=$($CTL api GET /api/bots/1 --jq .sig | tr -d '"') && $CTL api GET "/api/bots/1?chat_sig=$S&chat_delta=1" --jq .unchanged`。看到:再打開時訊息馬上就在;大腦對拿著同一份的請求只回 `true`(沒有變),不重送訊息。 - **主畫面 App**(covers `phone-app`):指令:走不到——加入主畫面後的全螢幕、瀏海和手勢條、邊緣滑回要真的 iPhone 或 Android。看到:最接近的真路是上一步的提示和 manifest。 - 自動測試:`cargo test remote::`、`cargo test remote_ui::`、`cargo test mirror_ui::`、`cargo test httpd::`;回答落在哪張卡:`.claude/skills/verify-approval-routing/run.sh --replay`。 @@ -45,4 +47,6 @@ - 手機上的卡沒用上時,要看現在在等什麼再按;開了很久的頁面先重新整理。用帳號登入的手機,頁面是帳號伺服器給的:伺服器還沒更新時,手機上的卡都答不了,要在電腦上答。 - 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。 - 自動重送只認同一則(手機給每則訊息一個代號,大腦記 10 分鐘):網路斷超過大約一分鐘,那則會標「沒送出」,要自己再送。允許卡片的按鈕不自動重送(卡片可能已經換了)。 +- 換新版後第一次打開:還在連線畫面時就換上新頁面(頁面會自己重新載入一次);已經進去了才發現的話,先用舊頁面,App 退到背景、手上沒東西時換上(有東西就等下一次退到背景)。舊頁面答卡片的規則照 `phone-cards`;說「頁面太舊」時重新整理,重新整理一定拿伺服器的新頁面。 +- (驗證)Service Worker 要沒有憑證錯誤才裝得上:用自簽憑證的直接連線,瀏覽器沒有信任那張憑證時不會存頁面,每次打開照舊下載(壓縮過、沒換版只回「沒有變」)。 - (驗證)無頭 Chrome 不是 iPhone:通知、主畫面的全螢幕和手勢都不會出現;卡片和選單用 `wait` 等它滑進來再按。 diff --git a/mobile/index.html b/mobile/index.html index 8ab3fa6..928cd94 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -468,6 +468,19 @@ textarea.field{min-height:96px;line-height:1.5} .login p{text-align:center;color:var(--text3);margin:0 0 8px;font-size:var(--fs-ui)} .login .err{color:var(--danger);font-size:var(--fs-small);text-align:center;min-height:18px} .link{color:var(--accent-ink);font-size:var(--fs-ui);text-align:center;padding:6px} +/* ---- connecting: the icon the app opened with stays in the middle, breathing, rings spreading + out from it — no words (a screen reader still hears 正在連線) ---- */ +.gate{margin:auto;position:relative;width:96px;height:96px} +.gate img{position:relative;z-index:1;width:100%;height:100%;display:block;border-radius:22%;box-shadow:0 6px 24px #0000001f} +.gate::before,.gate::after{content:"";position:absolute;inset:0;border-radius:22%;background:color-mix(in srgb,var(--text3) 24%,transparent);opacity:0} +@media (prefers-reduced-motion: no-preference){ + .gate img{animation:breathe 2s ease-in-out infinite} + .gate::before,.gate::after{animation:ripple 2s cubic-bezier(.2,.6,.3,1) infinite} + .gate::after{animation-delay:1s} +} +@keyframes breathe{50%{transform:scale(1.045)}} +@keyframes ripple{0%{opacity:.6;transform:scale(1)}100%{opacity:0;transform:scale(1.8)}} +.vh{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap} /* ---- page viewer ---- */ .page{padding:var(--sp-2) 18px 40px;max-width:760px;margin:0 auto} @@ -580,11 +593,7 @@ button,.row,.ib,.island,.opt,.chip,.tab,label.sw,[role="button"]{-webkit-user-se
- +
正在連線
@@ -900,7 +909,15 @@ const WAIT_MS = 60000; // reach the computer right now). const OFFLINE_MSG = "連不上,網路好像斷了"; function offline() { const e = new Error(OFFLINE_MSG); e.transient = true; return e; } +// Requests that change something (a message, an upload, an answer), on their way: the page is not +// swapped for a new build under them (swapWhenAway). +let writing = 0; async function api(path, opts = {}) { + const writes = (opts.method || (opts.body || opts.json !== undefined ? "POST" : "GET")) !== "GET"; + if (writes) writing++; + try { return await apiOnce(path, opts); } finally { if (writes) writing--; } +} +async function apiOnce(path, opts) { const headers = Object.assign({}, opts.headers || {}); if (S.token) headers.Authorization = "Bearer " + S.token; // (An upload has no deadline: a photo on a slow line takes what it takes.) @@ -1122,7 +1139,7 @@ $("b-login").onclick = async () => { $("f-pass").addEventListener("keydown", (e) => { if (e.key === "Enter") $("b-login").click(); }); function signOut(expired) { if (S.token && !expired) api(S.relay ? "relay/logout" : "api/logout", {json: {}}).catch(() => {}); - S.token = ""; localStorage.removeItem("anybot.token"); S.version = 0; S.entered = false; NAV.length = 0; show("login"); + S.token = ""; localStorage.removeItem("anybot.token"); S.version = 0; S.entered = false; NAV.length = 0; CHATS.clear(); callOffEarly(); EARLY.me = null; show("login"); if (expired) $("login-err").textContent = "登入已失效,請重新登入"; } $("b-out1").innerHTML = ic("log-out", 20); @@ -1134,7 +1151,8 @@ let hostRetry = null; async function pickHost() { clearTimeout(hostRetry); let me; - try { me = await api("relay/me", {timeout: 15000}); netDown(false); } catch (e) { if (e.transient) netDown(true); else toast(e.message); if (S.token) hostRetry = setTimeout(pickHost, 3000); return; } + const pre = EARLY.me; EARLY.me = null; + try { me = await (pre || api("relay/me", {timeout: 15000})); netDown(false); } catch (e) { if (e.transient) netDown(true); else toast(e.message); if (S.token) hostRetry = setTimeout(pickHost, 3000); return; } const all = me.hosts || []; const byId = Object.fromEntries(all.map((h) => [h.id, h])); // A link or an old choice that isn't one of this account's AnyBots is forgotten. @@ -1161,7 +1179,7 @@ async function pickHost() { const waiting = hosts.length && !live.length && wanted ? `
「${esc(wanted.name)}」暫時沒有連線(可能正在重新啟動,或那台電腦睡著了)。
連上後會自動進入,不用重新整理。
` : ""; $("hosts").innerHTML = waiting + (hosts.length ? hosts.map((h) => `
${ic(h.online ? "monitor" : "power", 18)}
${esc(h.name)}
${h.online ? "在線上" : "離線(" + esc(h.last_seen_text || "很久沒連線") + ")"}${note(h)}
`).join("") : `
這個帳號還沒有連上任何 AnyBot。
在電腦上打開 AnyBot › 設定 › 手機與帳號,登入同一個帳號。
`); - document.querySelectorAll("#hosts .row").forEach((r) => r.onclick = () => { clearTimeout(hostRetry); S.host = r.dataset.h; localStorage.setItem("anybot.host", S.host); if (!S.entered) show("gate"); start(); }); + document.querySelectorAll("#hosts .row").forEach((r) => r.onclick = () => { clearTimeout(hostRetry); toHost(r.dataset.h); if (!S.entered) show("gate"); start(); }); show("hosts"); if (S.token && !live.length) hostRetry = setTimeout(pickHost, 3000); } @@ -1198,9 +1216,11 @@ async function start() { // when their signature changed, and then only from where they differ (api/state?bot=… // &chat_sig=…&chat_delta=1). The rest of the state likewise: only what changed since the // state this page holds (ssig). - const open = S.open && (S.view === "chat" || !S.entered) ? "&bot=" + S.open + "&chat_sig=" + encodeURIComponent(S.chatSig) + "&chat_delta=1" : ""; - const held = S.version && S.ssig ? "&ssig=" + encodeURIComponent(S.ssig) : ""; - let v = await api(base() + "api/state?since=" + S.version + "&tz=" + encodeURIComponent(TZ) + held + open, {timeout: POLL_MS, signal: pollCtl.signal}); + const path = statePath(), pre = EARLY.state, mine = pre && pre.path === path; + EARLY.state = null; + if (pre && !mine) pre.ctl.abort(); + if (mine) pollCtl.signal.addEventListener("abort", () => pre.ctl.abort(), {once: true}); + let v = await (mine ? pre.p : api(path, {timeout: POLL_MS, signal: pollCtl.signal})); fails = 0; netDown(false); if (v.base !== undefined) { const whole = v.base === S.ssig && S.st ? mergeState(S.st, v) : null; @@ -1223,13 +1243,31 @@ async function start() { } S.polling = false; } +function statePath() { + const open = S.open && (S.view === "chat" || !S.entered) ? "&bot=" + S.open + "&chat_sig=" + encodeURIComponent(S.chatSig) + "&chat_delta=1" : ""; + const held = S.version && S.ssig ? "&ssig=" + encodeURIComponent(S.ssig) : ""; + return base() + "api/state?since=" + S.version + "&tz=" + encodeURIComponent(TZ) + held + open; +} // The brain holds a poll up to 20 s (the account server 35 s): past this the connection is gone. const POLL_MS = 45000; +// A remembered way in: relay/me and the first state set off at once, beside api/hello, instead +// of one after the other — each used only when it is the very request that would have been made. +// (Still in only once the state is here.) +const EARLY = {me: null, state: null}; +function setOff() { + const known = localStorage.getItem("anybot.relay"); + if (!S.token || known === null) return; + S.relay = known === "1"; + if (S.relay) { EARLY.me = api("relay/me", {timeout: 15000}); EARLY.me.catch(() => {}); } + if (!S.relay || S.host) { const path = statePath(), ctl = new AbortController(); EARLY.state = {path, ctl, p: api(path, {timeout: POLL_MS, signal: ctl.signal})}; EARLY.state.p.catch(() => {}); } +} +function callOffEarly() { if (EARLY.state) EARLY.state.ctl.abort(); EARLY.state = null; } let pollCtl = null; // Back in front, or the network is back: ask now — not after a request on a connection that may // have died meanwhile, or the rest of a back-off. function kick() { if (!S.token) return; + callOffEarly(); if (S.polling && pollCtl) pollCtl.abort(); wake(); } @@ -1455,8 +1493,27 @@ function chatHead() { $("b-newchat").style.display = owner() ? "" : "none"; } $("island").onclick = () => go("details", {bot: S.open}); +// 看過的聊天記在這頁裡(每個 Bot 一份,最多 12 份):回到它先畫上次看到的,再只拿有變的部分。 +const CHATS = new Map(); +const chatKey = (id) => S.host + ":" + id; +function toHost(h) { + if (h === S.host) return; + if (S.chatSig) { keepChat(S.open, S.msgs, S.chatSig); S.open = 0; S.msgs = []; S.chatSig = ""; } + S.host = h; localStorage.setItem("anybot.host", h); +} +function keepChat(id, msgs, sig) { + if (!id || !sig) return; + // (Only the brain's list, which `sig` is of: words shown before they arrived are not in it.) + CHATS.delete(chatKey(id)); CHATS.set(chatKey(id), {msgs: msgs.filter((m) => !m.local), sig}); + while (CHATS.size > 12) CHATS.delete(CHATS.keys().next().value); +} function openChat(id) { - if (S.open !== id) { S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; S.prevFirst = ""; MODE_OPEN = ""; $("msgs").innerHTML = ""; } + 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 = ""; + const kept = CHATS.get(chatKey(id)); + if (kept) { S.msgs = kept.msgs; S.chatSig = kept.sig; } + } S.open = id; // Your bubbles as 聊天的顏色 on the computer says (ob.bubble): "quiet" a light grey with the // page's ink (the default), "bot" the bot's colour, "black". (An older AnyBot sends no field: its colour.) @@ -1475,11 +1532,19 @@ async function loadChat(jump) { if (!S.open) return; if (loading) { again = true; return; } loading = true; + const id = S.open, held = S.chatSig; try { - const v = await api(base() + "api/bots/" + S.open); - const sc = $("scroller"); const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140; - S.msgs = v.messages || []; S.chatSig = v.sig || ""; renderMsgs(); - if (jump || near) sc.scrollTop = sc.scrollHeight; + // Only what changed since the copy this page holds (an older brain sends all of it). + const v = await api(base() + "api/bots/" + id + (held ? "?chat_sig=" + encodeURIComponent(held) + "&chat_delta=1" : "")); + // (Another chat opened meanwhile, or the poll already brought a newer copy: not this answer.) + if (S.open === id && S.chatSig === held && !v.unchanged) { + const msgs = v.from === undefined ? v.messages || [] : v.base === held ? S.msgs.slice(v.drop || 0).slice(0, v.from).concat(v.messages || []) : null; + if (msgs) { + const sc = $("scroller"); const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140; + S.msgs = msgs; S.chatSig = v.sig || ""; renderMsgs(); + if (jump || near) sc.scrollTop = sc.scrollHeight; + } else { S.chatSig = ""; again = true; } + } } catch (e) { toast(e.message); } loading = false; if (again) { again = false; loadChat(); } @@ -2022,7 +2087,7 @@ async function send() { memReset(); input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash(); const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/(usage|doctor|context|compact)\s*$/i.test(text) || /^\/(fork|rewind)(\s|$)/.test(text); - if (!b.busy && !quiet) { if (navigator.vibrate) navigator.vibrate(8); S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; } + if (!b.busy && !quiet) { if (navigator.vibrate) navigator.vibrate(8); S.msgs.push({role: "user", text, attachments: [], memories: memories || [], local: true}); renderMsgs(); $("scroller").scrollTop = 1e9; } // 先顯示: while it works the words aren't in the chat yet — shown at once all the same. const sent = b.busy && text ? {bot: S.open, text, at: Date.now(), failed: false} : null; if (sent) { S.sending.push(sent); renderMsgs(); $("scroller").scrollTop = 1e9; } @@ -3676,7 +3741,8 @@ if (navigator.standalone === true) { document.addEventListener("touchend", end); document.addEventListener("touchcancel", end); } -if (pushOK()) navigator.serviceWorker.register("sw.js").catch(() => {}); +// The page and its icons kept on this phone (sw.js), not only for notifications. +if ("serviceWorker" in navigator && window.isSecureContext) navigator.serviceWorker.register("sw.js").catch(() => {}); // A tapped notification opens that chat. function openFromHash() { const h = new URLSearchParams(location.hash.slice(1)); @@ -3693,10 +3759,38 @@ function openFromHash() { if (sc) S.sc = sc; if (location.hash || location.search) history.replaceState(null, "", location.pathname); } +// A file or camera picker is open (it hides the page): what is picked must come back to this page. +let picking = false; +document.addEventListener("click", (e) => { if (e.target instanceof HTMLInputElement && e.target.type === "file") picking = true; }, true); +document.addEventListener("change", (e) => { if (e.target instanceof HTMLInputElement && e.target.type === "file") picking = false; }, true); +// What this page was opened with (a notification's chat and answer, a shortcut): a reload for a +// new build opens with it again. +const LAUNCH = location.search + location.hash; openFromHash(); +// A new build was kept while this page was in use: it is taken when the app goes to the +// background with nothing in hand (nothing typed, attached, on its way or being recorded, no +// sheet open), back in the same chat. +function swapWhenAway() { + if (!S.fresh || !S.entered || !document.hidden) return; + if (picking || writing || rec || $("input").value.trim() || S.pending.length || S.sending.length || S.resending || $("sheet").classList.contains("on")) return; + history.replaceState(null, "", location.pathname + (S.view === "chat" && S.open ? "#bot=" + S.open + (S.relay && S.host ? "&host=" + encodeURIComponent(S.host) : "") : "")); + location.reload(); +} if ("serviceWorker" in navigator) navigator.serviceWorker.addEventListener("message", (e) => { + // A new build of this page was just kept: still on the connecting screen, take it now (once a minute at + // most); already in, it is the one the next opening uses. + if (e.data && e.data.fresh) { + S.fresh = true; + let last = 0; try { last = +sessionStorage.getItem("anybot.fresh") || 0; } catch (_) {} + if (!S.entered && S.view === "gate" && Date.now() - last > 60000) { + try { sessionStorage.setItem("anybot.fresh", String(Date.now())); } catch (_) {} + history.replaceState(null, "", location.pathname + LAUNCH); + location.reload(); + } + return; + } const d = e.data && e.data.open; if (!d) return; - if (d.host && d.host !== S.host && S.relay) { S.host = d.host; localStorage.setItem("anybot.host", S.host); S.version = 0; } + if (d.host && d.host !== S.host && S.relay) { toHost(d.host); S.version = 0; } if (d.answer && d.ask && d.bot) { // (Not signed in yet: kept, and sent once the phone is — apply.) if (S.token) api(base() + `api/bots/${d.bot}/answer`, {json: {answer: d.answer, call: d.ask, from: "notice"}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message)); @@ -3714,10 +3808,11 @@ if (window.visualViewport) { visualViewport.addEventListener("resize", kb); visualViewport.addEventListener("scroll", kb); } -document.addEventListener("visibilitychange", () => { if (document.hidden) return; if (S.msgsStale) renderMsgs(); kick(); if (S.view === "screen") startFrames(); }); +document.addEventListener("visibilitychange", () => { if (document.hidden) { swapWhenAway(); return; } setTimeout(() => { picking = false; }, 1000); if (S.msgsStale) renderMsgs(); kick(); if (S.view === "screen") startFrames(); }); addEventListener("online", kick); addEventListener("offline", () => { if (S.token) netDown(true); }); addEventListener("pageshow", (e) => { if (e.persisted) kick(); }); +setOff(); hello(); diff --git a/mobile/sw.js b/mobile/sw.js index 05ea9cc..e8d80db 100644 --- a/mobile/sw.js +++ b/mobile/sw.js @@ -1,7 +1,84 @@ -// AnyBot 手機 App 的 Service Worker(帳號伺服器送出):推播通知、點通知打開那個 Bot、App 圖示上的數字。 +// AnyBot 手機 App 的 Service Worker(帳號伺服器和直接連線都送):頁面存在手機上、推播通知、點通知打開那個 Bot、App 圖示上的數字。 // 通知的圖示是 AnyBot 的貓(黃色底);Android 狀態列的小圖示只能是單色,用那隻貓的剪影(badge-96.png)。 -self.addEventListener("install", () => self.skipWaiting()); -self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim())); + +// 打開得快:頁面、圖示、App 資訊存在這支手機上(只有這幾個每個人都一樣的檔,沒有聊天或帳號資料), +// 打開時直接用。頁面每次打開都在背景問一次換版沒(帶著存的那份的版本標記,沒換只回「沒有變」); +// 換了就存新的、先告訴頁面(還在連線畫面就重新載入;已經進去的話,App 退到背景、手上沒東西時才換), +// 再重抓圖示。重新整理(reload)一定先問伺服器,連不上才用存的。 +const SHELL = "anybot-shell-v1"; +// (Not novnc.js: the screen page, always asked from the server, must get the one it was built with.) +const KEPT = ["", "index.html", "manifest.webmanifest", "icon.svg", "icon-180.png", "icon-192.png", "icon-512.png", "icon-maskable-192.png", "icon-maskable-512.png", "badge-96.png"]; +// What the page shows while it connects: kept at install, so even the first reopen needs nothing. +const FIRST = ["", "manifest.webmanifest", "icon.svg", "icon-180.png", "icon-192.png"]; +const scope = () => self.registration.scope; +// The one key a kept file is under (the page under the folder's own address), or null: not one of +// them (the API, a published site, a download, the screen — never touched here). +function keyOf(url) { + const u = new URL(url), root = new URL(scope()); + if (u.origin !== root.origin || !u.pathname.startsWith(root.pathname)) return null; + const rest = u.pathname.slice(root.pathname.length); + return KEPT.includes(rest) ? new URL(rest === "index.html" ? "" : rest, root).href : null; +} +// Kept as the plain bytes that arrived: the body is unpacked by then, so how it was packed for the +// trip (and its length on the wire) is not said again. +async function keepable(r) { + const h = new Headers(r.headers); + h.delete("Content-Encoding"); h.delete("Content-Length"); + return new Response(await r.blob(), {status: r.status, statusText: r.statusText, headers: h}); +} +async function store(c, key) { + const r = await fetch(key, {cache: "no-cache"}); + if (r.status !== 200 || r.redirected) throw new Error("not kept"); + const k = await keepable(r); + await c.put(key, k.clone()); + return k; +} +// The page from the server, asked against the build kept ("not modified": {}): another build is +// kept at once (`changed`). +async function renew(c, held) { + const key = scope(), was = held.headers.get("ETag"); + const r = await fetch(key, {cache: "no-store", headers: was ? {"If-None-Match": was} : {}}); + if (r.status !== 200 || r.redirected) return {}; + const page = await keepable(r); + // (No tag from the server: never taken for a new build, or every opening would be one.) + const now = page.headers.get("ETag"), changed = !!now && now !== was; + if (changed) await c.put(key, page.clone()); + return {page, changed}; +} +async function iconsAgain(c) { + const key = scope(); + await Promise.all((await c.keys()).map((q) => q.url).filter((k) => k !== key).map((k) => store(c, k).catch(() => {}))); +} +async function tell() { + for (const w of await self.clients.matchAll({type: "window"})) w.postMessage({fresh: true}); +} +self.addEventListener("install", (e) => { + self.skipWaiting(); + e.waitUntil(caches.open(SHELL).then((c) => Promise.all(FIRST.map((k) => store(c, new URL(k, scope()).href).catch(() => {}))))); +}); +self.addEventListener("activate", (e) => e.waitUntil((async () => { + for (const k of await caches.keys()) if (k.startsWith("anybot-shell-") && k !== SHELL) await caches.delete(k); + await self.clients.claim(); +})())); +self.addEventListener("fetch", (e) => { + if (e.request.method !== "GET") return; + const key = keyOf(e.request.url); + if (!key) return; + e.respondWith((async () => { + const c = await caches.open(SHELL); + const held = await c.match(key); + if (!held) return store(c, key).catch(() => fetch(e.request)); + if (key !== scope()) return held; + // 重新整理: the server's first (this build if nothing changed); the kept one only when it can't be reached. + if (e.request.mode === "navigate" && (e.request.cache === "reload" || e.request.cache === "no-cache")) { + const {page, changed} = await renew(c, held).catch(() => ({})); + if (changed) e.waitUntil(iconsAgain(c).catch(() => {})); + return page || held; + } + e.waitUntil(renew(c, held).then(async ({changed}) => { if (changed) { await tell(); await iconsAgain(c); } }).catch(() => {})); + return held; + })()); +}); // kind: need(需要你允許、問你、需要你處理)、done(做完了)、routine(例行任務暫停)、file(收到傳來的檔案)、test。 self.addEventListener("push", (e) => { diff --git a/src/remote.rs b/src/remote.rs index 8ff1933..539df75 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -509,6 +509,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { ("GET", ["screen"]) => return Resp::bytes("text/html; charset=utf-8", SCREEN_PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE))), ("GET", ["novnc.js"]) => return Resp::bytes("text/javascript; charset=utf-8", NOVNC.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"), ("GET", ["manifest.webmanifest"]) => return Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()), + // (Keeps the page and its icons on the phone; see mobile/sw.js.) + ("GET", ["sw.js"]) => return Resp::bytes("text/javascript; charset=utf-8", SW.as_bytes().to_vec()), // (The icons are kept a day: the page shows one while it connects, on every opening.) ("GET", ["icon.svg"]) => return Resp::bytes("image/svg+xml", ICON.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"), ("GET", [name]) if ICON_PNGS.iter().any(|(n, _)| n == name) => return Resp::bytes("image/png", ICON_PNGS.iter().find(|(n, _)| n == name).map(|(_, b)| b.to_vec()).unwrap_or_default()).with_header("Cache-Control", "public, max-age=86400"), @@ -645,12 +647,15 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { Err(e) => Resp::error(422, &e), } } + // A chat; for a page holding a copy (`&chat_sig=…&chat_delta=1`), only what changed since. ("GET", ["api", "bots", id]) => { let id: u64 = id.parse().unwrap_or(0); + let held = req.query.get("chat_sig").map(String::as_str).unwrap_or(""); + let part = req.query.get("chat_delta").is_some_and(|d| d == "1"); let v = hub().view.lock().unwrap(); match v.messages.get(&id) { Some(m) => { - let mut out = chat_for(id, messages_for_role(m, &role), "", false); + let mut out = chat_for(id, messages_for_role(m, &role), held, part); out["version"] = json!(v.version); Resp::json(&out) } @@ -3110,6 +3115,8 @@ const NOVNC: &str = include_str!("../mobile/novnc.js"); pub const MANIFEST: &str = include_str!("../mobile/manifest.webmanifest"); /// The app's icon, the same drawing everywhere (icons/anybot.svg is the Mac/Linux one). pub const ICON: &str = include_str!("../mobile/icon.svg"); +/// The phone page's service worker: the page kept on the phone, notifications (shared with relay/). +pub const SW: &str = include_str!("../mobile/sw.js"); /// PNGs for the iPhone home screen (it ignores SVG), Android (full-bleed ones for its masks) and /// the one-colour cat Android shows in the status bar. pub const ICON_PNGS: [(&str, &[u8]); 6] = [ @@ -3583,9 +3590,29 @@ mod tests { assert_eq!(ok.status, 200); let token = serde_json::from_slice::(&ok.body).unwrap()["token"].as_str().unwrap().to_string(); let colours = json!({"light": palette_json(&crate::theme::shell(1.0, "clay", 1.0, false)), "dark": palette_json(&crate::theme::shell(1.0, "clay", 1.0, true))}); - hub().publish(View { host: "測試 Mac".into(), bots: vec![json!({"id": 1, "name": "小助理"})], theme: "dark".into(), palettes: colours, ..Default::default() }); + let said = |n: u64| (0..n).map(|i| json!({"index": i, "role": "bot", "text": format!("第 {i} 則")})).collect::>(); + hub().publish(View { host: "測試 Mac".into(), bots: vec![json!({"id": 1, "name": "小助理"})], theme: "dark".into(), palettes: colours.clone(), messages: HashMap::from([(1, said(3))]), ..Default::default() }); let mut req = Req { method: "GET".into(), path: "/api/state".into(), ..Default::default() }; req.headers.insert("authorization".into(), format!("Bearer {token}")); + // A chat the page holds a copy of: "unchanged", or only what came after (an older page: all). + let chat = |q: &[(&str, &str)]| { + let mut r = Req { method: "GET".into(), path: "/api/bots/1".into(), headers: req.headers.clone(), ..Default::default() }; + r.query = q.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + let a = handle(r, false); + assert_eq!(a.status, 200); + serde_json::from_slice::(&a.body).unwrap() + }; + let whole = chat(&[]); + let sig = whole["sig"].as_str().unwrap().to_string(); + assert_eq!(whole["messages"].as_array().unwrap().len(), 3); + assert_eq!(chat(&[("chat_sig", &sig), ("chat_delta", "1")])["unchanged"], true); + hub().publish(View { host: "測試 Mac".into(), bots: vec![json!({"id": 1, "name": "小助理"})], theme: "dark".into(), palettes: colours.clone(), messages: HashMap::from([(1, said(4))]), ..Default::default() }); + let part = chat(&[("chat_sig", &sig), ("chat_delta", "1")]); + assert_eq!((part["base"].as_str(), part["from"].as_u64(), part["messages"].as_array().map(Vec::len)), (Some(sig.as_str()), Some(3), Some(1))); + assert_eq!(chat(&[("chat_sig", &sig)])["messages"].as_array().unwrap().len(), 4); + // The service worker that keeps the page on the phone, without signing in. + let sw = handle(Req { method: "GET".into(), path: "/sw.js".into(), ..Default::default() }, false); + assert_eq!((sw.status, sw.body.as_slice()), (200, SW.as_bytes())); let st = handle(req.clone(), false); assert_eq!(st.status, 200, "{}", String::from_utf8_lossy(&st.body)); let v: Value = serde_json::from_slice(&st.body).unwrap();