@ -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 ? `< div class = "empty" > 「${esc(wanted.name)}」暫時沒有連線(可能正在重新啟動,或那台電腦睡著了)。< br > 連上後會自動進入,不用重新整理。< / div > ` : "";
$("hosts").innerHTML = waiting + (hosts.length ? hosts.map((h) => `< div class = "row" data-h = "${esc(h.id)}" > < div class = "av" style = "border-radius:var(--r-m);background:var(--active)" > ${ic(h.online ? "monitor" : "power", 18)}< / div > < div class = "mid" > < div class = "nm" > < span class = "t" > ${esc(h.name)}< / span > < / div > < div class = "pv ${h.online ? " busy " : " " } " > ${h.online ? "在線上" : "離線(" + esc(h.last_seen_text || "很久沒連線") + ") "}${note(h)}< / div > < / div > < / div > `).join("")
: `< div class = "empty" > 這個帳號還沒有連上任何 AnyBot。< br > 在電腦上打開 AnyBot › 設定 › 手機與帳號,登入同一個帳號。< / div > `);
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" ? `< div class = "m bot" > < div class = "typing" > < i > < / i > < i > < / i > < i > < / i > < / div > < / div > ` : "";
if (busy & & b.status) h += `< div class = "working" > ${face(b, "sm")}< div class = "presence" > ${esc(b.status)}< / div > < / div > `;
if (!busy & & lastMsg & & lastMsg.role === "user" & & !lastMsg.wake & & owner()) h += S.resending ? `< div class = "meta" style = "align-self:flex-end" > 網路不穩,重新傳送中…< / div > ` : `< div class = "meta" style = "align-self:flex-end" > 還沒有回覆 < button data-resend = "1" > ${ic("refresh", 14)} 重新傳送< / button > < / div > `;
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 += `< div class = "meta" style = "align-self:flex-end" > 還沒有回覆 < button data-resend = "1" > ${ic("refresh", 14)} 重新傳送< / button > < / div > `;
if (!S.msgs.length & & !S.chatLoaded) h = S.stale || S.offline ? `< div class = "empty" > 這個聊天還沒存在這支手機上,連上後就會出現。< / div > ` : "";
else if (!S.msgs.length) {
h = `< div class = "intro" > ${face(b, "lg")}< div class = "hi" > 嗨,我是${esc(b.name || "Bot")}< / div > < div class = "sub" > ${esc(b.description || "想做什麼?點一個開始,或直接打字。")}< / div > < / div > < div class = "sugs" > ${SUGGEST.map((x, k) => `< button class = "sug" data-sugg = "${k}" > ${ic(x[0], 20)}< span > < div class = "tt" > ${esc(x[1])}< / div > < div class = "dd" > ${esc(x[2])}< / div > < / span > < / button > `).join("")}< / div > `;
}
// 先顯示: 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 += `< div class = "m user sending${x.failed ? " failed " : " " } " data-unsent = "${k}" > < div class = "bub" > ${esc(x.text)}< / div > < div class = "sn" > ${x.failed ? "沒送出,點一下拿回來重送" : x.retrying ? "網路不穩,重新傳送中…" : Date.now() - x.at < 1200 ? " 傳送中 … " : " 已排入 , 它下一步會看到 " } < / div > < / div > `;
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 ? `< div class = "sn" > ${ic("paperclip", 12)} ${esc([...x.files.map((f) => f.name), ...x.attachments.map((p) => String(p).split("/").pop())].join("、"))}< / div > ` : "";
const held = !x.sentAt & & !x.going;
const said = x.failed ? "沒送出,點一下拿回來重送" : x.sentAt ? (busy ? "已排入,它下一步會看到" : "已送出") : x.going ? "傳送中…" : "等連線後送出(點一下拿回來)";
h += `< div class = "m user sending${x.failed ? " failed " : " " } $ { held ? " held " : " " } " data-unsent = "${esc(x.id)}" > ${x.text ? `< div class = "bub" > ${esc(x.text)}< / div > ` : ""}${names}< div class = "sn" > ${said}< / div > < / div > `;
});
$("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) => `< span class = "chip" > ${ic(p.image ? "image" : "file", 14)}< span > ${esc(p.name)}< / span > < button data-i = "${i}" > ${ic("x", 12)}< / button > < / span > `).join("");
$("chips").innerHTML = S.pending.map((p, i) => `< span class = "chip" $ { p . blob ? ' title = "連上後跟訊息一起上傳" ' : " " } > ${ic(p.blob ? "cloud" : p.image ? "image" : "file", 14)}< span > ${esc(p.name)}< / span > < button data-i = "${i}" > ${ic("x", 12)}< / button > < / span > `).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) : ""}< div class = "mid" > < div class = "k" > ${esc(o.k)}< / div > ${o.v ? `< div class = "v" > ${esc(o.v)}< / div > ` : ""}< / div > ${o.r != null ? `< div class = "r" > ${esc(o.r)}< / div > ` : ""}${o.sw != null ? `< label class = "sw" > < input type = "checkbox" $ { o . sw ? " checked " : " " } $ { o . swdata | | " " } $ { o . disabled ? " disabled " : " " } > < i > < / i > < / label > ` : ""}${o.tap & & o.chev !== false ? `< span class = "chev" > ${ic("chevron-right", 16)}< / span > ` : ""}< /${o.tap ? "button" : "div"}>`;
const group = (title, inner, extra = "") => `${title ? `< div class = "gt" > ${esc(title)}${extra}< / div > ` : ""}< div class = "group" > ${inner}< / div > `;
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 = `< div class = "empty" > 載入中…< / div > `; await loadDetail(id); }
// What this phone has first (drawn now), the brain's newer one when it comes.
if (!S.detail[id]) { $("details").innerHTML = `< div class = "empty" > 載入中…< / div > `; 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 = `< img src = "${u}" > `; } 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 = `< div class = "form" > < div style = "font-size:var(--fs-h3);font-weight:600" > ${esc(r.title)}< / div > < div class = "v" style = "color:var(--text3);font-size:var(--fs-small)" > ${esc(r.trigger ? "事件觸發:" + r.trigger : r.repeat)} · ${esc(r.when)}${r.last ? " · 上次 " + esc(r.last) : ""}< / div > ${r.status ? `< div class = "note" style = "padding:0" > ${esc(r.status)}< / div > ` : ""}${r.target ? `< div class = "v" style = "color:var(--text2);font-size:var(--fs-small)" > ${esc(r.target)}< / div > ` : ""}${r.paused_why ? `< div class = "note" style = "padding:0;color:var(--attention)" > ${esc(r.paused_why)}< / div > ` : ""}${(r.runs || []).length ? `< label > 最近執行< / label > ${r.runs.map((x) => `< div style = "font-size:var(--fs-small);line-height:1.5;color:${x.bad ? " var ( --attention ) " : " var ( --text3 ) " } " > ${esc(x.line)}< / div > ${(x.sends || []).map((l) => `< div style = "font-size:var(--fs-caption);line-height:1.5;color:var(--text3);padding-left:12px;overflow-wrap:anywhere" > · ${esc(l)}< / div > `).join("")}`).join("")}` : ""}< label > 每次要做的事< / label > < div style = "white-space:pre-wrap;font-size:var(--fs-ui);background:var(--hover);border-radius:var(--r-m);padding:10px 12px" > ${esc(r.prompt)}< / div > < / div > `;
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); });
cons t d = S.detail[id] || await loadDetail(id) || {};
le t 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 = `< div class = "hero" > ${face(b, "lg")}< div class = "n" > ${esc(b.name)}< / div > < / div > `;
// Shown from a copy kept from before: read anew first, then it can be changed.
const held = !isNew(id);
let h = `< div class = "hero" > ${face(b, "lg")}< div class = "n" > ${esc(b.name)}< / div > ${held ? `< div class = "d" > 顯示的是上次的設定,讀到最新的才能改< / div > ` : ""}< / div > `;
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 + `< div style = "height:calc(var(--safe-b) + 24px)" > < / div > `;
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 = `< div class = "empty" > 載入中…< / div > `; await loadSettings(); }
// (Drawn from what this phone has at once; read again behind it when it may be old.)
if (!S.settings) { el.innerHTML = `< div class = "empty" > 載入中…< / div > `; 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 = `< div class = "empty" > 載入中…< / div > `;
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 = `< div class = "empty" > 載入中…< / div > `; 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 = `< div class = "empty" > 載入中…< / div > `;
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("")) : `< div class = "empty" > 還沒有頁面。請 Bot 研究一件事並「整理成一頁」,頁面會出現在這裡。< / div > `;
}
@ -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(); });
< / script >
< / body >
< / html >