@@ -791,7 +794,8 @@ const LUCIDE = {
function ic(name, size = 18) { return ``; }
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 ? `