From 04bc58f4a5fe1e72a502f80894824cc3787bd036 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 11:03:50 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=89=8B=E6=A9=9F=E9=A0=81=E9=9D=A2?= =?UTF-8?q?=E7=B6=B2=E8=B7=AF=E6=85=A2=E6=88=96=E6=96=B7=E7=B7=9A=E9=83=BD?= =?UTF-8?q?=E4=B8=8D=E6=93=8B=E6=93=8D=E4=BD=9C=E2=80=94=E2=80=94=E7=94=A8?= =?UTF-8?q?=E5=AD=98=E7=9A=84=E5=85=A7=E5=AE=B9=E7=9B=B4=E6=8E=A5=E9=80=B2?= =?UTF-8?q?=E5=8E=BB=E3=80=81=E8=A8=8A=E6=81=AF=E6=8E=92=E9=9A=8A=E9=80=A3?= =?UTF-8?q?=E4=B8=8A=E6=89=8D=E9=80=81=E3=80=81=E6=94=B9=E6=9D=B1=E8=A5=BF?= =?UTF-8?q?=E7=85=A7=E6=9C=80=E6=96=B0=E7=9A=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用者:「只要沒網路就很難用,網路延遲會影響到畫面表現,這不能被允許」。以前沒拿到第一份狀態 就一直停在連線畫面;斷線約一分鐘訊息就標「沒送出」;看過的聊天只在記憶體裡。 打開不等網路 - 每台電腦上次的狀態、看過的聊天(合計 12 個)、Bot 詳細資料、設定存在這個網址的 IndexedDB; 存過就直接用它進去,連上後第一個請求帶著那份狀態的指紋,只補變了的。只有第一次才停在連線畫面。 - 浮著的提示:「離線中:顯示的是上次的內容」/「顯示的是上次的內容,正在更新…」,拿到大腦的 狀態就消失。用帳號連、那台不在線上時留在它上次的內容裡,不換到別台。 - 設定、詳細資料、例行任務、頁面先畫手上有的再在背景讀(例行任務各 Bot 同時問)。 - 儲存空間 3 秒打不開或被系統關掉時下次再開;打不開也照樣能用,只是不存。登出全部清掉。 訊息不等網路 - 按下送出就出現在聊天裡;連不上標「等連線後送出(點一下拿回來)」,每則各存一份在手機上 (連同離線時選的附件),關掉 App 也還在;連上後照順序送、不限時間,每台電腦各排各的。 - 大腦記訊息代號從 10 分鐘改成一天、最多 5 萬個(src/remote.rs DELIVERY_TTL),晚送的不會多收一次。 - 可能已經送到(逾時、送出去幾秒後才斷、帳號伺服器說斷線了/收到了但沒回應)的,拿回前先問。 - 附件超過 30 MB 選的時候就說;伺服器 90 秒內傳不完三次就標「沒送出」,不擋後面的。 - /goal clear 這類指令不排隊,送不出去字和附件放回輸入框。 改東西照大腦現在的那份 - Bot 設定頁是上次存的就變淡、寫「讀到最新的才能改」;例行任務的暫停/編輯、指示、描述、 成員用 30 秒內讀到的那份;能力、技能、可以用的電腦、成員打勾送的是大腦現在的清單只改那一格, 連續按的一個一個送。 - 換電腦時前一台的清單、狀態、詳細資料、設定、從通知帶來的回答一律不帶過去。 允許路徑(需實機測試與人類簽名) - 從通知打開、用存的內容進去時,通知上按的允許/拒絕等拿到大腦自己的狀態才送(enter() 的閘門); 送的內容和卡片的 key 沒變。coverage.tsv 新增 page.enter_answer 追蹤這一段,page.banner_message 重算(那段的允許部分沒變)。 已驗證: cargo test 756 通過(含 featuremap::、layout_audit::);verify-approval-routing --replay AllSurfaces 通過、replay 10 個都過(desk.approval_body 等 5 段的「改過了」在 HEAD 就是如此); verify-anybot 照 phone.md 從頭到尾全過,含新的「沒網路也打得開」(大腦關著 0.4 秒看到清單、離線 傳的那句關掉重開還在、大腦回來只收到一次、拿回的那句沒送);另外實跑:離線打開 Bot 設定變淡不能改、 連上自己恢復;電腦那邊關掉「上網」後手機改別的能力不會把它打開;連按兩個能力兩個都生效;31 MB 檔案 選的時候就擋;沒存過的聊天離線顯示提示;登出清掉手機上的資料。四輪乾淨脈絡獨立審查,前三輪的 P1(佇列互卡、拿舊資料改設定、狀態存到別台、選電腦清單出不來、排隊清單被蓋掉、上傳卡死、連按互蓋) 都修了,第四輪沒有 P0/P1。 未驗證: 真的 iPhone/Android(IndexedDB 在 iOS 背景的行為、主畫面 App);帳號連線多台電腦的切換 (scratch 不帶帳號伺服器,靠讀程式與審查);允許路徑的實機測試與人類簽名,本輪不發佈。 已知 P2 留到下一輪:帳戶選單的登出沒寫清掉幾則、改密碼輸錯被登出會清掉排隊、存的附件讀不出來時 佇列卡住、稽核紀錄登出不清(舊的)等。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha5JgTkqJjkgMtrEXrn --- .../skills/verify-approval-routing/SKILL.md | 2 +- .../verify-approval-routing/coverage.tsv | 3 +- FEATURES.md | 4 +- docs/feature-map/phone.md | 12 +- mobile/index.html | 475 ++++++++++++++---- src/remote.rs | 12 +- 6 files changed, 405 insertions(+), 103 deletions(-) diff --git a/.claude/skills/verify-approval-routing/SKILL.md b/.claude/skills/verify-approval-routing/SKILL.md index b2df53d..3918d29 100644 --- a/.claude/skills/verify-approval-routing/SKILL.md +++ b/.claude/skills/verify-approval-routing/SKILL.md @@ -96,7 +96,7 @@ Bot 要做會動到你電腦的事時,大腦放一張卡等你:「允許/ | `YouAnswerOnDesk` | `desk.approval_dock`、`desk.approval_body`、`desk.question_card`、`brain.answer`(src/app.rs) | 同一個畫面格裡畫出現在的卡、讀按鈕或 Enter/Esc、呼叫 `answer()`:看到的就是現在的卡。問題卡的表單(步驟、勾選、打的字)照卡的 key 認,換了一張(就算同一個 call_0、題數一樣)就從頭開始。 | | `PageRefreshes` | `page.approval_json`、`page.phone_cards`(src/app/remote_ui.rs)、`page.render_dock`、`page.question`(mobile/index.html) | 手機拿到的是大腦某一刻的 `approvals`,每張卡帶自己的 `key`(支線的卡放在主線的聊天、`target` 是支線、帶支線的 key);可以一直不更新。 | | `YouTapOnPage` | `page.render_dock`、`page.question`、`remote.answer_routes`(src/remote.rs) | 按下就清掉手機上的卡,POST `{answer, call: a.key}`(問題卡 `{answer: "answered"\|"reject", text, call}`);更新前就開著的舊頁面不帶 `call`。 | -| `YouTapBanner` | `banner.notificationclick`(mobile/sw.js)、`page.banner_answer`、`page.open_from_hash`、`page.banner_message`(mobile/index.html) | 只有 allow → `once`、deny → `reject`;帶 `call = d.ask`(推通知時那張卡的 key)和 `from: "notice"`。同一個 Bot 新的通知蓋掉舊的。 | +| `YouTapBanner` | `banner.notificationclick`(mobile/sw.js)、`page.banner_answer`、`page.enter_answer`(從通知打開、用手機上存的內容進去時,等拿到大腦自己的狀態才送)、`page.open_from_hash`、`page.banner_message`(mobile/index.html) | 只有 allow → `once`、deny → `reject`;帶 `call = d.ask`(推通知時那張卡的 key)和 `from: "notice"`。同一個 Bot 新的通知蓋掉舊的。 | | `ScreenRefreshes` | `screen.view`、`screen.sync`(src/app/mirror_ui.rs) | 大腦給的每張卡帶 `key`;螢幕電腦把 `approvals` 整份換進來,key 記在 `mir.keys`,key 變了才算新卡,新卡用 `new_approval_keyed` 把同一把 key 放進自己的 `ask_keys`;可以一直不更新。 | | `YouAnswerOnScreen` | `brain.answer` 的 `mir.on` 分支、`remote.answer_routes` | 螢幕電腦先拿掉自己的卡,送 `{"bot", "action": "answer", "answer", "text", "call": mir.keys 裡那把}`;舊版螢幕電腦不帶 `call`。 | | `BrainTakesAnswer` | `brain.cmd_answer`(src/app/remote_ui.rs `Cmd::Answer`)、`brain.notice_answers`、`brain.answer` | UI 執行緒一次做完:有卡在等、帶了 key、key 是現在 `ask_keys` 那把(`ThisCard`),而且不是通知、或是 `notice_answers` 的卡加上 once/reject(`Fits`),才交給 `answer()`;不然不動(有卡在等時在主線的聊天寫「沒有用上」,寫什麼看它從哪條路來;模型不管寫不寫、寫什麼)。「一律允許」的 grant 讀現在這張卡的。 | diff --git a/.claude/skills/verify-approval-routing/coverage.tsv b/.claude/skills/verify-approval-routing/coverage.tsv index b2d1385..50c75cb 100644 --- a/.claude/skills/verify-approval-routing/coverage.tsv +++ b/.claude/skills/verify-approval-routing/coverage.tsv @@ -15,8 +15,9 @@ page.phone_cards src/app/remote_ui.rs block ^ fn phone_cards\( } 04a17f474fae page.render_dock mobile/index.html block ^function renderDock\(\) \{ } ad5f4140c16b7beadae7c08c53383ba4f17eed68ae357f3aa34750091a86659b page.question mobile/index.html block ^function renderQuestion\(a, force\) \{ } 829ae3088ec69585ecd9cff0d12cf5fd538ccc86869c4e46a6e9d8c4110d3a40 page.banner_answer mobile/index.html block ^ if \(S\.answer && S\.token\) \{ } 04f38fec448257ad65387689db94759688822087e9d4b1635d37f431b9e0ff0a +page.enter_answer mobile/index.html block ^ if \(S\.answer && S\.token && !S\.stale\) \{ } 07c4e32e1227c0d738c00f64484ac2ac247e6b34b1b6a3d14f21e76cce35e63e page.open_from_hash mobile/index.html block ^function openFromHash\(\) \{ } 5306ec26de8b8e458d92129b94dfa576b10df210ae5266c725567324e3a43a9c -page.banner_message mobile/index.html block ^if \("serviceWorker" in navigator\) navigator\.serviceWorker\.addEventListener\("message" }); 69c873dddd0316fe2dda023bf32d815dbc1238f5a7f810011d678272cd19b70d +page.banner_message mobile/index.html block ^if \("serviceWorker" in navigator\) navigator\.serviceWorker\.addEventListener\("message" }); 54f6736b39126ce3defead55a4954bee1c4acd5b1618df1ec48a366c51d9e849 banner.notificationclick mobile/sw.js block ^self\.addEventListener\("notificationclick" }); e6d98794998fa048ef0179a4893291d4c1bb67a34a7d25b7cbdff3f022ce4bc3 remote.answer_routes src/remote.rs grep => Cmd::Answer \{ - 02c54c27a1e19ef9e185dba4ee11f3881ec24c9408f24696a8422ab46d5881a1 screen.view src/app/mirror_ui.rs until ^ out\["approvals"\] = self \.collect\(\); 5ff7997d09ce6b9b30ea393be31d5af104762c1dcb2a176e68e178ea062cb4e7 diff --git a/FEATURES.md b/FEATURES.md index 3acb4d4..f644f63 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 分鐘內同一代號只收一次。還沒連上之前停在最外面的連線畫面(打開 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`、第一份狀態同時出發。 +- **網路不穩**:每個請求有期限(等新東西 45 秒、其他 60 秒,上傳不限),連線無聲斷掉也會發現;連不上時頂端浮一個小提示「連線中斷,正在重新連線…」(用上次存的內容打開、還沒連上時是「離線中:顯示的是上次的內容」,連得上但還沒拿到大腦的狀態時是「顯示的是上次的內容,正在更新…」;用帳號連、那台電腦不在線上時是「「…」目前沒有連線,連上後自動更新」),不擋畫面,重試間隔 1 秒起倍增到 15 秒,回到前景、網路恢復時立刻重連。**網路慢或斷線不擋操作**:這支手機存過這台電腦的資料時,打開 App 直接用上次的狀態進去(Bot 清單、看過的聊天、Bot 詳細資料、設定都在),不等網路;連上後只補上次之後變了的(第一個請求帶著那份狀態的指紋)。只有第一次(這支手機還沒有這台電腦的資料)才停在最外面的連線畫面(打開 App 時的頭像留在正中間呼吸、外圈漾開,不顯示文字;讀螢幕軟體唸「正在連線」,減少動態時不動),第一份狀態到手才進去。用帳號連、已經用上次的資料進去時,那台電腦不在線上就留在它的內容裡等,不換到別台。設定頁、Bot 詳細資料、例行任務、頁面清單都先畫手上有的,再在背景讀新的(例行任務的各 Bot 資料同時問,不一個等一個)。改東西一定照大腦現在的那份:Bot 設定頁是上次存的時候變淡、寫「顯示的是上次的設定,讀到最新的才能改」,讀到才能按;例行任務的暫停/編輯、指示、描述、擅長、不找它做的事、成員,改之前用 30 秒內讀到的那份(太舊就先讀一次,讀不到說「連上後才能改」);能力、技能、可以用的電腦、成員打勾時,送的是大腦現在那份清單只改這一格(連續按的一個一個送,後一個照前一個改完的清單),不會拿舊的整份蓋掉電腦上改過的。還沒存在手機上的聊天,離線時寫「這個聊天還沒存在這支手機上,連上後就會出現」,不畫成新的對話。換到帳號裡的另一台電腦時,前一台的清單、狀態、詳細資料、設定一律不帶過去(有那台存過的就直接用那台的);登出時正在讀的設定不會再寫回手機。通知帶來的「允許/拒絕」等連上、拿到大腦自己的狀態才送。**傳訊息不等網路**:按下送出,訊息立刻出現在聊天裡;連得上就送,連不上就標「等連線後送出(點一下拿回來)」,存在手機上排隊(關掉 App 也還在),連上後照順序自己送,不限時間,每台電腦各排各的(一台睡著不會擋住送給別台的);點一下拿回輸入框(連同附件);上一次送出等到逾時、送出去幾秒後才斷,或帳號伺服器說「那台斷線了」「傳來的資料壞掉了」「收到了但沒回應」時,拿回之前先問(大腦可能已經收到);一開始就連不上的不問。附件一個檔最大 30 MB(選的時候就說傳不上去);伺服器一個請求只給 90 秒,同一個檔三次都在時間內傳不完就標「沒送出」,不再擋後面的。帳號裡已經沒有的那台電腦的排隊訊息會說一聲後丟掉;大腦拒收、放了一週沒拿回的也丟掉。附件連不上時也先留在手機上(輸入框上方的檔名換成雲的圖示),跟訊息一起等連線再上傳。每則帶一個代號,大腦一天內同一代號只收一次(重送時回答在路上掉了也不會變兩則;最多記 5 萬個,大腦重新啟動會忘記)。登出時排隊的訊息跟著清掉:設定 › 手機與帳號 的「登出這支手機」確認寫會清掉幾則(帳戶選單和選電腦頁的登出沒寫),登入失效的登入頁寫清掉了幾則。換到另一台電腦時,從通知帶來、還沒送出的允許/拒絕不帶過去。大腦拒收的標「沒送出,點一下拿回來重送」(給已經刪掉的 Bot 的訊息,大腦照樣收下、不會有回應,這是原本就有的行為)。`/goal clear` 這類指令不排隊:連不上時說一聲,字和附件放回輸入框;還沒上傳的附件不跟指令走,留著給下一則。從通知打開 App 時按的「允許/拒絕」等拿到大腦自己的狀態才送;App 開著時按的,連不上就說一聲。 +- **傳輸**:直接連線的連線留著給下一個請求(30 秒沒用才關,手機不用每次重做 TCP 和 TLS 握手)、文字回答用 gzip 壓縮、手機頁面帶版本標記(沒換版只回「沒有變」);帳號連線時,電腦回給手機的資料壓縮著上傳到帳號伺服器,在那裡打開、再由帳號伺服器自己用 gzip 壓縮給手機(頁面、狀態、聊天都是;不靠前面的 Caddy 或 `tailscale serve`)。連線時畫面上的圖示瀏覽器留一天,不用每次打開都重新下載。頁面和圖示由 Service Worker(`mobile/sw.js`,帳號伺服器和直接連線都送)存在手機上:打開時直接用,背景用版本標記問一次換版沒,換了就存新的(還在連線畫面時頁面自己重新載入一次,通知帶來的聊天和回答照樣用上;已經進去的話,App 退到背景、手上沒東西——沒打字、沒附件、沒有改東西的請求在路上、沒在錄音、沒開選單、沒在選照片或拍照——才換,回到同一個聊天);重新整理一定先問伺服器,連不上才用存的。它只碰這幾個每個人都一樣的檔,API、發布的網站、下載、看畫面(含 `novnc.js`)都不經過它。存在這支手機上的(這個網址自己的 IndexedDB,`anybot` 資料庫):每台電腦上次的狀態、看過的聊天(每台電腦各自記,合計最多 12 個,還沒送到的訊息不算在聊天裡)、Bot 詳細資料、設定、還沒送到的訊息(每則各存一份,連同附件;沒有另外的清單,打開時讀得到幾則就是幾則,這次讀不到下一次再讀);登出(自己登出或登入失效)全部清掉。手機的儲存空間 3 秒打不開、或被系統關掉時,下次再開;打不開也照樣能用,只是不存。回到看過的聊天先顯示上次的,再用 `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 87b9133..40216d0 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` 網路不穩也能用:還沒連上之前停在最外面的連線畫面:只有打開 App 時那個頭像留在正中間輕輕呼吸、外圈一圈圈漾開,不顯示文字(讀螢幕軟體唸「正在連線」;系統設成減少動態時頭像不動),登入表單和 Bot 清單都還沒出現,連上、第一份狀態到手才進去,進去時清單已經在,可以直接點。已經進去之後斷線才留在裡面:上面出現「連線中斷,正在重新連線…」,自己重試(間隔越來越長,最長 15 秒),回到前景或網路恢復時立刻重連,不用重新整理;一個請求太久沒回音(連線斷了不會自己報錯)就放棄重來。傳出去的訊息沒送到會自己重送,同一則只會送到一次;Bot 工作中插的話重送時寫「網路不穩,重新傳送中…」,真的送不出去才標「沒送出,點一下拿回來重送」(Bot 沒在工作時,字放回輸入框)。只傳有變的部分:狀態只送改了的、打開的聊天只送從不一樣的地方開始的訊息;直接連線的連線留著給下一個請求用;兩種連線文字都壓縮(帳號伺服器自己壓,不靠前面的代理)。存在手機上的:頁面和圖示(打開時直接用,背景問一次換版沒;換了,還在連線畫面就自己重新載入,通知帶來的聊天和回答照樣用上;已經進去的話,App 退到背景、手上沒東西(沒打字、沒附件、沒有送到一半的訊息、沒在錄音、沒開選單、沒在選照片或拍照)時才換,回來還在同一個聊天;重新整理一定先問伺服器,連不上才用存的)、這次看過的聊天(最多 12 個,每台電腦各自記;回到那個聊天先顯示上次的,再只拿有變的部分;還沒送到的話不記;登出就清掉);聊天和帳號資料不會留在手機的儲存空間。登入過的手機打開時,確認連線、帳號裡的電腦和第一份狀態同時問,不一個等一個(還是拿到狀態才進去)。 +- `phone-net` 網路慢或斷線都不擋操作:存過這台電腦的資料,打開 App 就用上次的內容進去,不等網路,連上後只補變了的;浮著提示「離線中:顯示的是上次的內容」,拿到就消失。只有第一次(還沒有這台的資料)停在連線畫面:打開 App 時的頭像留在正中間呼吸、外圈漾開,不顯示文字(讀螢幕軟體唸「正在連線」;減少動態時不動),第一份狀態到手才進去。用帳號連、那台不在線上時留在它上次的內容裡,不換到別台。進去之後斷線:浮「連線中斷,正在重新連線…」,自己重試,回到前景或網路恢復時立刻重連。設定、詳細資料、例行任務、頁面先畫手上有的,背景再讀新的;要改的先讀到最新的。傳訊息不等網路:按下就出現在聊天裡;連不上標「等連線後送出(點一下拿回來)」,存在手機上排隊(關掉 App 也還在),連上後照順序自己送、不限時間,同一則只送到一次;點一下連同附件拿回輸入框;連不上時選的附件也跟著排隊。大腦拒收的才標「沒送出,點一下拿回來重送」。從通知打開時按的允許/拒絕等連上才送。只傳有變的部分、文字壓縮。頁面和圖示存在手機上:打開時直接用,背景問一次換版沒;換了,還在連線畫面就重新載入(通知帶來的聊天和回答照樣用上),已經進去就等 App 退到背景、手上沒東西(沒打字、附件、排隊的訊息、錄音、選單)才換;重新整理一定先問伺服器。上次的狀態、看過的聊天(合計最多 12 個)、詳細資料、設定、排隊的訊息每台電腦各自存在這個網址的儲存空間,登出(或登入失效)全部清掉。 - `phone-app` 像 App 一樣:加入主畫面後全螢幕、沒有網址列(瀏海、動態島、底部手勢條、橫放都避開);首頁會提示「把 AnyBot 裝成 App」(Android 直接安裝,iPhone 教你加入主畫面,可以關掉);換畫面會左右滑動;iPhone 主畫面 App 從左邊緣往右滑回上一頁。 ## 使用者怎麼到 @@ -34,7 +34,8 @@ - **顏色跟著電腦**(covers `phone-colors`):請 Bot 把電腦換成深色,重新整理;再把這支手機選「淺色」。指令:`$CTL phone send '換深色 [[call update_settings {"theme":"dark"}]]' && $CTL phone wait-text '主題 → dark' --in '#msgs' && $CTL phone open --listed && $CTL phone wait 'html[data-theme="dark"]' && $CTL phone shot phone-dark && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 這支手機的外觀 && $CTL phone click '#sheet-in .opt' --text 淺色 && $CTL phone wait 'html[data-theme="light"]'`。看到:外觀「跟著電腦」時變深色;選「淺色」就只有這支手機變回淺色。 - **設定頁**(covers `phone-pages`):帳戶選單 › 設定,再點「保險庫」。指令:`$CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone wait '[data-go="updates"]' && $CTL phone shot phone-settings && $CTL phone click '[data-go="vault"]' && $CTL phone wait-text '只在電腦上的 AnyBot 管理'`。看到:一般、模型、權限、整合、電腦、保險庫、手機與帳號、更新;保險庫只有一句說明(手機看不到密碼)。 - **裝成 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`):打開 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' 30 && $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`):看過聊天、回首頁後把大腦關掉,重新打開頁面;打開聊天傳一句,再重新打開一次,最後把大腦開回來。指令:`$CTL phone click '[data-back]' && $CTL stop && $CTL phone open --listed && $CTL phone wait '.row[data-bot="1"]' 3 && $CTL phone wait-text '離線中' --in '#net' 15 && $CTL phone click '.row[data-bot="1"]' && $CTL phone wait-text 'FAKE-MODEL 回答:斷線時傳的' --in '#msgs' 2 && $CTL phone send '要拿回來的' && $CTL phone click '.m.sending.held' && $CTL phone wait-gone '.m.sending' 5 && $CTL phone js 'document.querySelector("#input").value=""' && $CTL phone send '離線時傳的' && $CTL phone wait-text '等連線後送出' --in '#msgs' 30 && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone wait-text '離線時傳的' --in '#msgs' 3 && $CTL phone shot phone-kept && $CTL serve && $CTL phone wait-text 'FAKE-MODEL 回答:離線時傳的' --in '#msgs' 90`。看到:大腦關著也在 3 秒內看到 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`(沒有變),不重送訊息。 @@ -46,7 +47,8 @@ - 手機看不到保險庫,也看不到模型金鑰(只能寫入新的)。 - 手機上的卡沒用上時,要看現在在等什麼再按;開了很久的頁面先重新整理。用帳號登入的手機,頁面是帳號伺服器給的:伺服器還沒更新時,手機上的卡都答不了,要在電腦上答。 - 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。 -- 自動重送只認同一則(手機給每則訊息一個代號,大腦記 10 分鐘):網路斷超過大約一分鐘,那則會標「沒送出」,要自己再送。允許卡片的按鈕不自動重送(卡片可能已經換了)。 -- 換新版後第一次打開:還在連線畫面時就換上新頁面(頁面會自己重新載入一次);已經進去了才發現的話,先用舊頁面,App 退到背景、手上沒東西時換上(有東西就等下一次退到背景)。舊頁面答卡片的規則照 `phone-cards`;說「頁面太舊」時重新整理,重新整理一定拿伺服器的新頁面。 -- (驗證)Service Worker 要沒有憑證錯誤才裝得上:用自簽憑證的直接連線,瀏覽器沒有信任那張憑證時不會存頁面,每次打開照舊下載(壓縮過、沒換版只回「沒有變」)。 +- 排隊的訊息不限時間,幾天後連上也照送。自動重送只認同一則(手機給每則訊息一個代號,大腦記一天):排隊超過一天、或中間大腦重新啟動過,一則送到了但回答掉在路上的那種,可能會多收一次。允許卡片的按鈕不排隊(卡片可能已經換了),連不上時按了會說沒送出。 +- 「離線中」時,工作中、等你允許的卡片都是上次的樣子;被別的裝置登出的手機,連上之前也還看得到上次的內容。 +- 換新版後第一次打開多半還是舊頁面,App 退到背景、手上沒東西時才換上。舊頁面答卡片照 `phone-cards`;說「頁面太舊」時重新整理(一定拿伺服器的新頁面)。 +- (驗證)Service Worker 要沒有憑證錯誤才裝得上:用自簽憑證的直接連線,瀏覽器沒有信任那張憑證時不會存頁面,每次打開照舊下載。 - (驗證)無頭 Chrome 不是 iPhone:通知、主畫面的全螢幕和手勢都不會出現;卡片和選單用 `wait` 等它滑進來再按。 diff --git a/mobile/index.html b/mobile/index.html index 928cd94..3a4e8e6 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -219,6 +219,7 @@ details.dt>.dt-in{padding-left:var(--sp-4);margin-top:var(--sp-2)} .summary .tx{display:none;margin-top:6px;white-space:pre-wrap;overflow-wrap:anywhere} .summary.open .tx{display:block} /* cards in the chat */ +#botset.held .group{pointer-events:none;opacity:.55} .m.sending .bub{opacity:.55}.m.sending .sn{font-size:var(--fs-caption);color:var(--text3);align-self:flex-end;margin-top:2px}.m.sending.failed .sn{color:var(--danger)} .talk{border-radius:var(--r-l);background:none;box-shadow:inset 0 0 0 .5px var(--line);max-width:min(92%,560px);width:100%;margin:4px 0;padding:10px 12px;font-size:var(--fs-small);overflow:hidden} .talk .tk-h{display:flex;align-items:center;gap:5px;flex-wrap:wrap}.talk .tk-h span{color:var(--text3);font-size:var(--fs-caption);margin-left:2px} @@ -889,11 +890,11 @@ applyTheme(); // The phone switching light/dark while open: the status bar follows. try { matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => barColor()); } catch (_) {} -const S = { sending: [], voice: {}, - relay: false, token: localStorage.getItem("anybot.token") || "", host: localStorage.getItem("anybot.host") || "", +const S = { voice: {}, + relay: localStorage.getItem("anybot.relay") === "1", token: localStorage.getItem("anybot.token") || "", host: localStorage.getItem("anybot.host") || "", version: 0, bots: [], approvals: [], pages: [], models: [], hostName: "", mac: false, box: "", boxOn: false, role: "owner", prevShown: 0, prevFirst: "", answer: null, sc: "", - open: 0, msgs: [], pending: [], quote: null, unfold: {}, openSteps: {}, detail: {}, audit: {}, settings: null, polling: false, entered: false, + open: 0, msgs: [], pending: [], quote: null, unfold: {}, openSteps: {}, detail: {}, detailNew: {}, audit: {}, settings: null, polling: false, entered: false, chatSig: "", file: null, search: "", size: [0, 0], right: false, }; @@ -927,17 +928,23 @@ async function apiOnce(path, opts) { const timer = ms ? setTimeout(() => ctl.abort(), ms) : 0; if (opts.signal) { if (opts.signal.aborted) ctl.abort(); else opts.signal.addEventListener("abort", () => ctl.abort(), {once: true}); } let r, t; + const t0 = Date.now(); try { r = await fetch(path, {method: opts.method || (opts.body ? "POST" : "GET"), headers, body: opts.body, signal: ctl.signal}); if (opts.raw) { clearTimeout(timer); } else t = await r.text(); - } catch (_) { clearTimeout(timer); throw offline(); } + } catch (_) { + clearTimeout(timer); + // (Gone quiet past its deadline, or cut after a while — it was out: it may have arrived. Refused + // at once, or no line: it didn't.) + const e = offline(); e.unsure = ctl.signal.aborted || Date.now() - t0 > 3000; throw e; + } clearTimeout(timer); const signingIn = /(^|\/)(login|signup)$/.test(path); - if (r.status === 401 && !signingIn) { signOut(true); throw new Error("請重新登入"); } + if (r.status === 401 && !signingIn) { if (S.token) signOut(true); throw new Error("請重新登入"); } if (opts.raw) return r; let v = {}; try { v = t ? JSON.parse(t) : {}; } catch (_) {} - if (!r.ok) { const e = new Error(v.error || ("HTTP " + r.status)); e.transient = [408, 502, 503, 504].includes(r.status); throw e; } + if (!r.ok) { const e = new Error(v.error || ("HTTP " + r.status)); e.transient = [408, 502, 503, 504].includes(r.status); e.unsure = r.status === 504 || r.status === 502 || (r.status === 503 && /斷線了/.test(v.error || "")); e.status = r.status; throw e; } return v; } // Waits that the network coming back (or the app coming to the front) cuts short. @@ -947,9 +954,14 @@ function wake() { [...resting].forEach((end) => end()); } const backoff = (n, cap) => Math.min(cap, 1000 * 2 ** Math.min(n, 5)) * (0.6 + Math.random() * 0.4); // 「連線中斷」 at the top, only once it has lasted a moment (a single lost request doesn't flash it). let netTimer = 0; -function netDown(down) { +function netDown(down, said) { clearTimeout(netTimer); + S.offline = !!down; + // (In on what this phone kept and the line answers, but the brain's state isn't here yet: said, gently.) + if (!down && S.stale && S.entered) { down = true; said = "顯示的是上次的內容,正在更新…"; } if (!down) { $("net").classList.remove("on"); return; } + // (Opened on what this phone kept, not yet in touch: said so — what shows may be old.) + $("net").textContent = said || (S.stale ? "離線中:顯示的是上次的內容" : "連線中斷,正在重新連線…"); netTimer = setTimeout(() => $("net").classList.add("on"), 1500); } const mkId = () => Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(16).padStart(2, "0")).join(""); @@ -1045,6 +1057,7 @@ function show(v) { const was = S.view; document.querySelectorAll(".view").forEach((x) => x.classList.toggle("on", x.id === "v-" + v)); S.view = v; if (v !== "screen") stopFrames(); if (v !== "list") stopListTimer(); + if (was === "chat" && v !== "chat") keepNow(); // A new screen slides in (forward from the right, back from the left); redrawing the same one doesn't. const el = $("v-" + v), dir = S.dir; S.dir = ""; if (el && dir && was && was !== v) { el.classList.remove("in-fwd", "in-back"); void el.offsetWidth; el.classList.add(dir); el.addEventListener("animationend", () => el.classList.remove(dir), {once: true}); } @@ -1139,8 +1152,12 @@ $("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(() => {}); + const lost = OUT.filter((x) => !x.sentAt).length; 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 = "登入已失效,請重新登入"; + // 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(); + if (expired) $("login-err").textContent = "登入已失效,請重新登入" + (lost ? `(還沒送出的 ${lost} 則訊息已清掉)` : ""); } $("b-out1").innerHTML = ic("log-out", 20); $("b-out1").onclick = () => signOut(); @@ -1156,7 +1173,10 @@ async function pickHost() { 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. - if (S.host && !byId[S.host]) { S.host = ""; localStorage.removeItem("anybot.host"); } + if (S.host && !byId[S.host]) toHost(""); + // Messages waiting for a computer that is no longer this account's go nowhere: said, not kept. + const orphans = Array.isArray(me.hosts) ? OUT.filter((x) => x.relay && !x.sentAt && !byId[x.host]) : []; + if (orphans.length) { orphans.forEach(dropOut); toast(`${orphans.length} 則訊息沒有送出:那台電腦已經不在這個帳號裡`); } // 團隊邀請: someone shared their AnyBot with this account — nothing is opened until yes. for (const inv of me.invites || []) { const yes = await confirmSheet(`「${inv.owner}」邀請你使用他的 AnyBot「${inv.name}」`, `角色:${inv.role === "admin" ? "管理員" : "成員"}。接受後它會出現在你的清單裡。只接受你認識的人:對方的 AnyBot 回傳的內容會顯示在這裡。`, "接受", false); @@ -1168,18 +1188,22 @@ async function pickHost() { const sharers = (id) => all.filter((h) => h.uses === id).map((h) => h.name); const live = hosts.filter((h) => h.online); const used = live.filter((h) => sharers(h.id).length); - if (!S.host && used.length === 1) S.host = used[0].id; + if (!S.host && used.length === 1) toHost(used[0].id); if (S.host) { const t = target(S.host); - if (byId[t] && byId[t].online) { S.host = t; localStorage.setItem("anybot.host", t); return start(); } + if (byId[t] && byId[t].online) { toHost(t); return start(); } + // Already in, with what this phone kept of it: stays there until it is back (not another one). + if (S.entered && byId[t]) { netDown(true, `「${byId[t].name}」目前沒有連線,連上後自動更新`); hostRetry = setTimeout(pickHost, 3000); return; } } - if (live.length === 1) { S.host = live[0].id; localStorage.setItem("anybot.host", S.host); return start(); } + if (live.length === 1) { toHost(live[0].id); return start(); } const note = (h) => { const n = sharers(h.id); return n.length ? " · " + esc(n.join("、")) + " 也用這個大腦" : ""; }; const wanted = (S.host && byId[target(S.host)]) || (all.find((h) => sharers(h.id).length)) || hosts[0]; 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); toHost(r.dataset.h); if (!S.entered) show("gate"); start(); }); + // (In on a kept copy and now asked which computer: out again, so the one picked is gone into.) + S.entered = false; S.stale = false; show("hosts"); if (S.token && !live.length) hostRetry = setTimeout(pickHost, 3000); } @@ -1192,7 +1216,8 @@ function enter() { S.entered = true; netDown(false); if (!NAV.length) { NAV.push({v: "home", arg: {}}); history.replaceState({n: 1}, ""); } - if (S.answer && S.token) { + // (In on what was kept: a notification's answer goes with the brain's own state — apply.) + if (S.answer && S.token && !S.stale) { const a = S.answer; S.answer = null; api(base() + `api/bots/${a.bot}/answer`, {json: {answer: a.answer, call: a.call, from: "notice"}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message)); } @@ -1216,36 +1241,87 @@ 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 path = statePath(), pre = EARLY.state, mine = pre && pre.path === path; + const host = S.host, 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); + fails = 0; + // (Another computer was picked meanwhile: this answer is the other one's.) + if (S.host !== host) continue; if (v.base !== undefined) { const whole = v.base === S.ssig && S.st ? mergeState(S.st, v) : null; // (Not the state it was told against: the whole state, next time.) if (!whole) { S.version = 0; S.ssig = ""; continue; } v = whole; } - S.st = v; S.ssig = v.ssig || ""; - if (v.version !== S.version || !S.entered) { S.version = v.version; apply(v); } + S.st = v; S.ssig = v.ssig || ""; S.stHost = host; S.stale = false; netDown(false); + if (v.version !== S.version || !S.entered) { S.version = v.version; apply(v); keepSoon(); } if (!S.entered) enter(); + if (!outRead) loadOut(); + if (OUT.some((x) => !x.sentAt && !x.failed)) flush(); } catch (e) { if (!S.token) break; // Cut short by kick(): ask again at once. if (pollCtl.signal.aborted) continue; fails++; if (e.transient) netDown(true); - if (S.relay && /離線|offline|not connected/i.test(e.message)) toast("那台 AnyBot 目前沒有連線"); + if (S.relay && /離線|offline|not connected/i.test(e.message)) netDown(true, "那台 AnyBot 目前沒有連線,連上後自動更新"); await rest(backoff(fails - 1, 15000)); } } S.polling = false; } +// Last time's copy of this computer, kept on this phone: in at once on it (no waiting at the door +// on a slow or dead line); the brain's own state replaces it the moment it is here, and only +// what changed since that copy comes (its fingerprint goes with the first request). +async function restore() { + if (!S.token) return; + const host = S.host, token = S.token, same = () => S.token === token && S.host === host; + const [st, detail, settings, open] = await Promise.all(["st:" + host, "detail:" + host, "settings:" + host, "chat:" + chatKey(S.open)].map((k) => KEEP.get(k))); + await loadOut(); + // (Signed out, or another computer picked, while storage answered: none of this is for now.) + if (!same()) return; + if (open && open.sig && Array.isArray(open.msgs) && !CHATS.has(chatKey(S.open))) CHATS.set(chatKey(S.open), open); + // The other chats a moment later (the one in view first: a slow phone isn't held up by twelve). + setTimeout(async () => { + const all = await KEEP.all("chat:"); + if (!all || S.token !== token) return; + const kept = all.filter((c) => c && c.k && c.sig && Array.isArray(c.msgs)).sort((a, b) => (a.t || 0) - (b.t || 0)); + // (Oldest first, as if seen in that order: the ones over 12 go, here and on the phone.) + for (const c of kept) if (!CHATS.has(c.k)) { CHATS.set(c.k, c); if (CHATS.size > 12) { const old = CHATS.keys().next().value; CHATS.delete(old); KEEP.del("chat:" + old); } } + }); + if (detail && typeof detail === "object") S.detail = Object.assign(detail, S.detail); + if (settings && typeof settings === "object" && !S.settings) { S.settings = settings; S.settingsOld = true; } + const known = localStorage.getItem("anybot.relay"); + if (!st || !Array.isArray(st.bots) || S.entered || known === null || S.view === "hosts") return; + 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; } + apply(st); + enter(); +} +// The messages waiting on this phone, every one there is (no list of them that a write could +// leave short). Read again on the next answer from the brain when storage didn't answer now. +let outRead = false; +async function loadOut() { + if (outRead) return; + const token = S.token, all = await KEEP.all("out:"); + if (!all || S.token !== token) return; + outRead = true; + for (const x of all) { + if (!x || !x.id || OUT.some((o) => o.id === x.id)) continue; + // (Refused a week ago and never taken back: let go.) + if (x.failed && Date.now() - (x.at || 0) > 7 * 864e5) { KEEP.del("out:" + x.id); continue; } + OUT.push(Object.assign({attachments: [], files: []}, x)); + } + OUT.sort((a, b) => (a.at || 0) - (b.at || 0)); + if (OUT.length) flush(); +} 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) : ""; + const held = S.st && 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. @@ -1322,7 +1398,8 @@ function apply(v) { else if (c && c.bot === S.open && c.messages) applyChat(c.messages, c.sig); else loadChat(); } - else if (t.v === "details" && S.tab !== "memory" && Date.now() - (S.detailAt || 0) > 1500) renderDetails(t.arg.bot, S.tab, true); + else if (t.v === "details" && S.tab !== "memory" && Date.now() - (S.detailAt || 0) > 1500) renderDetails(t.arg.bot, S.tab, isNew(t.arg.bot)); + else if (t.v === "botset" && !isNew(t.arg.bot)) renderBotset(t.arg.bot); settingsChanged(); } @@ -1464,7 +1541,7 @@ $("b-me").onclick = () => { if (!installed() && (S.installPrompt || navigator.standalone === false)) items.push({icon: "download", label: "安裝成 App", on: installApp}); if (S.mac) items.push({icon: "monitor", label: "看這台 Mac 的螢幕", on: () => go("screen")}); if (S.relay && owner()) items.push({icon: "plus", label: "加一台電腦(Linux、伺服器)", on: pair}); - if (S.relay) items.push({icon: "refresh", label: "切換到別台 AnyBot", on: () => { S.host = ""; localStorage.removeItem("anybot.host"); S.version = 0; S.ssig = ""; S.entered = false; NAV.length = 0; show("gate"); kick(); pickHost(); }}); + if (S.relay) items.push({icon: "refresh", label: "切換到別台 AnyBot", on: () => { toHost(""); S.entered = false; NAV.length = 0; show("gate"); kick(); pickHost(); }}); items.push({icon: "log-out", label: "登出這支手機", danger: true, on: async () => { if (await confirmSheet("要登出這支手機嗎?", "", "登出", true)) signOut(); }}); sheet(S.hostName || "AnyBot", items); }; @@ -1484,7 +1561,8 @@ function chatSub(b) { return ["", b.model || ""]; } function chatHead() { - const b = bot(S.open); if (!b) return; + const b = bot(S.open); + if (!b) { $("isl-av").innerHTML = ""; $("isl-name").textContent = ""; $("isl-sub").textContent = ""; return; } $("isl-av").innerHTML = avatarSvg(b.shape, b.color); $("isl-name").textContent = b.name; const [cls, text] = chatSub(b); @@ -1493,25 +1571,85 @@ function chatHead() { $("b-newchat").style.display = owner() ? "" : "none"; } $("island").onclick = () => go("details", {bot: S.open}); -// 看過的聊天記在這頁裡(每個 Bot 一份,最多 12 份):回到它先畫上次看到的,再只拿有變的部分。 +// 存在這支手機上的(這個網址自己的儲存空間,登出就全部清掉):每台電腦上次的狀態、看過的聊天、 +// Bot 的詳細資料和設定,還有還沒送到的訊息。打開 App 先畫這些,不等網路;網路回來再只補變了的。 +// (No storage here — a private window, an old browser: everything still works, only from the network.) +const KEEP = (() => { + let db = null; + // (An open that never answers is given up after 3 s, and one the system closed — iOS does, in + // the background — is opened again: the next write tries anew.) + const open = () => db || (db = new Promise((ok, no) => { + const r = indexedDB.open("anybot", 1), late = setTimeout(() => no(new Error("timeout")), 3000); + r.onupgradeneeded = () => r.result.createObjectStore("kept"); + r.onsuccess = () => { clearTimeout(late); const d = r.result; d.onclose = () => { db = null; }; d.onversionchange = () => { d.close(); db = null; }; ok(d); }; + r.onerror = () => { clearTimeout(late); no(r.error); }; + r.onblocked = () => { clearTimeout(late); no(new Error("blocked")); }; + }).catch((e) => { db = null; throw e; })); + const run = (mode, f) => open().then((d) => new Promise((ok, no) => { + const t = d.transaction("kept", mode), q = f(t.objectStore("kept")); + t.oncomplete = () => ok(q.result); t.onerror = t.onabort = () => no(t.error); + })).catch((e) => { db = null; throw e; }); + return { + get: (k) => run("readonly", (s) => s.get(k)).catch(() => undefined), + // (Null when it couldn't be read — not the same as nothing there.) + all: (prefix) => run("readonly", (s) => s.getAll(IDBKeyRange.bound(prefix, prefix + "\uffff"))).catch(() => null), + put: (k, v) => run("readwrite", (s) => s.put(v, k)).catch(() => {}), + del: (k) => run("readwrite", (s) => s.delete(k)).catch(() => {}), + clear: () => run("readwrite", (s) => s.clear()).catch(() => {}), + }; +})(); +// What this page holds now, kept within 5 s of a change (at once when a chat is left or the app +// goes away). Not put off again by the next change: a bot at work changes it every second, and +// the copy must still be written — but not every second, a whole chat each time. +let keepTimer = 0; +function keepSoon() { if (!keepTimer) keepTimer = setTimeout(keepNow, 5000); } +function keepNow() { + clearTimeout(keepTimer); keepTimer = 0; + // (Only under the computer it is of: a switch since, and it is not this one's.) + 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); +} +// 看過的聊天(最多 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); + keepNow(); + if (S.chatSig) keepChat(S.open, S.msgs, S.chatSig); + S.open = 0; S.msgs = []; 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 + // settings are its own. In again on this one's kept copy, if this phone has one, at once. + S.st = null; S.ssig = ""; S.stHost = ""; S.version = 0; S.stale = false; S.bots = []; S.approvals = []; S.answer = null; + S.detail = {}; S.detailNew = {}; S.settings = null; + if (S.entered) { S.entered = false; NAV.length = 0; show("gate"); } + callOffEarly(); if (pollCtl) pollCtl.abort(); wake(); + if (!h) return; + KEEP.get("detail:" + h).then((d) => { if (d && S.host === h) S.detail = Object.assign(d, S.detail); }); + KEEP.get("settings:" + h).then((st) => { if (st && S.host === h && !S.settings) { S.settings = st; S.settingsOld = true; } }); + KEEP.get("st:" + h).then((st) => { + if (!st || !Array.isArray(st.bots) || S.host !== h || S.st || S.entered || !S.token) return; + S.st = st; S.ssig = st.ssig || ""; S.stHost = h; S.stale = true; + apply(st); enter(); + }); } 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); + // (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); + while (CHATS.size > 12) { const old = CHATS.keys().next().value; CHATS.delete(old); KEEP.del("chat:" + old); } } function openChat(id) { 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)); + S.chatLoaded = !!kept; if (kept) { S.msgs = kept.msgs; S.chatSig = kept.sig; } } S.open = id; @@ -1523,7 +1661,7 @@ function openChat(id) { if (bubble === "bot" && ob.color && ob.color_key !== "black") { chat.style.setProperty("--bot", ob.color); chat.style.setProperty("--bot-ink", "var(--on-color)"); } else { chat.style.removeProperty("--bot"); chat.style.removeProperty("--bot-ink"); } chatHead(); renderChips(); renderQuote(); - if (S.msgs.length) { renderMsgs(); $("scroller").scrollTop = $("scroller").scrollHeight; } + renderMsgs(); $("scroller").scrollTop = $("scroller").scrollHeight; loadChat(true); renderDock(); api(base() + `api/bots/${id}/read`, {json: {}}).catch(() => {}); } @@ -1532,30 +1670,30 @@ async function loadChat(jump) { if (!S.open) return; if (loading) { again = true; return; } loading = true; - const id = S.open, held = S.chatSig; + const id = S.open, held = S.chatSig, host = S.host; try { // 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) { + if (S.open === id && S.chatSig === held && S.host === host && !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(); + S.msgs = msgs; S.chatSig = v.sig || ""; S.chatLoaded = true; renderMsgs(); keepSoon(); if (jump || near) sc.scrollTop = sc.scrollHeight; } else { S.chatSig = ""; again = true; } } - } catch (e) { toast(e.message); } + } catch (e) { toast(e.message); if (S.open === id && !S.chatLoaded && S.view === "chat") renderMsgs(); } loading = false; if (again) { again = false; loadChat(); } } // The state poll carried the open chat's messages along (single trip): take them as-is. function applyChat(msgs, sig) { - S.chatSig = sig || ""; + S.chatSig = sig || ""; S.chatLoaded = true; const sc = $("scroller"); const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140; S.msgs = msgs; - renderMsgs(); + renderMsgs(); keepSoon(); if (near) sc.scrollTop = sc.scrollHeight; } // What a new chat offers (the desktop's 建議): the everyday jobs, one tap to start writing them. @@ -1723,15 +1861,24 @@ function renderMsgs() { // Still working: what it is doing now; a message nobody answered yet can be sent again. if (busy) h += (lastMsg && lastMsg.role !== "user" && !lastMsg.text && !(lastMsg.tools || []).length) || lastMsg?.role === "user" ? `
` : ""; if (busy && b.status) h += `
${face(b, "sm")}
${esc(b.status)}
`; - if (!busy && lastMsg && lastMsg.role === "user" && !lastMsg.wake && owner()) h += S.resending ? `
網路不穩,重新傳送中…
` : `
還沒有回覆
`; - if (!S.msgs.length) { + if (!busy && lastMsg && lastMsg.role === "user" && !lastMsg.wake && owner() && !OUT.some((x) => x.bot === S.open && x.host === S.host)) h += `
還沒有回覆
`; + if (!S.msgs.length && !S.chatLoaded) h = S.stale || S.offline ? `
這個聊天還沒存在這支手機上,連上後就會出現。
` : ""; + else if (!S.msgs.length) { h = `
${face(b, "lg")}
嗨,我是${esc(b.name || "Bot")}
${esc(b.description || "想做什麼?點一個開始,或直接打字。")}
${SUGGEST.map((x, k) => ``).join("")}
`; } - // 先顯示: words sent while it works, until the chat has them (or they failed: tap to take back). + // 先顯示: words not in the chat yet — waiting for the line, on their way, or there and not yet + // in what the brain sent back (taken off once they are; tap one still waiting to take it back). const tail = S.msgs.slice(-16).map((m) => String(m.text || "").trim()); - S.sending = S.sending.filter((x) => x.failed || (!tail.some((t) => t === x.text || t.endsWith(x.text)) && Date.now() - x.at < (busy ? 600000 : 8000))); - S.sending.filter((x) => x.bot === S.open).forEach((x, k) => { - h += `
${esc(x.text)}
${x.failed ? "沒送出,點一下拿回來重送" : x.retrying ? "網路不穩,重新傳送中…" : Date.now() - x.at < 1200 ? "傳送中…" : "已排入,它下一步會看到"}
`; + const here = (x) => x.bot === S.open && x.host === S.host; + for (let k = OUT.length - 1; k >= 0; k--) { + const x = OUT[k]; + if (x.sentAt && (!here(x) || (x.text && tail.some((t) => t === x.text || t.endsWith(x.text))) || (!x.text && x.sig !== null && S.chatSig !== x.sig) || Date.now() - x.sentAt > (busy ? 600000 : 8000))) OUT.splice(k, 1); + } + OUT.filter(here).forEach((x) => { + const names = x.attachments.length + x.files.length ? `
${ic("paperclip", 12)} ${esc([...x.files.map((f) => f.name), ...x.attachments.map((p) => String(p).split("/").pop())].join("、"))}
` : ""; + const held = !x.sentAt && !x.going; + const said = x.failed ? "沒送出,點一下拿回來重送" : x.sentAt ? (busy ? "已排入,它下一步會看到" : "已送出") : x.going ? "傳送中…" : "等連線後送出(點一下拿回來)"; + h += `
${x.text ? `
${esc(x.text)}
` : ""}${names}
${said}
`; }); $("msgs").innerHTML = h; renderSendBtn(); @@ -1745,7 +1892,19 @@ $("msgs").addEventListener("click", async (e) => { if (st) { const k = st.parentElement.dataset.step; S.openSteps[k] = !S.openSteps[k]; st.parentElement.classList.toggle("open"); return; } const f = e.target.closest(".fold"); if (f) { S.unfold[f.dataset.turn] = true; renderMsgs(); return; } const bs = e.target.closest("[data-brstop]"); if (bs) { try { await api(base() + `api/bots/${+bs.dataset.brstop}/stop`, {json: {}}); toast("已停止支線"); } catch (err) { toast(err.message); } return; } - const un = e.target.closest(".sending.failed"); if (un) { const mine = S.sending.filter((x) => x.bot === S.open); const x = mine[+un.dataset.unsent]; if (x) { S.sending = S.sending.filter((y) => y !== x); input.value = x.text; input.dispatchEvent(new Event("input")); renderMsgs(); input.focus(); } return; } + // A message not sent (still waiting for the line, or refused): back into the input with its files. + const un = e.target.closest(".sending.failed,.sending.held"); + if (un) { + const x = OUT.find((o) => o.id === un.dataset.unsent); + if (x && x.unsure && !x.failed && !await confirmSheet("拿回這則?", "上一次送到一半網路斷了,大腦可能已經收到:拿回來之後,Bot 還是可能回覆這一則。", "拿回來", false)) return; + if (x && !x.going && !x.sentAt) { + dropOut(x); wake(); + input.value = x.text + (input.value.trim() ? "\n" + input.value : ""); input.dispatchEvent(new Event("input")); + S.pending.push(...x.attachments.map((p) => ({path: p, name: String(p).split("/").pop()})), ...x.files); renderChips(); + renderMsgs(); input.focus(); + } + return; + } const tg = e.target.closest(".tk-go"); if (tg && tg.dataset.bot) { go("chat", {bot: +tg.dataset.bot}); return; } const sm = e.target.closest("[data-sum]"); if (sm) { sm.classList.toggle("open"); return; } const c = e.target.closest("[data-copy]"); if (c) { copyText(S.msgs[+c.dataset.copy].text); return; } @@ -2081,43 +2240,120 @@ async function send() { return; } if (S.quote) { text = S.quote.raw.split("\n").map((l) => "> " + l).join("\n") + "\n\n" + text; S.quote = null; renderQuote(); } - const attachments = S.pending.map((p) => p.path); + 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); + // (Files picked while the line was down are still here, waiting to go up with the message.) + const attachments = S.pending.filter((p) => !p.blob).map((p) => p.path); + const files = S.pending.filter((p) => p.blob).map(({name, image, blob}) => ({name, image, blob})); // 記憶 ticked above the composer (none of it if the shelf never answered: the brain chooses). const memories = b.busy ? undefined : memPicks(); 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 || [], 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; } - const body = {text, attachments}; if (memories) body.memories = memories; - // While it is tried again by itself, no 重新傳送 button: a second press would be a second message. - const retrying = () => { - if (sent) { if (!sent.retrying) { sent.retrying = true; renderMsgs(); } } - else if (!S.resending) { S.resending = true; renderMsgs(); } - }; - try { await deliver(base() + `api/bots/${S.open}/send`, body, retrying); if (sent) sent.retrying = false; if (quiet) loadChat(); } catch (e) { toast(e.message); if (sent) { sent.failed = true; renderMsgs(); } else if (!input.value) input.value = text; } - finally { if (!sent && S.resending) { S.resending = false; renderMsgs(); } } + // (A command takes no file that isn't up yet: those stay above the input for the next message.) + const had = S.pending; S.pending = quiet ? S.pending.filter((p) => p.blob) : []; + input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); renderChips(); renderSlash(); + // A command (not words for the chat): sent now, or said that it couldn't be (its words and files back). + if (quiet) { try { await deliver(base() + `api/bots/${S.open}/send`, {text, attachments}); loadChat(); } catch (e) { toast(e.message); if (!input.value) { input.value = text; input.dispatchEvent(new Event("input")); } S.pending = [...had.filter((p) => !S.pending.includes(p)), ...S.pending]; renderChips(); } return; } + // 先顯示: in the chat at once, network or not; it goes when the line is there (kept on this + // phone meanwhile, so closing the app doesn't lose it). + if (navigator.vibrate) navigator.vibrate(8); + const x = {id: mkId(), host: S.host, relay: S.relay, bot: S.open, text, attachments, files, at: Date.now()}; + if (memories) x.memories = memories; + OUT.push(x); keepOut(x); + // (Off first: the message reads 傳送中 when it is on its way, 等連線 when others wait ahead of it.) + flush(); renderMsgs(); $("scroller").scrollTop = 1e9; +} +// 還沒送到的訊息(存在手機上):一則一則照順序送,網路斷了就等,回來再送(不限時間);每則有自己的 +// 代號,大腦同一則只收一次。送到後留在畫面上,直到聊天裡出現它。 +const OUT = []; +// Each kept on its own (a photo too big to keep loses only its own message), with the list of them. +// (One the brain refused is kept too: it is there to take back after the app was closed.) +function keepOut(x) { + if (!S.token) return; + if (x.sentAt) KEEP.del("out:" + x.id); + else { const {id, host, relay, bot, text, attachments, files, memories, at, failed, unsure} = x; KEEP.put("out:" + id, {id, host, relay, bot, text, attachments, files, memories, at, failed, unsure}); } +} +function dropOut(x) { + const k = OUT.indexOf(x); if (k >= 0) OUT.splice(k, 1); + KEEP.del("out:" + x.id); +} +// One line per computer: one that is away (asleep, restarting) holds up only its own messages. +const flushing = new Set(); +function flush() { + for (const h of new Set(OUT.filter((x) => !x.sentAt && !x.failed).map((x) => x.host))) if (!flushing.has(h)) flushHost(h); +} +async function flushHost(h) { + flushing.add(h); + try { + for (let x; S.token && (x = OUT.find((o) => o.host === h && !o.sentAt && !o.failed));) { + const at = (x.relay ? "h/" + encodeURIComponent(x.host) + "/" : "") + "api/bots/" + x.bot + "/"; + const here = () => x.bot === S.open && x.host === S.host; + const shown = () => { if (here() && S.view === "chat") renderMsgs(); }; + for (let n = 0; OUT.includes(x) && S.token; n++) { + x.going = true; + if (x.waiting) shown(); + try { + // The files first (each one only once: its place on the brain is kept as soon as it is up). + while (x.files.length) { + const f = x.files[0]; + // (The server gives a whole request 90 s: past that it is cut, and trying again only + // spends the phone's data — three such cuts and it is given up on, below.) + const t0 = Date.now(); + const r = await api(at + "upload?name=" + encodeURIComponent(f.name), {method: "POST", body: f.blob, headers: {"Content-Type": "application/octet-stream"}, timeout: 95000}) + .catch((e) => { e.slow = e.status === 408 || e.status === 413 || Date.now() - t0 > 60000; throw e; }); + if (!S.token || !OUT.includes(x)) break; + x.attachments.push(r.path); x.files.shift(); keepOut(x); + } + if (!S.token || !OUT.includes(x) || x.files.length) break; + const body = {id: x.id, text: x.text, attachments: x.attachments}; + if (x.memories) body.memories = x.memories; + await api(at + "send", {json: body, timeout: 20000}); + // (The chat as it was when it went: a message with only files is in it once the chat changes.) + x.sentAt = Date.now(); x.going = false; x.sig = here() ? S.chatSig : null; + if (x.host === S.host) netDown(false); + break; + } catch (e) { + x.going = false; + // The brain said no (the bot is gone, signed out): kept here, to take back. + if (!e.transient || !S.token) { x.failed = true; toast(e.message); break; } + if (e.slow && (x.slow = (x.slow || 0) + 1) >= 3) { x.failed = true; toast("附件太大或網路太慢,傳不上去:點那則拿回來"); break; } + if (e.unsure && !x.unsure) { x.unsure = true; keepOut(x); } + if (x.host === S.host) netDown(true); + x.waiting = true; shown(); + await rest(backoff(n, 15000)); + } + } + x.going = false; + if (OUT.includes(x)) keepOut(x); + shown(); + // (Still here, neither sent nor refused: only when signed out — nothing more goes.) + if (OUT.includes(x) && !x.sentAt && !x.failed) break; + } + } finally { flushing.delete(h); } } $("b-plus").onclick = () => sheet("", [ {icon: "image", label: "照片與檔案", on: () => $("file").click()}, {icon: "camera", label: "拍照", on: () => $("camera").click()}, {icon: "alarm-clock", label: "建立例行任務", on: () => { input.value = "幫我建立一個例行任務:"; input.focus(); input.dispatchEvent(new Event("input")); }}, ]); +// The most one request may carry (src/httpd.rs MAX_BODY): a bigger file can never go up. +const MAX_FILE = 30 * 1024 * 1024; async function upload(files) { for (const f of files) { + if (f.size > MAX_FILE) { toast(`「${f.name}」超過 30 MB,傳不上去`); continue; } toast("上傳 " + f.name + "…"); try { const r = await api(base() + `api/bots/${S.open}/upload?name=` + encodeURIComponent(f.name), {method: "POST", body: f, headers: {"Content-Type": "application/octet-stream"}}); S.pending.push(r); renderChips(); - } catch (err) { toast(err.message); } + } catch (err) { + // No line now: the file stays here and goes up with the message once there is. + if (err.transient) { S.pending.push({name: f.name, image: /^image\//.test(f.type), blob: f}); renderChips(); netDown(true); } + else toast(err.message); + } } } $("file").onchange = (e) => { upload([...e.target.files]); e.target.value = ""; }; $("camera").onchange = (e) => { upload([...e.target.files]); e.target.value = ""; }; function renderChips() { - $("chips").innerHTML = S.pending.map((p, i) => `${ic(p.image ? "image" : "file", 14)}${esc(p.name)}`).join(""); + $("chips").innerHTML = S.pending.map((p, i) => `${ic(p.blob ? "cloud" : p.image ? "image" : "file", 14)}${esc(p.name)}`).join(""); $("chips").querySelectorAll("button").forEach((b) => b.onclick = () => { S.pending.splice(+b.dataset.i, 1); renderChips(); }); renderSendBtn(); } @@ -2204,9 +2440,29 @@ $("b-botset").innerHTML = ic("settings", 20); $("b-botset").onclick = () => go("botset", {bot: cur().arg.bot}); async function loadDetail(id) { if (!owner()) return null; - try { S.detail[id] = await api(base() + `api/bots/${id}/detail`); S.detailAt = Date.now(); } catch (e) { toast(e.message); } + const host = S.host; + try { + const d = await api(base() + `api/bots/${id}/detail`); + if (S.host !== host) return null; + S.detail[id] = d; S.detailNew[id] = Date.now(); S.detailAt = Date.now(); keepDetailSoon(); + } catch (e) { toast(e.message); } return S.detail[id]; } +let detailTimer = 0; +function keepDetailSoon() { + clearTimeout(detailTimer); + const host = S.host; + detailTimer = setTimeout(() => { if (S.token && S.host === host) KEEP.put("detail:" + host, S.detail); }, 1000); +} +// A bot's details as the brain has them now: a change is made on these, never on a copy kept from +// before (an old list of abilities sent back whole would turn on again what was turned off since). +// Null when they can't be read now. +// (Read this session: shown as current. Read in the last 30 s: what a change is made on.) +const isNew = (id, age = Infinity) => !!(S.detailNew[id] && S.detail[id] && Date.now() - S.detailNew[id] < age); +async function freshDetail(id) { + if (!isNew(id, 30000)) await loadDetail(id); + return isNew(id, 30000) ? S.detail[id] : null; +} const item = (o) => `<${o.tap ? "button" : "div"} class="item ${o.danger ? "danger" : ""}" ${o.data || ""}>${o.icon ? ic(o.icon, 19) : ""}
${esc(o.k)}
${o.v ? `
${esc(o.v)}
` : ""}
${o.r != null ? `
${esc(o.r)}
` : ""}${o.sw != null ? `` : ""}${o.tap && o.chev !== false ? `${ic("chevron-right", 16)}` : ""}`; const group = (title, inner, extra = "") => `${title ? `
${esc(title)}${extra}
` : ""}
${inner}
`; async function loadAudit(id) { @@ -2217,7 +2473,9 @@ async function loadAudit(id) { async function renderDetails(id, tab, quiet) { const b = bot(id); if (!b) { back(); return; } S.tab = tab || S.tab || "activity"; - if (!quiet || !S.detail[id]) { if (!S.detail[id]) $("details").innerHTML = `
載入中…
`; await loadDetail(id); } + // What this phone has first (drawn now), the brain's newer one when it comes. + if (!S.detail[id]) { $("details").innerHTML = `
載入中…
`; await loadDetail(id); } + else if (!quiet) loadDetail(id).then(() => { const t = cur(); if (t.v === "details" && t.arg.bot === id && S.tab !== "memory") renderDetails(id, S.tab, true); }); if (cur().v !== "details") return; $("b-botset").style.display = isOwner() ? "" : "none"; const d = S.detail[id] || {}; @@ -2313,12 +2571,13 @@ function wireDetails(b, d) { on("[data-forget]", async (x) => { if (await app("forget", {what: x.dataset.forget}, b.id)) renderDetails(b.id, S.tab); }); on("[data-sg]", (x) => { const s = SUGGEST[+x.dataset.sg]; back(); setTimeout(() => { input.value = s[3]; input.focus(); input.dispatchEvent(new Event("input")); }, 60); }); on("[data-rt]", (x) => routineSheet(b, (d.routines || []).find((r) => r.id === +x.dataset.rt))); - on("[data-mem]", async (x) => { + on("[data-mem]", (x) => oneAtATime(async () => { if (!isOwner()) return; - const ids = new Set((d.members || []).map((m) => m.id)); const id = +x.dataset.mem; + const now = await freshDetail(b.id); if (!now) { toast("連上後才能改"); return; } + const ids = new Set((now.members || []).map((m) => m.id)); const id = +x.dataset.mem; ids.has(id) ? ids.delete(id) : ids.add(id); - if (await act("bot", {bot: b.id, key: "members", value: [...ids]}, "已更新成員")) renderDetails(b.id, S.tab); - }); + if (await act("bot", {bot: b.id, key: "members", value: [...ids]}, "已更新成員")) { delete S.detail[b.id]; renderDetails(b.id, S.tab); } + })); const t = $("box-thumb"); if (t) boxThumb(t); el.querySelectorAll(".files [data-img]").forEach(async (f) => { if (f.querySelector("img")) return; try { const u = await fileUrl(f.dataset.file); f.innerHTML = ``; } catch (_) {} }); el.querySelectorAll(".files [data-img]").forEach((f) => f.onclick = async () => { try { window.open(await fileUrl(f.dataset.file), "_blank"); } catch (e) { toast(e.message); } }); @@ -2463,6 +2722,8 @@ function pickComputer(b, d) { sheet("做事的電腦", list.map((n) => ({icon: "monitor", label: n, check: n === b.computer, on: () => setBot(b, {computer: n}, "之後預設在「" + n + "」做事")}))); } async function editInstructions(b, d) { + d = await freshDetail(b.id); + if (!d) { toast("連上後才能改"); return; } const t = await ask("指示(它的工作、口吻、界線)", d.instructions || "", "例如:你負責幫我經營 Threads…", true); if (t != null && t !== d.instructions && await app("update_bot", {instructions: t}, b.id, "已更新指示")) { delete S.detail[b.id]; if (cur().v === "details") renderDetails(b.id, S.tab); else if (cur().v === "botset") renderBotset(b.id); } } @@ -2472,11 +2733,19 @@ function routineSheet(b, r) { const html = `
${esc(r.title)}
${esc(r.trigger ? "事件觸發:" + r.trigger : r.repeat)} · ${esc(r.when)}${r.last ? " · 上次 " + esc(r.last) : ""}
${r.status ? `
${esc(r.status)}
` : ""}${r.target ? `
${esc(r.target)}
` : ""}${r.paused_why ? `
${esc(r.paused_why)}
` : ""}${(r.runs || []).length ? `${r.runs.map((x) => `
${esc(x.line)}
${(x.sends || []).map((l) => `
· ${esc(l)}
`).join("")}`).join("")}` : ""}
${esc(r.prompt)}
`; sheet("", !isOwner() ? [] : [ {icon: "play", label: "立即執行", on: () => app("run_routine_now", {id: r.id}, b.id, "已開始執行")}, - {icon: r.paused ? "play" : "pause", label: r.paused ? "繼續" : "暫停", on: async () => { if (await app("update_routine", {id: r.id, paused: !r.paused}, b.id, r.paused ? "已繼續" : "已暫停")) refreshAfter(b); }}, - {icon: "pen", label: "編輯", on: () => routineForm(b, r)}, + {icon: r.paused ? "play" : "pause", label: r.paused ? "繼續" : "暫停", on: async () => { const x = await routineNow(b, r); if (x && await app("update_routine", {id: x.id, paused: !x.paused}, b.id, x.paused ? "已繼續" : "已暫停")) refreshAfter(b); }}, + {icon: "pen", label: "編輯", on: async () => { const x = await routineNow(b, r); if (x) routineForm(b, x); }}, {icon: "trash", label: "刪除", danger: true, on: async () => { if (await confirmSheet(`刪除「${r.title}」?`, "這會停止它之後的執行,無法復原。", "刪除") && await app("delete_routine", {id: r.id}, b.id, "已刪除例行任務")) refreshAfter(b); }}, ], html); } +// The routine as the brain has it now (editing an old copy would save its old words and times). +async function routineNow(b, r) { + const d = await freshDetail(b.id); + if (!d) { toast("連上後才能改"); return null; } + const x = (d.routines || []).find((y) => y.id === r.id); + if (!x) toast("這個例行任務已經不在了"); + return x || null; +} function refreshAfter(b) { delete S.detail[b.id]; setTimeout(() => { const t = cur(); if (t.v === "details") renderDetails(b.id, S.tab); else if (t.v === "list") renderList(t.arg); }, 300); } const FREQ = [["daily", "每天"], ["workdays", "每個工作日"], ["weekly", "每週"], ["hourly", "每小時"], ["monthly", "每月"], ["once", "僅一次"]]; const DAYS = [["MO", "一"], ["TU", "二"], ["WE", "三"], ["TH", "四"], ["FR", "五"], ["SA", "六"], ["SU", "日"]]; @@ -2513,15 +2782,21 @@ function routineForm(b, r) { } // ---------- Bot 設定 (the desktop's bot editor) ---------- +// Changes that send a whole list go one after the other: the next is built on the list the brain +// has after the one before (two quick ticks used to send the second on a list without the first). +let changing = Promise.resolve(); +function oneAtATime(f) { changing = changing.then(f, f).catch(() => {}); return changing; } async function renderBotset(id) { const b = bot(id); if (!b) { back(); return; } $("botset-title").textContent = "設定 " + b.name; if (!S.settings) loadSettings().then(() => { if (cur().v === "botset") renderBotset(id); }); - const d = S.detail[id] || await loadDetail(id) || {}; + let d = S.detail[id] || await loadDetail(id) || {}; if (cur().v !== "botset") return; const st = S.settings || {}; const CTX = [[32000, "32K"], [64000, "64K"], [128000, "128K"], [200000, "200K"], [1000000, "1M"]]; - let h = `
${face(b, "lg")}
${esc(b.name)}
`; + // Shown from a copy kept from before: read anew first, then it can be changed. + const held = !isNew(id); + let h = `
${face(b, "lg")}
${esc(b.name)}
${held ? `
顯示的是上次的設定,讀到最新的才能改
` : ""}
`; h += group("基本", item({k: "名稱", r: b.name, tap: 1, data: 'data-e="name"'}) + item({k: "描述", v: d.description || "還沒有寫", tap: 1, data: 'data-e="desc"'}) + item({k: "指示", v: d.instructions ? d.instructions.slice(0, 160) + (d.instructions.length > 160 ? "…" : "") : "還沒有寫", tap: 1, data: 'data-e="instr"'})); if (isOwner()) { h += group("個人檔案", item({k: "擅長", v: d.strengths || "還沒有寫(同事會看到,知道什麼事找它)", tap: 1, data: 'data-e="strengths"'}) + item({k: "不找它做的事", v: d.not_for || "還沒有寫", tap: 1, data: 'data-e="not_for"'})); @@ -2538,16 +2813,23 @@ async function renderBotset(id) { h += group("", item({icon: "refresh", k: "重新啟動這個 Bot", v: "卡住時用:停止它正在做的事和背景指令", tap: 1, data: 'data-e="restart"', chev: false}) + item({icon: "trash", k: "清除聊天記錄", tap: 1, data: 'data-e="clear"', danger: true, chev: false}) + (isOwner() ? item({icon: "trash", k: "刪除 Bot", tap: 1, data: 'data-e="delete"', danger: true, chev: false}) : "")); $("botset").innerHTML = h + `
`; const el = $("botset"); + el.classList.toggle("held", held); + if (held) loadDetail(id).then(() => { if (isNew(id) && cur().v === "botset" && cur().arg.bot === id) renderBotset(id); }); const refresh = () => { delete S.detail[id]; setTimeout(() => cur().v === "botset" && renderBotset(id), 300); }; el.querySelectorAll("[data-shape]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "shape", value: x.dataset.shape}, false)) refresh(); }); el.querySelectorAll("[data-color]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "color", value: x.dataset.color}, false)) refresh(); }); el.querySelectorAll("[data-rule]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "allow_remove", value: x.dataset.rule}, "已移除")) refresh(); }); - el.querySelectorAll("[data-tick]").forEach((x) => x.onchange = async () => { + el.querySelectorAll("[data-tick]").forEach((x) => x.onchange = () => oneAtATime(async () => { // (The whole ticked list goes: the app keeps "all of them" as no list at all.) - const k = x.dataset.tick; - const on = [...el.querySelectorAll(`[data-tick="${k}"]`)].filter((y) => y.checked).map((y) => y.dataset.key); - if (!await act("bot", {bot: id, key: k, value: on}, false)) x.checked = !x.checked; else delete S.detail[id]; - }); + // (Built on the brain's list as it is now, with only this tick changed: never a list read + // earlier, which would turn back on what was turned off since.) + const k = x.dataset.tick, want = x.checked; + const now = await freshDetail(id); + if (!now) { x.checked = !want; toast("連上後才能改"); return; } + const on = (now[k] || []).filter((y) => (y.key === x.dataset.key ? want : y.on)).map((y) => y.key); + if (!await act("bot", {bot: id, key: k, value: on}, false)) x.checked = !want; + else { delete S.detail[id]; refresh(); } + })); el.querySelectorAll("[data-sw]").forEach((x) => x.onchange = async () => { const k = x.dataset.sw; if (k === "primary") { if (await act("bot", {bot: id, key: "primary", value: true}, "已設為主要 Bot")) refresh(); return; } @@ -2556,6 +2838,8 @@ async function renderBotset(id) { el.querySelectorAll("[data-e]").forEach((x) => x.onclick = async () => { const k = x.dataset.e; if (k === "name") { const n = await ask("名稱", b.name); if (n && n !== b.name && await app("update_bot", {name: n}, id, "已改名")) refresh(); } + // (Words to edit start from what the brain has now: `d` becomes that, or stays as it was.) + else if (["desc", "strengths", "not_for"].includes(k) && !await freshDetail(id).then((v) => v && (d = v))) toast("連上後才能改"); else if (k === "desc") { const n = await ask("描述(一句話說它做什麼)", d.description || ""); if (n != null && await app("update_bot", {description: n}, id, "已更新描述")) refresh(); } else if (k === "instr") editInstructions(b, d); else if (k === "strengths") { const n = await ask("擅長(什麼事找它)", d.strengths || "", "例如:查資料、寫摘要、追 Threads 上的討論", true); if (n != null && n !== (d.strengths || "") && await act("bot", {bot: id, key: "strengths", value: n}, "已更新")) refresh(); } @@ -2576,7 +2860,11 @@ async function renderBotset(id) { async function loadSettings() { if (!owner()) return null; S.settingsOld = false; - try { S.settings = await api(base() + "api/settings"); } catch (e) { toast(e.message); } + const host = S.host; + try { + const st = await api(base() + "api/settings"); + if (S.host === host && S.token) { S.settings = st; KEEP.put("settings:" + host, st); } + } catch (e) { S.settingsOld = true; toast(e.message); } return S.settings; } const SETTINGS_PAGES = ["computers", "settings", "general", "models", "perms", "integrations", "vault", "account", "updates"]; @@ -2604,16 +2892,24 @@ async function renderList(arg) { if (kind === "routines") return listRoutines(el); if (kind === "pages") return listPages(el); if (SETTINGS_PAGES.includes(kind)) { - if (!S.settings || S.settingsOld) { if (!S.settings) el.innerHTML = `
載入中…
`; await loadSettings(); } + // (Drawn from what this phone has at once; read again behind it when it may be old.) + if (!S.settings) { el.innerHTML = `
載入中…
`; await loadSettings(); } + else if (S.settingsOld) loadSettings().then(() => { if (cur().v === "list" && cur().arg.kind === kind) drawSettings(kind, true); }); if (cur().v !== "list" || cur().arg.kind !== kind) return; drawSettings(kind); // Things that change on their own (Bot 的電腦 updating, a channel connecting): look again. if (["computers", "integrations"].includes(kind)) listTimer = setInterval(async () => { await loadSettings(); if (cur().v === "list" && cur().arg.kind === kind) drawSettings(kind, true); }, 4000); } } -async function listRoutines(el) { - el.innerHTML = `
載入中…
`; - for (const b of S.bots) if (!S.detail[b.id]) await loadDetail(b.id); +async function listRoutines(el, again) { + // (Every bot's details asked at once, not one after the other; what this phone has is drawn first.) + const missing = again ? [] : S.bots.filter((b) => !isNew(b.id)); + if (missing.length) { + const here = () => cur().v === "list" && cur().arg.kind === "routines"; + const asked = Promise.all(missing.map((b) => loadDetail(b.id))); + if (S.bots.every((b) => !S.detail[b.id])) { el.innerHTML = `
載入中…
`; await asked; return here() && listRoutines(el, true); } + asked.then(() => here() && listRoutines(el, true)); + } if (cur().arg.kind !== "routines") return; let h = ""; for (const b of S.bots) { @@ -2629,10 +2925,10 @@ async function listRoutines(el) { else sheet("交給哪個 Bot?", S.bots.filter((b) => !b.members).map((b) => ({label: b.name, on: () => setTimeout(() => pick(b), 60)}))); }; } -async function listPages(el) { - el.innerHTML = `
載入中…
`; - let pages = S.pages; - try { pages = (await act("pages", {}, false) || {}).pages || pages; } catch (_) {} +async function listPages(el, more) { + // The newest ones the state already has, drawn now; all of them when the brain answers. + let pages = more || S.pages; + if (!more) act("pages", {}, false).then((v) => { if (v && v.pages && cur().v === "list" && cur().arg.kind === "pages") listPages(el, v.pages); }); if (cur().arg.kind !== "pages") return; el.innerHTML = pages.length ? group("", pages.map((p) => item({icon: "file-text", k: p.title, v: (p.bot ? p.bot + " · " : "") + (p.updated || ""), tap: 1, data: `data-page="${p.id}"`})).join("")) : `
還沒有頁面。請 Bot 研究一件事並「整理成一頁」,頁面會出現在這裡。
`; } @@ -2896,8 +3192,8 @@ function wireSettings(kind, st) { else if (k === "2fa") twoFaSheet(); else if (k === "devices") devicesSheet(); else if (k === "pair") pair(); - else if (k === "host") { S.host = ""; localStorage.removeItem("anybot.host"); S.version = 0; S.ssig = ""; S.entered = false; NAV.length = 0; show("gate"); kick(); pickHost(); } - else if (k === "out") { if (await confirmSheet("要登出這支手機嗎?", "", "登出")) signOut(); } + else if (k === "host") { toHost(""); S.entered = false; NAV.length = 0; show("gate"); kick(); pickHost(); } + else if (k === "out") { const n = OUT.filter((x) => !x.sentAt).length; if (await confirmSheet("要登出這支手機嗎?", n ? `還沒送出的 ${n} 則訊息會跟著清掉。` : "", "登出")) signOut(); } }); on("[data-bx]", "onclick", async (x) => { const k = x.dataset.bx, box = st.box || {}; @@ -3772,7 +4068,7 @@ openFromHash(); // 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; + if (picking || writing || rec || $("input").value.trim() || S.pending.length || S.answer || OUT.some((x) => !x.sentAt && !x.failed) || $("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(); } @@ -3808,12 +4104,13 @@ if (window.visualViewport) { visualViewport.addEventListener("resize", kb); visualViewport.addEventListener("scroll", kb); } -document.addEventListener("visibilitychange", () => { if (document.hidden) { swapWhenAway(); return; } setTimeout(() => { picking = false; }, 1000); if (S.msgsStale) renderMsgs(); kick(); if (S.view === "screen") startFrames(); }); +document.addEventListener("visibilitychange", () => { if (document.hidden) { keepNow(); 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(); +addEventListener("pagehide", keepNow); +// (Storage that doesn't answer — it happens — never holds the app at the door.) +Promise.race([restore().catch(() => {}), new Promise((ok) => setTimeout(ok, 800))]).then(() => { setOff(); hello(); flush(); }); diff --git a/src/remote.rs b/src/remote.rs index 539df75..b77c051 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -953,9 +953,10 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { } } -/// How long a phone's message id is remembered: its tries again on a bad network all fall -/// within this. -const DELIVERY_TTL: Duration = Duration::from_secs(600); +/// How long a phone's message id is remembered: its tries again all fall within this — a phone +/// keeps an unsent message until the line is back (hours on a plane), and the try that reached the +/// brain may be the one whose answer was lost. +const DELIVERY_TTL: Duration = Duration::from_secs(24 * 3600); /// False when this message (the phone's id for it, per bot) has already come: a try again after /// the answer to the first was lost on the way back. No id (an older page): always the first. @@ -966,8 +967,9 @@ fn first_delivery(bot: u64, id: &str) -> bool { } let mut seen = SEEN.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()); seen.retain(|_, at| at.elapsed() < DELIVERY_TTL); - // Full: the oldest makes room (it used to stop telling repeats apart without a word). - if seen.len() >= 4096 { + // Full: the oldest makes room (it used to stop telling repeats apart without a word). Room for + // a day of every phone's messages and every screen's actions. + if seen.len() >= 50_000 { if let Some(k) = seen.iter().min_by_key(|(_, at)| **at).map(|(k, _)| k.clone()) { seen.remove(&k); }