diff --git a/FEATURES.md b/FEATURES.md index 0cb1e8e..310290a 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -2185,6 +2185,9 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 建立、修改、刪除 Bot/例行任務/記憶/頁面/分區,以及設定、金鑰、訊息管道、MCP、登出別支手機、快照和重設電腦,只有擁有者能做(手機上也不會顯示這些按鈕)。 - 畫面更新:手機問「有沒有新東西」會等最多 20 秒,有變化就立刻回來,所以不用一直刷新。 - **單趟同步**:開著對話時,狀態檢查順帶把那個對話的訊息帶回來(手機附上簽名,沒變不重傳):Bot 串流輸出時每趟少一個請求,訊息和側欄狀態永遠同一刻。 +- **只傳有變的**:手機附上它手上那份狀態的指紋,大腦只回改了的部分(沒變的欄位不送、沒變的 Bot 只寫代號);對話也只送從不一樣的地方開始的訊息(最舊的滑出視窗、最後一則長大、多了新的,都不必整段重送)。大腦記得最近幾千份給過的指紋,慢的網路隔很多次更新再問也對得上;對不上就整份重送。舊版頁面不帶指紋,照舊拿整份。 +- **網路不穩**:每個請求有期限(等新東西 45 秒、其他 60 秒,上傳不限),連線無聲斷掉也會發現;連不上時頂端顯示「連線中斷,正在重新連線…」,重試間隔 1 秒起倍增到 15 秒,回到前景、網路恢復時立刻重連。傳出的訊息帶一個代號自動重送(約一分鐘內),大腦 10 分鐘內同一代號只收一次。打開頁面時連不上,照上次記得的登入方式(帳號或手機密碼)等它連上,不會誤顯示另一種登入。 +- **傳輸**:直接連線的連線留著給下一個請求(30 秒沒用才關,手機不用每次重做 TCP 和 TLS 握手)、文字回答用 gzip 壓縮、手機頁面帶版本標記(沒換版只回「沒有變」);帳號連線時,電腦回給手機的資料壓縮著上傳到帳號伺服器,在那裡打開、再由 Caddy 壓縮給手機。 ### 設定 › 手機與帳號 diff --git a/docs/feature-map/account.md b/docs/feature-map/account.md index 667c036..d24e015 100644 --- a/docs/feature-map/account.md +++ b/docs/feature-map/account.md @@ -4,7 +4,7 @@ ## 子功能 -- `account-login` AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、一個字的名字(同一個 Docker 網路),或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。登入、還原、配對和之後的每個請求都照這個查(長連線在連上、重連時查,連著時不中途重查)。不符合時,登入、還原、配對回到表單說原因;長連線和備用連線在「AnyBot 帳號」的狀態寫原因、之後自己再試(`--serve` 的 `ANYBOT_ACCOUNT` 寫進紀錄、每 30 秒再試)。 +- `account-login` AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、一個字的名字(同一個 Docker 網路),或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。登入、還原、配對和之後的每個請求都照這個查(長連線在連上、重連時查,連著時不中途重查)。帳號伺服器轉給手機的回答,電腦那段壓縮著上傳(家裡網路的上傳最慢),到帳號伺服器才打開。不符合時,登入、還原、配對回到表單說原因;長連線和備用連線在「AnyBot 帳號」的狀態寫原因、之後自己再試(`--serve` 的 `ANYBOT_ACCOUNT` 寫進紀錄、每 30 秒再試)。 - `account-backup` 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 Bot 換成帳號裡最新的備份。 - `account-brain` 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效,[computers](computers.md))。螢幕電腦上的大腦那一欄分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等。 - `account-computers` 帳號裡的電腦:同一個帳號的每台 AnyBot,在線或離線;那台打開「裝置連結」後,會出現在 Bot 可以用的電腦裡。 diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index c2de7f9..880b1d5 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -9,6 +9,7 @@ - `phone-look` 長相(和電腦版同一份設計規格:字級、間距、圓角都是同一組數字):Bot 的回答不放在泡泡裡,像文件一樣直接排在畫面上,用宋體(思源宋體,沒有就用系統的宋體)、16px、行距寬;裡面的表格只有橫向細線、數字欄靠右,提示框([!NOTE] 等)同一種淡底、只有圖示依種類上色,程式碼是淡底圓角塊。你自己的訊息(泡泡)和所有按鈕、清單、設定用黑體。手機沒有字型選項。 - `phone-colors` 顏色跟電腦版一樣:電腦上 設定 › 一般 › 外觀 的主題(淺色/深色/跟隨系統)、底色、強調色、對比,手機照著穿;手機自己的「外觀」可以選「跟著電腦」(預設)、「跟著手機」、「淺色」、「深色」。狀態列的顏色跟著畫面。舊版的電腦沒送顏色時,手機用內建的「紙」。 - `phone-claude` 像 Claude 的手機 App:上面一條簡單的標題列(Bot 名稱,第二行是它在做什麼或用哪個模型),輸入框是底部一張圓角卡片,回答下面只有時間和複製/重新產生/⋯;按鈕和點的地方至少 44px;清單每列的說明只有一行(太長以 … 結尾);顏色少,強調色只用在連結、選取和新訊息的點。 +- `phone-net` 網路不穩也能用:連不上時上面出現「連線中斷,正在重新連線…」,自己重試(間隔越來越長,最長 15 秒),回到前景或網路恢復時立刻重連,不用重新整理;一個請求太久沒回音(連線斷了不會自己報錯)就放棄重來。傳出去的訊息沒送到會自己重送,同一則只會送到一次;Bot 工作中插的話重送時寫「網路不穩,重新傳送中…」,真的送不出去才標「沒送出,點一下拿回來重送」(Bot 沒在工作時,字放回輸入框)。只傳有變的部分:狀態只送改了的、打開的聊天只送從不一樣的地方開始的訊息;直接連線的連線留著給下一個請求用、文字壓縮,頁面沒換版就不重新下載。打開時連不上,照上次的方式(帳號或手機密碼)等它連上。 - `phone-app` 像 App 一樣:加入主畫面後全螢幕、沒有網址列(瀏海、動態島、底部手勢條、橫放都避開);首頁會提示「把 AnyBot 裝成 App」(Android 直接安裝,iPhone 教你加入主畫面,可以關掉);換畫面會左右滑動;iPhone 主畫面 App 從左邊緣往右滑回上一頁。 ## 使用者怎麼到 @@ -32,6 +33,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`):拿著同一份狀態的指紋再問一次。指令:`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 清單和主機名稱沒有重送。 - **主畫面 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`。 @@ -40,4 +43,5 @@ - 手機看不到保險庫,也看不到模型金鑰(只能寫入新的)。 - 手機上的卡沒用上時,要看現在在等什麼再按;開了很久的頁面先重新整理。用帳號登入的手機,頁面是帳號伺服器給的:伺服器還沒更新時,手機上的卡都答不了,要在電腦上答。 - 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。 +- 自動重送只認同一則(手機給每則訊息一個代號,大腦記 10 分鐘):網路斷超過大約一分鐘,那則會標「沒送出」,要自己再送。允許卡片的按鈕不自動重送(卡片可能已經換了)。 - (驗證)無頭 Chrome 不是 iPhone:通知、主畫面的全螢幕和手勢都不會出現;卡片和選單用 `wait` 等它滑進來再按。 diff --git a/mobile/index.html b/mobile/index.html index 253cc60..0fd2afc 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -458,6 +458,8 @@ textarea.field{min-height:96px;line-height:1.5} .seltext .quote{display:block;-webkit-line-clamp:none;overflow:visible} .toast{position:fixed;left:50%;top:calc(var(--safe-t) + 60px);transform:translate(-50%,-12px);background:var(--primary);color:var(--on-primary);padding:9px 16px;border-radius:999px;font-size:var(--fs-ui);opacity:0;pointer-events:none;transition:.2s;z-index:40;max-width:86vw;text-align:center} .toast.on{opacity:1;transform:translate(-50%,0)} +.net{position:fixed;left:50%;top:calc(var(--safe-t) + 64px);transform:translate(-50%,-12px);background:var(--elev);color:var(--text2);border:1px solid var(--line);box-shadow:0 2px 10px #0000001a;padding:5px 12px;border-radius:999px;font-size:var(--fs-small);opacity:0;pointer-events:none;transition:.2s;z-index:39;white-space:nowrap} +.net.on{opacity:1;transform:translate(-50%,0)} /* ---- sign in ---- */ .login{max-width:360px;margin:auto;padding:24px;display:flex;flex-direction:column;gap:10px;width:100%} @@ -706,6 +708,7 @@ button,.row,.ib,.island,.opt,.chip,.tab,label.sw,[role="button"]{-webkit-user-se
+
連線中斷,正在重新連線…
@@ -791,7 +794,8 @@ const LUCIDE = { function ic(name, size = 18) { return `${LUCIDE[name] || ""}`; } const $ = (id) => document.getElementById(id); function esc(s) { return String(s ?? "").replace(/[&<>"']/g, (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); } -function toast(t) { const e = $("toast"); e.textContent = t; e.classList.add("on"); clearTimeout(toast.t); toast.t = setTimeout(() => e.classList.remove("on"), 2600); } +// (No network is told once, by the line at the top — not again by every request that failed.) +function toast(t) { if (t === OFFLINE_MSG) return netDown(true); const e = $("toast"); e.textContent = t; e.classList.add("on"); clearTimeout(toast.t); toast.t = setTimeout(() => e.classList.remove("on"), 2600); } const nap = (ms) => new Promise((r) => setTimeout(r, ms)); // Times as the desktop's sidebar shows them: 剛剛 / 5 分鐘 / 3 小時 / 昨天 / 4 天 / 11/5. function ago(ms) { @@ -878,19 +882,62 @@ const isOwner = () => S.role === "owner"; const bot = (id) => S.bots.find((b) => b.id === id); function base() { return S.relay ? "h/" + encodeURIComponent(S.host) + "/" : ""; } +// A request that hears nothing back in this long is given up: a connection that died without +// saying so (Wi-Fi to cellular, a lift, back from the background) never fails by itself. +const WAIT_MS = 60000; +// The network, not the brain, said no: worth trying again (502–504: the account server can't +// reach the computer right now). +const OFFLINE_MSG = "連不上,網路好像斷了"; +function offline() { const e = new Error(OFFLINE_MSG); e.transient = true; return e; } async function api(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.) + const ms = opts.timeout !== undefined ? opts.timeout : opts.body && opts.json === undefined ? 0 : WAIT_MS; if (opts.json !== undefined) { headers["Content-Type"] = "application/json"; opts.body = JSON.stringify(opts.json); } - const r = await fetch(path, {method: opts.method || (opts.body ? "POST" : "GET"), headers, body: opts.body}); + const ctl = new AbortController(); + 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; + 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(); } + clearTimeout(timer); const signingIn = /(^|\/)(login|signup)$/.test(path); if (r.status === 401 && !signingIn) { signOut(true); throw new Error("請重新登入"); } if (opts.raw) return r; - const t = await r.text(); let v = {}; try { v = t ? JSON.parse(t) : {}; } catch (_) {} - if (!r.ok) throw new Error(v.error || ("HTTP " + r.status)); + if (!r.ok) { const e = new Error(v.error || ("HTTP " + r.status)); e.transient = [408, 502, 503, 504].includes(r.status); throw e; } return v; } +// Waits that the network coming back (or the app coming to the front) cuts short. +const resting = new Set(); +function rest(ms) { return new Promise((done) => { const end = () => { clearTimeout(t); resting.delete(end); done(); }; const t = setTimeout(end, ms); resting.add(end); }); } +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) { + clearTimeout(netTimer); + if (!down) { $("net").classList.remove("on"); return; } + netTimer = setTimeout(() => $("net").classList.add("on"), 1500); +} +const mkId = () => Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(16).padStart(2, "0")).join(""); +// Words to a bot that survive a bad network: the same id on every try, so the brain takes them once +// even when an answer was lost on the way back. +async function deliver(path, body, retrying) { + body.id = body.id || mkId(); + for (let n = 0; ; n++) { + try { const v = await api(path, {json: body, timeout: 20000}); netDown(false); return v; } + catch (e) { + if (!e.transient || !S.token || n >= 7) throw e; + netDown(true); if (retrying) retrying(); + await rest(backoff(n, 10000)); + } + } +} // One of the desktop's actions (api/act/), with its answer as a toast. async function act(what, body, ok) { try { @@ -1013,8 +1060,16 @@ function draw(v, arg) { const cur = () => NAV[NAV.length - 1] || {v: "home", arg: {}}; // ---------- sign in ---------- -async function hello() { - try { const r = await fetch("api/hello"); const v = await r.json(); S.relay = v.app === "anybot-relay"; } catch (_) { S.relay = false; } +async function hello(tries = 0) { + // Opened on a bad network: the way in it had last time (the account's or the phone password's), + // not the phone password's because nothing answered. + const known = localStorage.getItem("anybot.relay"); + try { const v = await api("api/hello", {timeout: 12000}); S.relay = v.app === "anybot-relay"; localStorage.setItem("anybot.relay", S.relay ? "1" : "0"); netDown(false); } + catch (e) { + if (!e.transient) S.relay = false; + else if (known !== null) { S.relay = known === "1"; netDown(true); } + else { netDown(true); await rest(backoff(tries, 15000)); return hello(tries + 1); } + } $("f-user").style.display = S.relay ? "" : "none"; $("b-mode").style.display = S.relay ? "" : "none"; $("login-desc").textContent = S.relay ? "用你的 AnyBot 帳號登入。在哪裡都能用,電腦不用開任何連接埠。" : "輸入這台 AnyBot 的手機密碼(在 AnyBot 設定 › 手機與帳號 設定)。"; @@ -1064,7 +1119,7 @@ let hostRetry = null; async function pickHost() { clearTimeout(hostRetry); let me; - try { me = await api("relay/me"); } catch (e) { toast(e.message); if (S.token) hostRetry = setTimeout(pickHost, 3000); return; } + 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 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. @@ -1105,21 +1160,61 @@ async function start() { } else { const t = cur(); draw(t.v, t.arg); } if (S.polling) return; S.polling = true; + let fails = 0; while (S.token) { + pollCtl = new AbortController(); try { // 單趟同步: when a chat is open, the state poll carries its messages too — sent only - // when their signature changed (api/state?bot=…&chat_sig=…). - const open = S.view === "chat" && S.open ? "&bot=" + S.open + "&chat_sig=" + encodeURIComponent(S.chatSig) : ""; - const v = await api(base() + "api/state?since=" + S.version + "&tz=" + encodeURIComponent(TZ) + open); + // 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.view === "chat" && S.open ? "&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}); + fails = 0; netDown(false); + 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.version = v.version; apply(v); } } 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 目前沒有連線"); - await nap(2500); + await rest(backoff(fails - 1, 15000)); } } S.polling = false; } +// The brain holds a poll up to 20 s (the account server 35 s): past this the connection is gone. +const POLL_MS = 45000; +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; + if (S.polling && pollCtl) pollCtl.abort(); + wake(); +} +// What changed, over the state this page holds: keys left out are as they were, and a bot that +// is only {id, same} too. +function mergeState(prev, v) { + const m = Object.assign({}, prev, v); + delete m.base; + m.chat = v.chat; + if (v.bots) { + const had = new Map((prev.bots || []).map((b) => [b.id, b])); + m.bots = v.bots.map((b) => (b.same ? had.get(b.id) : b)); + if (m.bots.some((b) => !b)) return null; + } + return m; +} function apply(v) { S.bots = v.bots || []; S.approvals = v.approvals || []; S.hostName = v.host || ""; S.mac = !!v.mac; // An approval answered from a notification banner, and a home-screen shortcut (主要 Bot, 未讀). @@ -1145,6 +1240,9 @@ function apply(v) { const c = v.chat; // (A poll that left before the person switched chats carries the old chat: ignore it.) if (c && c.bot === S.open && c.unchanged) { /* the chat did not change — nothing to draw */ } + // Only where it differs from what this page holds: drop the first few (the oldest left the + // window), keep the next `from`, then the new ones. Told against another list: all of it again. + else if (c && c.bot === S.open && c.messages && c.from !== undefined) { if (c.base === S.chatSig) applyChat(S.msgs.slice(c.drop || 0).slice(0, c.from).concat(c.messages), c.sig); else loadChat(); } else if (c && c.bot === S.open && c.messages) applyChat(c.messages, c.sig); else loadChat(); } @@ -1517,7 +1615,7 @@ 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 += `
還沒有回覆
`; + if (!busy && lastMsg && lastMsg.role === "user" && !lastMsg.wake && owner()) h += S.resending ? `
網路不穩,重新傳送中…
` : `
還沒有回覆
`; if (!S.msgs.length) { h = `
${face(b, "lg")}
嗨,我是${esc(b.name || "Bot")}
${esc(b.description || "想做什麼?點一個開始,或直接打字。")}
${SUGGEST.map((x, k) => ``).join("")}
`; } @@ -1525,7 +1623,7 @@ function renderMsgs() { 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 ? "沒送出,點一下拿回來重送" : Date.now() - x.at < 1200 ? "傳送中…" : "已排入,它下一步會看到"}
`; + h += `
${esc(x.text)}
${x.failed ? "沒送出,點一下拿回來重送" : x.retrying ? "網路不穩,重新傳送中…" : Date.now() - x.at < 1200 ? "傳送中…" : "已排入,它下一步會看到"}
`; }); $("msgs").innerHTML = h; renderSendBtn(); @@ -1894,7 +1992,13 @@ async function send() { 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; - try { await api(base() + `api/bots/${S.open}/send`, {json: body}); if (quiet) loadChat(); } catch (e) { toast(e.message); if (sent) { sent.failed = true; renderMsgs(); } else input.value = text; } + // 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(); } } } $("b-plus").onclick = () => sheet("", [ {icon: "image", label: "照片與檔案", on: () => $("file").click()}, @@ -3575,7 +3679,10 @@ if (window.visualViewport) { visualViewport.addEventListener("resize", kb); visualViewport.addEventListener("scroll", kb); } -document.addEventListener("visibilitychange", () => { if (!document.hidden && S.view === "screen") startFrames(); }); +document.addEventListener("visibilitychange", () => { if (document.hidden) return; kick(); if (S.view === "screen") startFrames(); }); +addEventListener("online", kick); +addEventListener("offline", () => { if (S.token) netDown(true); }); +addEventListener("pageshow", (e) => { if (e.persisted) kick(); }); hello(); diff --git a/relay/Cargo.lock b/relay/Cargo.lock index a553f2d..a651a08 100644 --- a/relay/Cargo.lock +++ b/relay/Cargo.lock @@ -24,6 +24,7 @@ dependencies = [ "argon2", "base64 0.22.1", "chrono", + "flate2", "ring", "serde", "serde_json", diff --git a/relay/Cargo.toml b/relay/Cargo.toml index 80bec51..6598f01 100644 --- a/relay/Cargo.toml +++ b/relay/Cargo.toml @@ -12,6 +12,7 @@ serde_json = "1" ring = "0.17" argon2 = "0.5" base64 = "0.22" +flate2 = "1" chrono = "0.4" ureq = "3" tungstenite = { version = "0.30", default-features = false, features = ["handshake"] } diff --git a/relay/src/main.rs b/relay/src/main.rs index c31a4c2..e2def12 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -245,6 +245,20 @@ impl Answer { } } +fn page_tag() -> &'static str { + static TAG: std::sync::OnceLock = std::sync::OnceLock::new(); + TAG.get_or_init(|| httpd::etag_of(PAGE.as_bytes())) +} + +/// A compressed answer opened (None: broken, or larger than any answer may be). +fn unzip(b: &[u8]) -> Option> { + use std::io::Read; + let max = (httpd::MAX_BODY * 2) as u64; + let mut out = vec![]; + flate2::read::DeflateDecoder::new(b).take(max + 1).read_to_end(&mut out).ok()?; + (out.len() as u64 <= max).then_some(out) +} + /// The content type a forwarded answer may carry: data (JSON, text), pictures that hold no /// script, sound, video, PDF. HTML, SVG, XML and everything unknown become a plain download. fn safe_ctype(ctype: &str) -> &str { @@ -642,8 +656,17 @@ impl Relay { } /// Hand a request to a host and wait for its answer. + /// (Its answer comes up compressed — a home line's upload is the slow part — and is opened + /// here: Caddy gzips it on to the phone.) fn forward(&self, host_id: &str, method: &str, path: &str, query: &HashMap, body: &[u8], who: (&str, &str)) -> Resp { - self.forward_raw(host_id, method, path, query, body, false, who, false, "").into_resp() + let mut a = self.forward_raw(host_id, method, path, query, body, false, who, true, ""); + if a.z { + a = match unzip(&a.body) { + Some(body) => Answer { body, z: false, ..a }, + None => Answer::error(502, "那台 AnyBot 傳來的資料壞掉了"), + }; + } + a.into_resp() } /// `z`: the body is compressed; `z_ok`: the asker reads a compressed answer. @@ -918,9 +941,13 @@ impl Relay { let parts: Vec = req.parts().iter().map(|s| s.to_string()).collect(); let p: Vec<&str> = parts.iter().map(|s| s.as_str()).collect(); match (req.method.as_str(), p.as_slice()) { + // (Asked again each time it opens; only "not modified" when the browser holds this build's.) + ("GET", []) | ("GET", ["index.html"]) if httpd::holds(&req, page_tag()) => Resp::empty(304).with_header("ETag", page_tag()).with_header("Cache-Control", "no-cache"), ("GET", []) | ("GET", ["index.html"]) => Resp::bytes("text/html; charset=utf-8", PAGE.as_bytes().to_vec()) .with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; frame-src 'self' blob:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'none'", httpd::script_src(PAGE))) - .with_header("Strict-Transport-Security", "max-age=31536000"), + .with_header("Strict-Transport-Security", "max-age=31536000") + .with_header("ETag", page_tag()) + .with_header("Cache-Control", "no-cache"), ("GET", ["screen"]) => 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' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE))) .with_header("Strict-Transport-Security", "max-age=31536000"), @@ -2174,7 +2201,17 @@ mod tests { let (st, body) = get(port, "/relay/host/next", &ht); if st == 200 { let job: Value = serde_json::from_slice(&body).unwrap(); - let answer = json!({"status": 200, "ctype": "application/json", "body": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, json!({"path": job["path"], "q": job["query"]}).to_string()), "headers": [["X-Size", "10x20"], ["Set-Cookie", "no"]]}); + let words = json!({"path": job["path"], "q": job["query"], "z_ok": job["z_ok"], "pad": "字".repeat(3000)}).to_string(); + // (An AnyBot compresses its answer when the relay says it reads that.) + let (bytes, z) = if job["path"] == "/api/big" && job["z_ok"] == true { + use std::io::Write; + let mut e = flate2::write::DeflateEncoder::new(vec![], flate2::Compression::fast()); + e.write_all(words.as_bytes()).unwrap(); + (e.finish().unwrap(), true) + } else { + (words.into_bytes(), false) + }; + let answer = json!({"status": 200, "ctype": "application/json", "z": z, "body": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes), "headers": [["X-Size", "10x20"], ["Set-Cookie", "no"]]}); post(port, &format!("/relay/host/reply/{}", job["id"].as_str().unwrap()), &ht, answer); } }); @@ -2187,6 +2224,12 @@ mod tests { let v: Value = serde_json::from_str(&resp.body_mut().read_to_string().unwrap()).unwrap(); assert_eq!(v["path"], "/api/state"); assert_eq!(v["q"]["since"], "3"); + // The phone's answers come up compressed (the home line's upload is the slow part) and + // reach the phone opened. + let (st, big) = get(port, &format!("/h/{host_id}/api/big"), &session); + assert_eq!(st, 200); + let big: Value = serde_json::from_slice(&big).unwrap(); + assert_eq!((big["path"].as_str(), big["z_ok"].as_bool()), (Some("/api/big"), Some(true))); // The device endpoint is only for the account's other AnyBots, never the phone. assert_eq!(get(port, &format!("/h/{host_id}/api/device/run"), &session).0, 404); diff --git a/src/httpd.rs b/src/httpd.rs index d98e284..4cde336 100644 --- a/src/httpd.rs +++ b/src/httpd.rs @@ -1,7 +1,8 @@ // (Shared with relay/, which uses the parts the app doesn't.) #![allow(dead_code)] // A very small HTTP/1.1 server (one thread per connection), shared by the phone page on this -// computer and by the relay (the thin backend). No keep-alive: every answer closes the connection. +// computer and by the relay (the thin backend). The relay's answers close the connection; the +// phone page's keep it a while (`serve_kept`), so a phone doesn't open TCP and TLS anew each time. use std::collections::HashMap; use std::io::{Read, Write}; @@ -189,6 +190,7 @@ fn reason(status: u16) -> &'static str { match status { 200 => "OK", 204 => "No Content", + 304 => "Not Modified", 400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", @@ -408,13 +410,26 @@ fn clean_header_name(s: &str) -> String { } pub fn write_response(c: &mut TcpStream, r: &Resp) { + write_kept(c, r, false); +} + +/// How long a kept connection waits for its next request. +const KEEP_IDLE: Duration = Duration::from_secs(30); + +/// Write the answer, saying whether the connection stays open for another request (`keep`). +/// False when it couldn't be written whole (the connection is shut then). +fn write_kept(c: &mut TcpStream, r: &Resp, keep: bool) -> bool { let ctype = clean_header_val(&r.ctype); + // (Told a little less than KEEP_IDLE, so a browser doesn't send on a connection being closed.) + let connection = if keep { format!("keep-alive\r\nKeep-Alive: timeout={}", KEEP_IDLE.as_secs() - 5) } else { "close".to_string() }; + let own_cache = r.headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("cache-control")); let mut head = format!( - "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\n", + "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: {connection}\r\n{}X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\n", r.status, reason(r.status), if ctype.is_empty() { "application/octet-stream" } else { &ctype }, - r.body.len() + r.body.len(), + if own_cache { "" } else { "Cache-Control: no-store\r\n" }, ); for (k, v) in &r.headers { let k = clean_header_name(k); @@ -441,12 +456,43 @@ pub fn write_response(c: &mut TcpStream, r: &Resp) { true }; if send(head.as_bytes()) && send(&r.body) { - let _ = c.flush(); + c.flush().is_ok() } else { let _ = c.shutdown(std::net::Shutdown::Both); + false } } +/// A kept connection: true once the next request starts coming, false when it stays quiet past +/// KEEP_IDLE, ends, or the server is told to stop (`alive`) meanwhile. +fn next_request_comes(c: &TcpStream, alive: &(dyn Fn() -> bool + Send + Sync)) -> bool { + let until = std::time::Instant::now() + KEEP_IDLE; + let _ = c.set_read_timeout(Some(Duration::from_secs(1))); + let mut b = [0u8; 1]; + while std::time::Instant::now() < until { + if !alive() { + return false; + } + match c.peek(&mut b) { + Ok(n) => return n > 0, + Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {} + Err(_) => return false, + } + } + false +} + +/// A quoted tag for a body that only changes with a new build (the phone page), for If-None-Match. +pub fn etag_of(body: &[u8]) -> String { + let d = ring::digest::digest(&ring::digest::SHA256, body); + format!("\"{}\"", hex_of(&d.as_ref()[..12])) +} + +/// The browser already holds the body tagged `etag`. +pub fn holds(req: &Req, etag: &str) -> bool { + req.header("if-none-match").split(',').any(|t| t.trim().trim_start_matches("W/") == etag) +} + pub type Handler = Arc Resp + Send + Sync>; /// Takes over a connection that asked to become a WebSocket (it answers the handshake itself). pub type Upgrade = Arc; @@ -473,6 +519,15 @@ pub fn serve(listener: TcpListener, handler: Handler, alive: Arc boo /// Like `serve`, and connections asking for a WebSocket go to `upgrade`. pub fn serve_upgrade(listener: TcpListener, handler: Handler, upgrade: Option, alive: Arc bool + Send + Sync>) { + serve_with(listener, handler, upgrade, alive, false) +} + +/// Like `serve_upgrade`, and a connection stays open for the next request (KEEP_IDLE). +pub fn serve_kept(listener: TcpListener, handler: Handler, upgrade: Option, alive: Arc bool + Send + Sync>) { + serve_with(listener, handler, upgrade, alive, true) +} + +fn serve_with(listener: TcpListener, handler: Handler, upgrade: Option, alive: Arc bool + Send + Sync>, keep: bool) { use std::sync::atomic::{AtomicUsize, Ordering}; struct Slot(Arc); impl Drop for Slot { @@ -529,32 +584,48 @@ pub fn serve_upgrade(listener: TcpListener, handler: Handler, upgrade: Option { - // A lasting connection leaves the requests' room for its own. - if socks.load(Ordering::SeqCst) >= MAX_SOCKETS { - write_response(&mut c, &Resp::error(503, "伺服器忙碌中,請稍後再試")); + let mut first = true; + loop { + if !first && !next_request_comes(&c, &*alive) { + return; + } + first = false; + match read_request(&mut c) { + Ok(req) if req.header("upgrade").eq_ignore_ascii_case("websocket") && up.is_some() => { + // A lasting connection leaves the requests' room for its own. + if socks.load(Ordering::SeqCst) >= MAX_SOCKETS { + write_response(&mut c, &Resp::error(503, "伺服器忙碌中,請稍後再試")); + return; + } + socks.fetch_add(1, Ordering::SeqCst); + let _sock = Slot(socks.clone()); + drop(slot); + if let Some(u) = up { + u(req, c) + } return; } - socks.fetch_add(1, Ordering::SeqCst); - let _sock = Slot(socks.clone()); - drop(slot); - if let Some(u) = up { - u(req, c) + Ok(req) if !matches!(req.method.as_str(), "GET" | "HEAD") && !same_origin(&req) => { + write_response(&mut c, &Resp::error(403, "forbidden origin")); + return; + } + Ok(req) => { + let again = keep && !req.header("connection").eq_ignore_ascii_case("close"); + let resp = h(req); + if !write_kept(&mut c, &resp, again) || !again { + return; + } + } + Err(code) => { + write_response(&mut c, &Resp::error(code, "bad request")); + return; } } - Ok(req) if !matches!(req.method.as_str(), "GET" | "HEAD") && !same_origin(&req) => { - write_response(&mut c, &Resp::error(403, "forbidden origin")); - } - Ok(req) => { - let resp = h(req); - write_response(&mut c, &resp); - } - Err(code) => write_response(&mut c, &Resp::error(code, "bad request")), } }) .is_err() @@ -938,6 +1009,56 @@ mod tests { assert_eq!(v["p"], "/a/b"); } + /// The phone page's server keeps a connection for the next request (no new TCP and TLS each + /// time); the relay's still closes it. An answer's own Cache-Control stands alone. + #[test] + fn a_kept_connection_carries_the_next_request() { + use std::io::{BufRead, BufReader, Write}; + let h: Handler = Arc::new(|r: Req| if r.path == "/c" { Resp::json(&serde_json::json!({})).with_header("Cache-Control", "no-cache") } else { Resp::json(&serde_json::json!({"p": r.path})) }); + let answer = |rd: &mut BufReader| -> (String, String) { + let mut head = String::new(); + loop { + let mut l = String::new(); + if rd.read_line(&mut l).unwrap() == 0 || l == "\r\n" { + break; + } + head.push_str(&l); + } + let n: usize = head.lines().find_map(|l| l.strip_prefix("Content-Length: ")).unwrap().trim().parse().unwrap(); + let mut body = vec![0u8; n]; + std::io::Read::read_exact(rd, &mut body).unwrap(); + (head, String::from_utf8(body).unwrap()) + }; + let l = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let h2 = h.clone(); + std::thread::spawn(move || serve_kept(l, h2, None, Arc::new(|| true))); + let mut c = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut rd = BufReader::new(c.try_clone().unwrap()); + c.write_all(b"GET /a HTTP/1.1\r\nHost: x\r\n\r\n").unwrap(); + let (head, body) = answer(&mut rd); + assert!(head.contains("Connection: keep-alive") && body.contains("/a"), "{head}"); + c.write_all(b"GET /c HTTP/1.1\r\nHost: x\r\n\r\n").unwrap(); + let (head, _) = answer(&mut rd); + assert_eq!(head.matches("Cache-Control").count(), 1, "{head}"); + assert!(head.contains("Cache-Control: no-cache"), "{head}"); + c.write_all(b"GET /b HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n").unwrap(); + let (head, body) = answer(&mut rd); + assert!(head.contains("Connection: close") && body.contains("/b"), "{head}"); + let mut rest = vec![]; + assert_eq!(std::io::Read::read_to_end(&mut rd, &mut rest).unwrap(), 0, "closed after it"); + + let l = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + std::thread::spawn(move || serve(l, h, Arc::new(|| true))); + let mut c = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut rd = BufReader::new(c.try_clone().unwrap()); + c.write_all(b"GET /a HTTP/1.1\r\nHost: x\r\n\r\n").unwrap(); + let (head, _) = answer(&mut rd); + assert!(head.contains("Connection: close") && head.contains("Cache-Control: no-store"), "{head}"); + assert_eq!(std::io::Read::read_to_end(&mut rd, &mut rest).unwrap(), 0, "the relay's closes"); + } + /// An upload cut off on the way is no request (it used to be answered as a whole one). #[test] fn half_a_body_is_not_a_request() { diff --git a/src/remote.rs b/src/remote.rs index fbbfbe3..2b346d2 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -15,6 +15,7 @@ use crate::httpd::{self, Req, Resp}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::HashMap; +use std::io::Write; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; @@ -256,7 +257,8 @@ pub struct View { } pub struct Hub { - view: Mutex, + /// (Shared, not copied, by every poll that wakes: it holds every bot's chat.) + view: Mutex>, changed: Condvar, cmds: Mutex>, repaint: Mutex>>, @@ -287,7 +289,7 @@ pub struct SyncReq { pub fn hub() -> &'static Hub { static H: OnceLock = OnceLock::new(); - H.get_or_init(|| Hub { view: Mutex::new(View::default()), changed: Condvar::new(), cmds: Mutex::new(vec![]), repaint: Mutex::new(None), settings: Mutex::new(Settings::default()), fails: Mutex::new(HashMap::new()), relay_status: Mutex::new(String::new()), sync: Mutex::new(vec![]), voice: Mutex::new(Default::default()) }) + H.get_or_init(|| Hub { view: Mutex::new(Arc::new(View::default())), changed: Condvar::new(), cmds: Mutex::new(vec![]), repaint: Mutex::new(None), settings: Mutex::new(Settings::default()), fails: Mutex::new(HashMap::new()), relay_status: Mutex::new(String::new()), sync: Mutex::new(vec![]), voice: Mutex::new(Default::default()) }) } static VERSION: AtomicU64 = AtomicU64::new(1); @@ -295,7 +297,7 @@ static VERSION: AtomicU64 = AtomicU64::new(1); impl Hub { pub fn publish(&self, mut v: View) { v.version = VERSION.fetch_add(1, Ordering::SeqCst) + 1; - *self.view.lock().unwrap() = v; + *self.view.lock().unwrap() = Arc::new(v); self.changed.notify_all(); } pub fn take_sync(&self) -> Vec { @@ -353,7 +355,7 @@ impl Hub { *self.relay_status.lock().unwrap() = s.to_string(); } /// The view once it is newer than `since` (or after the wait). - fn wait_newer(&self, since: u64, secs: u64) -> View { + fn wait_newer(&self, since: u64, secs: u64) -> Arc { let g = self.view.lock().unwrap(); let (g, _) = self.changed.wait_timeout_while(g, Duration::from_secs(secs), |v| v.version <= since).unwrap(); g.clone() @@ -501,7 +503,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { let parts = req.parts(); let path: Vec<&str> = parts.to_vec(); match (req.method.as_str(), path.as_slice()) { - ("GET", []) | ("GET", ["index.html"]) => return page(), + ("GET", []) | ("GET", ["index.html"]) => return page(&req), ("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()), @@ -584,7 +586,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { } else { v.bots.clone() }; - let mut out = json!({ + let out = json!({ "version": v.version, "host": v.host, "person": v.person, "accent": v.accent, "pin_order": v.pin_order, "newer": v.newer, "bots": bots, "approvals": if role == "member" { vec![] } else { v.approvals.clone() }, @@ -600,18 +602,16 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { // 語音: the mic shows only when this brain can hear (and read aloud). "voice": {"listen": hub().voice().listen.is_some(), "speak": hub().voice().speak.is_some()}, }); + // Only what changed since the state the page holds (`&ssig=…`; an older page sends + // none and gets all of it). + let mut out = state_for(out, req.query.get("ssig").map(String::as_str).unwrap_or("")); // Single-trip active chat sync: when the browser names its open bot (`&bot=ID`), - // include that chat's messages whenever their signature changed (`&chat_sig=…`). + // include that chat's messages whenever their signature changed (`&chat_sig=…`), only + // from where they differ for a page that takes that (`&chat_delta=1`). if let Some(open_id) = req.query.get("bot").and_then(|b| b.parse::().ok()).filter(|&id| id > 0) { if let Some(raw) = v.messages.get(&open_id) { - let msgs = messages_for_role(raw, &role); - let sig = chat_sig(&msgs); - let client_sig = req.query.get("chat_sig").map(String::as_str).unwrap_or(""); - out["chat"] = if client_sig == sig { - json!({"bot": open_id, "sig": sig, "unchanged": true}) - } else { - json!({"bot": open_id, "sig": sig, "messages": msgs}) - }; + let held = req.query.get("chat_sig").map(String::as_str).unwrap_or(""); + out["chat"] = chat_for(open_id, messages_for_role(raw, &role), held, req.query.get("chat_delta").is_some_and(|d| d == "1")); } } Resp::json(&out) @@ -647,9 +647,9 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { let v = hub().view.lock().unwrap(); match v.messages.get(&id) { Some(m) => { - let msgs = messages_for_role(m, &role); - let sig = chat_sig(&msgs); - Resp::json(&json!({"version": v.version, "sig": sig, "messages": msgs})) + let mut out = chat_for(id, messages_for_role(m, &role), "", false); + out["version"] = json!(v.version); + Resp::json(&out) } None => Resp::error(404, "找不到這個 Bot"), } @@ -771,6 +771,9 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { let is_admin_goal = role == "admin" && (crate::goal::command(&text).is_some() || crate::plan::command(&text).is_some()); let text = if role != "owner" && !who.is_empty() && !is_admin_goal { format!("【{who}】{text}") } else { text }; let member = role == "member"; + if !first_delivery(bot, b["id"].as_str().unwrap_or("")) { + return Resp::json(&json!({"ok": true, "again": true})); + } Cmd::Send { bot, text, attachments, from: String::new(), memories: if role == "owner" { picks_of(&b) } else { Some(vec![]) }, member } } "stop" => Cmd::Stop { bot }, @@ -933,6 +936,25 @@ 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); + +/// 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. +fn first_delivery(bot: u64, id: &str) -> bool { + static SEEN: OnceLock>> = OnceLock::new(); + if id.is_empty() || id.len() > 64 { + return true; + } + let mut seen = SEEN.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()); + seen.retain(|_, at| at.elapsed() < DELIVERY_TTL); + if seen.len() >= 4096 { + return true; + } + seen.insert((bot, id.to_string()), Instant::now()).is_none() +} + /// The memories picked under a composer: `"memories": [...]` (even empty: the person chose none), /// or nothing (they didn't look). fn picks_of(b: &Value) -> Option> { @@ -1104,13 +1126,117 @@ fn messages_for_role(m: &[Value], role: &str) -> Value { out } -fn chat_sig(msgs: &Value) -> String { +/// A part of what the phone is told, as a short fingerprint (what a page holds is compared by these). +fn fp(v: &Value) -> u64 { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); - msgs.to_string().hash(&mut h); + v.to_string().hash(&mut h); + h.finish() +} + +fn sig_of(parts: &T) -> String { + use std::hash::Hasher; + let mut h = std::collections::hash_map::DefaultHasher::new(); + parts.hash(&mut h); format!("{:016x}", h.finish()) } +/// The last few thousand things told to pages, by the fingerprint each page was given: a page +/// polling on a slow line still finds what it holds here after many changes. +struct Told { + order: std::collections::VecDeque, + by_sig: HashMap, +} + +impl Told { + const KEEP: usize = 2048; + fn new() -> Told { + Told { order: Default::default(), by_sig: HashMap::new() } + } + fn get(&self, sig: &str) -> Option { + self.by_sig.get(sig).cloned() + } + fn keep(&mut self, sig: &str, v: T) { + if self.by_sig.contains_key(sig) { + return; + } + self.by_sig.insert(sig.to_string(), v); + self.order.push_back(sig.to_string()); + while self.order.len() > Self::KEEP { + if let Some(old) = self.order.pop_front() { + self.by_sig.remove(&old); + } + } + } +} + +/// A state's fingerprints: each key's, and each bot's by id. +type StateFp = Arc<(HashMap, HashMap)>; + +fn told_states() -> &'static Mutex> { + static T: OnceLock>> = OnceLock::new(); + T.get_or_init(|| Mutex::new(Told::new())) +} + +fn told_chats() -> &'static Mutex>>> { + static T: OnceLock>>>> = OnceLock::new(); + T.get_or_init(|| Mutex::new(Told::new())) +} + +/// The state for a page holding the one fingerprinted `held` (empty: none, or an older page): only +/// what changed since — a key left out is as it was, an unchanged bot is `{id, same}`, and `base` +/// says which state it builds on. The fingerprint of the whole (`ssig`) either way. +fn state_for(mut out: Value, held: &str) -> Value { + let Some(obj) = out.as_object() else { return out }; + let keys: HashMap = obj.iter().filter(|(k, _)| k.as_str() != "version").map(|(k, v)| (k.clone(), fp(v))).collect(); + let bots: HashMap = obj.get("bots").and_then(Value::as_array).into_iter().flatten().filter_map(|b| Some((b["id"].as_u64()?, fp(b)))).collect(); + let mut sorted: Vec<(&String, &u64)> = keys.iter().collect(); + sorted.sort(); + let ssig = sig_of(&sorted); + let prev = if held.is_empty() { None } else { told_states().lock().unwrap_or_else(|e| e.into_inner()).get(held) }; + if let Some(prev) = prev { + let (prev_keys, prev_bots) = &*prev; + let o = out.as_object_mut().expect("an object"); + o.retain(|k, _| k == "version" || prev_keys.get(k) != Some(&keys[k])); + if let Some(list) = o.get_mut("bots").and_then(Value::as_array_mut) { + for b in list.iter_mut() { + if let Some(id) = b["id"].as_u64() { + if prev_bots.get(&id) == bots.get(&id) { + *b = json!({"id": id, "same": true}); + } + } + } + } + out["base"] = json!(held); + } + told_states().lock().unwrap_or_else(|e| e.into_inner()).keep(&ssig, Arc::new((keys, bots))); + out["ssig"] = json!(ssig); + out +} + +/// The open chat for a page holding the list fingerprinted `held`: `unchanged` when it is that +/// one; when the page takes a part (`part`), only from where the two differ — drop the first `drop` +/// it holds, keep the next `from`, then `messages`; otherwise all of it. +fn chat_for(bot: u64, msgs: Value, held: &str, part: bool) -> Value { + let list = msgs.as_array().map(Vec::as_slice).unwrap_or(&[]); + let hs: Vec = list.iter().map(fp).collect(); + let sig = sig_of(&(bot, &hs)); + if held == sig { + return json!({"bot": bot, "sig": sig, "unchanged": true}); + } + let prev = if part && !held.is_empty() { told_chats().lock().unwrap_or_else(|e| e.into_inner()).get(held) } else { None }; + let found = prev.as_deref().zip(hs.first()).and_then(|(old, first)| { + let drop = old.iter().position(|h| h == first)?; + Some((drop, old[drop..].iter().zip(&hs).take_while(|(a, b)| a == b).count())) + }); + let out = match found { + Some((drop, from)) => json!({"bot": bot, "sig": sig, "base": held, "drop": drop, "from": from, "messages": &list[from..]}), + None => json!({"bot": bot, "sig": sig, "messages": list}), + }; + told_chats().lock().unwrap_or_else(|e| e.into_inner()).keep(&sig, Arc::new(hs)); + out +} + /// A teammate's file request: only inside the file folder of a bot shared with the team. fn member_file_ok(want: &str, shared: &[u64]) -> bool { let Some(f) = safe_chat_path(want) else { return false }; @@ -1746,7 +1872,28 @@ fn serve_lan(gen: u64, listener: std::net::TcpListener) { } None => listener, }; - std::thread::spawn(move || httpd::serve_upgrade(served, Arc::new(|r| handle(r, false)), Some(Arc::new(move |r, c| lan_vnc(r, c, gen))), alive)); + std::thread::spawn(move || httpd::serve_kept(served, Arc::new(|r| { + let gz = r.header("accept-encoding").split(',').any(|e| e.trim().split(';').next() == Some("gzip")); + squeeze(handle(r, false), gz) + }), Some(Arc::new(move |r, c| lan_vnc(r, c, gen))), alive)); +} + +/// An answer to a phone on 區網 gzipped when it reads that (`gz`) and it is words worth it: the +/// page, the state, a chat (a JPEG or a zip is packed already). +fn squeeze(r: Resp, gz: bool) -> Resp { + let t = r.ctype.split(';').next().unwrap_or("").trim().to_ascii_lowercase(); + let words = t.starts_with("text/") || matches!(t.as_str(), "application/json" | "application/manifest+json" | "image/svg+xml"); + if !gz || !words || r.body.len() < 1024 || r.headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-encoding")) { + return r; + } + let mut e = flate2::write::GzEncoder::new(Vec::with_capacity(r.body.len() / 4), flate2::Compression::default()); + if e.write_all(&r.body).is_err() { + return r; + } + match e.finish() { + Ok(body) => Resp { body, ..r }.with_header("Content-Encoding", "gzip").with_header("Vary", "Accept-Encoding"), + Err(_) => r, + } } static LAN_CERT: Mutex> = Mutex::new(None); @@ -2921,14 +3068,110 @@ pub const ICON_PNGS: [(&str, &[u8]); 6] = [ ("badge-96.png", include_bytes!("../mobile/badge-96.png")), ]; -pub fn page() -> Resp { - Resp::bytes("text/html; charset=utf-8", PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; frame-src 'self' blob:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'none'", httpd::script_src(PAGE))) +/// The phone page: asked again each time it opens (no-cache), and only a "not modified" when the +/// browser already holds this build's. +pub fn page(req: &Req) -> Resp { + static TAG: OnceLock = OnceLock::new(); + let tag = TAG.get_or_init(|| httpd::etag_of(PAGE.as_bytes())); + if httpd::holds(req, tag) { + return Resp::empty(304).with_header("ETag", tag).with_header("Cache-Control", "no-cache"); + } + Resp::bytes("text/html; charset=utf-8", PAGE.as_bytes().to_vec()) + .with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; frame-src 'self' blob:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'none'", httpd::script_src(PAGE))) + .with_header("ETag", tag) + .with_header("Cache-Control", "no-cache") } #[cfg(test)] mod tests { use super::*; + /// A page holding a state is told only what changed: the keys that did, a bot that didn't as + /// {id, same}; one holding none (or an older page) all of it, with the fingerprint. + #[test] + fn the_state_is_told_as_what_changed() { + let a = json!({"version": 5, "host": "Mac", "models": [1, 2, 3], "bots": [{"id": 1, "name": "甲", "status": ""}, {"id": 2, "name": "乙"}]}); + let full = state_for(a.clone(), ""); + assert!(full["base"].is_null() && full["models"] == json!([1, 2, 3])); + let held = full["ssig"].as_str().unwrap().to_string(); + let mut b = a.clone(); + b["version"] = json!(6); + b["bots"][0]["status"] = json!("正在想…"); + let part = state_for(b.clone(), &held); + assert_eq!(part["base"], json!(held)); + assert_eq!(part["version"], 6); + assert!(part.get("host").is_none() && part.get("models").is_none(), "unchanged keys left out: {part}"); + assert_eq!(part["bots"][0]["status"], "正在想…"); + assert_eq!(part["bots"][1], json!({"id": 2, "same": true})); + assert_ne!(part["ssig"], json!(held)); + // The same again: nothing but the version (and the fingerprint is the same). + let same = state_for(b, part["ssig"].as_str().unwrap()); + assert_eq!(same["ssig"], part["ssig"]); + assert!(same.get("bots").is_none()); + assert!(state_for(a, "not-told").get("base").is_none(), "an unknown fingerprint: all of it"); + } + + /// A chat is told from where it differs from what the page holds — the last message grown, one + /// more, the oldest out of the window — and put back together it is the whole chat. + #[test] + fn a_chat_is_told_from_where_it_differs() { + let m = |i: u64, t: &str| json!({"index": i, "role": "bot", "text": t}); + let rebuild = |held: &[Value], c: &Value| -> Vec { + let drop = c["drop"].as_u64().unwrap_or(0) as usize; + let from = c["from"].as_u64().unwrap() as usize; + held[drop..][..from].iter().cloned().chain(c["messages"].as_array().unwrap().iter().cloned()).collect() + }; + let one: Vec = (0..5).map(|i| m(i, "x")).collect(); + let first = chat_for(77, json!(one), "", true); + assert!(first["from"].is_null() && first["messages"].as_array().unwrap().len() == 5); + let sig = first["sig"].as_str().unwrap().to_string(); + assert_eq!(chat_for(77, json!(one), &sig, true)["unchanged"], true); + // The last one grew and one more came; the oldest left the window. + let mut two: Vec = (1..5).map(|i| m(i, "x")).collect(); + two[3] = m(4, "xy"); + two.push(m(5, "new")); + let c = chat_for(77, json!(two), &sig, true); + assert_eq!((c["drop"].as_u64(), c["from"].as_u64(), c["base"].as_str()), (Some(1), Some(3), Some(sig.as_str()))); + assert_eq!(c["messages"].as_array().unwrap().len(), 2); + assert_eq!(rebuild(&one, &c), two); + // An older page (no part): all of it. + assert_eq!(chat_for(77, json!(two), &sig, false)["messages"].as_array().unwrap().len(), 5); + // Cleared: nothing to keep. + let gone = chat_for(77, json!([m(0, "fresh")]), c["sig"].as_str().unwrap(), true); + assert!(gone["from"].is_null()); + } + + /// A message tried again on a bad network (the same id) reaches the bot once. + #[test] + fn a_message_tried_again_is_taken_once() { + assert!(first_delivery(9, "abc123")); + assert!(!first_delivery(9, "abc123")); + assert!(first_delivery(10, "abc123"), "per bot"); + assert!(first_delivery(9, "") && first_delivery(9, ""), "no id (an older page): every time"); + } + + /// 區網 answers in words are gzipped for a browser that reads it; a picture isn't. The page is + /// "not modified" when the browser holds this build's. + #[test] + fn lan_answers_are_small() { + use std::io::Read; + let big = Resp::json(&json!({"t": "字".repeat(4000)})); + let z = squeeze(big.clone(), true); + assert!(z.headers.iter().any(|(k, v)| k == "Content-Encoding" && v == "gzip")); + assert!(z.body.len() < big.body.len() / 10); + let mut back = vec![]; + flate2::read::GzDecoder::new(&z.body[..]).read_to_end(&mut back).unwrap(); + assert_eq!(back, big.body); + assert_eq!(squeeze(big.clone(), false).body, big.body); + assert_eq!(squeeze(Resp::bytes("image/jpeg", vec![0; 5000]), true).body.len(), 5000); + let fresh = page(&Req::default()); + let tag = fresh.headers.iter().find(|(k, _)| k == "ETag").map(|(_, v)| v.clone()).unwrap(); + let mut again = Req::default(); + again.headers.insert("if-none-match".into(), tag); + let r = page(&again); + assert_eq!((r.status, r.body.len()), (304, 0)); + } + #[test] fn self_hop_shortcuts_only_your_own_tunnel_address() { use std::net::IpAddr;