會的技能)/, `$1
`);
h += ticks("可以用的電腦", "may_use", (d.may_use || []).length > 1 ? d.may_use : [], "它自己的電腦一定可以用。");
}
- h += `
頭像
${(st.shapes || []).map((s) => ``).join("")}
${(st.colors || []).map((c) => ``).join("")}
`;
- h += group("AI 與電腦", item({icon: "sparkles", k: "模型", v: b.via || b.model, r: b.runs || "", tap: 1, data: 'data-e="model"'}) + item({icon: "monitor", k: "做事的電腦", r: b.computer || "", tap: 1, data: 'data-e="comp"'}) + item({icon: "terminal", k: "電腦操作", v: S.settings && S.settings.direct_mode ? "直接操作開著:照樣可以用電腦(關掉直接操作才照這裡)" : "關掉時,用電腦前會先問你", sw: d.tools_enabled !== false, swdata: 'data-sw="tools"', disabled: !isOwner()}) + item({icon: "brain", k: "模型可讀長度", r: (CTX.find((c) => c[0] === d.context_tokens) || [0, Math.round((d.context_tokens || 0) / 1000) + "K"])[1], tap: 1, data: 'data-e="ctx"'}));
+ h += `
頭像
${(st.shapes || []).map((s) => ``).join("")}
${(st.colors || []).map((c) => ``).join("")}${isOwner() ? `` : ""}
`;
+ // (As on the computer's Bot 設定: who carries out the planned steps, and how long it thinks.)
+ const EFFORTS = [["", "自動(模型自己決定)"], ["low", "快速(想得少,回得快)"], ["medium", "平衡"], ["high", "深入(想得久,較慢)"]];
+ const stepShown = !d.step_model ? "自動" : d.step_model === "off" ? "不分開" : d.step_model;
+ const fbs = d.fallbacks || [];
+ const extra2 = isOwner() ? sitem({icon: "refresh", k: "備用模型", v: fbs.length ? fbs.map((f) => f.model).join("、") : "主模型失敗時改用(還沒有)", tap: 1, data: 'data-e="fallbacks"'}) + sitem({icon: "folder", k: "起始資料夾", v: d.workdir || "", tap: 1, data: 'data-e="workdir"'}) : "";
+ const extra = isOwner() ? sitem({icon: "zap", k: "執行步驟用的模型", v: "想計畫和確認用上面的模型;照計畫做的步驟交給這個比較快的", r: stepShown, tap: 1, data: 'data-e="step"'}) + sitem({icon: "lightbulb", k: "思考模式", r: (EFFORTS.find((e) => e[0] === (d.thinking || "")) || EFFORTS[0])[1].replace(/(.*)/, ""), tap: 1, data: 'data-e="think"'}) : "";
+ h += group("AI 與電腦", sitem({icon: "sparkles", k: "模型", v: b.via || b.model, r: b.runs || "", tap: 1, data: 'data-e="model"'}) + extra + extra2 + sitem({icon: "monitor", k: "做事的電腦", r: b.computer || "", tap: 1, data: 'data-e="comp"'}) + sitem({icon: "terminal", k: "電腦操作", v: S.settings && S.settings.direct_mode ? "直接操作開著:照樣可以用電腦(關掉直接操作才照這裡)" : "關掉時,用電腦前會先問你", sw: d.tools_enabled !== false, swdata: 'data-sw="tools"', disabled: !isOwner()}) + sitem({icon: "brain", k: "模型可讀長度", r: (CTX.find((c) => c[0] === d.context_tokens) || [0, Math.round((d.context_tokens || 0) / 1000) + "K"])[1], tap: 1, data: 'data-e="ctx"'}));
+ // 語音聊天 (as the computer's right panel): read every answer aloud, the voice, speed, language.
+ if (isOwner()) h += group("語音", sitem({icon: "audio-lines", k: "朗讀每個回答", v: "回答好了就唸出來(要先在 設定 › 語音 選「說」的服務)", sw: !!d.speak_replies, swdata: 'data-sw="speak_replies"'}) + sitem({icon: "smile-plus", k: "聲音", r: d.voice || "跟著 設定 › 語音", tap: 1, data: 'data-e="voice"'}) + sitem({icon: "zap", k: "速度", r: (d.voice_rate || 1) + " 倍", tap: 1, data: 'data-e="rate"'}) + sitem({icon: "globe", k: "語言", r: ({"": "自動", "zh-TW": "中文", en: "英文", ja: "日文"})[d.voice_lang || ""] || d.voice_lang, tap: 1, data: 'data-e="vlang"'}));
if (isOwner()) h += group("已設定「一律允許」", (d.allow_rules || []).map((r) => `
`).join("") || `
還沒有。在核准時選「一律允許」就會記在這裡。
`);
- h += group("整理", item({icon: "pin", k: "釘選", sw: !!d.pinned, swdata: 'data-sw="pinned"'}) + item({icon: "star", k: "主要 Bot", v: d.primary ? "這是主要 Bot" : "", sw: !!d.primary, swdata: 'data-sw="primary"', disabled: !!d.primary}) + item({icon: "folder", k: "分區", r: d.folder || "未分區", tap: 1, data: 'data-e="folder"'}));
- if ((d.demos || []).length) h += group("示範教學", d.demos.map((x) => item({icon: "eye", k: x.name, v: `${x.steps} 個步驟 · ${x.created}`})).join("") + `
示範要在那台電腦上錄;Bot 在對話裡會照著做。
`);
- 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}) : ""));
+ h += group("整理", sitem({icon: "pin", k: "釘選", sw: !!d.pinned, swdata: 'data-sw="pinned"'}) + sitem({icon: "star", k: "主要 Bot", v: d.primary ? "這是主要 Bot" : "", sw: !!d.primary, swdata: 'data-sw="primary"', disabled: !!d.primary}) + sitem({icon: "folder", k: "分區", r: d.folder || "未分區", tap: 1, data: 'data-e="folder"'}));
+ if ((d.demos || []).length) h += group("示範教學", d.demos.map((x) => sitem({icon: "eye", k: x.name, v: `${x.steps} 個步驟 · ${x.created}`})).join("") + `
示範要在那台電腦上錄;Bot 在對話裡會照著做。
`);
+ h += group("", sitem({icon: "refresh", k: "重新啟動這個 Bot", v: "卡住時用:停止它正在做的事和背景指令", tap: 1, data: 'data-e="restart"', chev: false}) + sitem({icon: "trash", k: "清除聊天記錄", tap: 1, data: 'data-e="clear"', danger: true, chev: false}) + (isOwner() ? sitem({icon: "trash", k: "刪除 Bot", tap: 1, data: 'data-e="delete"', danger: true, chev: false}) : ""));
$("botset").innerHTML = h + `
`;
const el = $("botset");
el.classList.toggle("held", held);
@@ -3063,7 +3295,21 @@ async function 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(); });
+ // 自訂顏色: the phone's own colour picker; the bot wears #rrggbb.
+ el.querySelectorAll("[data-color-own]").forEach((x) => x.onclick = () => {
+ const pick = document.createElement("input"); pick.type = "color"; pick.value = /^#[0-9a-f]{6}$/i.test(d.color || "") ? d.color : "#c06244";
+ pick.style.cssText = "position:fixed;opacity:0;pointer-events:none"; document.body.appendChild(pick);
+ pick.onchange = async () => { pick.remove(); if (await act("bot", {bot: id, key: "color", value: pick.value}, "已換顏色")) refresh(); };
+ pick.click();
+ });
el.querySelectorAll("[data-rule]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "allow_remove", value: x.dataset.rule}, "已移除")) refresh(); });
+ // 技能:全選/全不選 at once (the brain's list as it is now, all on or all off).
+ el.querySelectorAll("[data-allsk]").forEach((x) => x.onclick = () => oneAtATime(async () => {
+ const now = await freshDetail(id);
+ if (!now) { toast("連上後才能改"); return; }
+ const all = (now.skills || []).every((y) => y.on);
+ if (await act("bot", {bot: id, key: "skills", value: all ? [] : (now.skills || []).map((y) => y.key)}, all ? "技能都不帶了" : "技能都帶上了")) { delete S.detail[id]; refresh(); }
+ }));
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.)
// (Built on the brain's list as it is now, with only this tick changed: never a list read
@@ -3091,6 +3337,26 @@ async function renderBotset(id) {
else if (k === "not_for") { const n = await ask("不找它做的事", d.not_for || "", "例如:不寫程式、不碰帳務", true); if (n != null && n !== (d.not_for || "") && await act("bot", {bot: id, key: "not_for", value: n}, "已更新")) refresh(); }
else if (k === "model") modelSheet(b);
else if (k === "comp") pickComputer(b, d);
+ else if (k === "fallbacks") {
+ const save = async (list, ok) => { if (await act("bot", {bot: id, key: "fallbacks", value: list.map((f) => ({provider: f.provider, model: f.model}))}, ok)) refresh(); };
+ const add = () => {
+ const items = [];
+ for (const p of S.models || []) { items.push({group: p.label}); for (const m of p.models || []) items.push({label: m, on: () => save([...fbs, {provider: p.provider, model: m}], "已加入備用模型")}); }
+ sheet("加一個備用模型", items);
+ };
+ sheet("備用模型(照順序試)", [{group: "主模型失敗(額度用完、連不上)時照順序改用"}, ...fbs.map((f, i) => ({icon: "x", label: `${i + 1}. ${f.label} · ${f.model}`, x: "移除", on: () => save(fbs.filter((_, j) => j !== i), "已移除")})), ...(fbs.length < 8 ? [{icon: "plus", label: "加一個備用模型…", on: () => setTimeout(add, 60)}] : [])]);
+ }
+ else if (k === "voice") { const v = await ask("聲音(空白=跟著 設定 › 語音)", d.voice || ""); if (v != null && await act("bot", {bot: id, key: "voice", value: v}, "已更新")) refresh(); }
+ else if (k === "rate") sheet("朗讀速度", [0.8, 1, 1.2, 1.5, 2].map((r) => ({label: r + " 倍", check: (d.voice_rate || 1) === r, on: async () => { if (await act("bot", {bot: id, key: "voice_rate", value: r}, "已更新")) refresh(); }})));
+ else if (k === "vlang") sheet("朗讀的語言", [["", "自動"], ["zh-TW", "中文"], ["en", "英文"], ["ja", "日文"]].map(([v, n]) => ({label: n, check: (d.voice_lang || "") === v, on: async () => { if (await act("bot", {bot: id, key: "voice_lang", value: v}, "已更新")) refresh(); }})));
+ else if (k === "workdir") { const w = await ask("起始資料夾(它的檔案和指令從這裡開始)", d.workdir || ""); if (w && w !== d.workdir && await act("bot", {bot: id, key: "workdir", value: w}, "已更新起始資料夾")) refresh(); }
+ else if (k === "think") sheet("思考模式", [{group: "想得越久越仔細,也越慢、越花額度"}].concat(EFFORTS.map(([v, l]) => ({label: l, check: v === (d.thinking || ""), on: async () => { if (await act("bot", {bot: id, key: "thinking", value: v}, "已更新")) refresh(); }}))));
+ else if (k === "step") {
+ const models = ((S.models || []).find((p) => p.provider === b.provider) || {}).models || [];
+ const pick = (v, ok) => async () => { if (await act("bot", {bot: id, key: "step_model", value: v}, ok)) refresh(); };
+ sheet("執行步驟用的模型", [{label: "自動", check: !d.step_model, on: pick("", "已改成自動")}, {label: "不分開(每一步都用上面的模型)", check: d.step_model === "off", on: pick("off", "已改成不分開")}]
+ .concat(models.filter((m) => m !== b.model).map((m) => ({label: m, check: d.step_model === m, on: pick(m, "步驟改用 " + m)}))));
+ }
else if (k === "ctx") sheet("模型可讀長度", CTX.map(([n, l]) => ({label: l + " 個 token", check: n === d.context_tokens, on: async () => { if (await act("bot", {bot: id, key: "context", value: n}, "已更新")) refresh(); }})));
else if (k === "folder") moveToFolder(b);
else if (k === "restart") act("restart_bot", {bot: id});
@@ -3112,7 +3378,7 @@ async function loadSettings() {
} catch (e) { S.settingsOld = true; toast(e.message); }
return S.settings;
}
-const SETTINGS_PAGES = ["computers", "settings", "general", "models", "perms", "integrations", "vault", "account", "updates"];
+const SETTINGS_PAGES = ["computers", "settings", "general", "models", "perms", "integrations", "vault", "voice", "account", "updates"];
/** Something changed on the computer (the state's version moved): the settings read before are
* old — the page showing them is read again now, any other the next time it opens. (They were
* read once: after /always-approve filled the 一律詢問 rules, 權限 still said 還沒有規則.) */
@@ -3127,7 +3393,7 @@ async function settingsChanged() {
}
let listTimer = null;
function stopListTimer() { clearInterval(listTimer); listTimer = null; }
-const TITLES = {tasks: "任務", routines: "例行任務", pages: "頁面", computers: "電腦", settings: "設定", general: "一般", models: "模型", perms: "權限", integrations: "整合", vault: "保險庫", account: "手機與帳號", updates: "更新"};
+const TITLES = {tasks: "任務", files: "所有檔案", schedule: "日程", workflows: "工作流", routines: "例行任務", pages: "頁面", computers: "電腦", settings: "設定", general: "一般", me: "個人資料與用量", models: "模型", perms: "權限", integrations: "整合", vault: "保險庫", voice: "語音", account: "手機與帳號", updates: "更新"};
async function renderList(arg) {
const kind = arg.kind;
$("list-title").textContent = TITLES[kind] || "";
@@ -3137,6 +3403,10 @@ async function renderList(arg) {
if (kind === "tasks") return listTasks(el);
if (kind === "routines") return listRoutines(el);
if (kind === "pages") return listPages(el);
+ if (kind === "me") return listMe(el);
+ if (kind === "workflows") return listWorkflows(el, arg.wf);
+ if (kind === "schedule") return listSchedule(el);
+ if (kind === "files") return listFiles(el);
if (SETTINGS_PAGES.includes(kind)) {
// (Drawn from what this phone has at once; read again behind it when it may be old.)
if (!S.settings) { el.innerHTML = `
載入中…
`; await loadSettings(); }
@@ -3147,6 +3417,221 @@ async function renderList(arg) {
if (["computers", "integrations"].includes(kind)) listTimer = setInterval(async () => { await loadSettings(); if (cur().v === "list" && cur().arg.kind === kind) drawSettings(kind, true); }, 4000);
}
}
+// ---------- 所有檔案 ----------
+// Every file the bots handed over or were given, across bots and conversations (from the
+// attachments the chats keep, as on the computer): by kind, a search, pictures as a grid; a tap
+// opens it in the viewer. A file moved or deleted since is greyed out and says 不見了.
+const LIB = {kind: "all", q: "", files: null};
+const THUMBS = new Map();
+const LIB_KINDS = [["all", "全部"], ["image", "圖片"], ["doc", "文件"], ["code", "程式碼"], ["sheet", "表格"], ["media", "影音"], ["other", "其他"]];
+const LIB_ICON = {image: "image", doc: "file-text", code: "terminal", sheet: "list-checks", media: "play", other: "file"};
+const fsize = (n) => !n ? "" : n < 1024 ? n + " B" : n < 1048576 ? Math.round(n / 1024) + " KB" : (n / 1048576).toFixed(1) + " MB";
+async function listFiles(el) {
+ const here = () => cur().v === "list" && cur().arg.kind === "files";
+ if (LIB.files) drawFiles(el); else el.innerHTML = `
載入中…
`;
+ const v = await act("library", {}, false);
+ if (!here() || !v) return;
+ LIB.files = v.files || [];
+ drawFiles(el);
+}
+function drawFiles(el) {
+ const all = LIB.files || [], q = LIB.q.trim().toLowerCase();
+ const byQ = all.filter((f) => !q || f.name.toLowerCase().includes(q));
+ const count = (k) => byQ.filter((f) => k === "all" || f.kind === k).length;
+ if (LIB.kind !== "all" && !count(LIB.kind)) LIB.kind = "all";
+ const shown = byQ.filter((f) => LIB.kind === "all" || f.kind === LIB.kind);
+ let h = `
`;
+ if (!all.length) h += `
還沒有檔案。
你傳給 Bot、Bot 交給你的檔案都會收在這裡。
`;
+ else if (!shown.length) h += `
沒有相符的檔案
`;
+ else {
+ const pics = shown.filter((f) => f.image && f.there), rest = shown.filter((f) => !(f.image && f.there));
+ if (pics.length) h += `
${pics.slice(0, 120).map((f) => `
`).join("")}
`;
+ if (rest.length) h += group("", rest.slice(0, 300).map((f) => { const b = bot(f.bot) || {}; return `
`; }).join(""));
+ }
+ h += `
`;
+ el.innerHTML = h;
+ const qEl = $("lib-q");
+ qEl.oninput = () => { LIB.q = qEl.value; const pos = qEl.selectionStart; drawFiles(el); const n = $("lib-q"); n.focus(); n.setSelectionRange(pos, pos); };
+ el.querySelectorAll("[data-lk]").forEach((b) => b.onclick = () => { LIB.kind = b.dataset.lk; drawFiles(el); });
+ el.querySelectorAll("[data-lf]").forEach((b) => b.onclick = () => openFile(b.dataset.lf, b.dataset.ln));
+ // Thumbnails as they come into view (the brain's own small copies of the pictures).
+ const io = new IntersectionObserver((es) => es.forEach(async (e) => {
+ if (!e.isIntersecting) return;
+ io.unobserve(e.target);
+ try { const r = await api(base() + "api/preview/image?path=" + encodeURIComponent(e.target.dataset.thumb), {raw: true}); if (r.ok) { const u = URL.createObjectURL(await safeBlob(r)); THUMBS.set(e.target.dataset.thumb, u); e.target.src = u; } } catch (_) {}
+ }), {root: el});
+ el.querySelectorAll("img[data-thumb]").forEach((i) => io.observe(i));
+}
+// ---------- 日程 ----------
+// What the bots are set to do, as on the computer's 日程: 即將執行 (each routine or workflow once,
+// at its next time), then day by day from three days back to a week ahead — what ran on its own
+// and how it went (✓ ✗ ■), what is coming, what is paused. (What you ran by hand is in each
+// one's own runs, not here.)
+const SCH_MARK = {done: ["good", "circle-check", "完成"], failed: ["bad", "circle-x", "失敗"], stopped: ["", "minus", "停止了"], running: ["go", "loader", "執行中"], coming: ["", "clock", ""], paused: ["todo", "pause", "暫停中"]};
+async function listSchedule(el) {
+ const here = () => cur().v === "list" && cur().arg.kind === "schedule";
+ S.schedShown = false;
+ if (S.sched) drawSchedule(el); else el.innerHTML = `
載入中…
`;
+ const v = await act("schedule", {}, false);
+ if (!here() || !v) return;
+ S.sched = v;
+ drawSchedule(el);
+}
+function schedDay(d, today) {
+ const [y, m, dd] = d.split("-").map(Number), t = new Date(y, m - 1, dd), [ty, tm, td] = today.split("-").map(Number);
+ const diff = Math.round((t - new Date(ty, tm - 1, td)) / 864e5);
+ const wd = "日一二三四五六"[t.getDay()];
+ return (diff === 0 ? "今天・" : diff === 1 ? "明天・" : diff === -1 ? "昨天・" : "") + `${m}月${dd}日(${wd})`;
+}
+function drawSchedule(el) {
+ const v = S.sched || {}, items = v.items || [], today = v.today || "";
+ const row = (i, showDay) => {
+ const b = bot(i.bot) || {}, [cls, icon, word] = SCH_MARK[i.status] || ["", "clock", ""];
+ const right = showDay ? (i.day === today ? "今天 " : schedDay(i.day, today).replace(/(.)$/, "") + " ") + i.clock : word;
+ return `
`;
+ };
+ let h = group("即將執行", (v.coming || []).map((i) => row(i, true)).join("") || `
接下來兩週沒有排定的事
`);
+ const days = [...new Set(items.map((i) => i.day))];
+ if (!days.includes(today)) days.push(today);
+ days.sort();
+ for (const d of days) {
+ const list = items.filter((i) => i.day === d);
+ if (!list.length && d !== today) continue;
+ h += group(schedDay(d, today), list.map((i) => row(i, false)).join("") || `
這一天沒有排定的事
`);
+ }
+ h += `
只放排程或事件自己跑的;你按的「立即執行」在各自的執行紀錄裡。新增:在聊天裡跟 Bot 說「每天早上 9 點幫我…」。
`;
+ const sc = el.scrollTop;
+ el.innerHTML = h;
+ // (Today in view the first time; where you were after that.)
+ if (!S.schedShown) { S.schedShown = true; const t = [...el.querySelectorAll(".gt")].find((g) => g.textContent.startsWith("今天")); if (t) t.scrollIntoView({block: "start"}); } else el.scrollTop = sc;
+ el.querySelectorAll("[data-sch]").forEach((x) => x.onclick = async () => {
+ const [kind, id, bid] = x.dataset.sch.split(":");
+ if (kind === "workflow") return go("list", {kind: "workflows", wf: +id});
+ const b = bot(+bid); if (!b) return;
+ const d = S.detail[b.id] || await loadDetail(b.id) || {};
+ const r = (d.routines || []).find((y) => y.id === +id);
+ if (r) routineSheet(b, r); else go("chat", {bot: b.id});
+ });
+}
+// ---------- 工作流 ----------
+// The workflows on the brain: what starts each, its steps in order, how its runs went — run it,
+// stop it, answer the 等你確認 a 審批 step waits on. (Drawing and editing are on the computer's
+// canvas, or by asking a bot in the chat.)
+const WF_ICON = {"觸發器": "zap", "提示詞": "text-cursor", "素材": "paperclip", "助手": "bot", "LLM": "sparkles", "圖片": "image", "影片": "play", "審批": "hand", "條件": "list-checks", "輸出": "send"};
+const WF_STATE = {running: ["go", "執行中"], waiting: ["wait", "等你確認"], done: ["good", "完成"], failed: ["bad", "失敗"], stopped: ["", "停止了"]};
+// A step's own state: not reached yet is just dimmed; the one a waiting run stands on waits for you.
+const WF_STEP = {waiting: ["todo", ""], running: ["go", "進行中"], done: ["good", "完成"], failed: ["bad", "失敗"], skipped: ["skip", "略過"]};
+const stepLook = (s, run, id) => !s ? ["", ""] : s.state === "running" && run && run.state === "waiting" && (run.steps || []).find((x) => x.state === "running") === s ? ["wait", "等你確認"] : WF_STEP[s.state] || ["", ""];
+async function listWorkflows(el, wf) {
+ const here = () => cur().v === "list" && cur().arg.kind === "workflows" && cur().arg.wf === wf;
+ if (S.wfs) drawWorkflows(el, wf); else el.innerHTML = `
載入中…
`;
+ const v = await act("workflows", {}, false);
+ if (!here()) return;
+ S.wfs = (v && v.workflows) || S.wfs || [];
+ drawWorkflows(el, wf);
+ // (While one runs, how it goes is read again every few seconds.)
+ stopListTimer();
+ if (S.wfs.some((w) => w.live)) listTimer = setInterval(async () => { const v = await act("workflows", {}, false); if (!here()) return stopListTimer(); if (v) { S.wfs = v.workflows || []; drawWorkflows(el, wf); if (!S.wfs.some((w) => w.live)) stopListTimer(); } }, 3000);
+}
+function wfLine(w) {
+ const r = w.live || w.runs[0];
+ return [w.when, w.step_count + " 個步驟", w.next ? "下次 " + w.next : ""].filter(Boolean).join(" · ") + (r ? `\n${w.live ? "" : "最近一次:"}${r.words}${w.live ? "" : " · " + ago((r.ended || r.started) * 1000)}` : "");
+}
+function wfWaiting(w) {
+ const r = w.live;
+ if (!r || r.state !== "waiting" || !isOwner()) return "";
+ return `
${ic("hand", 15)}等你確認:${esc(r.asks || "要繼續嗎?")}
`;
+}
+function drawWorkflows(el, wf) {
+ const list = S.wfs || [];
+ if (wf) {
+ const w = list.find((x) => x.id === wf);
+ if (!w) { el.innerHTML = `
找不到這個工作流(可能刪掉了)
`; return; }
+ $("list-title").textContent = w.name;
+ const r = w.live || w.runs[0];
+ const stepOf = (id) => r && (r.steps || []).find((s) => s.node === id);
+ let h = `
${esc(w.when)}${w.next ? " · 下次 " + esc(w.next) : ""}
${isOwner() ? (w.live ? `
` : `
`) : ""}
`;
+ h += wfWaiting(w);
+ h += `
步驟${r ? `(${w.live ? "這一次" : "最近一次"}:${esc(r.words)})` : ""}
${w.steps.map((st, i) => {
+ const s = stepOf(st.id), [cls, word] = stepLook(s, r, st.id);
+ return `
${ic(WF_ICON[st.kind] || "circle-dot", 15)}${esc(st.kind)}${st.bot ? ` · ${esc(st.bot)}` : ""}${word ? ` ${esc(word)}` : ""}
${st.words ? `
${esc(st.words)}
` : ""}${s && s.output ? `
${esc(s.output.split("\n").slice(0, 3).join("\n"))}
` : ""}
`;
+ }).join("")}
`;
+ h += group("執行紀錄", (w.runs || []).map((x, i) => item({icon: x.state === "done" ? "circle-check" : x.state === "failed" ? "circle-x" : x.state === "waiting" ? "hand" : x.state === "running" ? "loader" : "minus", k: x.words, v: (x.by || "") + " · " + ago(x.started * 1000), tap: 1, data: `data-wfrun="${i}"`})).join("") || `
還沒有跑過
`);
+ h += `
畫布在電腦上改;或在聊天裡請 Bot 改這個工作流。
`;
+ el.innerHTML = h;
+ el.querySelectorAll("[data-wfout]").forEach((x) => x.onclick = () => { const s = stepOf(+x.dataset.wfout); if (s) sheet("這一步的結果", [{group: s.output.slice(0, 600)}, {icon: "copy", label: "複製", on: () => copyText(s.output)}]); });
+ el.querySelectorAll("[data-wfrun]").forEach((x) => x.onclick = () => {
+ const run = w.runs[+x.dataset.wfrun];
+ sheet(run.words, (run.steps || []).map((s) => { const st = w.steps.find((y) => y.id === s.node) || {kind: "步驟"}; return {icon: WF_ICON[st.kind] || "circle-dot", label: st.kind + ":" + (stepLook(s, run, s.node)[1] || "還沒到"), x: (s.output || "").slice(0, 24), on: () => s.output && copyText(s.output)}; }));
+ });
+ } else {
+ el.innerHTML = list.length ? `
${list.map((w) => {
+ const st = w.live ? WF_STATE[w.live.state] || ["", ""] : null;
+ return `
${ic("workflow", 18)}${esc(w.name)}${st ? ` ${st[1]}` : ""}
${esc(wfLine(w))}
${isOwner() ? (w.live ? `
` : `
`) : ""}
${wfWaiting(w)}
`;
+ }).join("")}
` : `
還沒有工作流。
在聊天裡請 Bot「做一個每天早上整理新聞的工作流」,或在電腦上畫。
`;
+ el.querySelectorAll("[data-wfopen]").forEach((x) => x.onclick = (e) => { if (e.target.closest("button")) return; go("list", {kind: "workflows", wf: +x.dataset.wfopen}); });
+ }
+ el.querySelectorAll("[data-wfdo]").forEach((b) => b.onclick = async (e) => {
+ e.stopPropagation();
+ const what = b.dataset.wfdo, id = +b.dataset.wf;
+ if (what === "stop" && !await confirmSheet("停止這次執行?", "已經做完的步驟不會復原。", "停止")) return;
+ b.disabled = true;
+ if (await act("workflow", {wf: id, do: what})) setTimeout(() => { if (cur().v === "list" && cur().arg.kind === "workflows" && cur().arg.wf === wf) listWorkflows(el, wf); }, 600);
+ else b.disabled = false;
+ });
+}
+// ---------- 個人資料與用量(設定)----------
+// The year in figures, a heat map of its days, and 用量 by period — as on the computer
+// (設定 › 個人資料): big numbers and bars instead of lines of words; the fine print in a tap.
+const ME = {span: "30", by: "model", data: null, at: 0};
+const wan = (n) => { n = n || 0; return n < 1e4 ? n.toLocaleString("en-US") : n < 1e7 ? (n / 1e4).toFixed(1).replace(/\.0$/, "") + "萬" : n < 1e8 ? Math.round(n / 1e4).toLocaleString("en-US") + "萬" : (n / 1e8).toFixed(2).replace(/\.00$/, "") + "億"; };
+const costWords = (micros, unpriced, calls) => !micros ? "未定價" : "US$" + (micros / 1e6).toFixed(2) + (unpriced > 0 && unpriced < calls ? `(另有 ${unpriced} 次呼叫未定價)` : "");
+const shortDate = (d) => { const [, m, dd] = (d || "").split("-"); return m ? `${+m}月${+dd}日` : d || ""; };
+async function listMe(el) {
+ if (ME.data) drawMe(el); else el.innerHTML = `
正在算過去一年的用量…
`;
+ if (ME.data && Date.now() - ME.at < 60000) return;
+ try { ME.data = await api(base() + "api/stats"); ME.at = Date.now(); }
+ catch (e) { if (!ME.data) { el.innerHTML = `
讀不到用量:${esc(e.message)}
`; return; } }
+ if (cur().v === "list" && cur().arg.kind === "me") drawMe(el);
+}
+function drawMe(el) {
+ const d = ME.data || {};
+ const figs = [[wan(d.tokens_year), "Token・一年"], [wan(d.messages_year), "訊息・一年"], [(d.streak_now || 0) + " 天", "連續使用"], [(d.streak_best || 0) + " 天", "最長連續"]];
+ let h = `
${figs.map(([v, l]) => `
${esc(v)}${esc(l)}
`).join("")}
`;
+ // The year: a dot a day, a column a week (Sunday on top), deeper the busier.
+ const days = d.days || [], off = d.weekday_first || 0, weeks = Math.ceil((days.length + off) / 7) || 1;
+ const cell = 7, W = weeks * cell, H = 7 * cell;
+ const lv = ["var(--hover)", "color-mix(in srgb,var(--accent) 30%,transparent)", "color-mix(in srgb,var(--accent) 50%,transparent)", "color-mix(in srgb,var(--accent) 75%,transparent)", "var(--accent)"];
+ const dots = days.map((x, i) => { const k = i + off; return `
${esc(shortDate(x[0]))}:${wan(x[1])} token、${x[2]} 則訊息`; }).join("");
+ const busy = d.busiest && d.busiest.date ? `最活躍:${shortDate(d.busiest.date)}・${wan(d.busiest.tokens)} token` : "";
+ h += `
活動
過去一年有 ${d.active_days || 0} 個活躍日${busy ? "・" + esc(busy) : ""}
`;
+ // 用量: the period's big number, a bar a day, then by model or by bot.
+ const u = (d.periods || {})[ME.span] || {};
+ const seg = (list, cur, key) => `
${list.map(([v, l]) => ``).join("")}
`;
+ h += `
用量
${seg([["7", "7 天"], ["30", "30 天"], ["90", "90 天"], ["365", "一年"]], ME.span, "mespan")}`;
+ h += `
${wan(u.tokens)} token
${wan(u.calls)} 次呼叫・花費 ${esc(costWords(u.cost_micros, u.unpriced, u.calls))}・新讀 ${wan((u.input || 0) + (u.cache_write || 0))}、寫 ${wan(u.output)}、快取 ${wan(u.cache_read)}
`;
+ const daily = u.daily || [], max = Math.max(1, ...daily.map((x) => x[1] || 0)), bw = 100 / Math.max(1, daily.length);
+ h += `
`;
+ const rows = (u[ME.by === "bot" ? "by_bot" : "by_model"] || []).slice(0, 8);
+ const total = Math.max(1, rows.reduce((n, r) => n + (r.tokens || 0), 0));
+ const cat = (i) => `var(--cat${(i % 6) + 1})`;
+ h += seg([["model", "依模型"], ["bot", "依 Bot"]], ME.by, "meby");
+ if (!rows.length) h += `
這段時間沒有用量紀錄
`;
+ else {
+ if (ME.by === "model") h += `
${rows.map((r, i) => ``).join("")}
`;
+ const top = Math.max(1, rows[0].tokens || 0);
+ h += rows.map((r, i) => {
+ const b = ME.by === "bot" ? S.bots.find((x) => x.name === r.name) : null;
+ const mark = ME.by === "bot" ? `
${b ? avatarSvg(b.shape, b.color) : ""}` : `
`;
+ const bar = ME.by === "bot" ? `
` : "";
+ return `
${mark}${esc(r.name)}${bar}${wan(r.tokens)}・${Math.round((r.tokens || 0) / total * 100)}%
`;
+ }).join("");
+ }
+ h += `
`;
+ el.innerHTML = h;
+ el.querySelectorAll("[data-mespan]").forEach((b) => b.onclick = () => { ME.span = b.dataset.mespan; drawMe(el); });
+ el.querySelectorAll("[data-meby]").forEach((b) => b.onclick = () => { ME.by = b.dataset.meby; drawMe(el); });
+}
// ---------- 任務 ----------
// Every bot's tasks as the brain works them out — from the steps, the turn's end, the follow-ups,
// the goal checks and whether a device showed the files, never from what a bot says. They come
@@ -3185,7 +3670,9 @@ function listTasks(el) {
// 任務 → 那則訊息: the chat at where the task began, lit a moment (once that message is here).
function jumpTo() {
if (!S.jumpAt || S.view !== "chat") return false;
- const i = S.msgs.findIndex((m) => m.at === S.jumpAt && m.role === "user");
+ // (A task opens at the person's opening message; a search hit may be any message.)
+ let i = S.msgs.findIndex((m) => m.at === S.jumpAt && m.role === "user");
+ if (i < 0) i = S.msgs.findIndex((m) => m.at === S.jumpAt);
const el = i < 0 ? null : document.querySelector(`#msgs [data-msg="${i}"]`);
if (!el) return false;
S.jumpAt = 0;
@@ -3233,64 +3720,116 @@ function drawSettings(kind, quiet) {
const sc = el.scrollTop;
let h = "";
if (kind === "settings") {
+ // 搜尋設定 (the computer's index): what matches stands where the pages were.
+ h += `
`;
+ if (S.setQ && S.setHits) h += group("", S.setHits.map((x) => sitem({icon: setIcon(x.title), k: x.title, v: x.path, tap: 1, data: `data-go="${x.page}"`})).join("") || `
沒有符合的設定
`);
+ }
+ if (kind === "settings" && !(S.setQ && S.setHits)) {
h += group("", [
- ["general", "settings", "一般", "外觀、時區、通知總開關"], ["models", "sparkles", "模型", "可以用的 AI 服務"], ["perms", "shield", "權限", st.direct_mode ? "直接操作:開" : "Bot 做事前的規則"],
- ["integrations", "plug", "整合", "訊息管道、連接器、技能"], ["computers", "monitor", "電腦", "Bot 的電腦和你帳號裡的電腦"], ["vault", "lock", "保險庫", "密碼和卡號"],
+ ["general", "settings", "一般", "外觀、時區、通知總開關"], ...(isOwner() ? [["me", "activity", "個人資料與用量", ""]] : []), ["models", "sparkles", "模型", "可以用的 AI 服務"], ["perms", "shield", "權限", st.direct_mode ? "直接操作:開" : "Bot 做事前的規則"],
+ ["integrations", "plug", "整合", "訊息管道、連接器、技能"], ["computers", "monitor", "電腦", "Bot 的電腦和你帳號裡的電腦"], ["vault", "lock", "保險庫", "密碼和卡號"], ["voice", "audio-lines", "語音", "聽和說的服務"],
["account", "smartphone", "手機與帳號", "登入的手機、這支手機的通知"], ["updates", "download", "更新", st.version || ""],
- ].map(([k, i, n, v]) => item({icon: i, k: n, r: k === "updates" ? v : "", tap: 1, data: `data-go="${k}"`})).join(""));
+ ].map(([k, i, n, v]) => sitem({icon: i, k: n, r: k === "updates" ? v : "", tap: 1, data: `data-go="${k}"`})).join(""));
}
if (kind === "general") {
st.accent = ({Quiet: "quiet", BotColor: "bot_color", Black: "black"})[st.accent] || st.accent;
- // (The computer's own 主題 and 聊天的顏色 are set on the computer; this phone has its own 外觀 below.)
- h += group("", item({icon: "globe", k: "時區", r: st.timezone || "", tap: 1, data: 'data-s="tz"'}) + item({icon: "bell", k: "通知總開關", v: "Bot 做完或等你時通知,電腦和手機都算;關掉就都不通知", sw: !!st.notify, swdata: 'data-sset="notify"', disabled: !isOwner()}));
- h += group("這支手機", item({icon: "smartphone", k: "外觀", r: (THEMES.find((t) => t[0] === phoneTheme()) || THEMES[0])[1], tap: 1, data: 'data-s="phonetheme"'}));
+ // The computer's 主題 and 聊天的顏色 (the phone follows them unless its own 外觀 says otherwise).
+ const ACC = {quiet: "安靜(淡灰泡泡)", bot_color: "跟著 Bot", black: "只用黑色"};
+ // 風格: a little picture of each (the sidebar, words, your bubble, the accent, its backdrop).
+ if (isOwner() && (st.styles || []).length) {
+ const dk = isDark();
+ h += `
風格
${st.styles.map((t) => {
+ const c = dk ? t.dark : t.light, on = st.style === t.id;
+ const bd = t.backdrop === "dots" ? `background-image:radial-gradient(${c.grid} 1px,transparent 1.2px);background-size:9px 9px;` : t.backdrop === "grid" ? `background-image:linear-gradient(${c.grid} 1px,transparent 1px),linear-gradient(90deg,${c.grid} 1px,transparent 1px);background-size:10px 10px;` : t.backdrop === "waves" ? `background-image:radial-gradient(circle at 50% 100%,transparent 6px,${c.grid} 6.5px,${c.grid} 7.5px,transparent 8px);background-size:14px 7px;` : "";
+ return ``;
+ }).join("")}
${st.style ? "" : `
現在是自訂的顏色(電腦上的強調色);點一個風格整套換,電腦和手機一起。
`}`;
+ }
+ const accName = ((st.accents || []).find((a) => a.key === st.shell_accent) || {}).name || "";
+ const look = isOwner() ? sitem({icon: "palette", k: "強調色", r: st.style ? "跟著風格" : accName, tap: 1, data: 'data-s="accentcolor"'}) + sitem({icon: "palette", k: "對比", r: (st.shell_contrast || 1) < 0.95 ? "柔和" : (st.shell_contrast || 1) > 1.1 ? "鮮明" : "標準", tap: 1, data: 'data-s="contrast"'}) + sitem({icon: "globe", k: "語言", r: st.language === "auto" || !st.language ? "自動偵測" : ((st.languages || []).find((l) => l[0] === st.language) || [0, st.language])[1], tap: 1, data: 'data-s="lang"'}) : "";
+ if (isOwner()) h += group("電腦的外觀", look + sitem({icon: "moon", k: "主題", r: ({system: "跟隨系統", light: "淺色", dark: "深色"})[st.theme] || "跟隨系統", tap: 1, data: 'data-s="theme"'}) + sitem({icon: "message", k: "聊天的顏色", r: ACC[st.accent || "quiet"] || "", tap: 1, data: 'data-s="accent"'}));
+ h += group("", sitem({icon: "globe", k: "時區", r: st.timezone || "", tap: 1, data: 'data-s="tz"'}) + sitem({icon: "bell", k: "通知總開關", v: "Bot 做完或等你時通知,電腦和手機都算;關掉就都不通知", sw: !!st.notify, swdata: 'data-sset="notify"', disabled: !isOwner()}));
+ if (isOwner()) h += group("記憶與文件", sitem({icon: "brain", k: "用意思找記憶", v: "在這台電腦上算,不會上傳", r: ({local: "本機模型", ollama: "Ollama", off: "關閉"})[st.embed] || "本機模型", tap: 1, data: 'data-s="embed"'})
+ + (st.doc_folders || []).map((f) => `
`).join("")
+ + sitem({icon: "plus", k: (st.doc_folders || []).length ? "再加一個 Bot 可以翻的資料夾" : "Bot 可以翻的資料夾", v: "Bot 在這些資料夾的文字檔裡找答案(在那台電腦上的路徑)", tap: 1, data: 'data-s="docadd"', chev: false}));
+ h += group("這支手機", sitem({icon: "smartphone", k: "外觀", r: (THEMES.find((t) => t[0] === phoneTheme()) || THEMES[0])[1], tap: 1, data: 'data-s="phonetheme"'}));
}
if (kind === "models") {
- h += group("AI 服務", (st.providers || []).map((p, i) => item({k: p.label, v: [p.runs, p.ready && p.default_model ? p.default_model : ""].filter(Boolean).join(" · "), r: p.ready ? "可以用" : "未設定", tap: isOwner() ? 1 : 0, data: `data-prov="${i}"`})).join(""));
+ h += group("AI 服務", (st.providers || []).map((p, i) => sitem({icon: "sparkles", k: p.label, v: [p.runs, p.ready && p.default_model ? p.default_model : "", p.status || ""].filter(Boolean).join(" · "), r: p.ready ? "可以用" : "未設定", tap: isOwner() ? 1 : 0, data: `data-prov="${i}"`})).join(""));
h += `
金鑰只存在這台 AnyBot,手機寫得進去、看不到。
`;
}
if (kind === "perms") {
- h += group("", item({icon: "zap", k: "直接操作", v: st.direct_locked ? "已由管理員關閉" : "Bot 直接做事,只有危險操作和「一律詢問」規則會先問你", sw: !!st.direct_mode, swdata: 'data-sset="direct_mode"', disabled: !isOwner() || st.direct_locked}) + item({icon: "shield", k: "自動審核", v: "照下面的規則自動允許或先問你", sw: !!st.auto_review, swdata: 'data-sset="auto_review"', disabled: !isOwner()}));
+ h += group("", sitem({icon: "zap", k: "直接操作", v: st.direct_locked ? "已由管理員關閉" : "Bot 直接做事,只有危險操作和「一律詢問」規則會先問你", sw: !!st.direct_mode, swdata: 'data-sset="direct_mode"', disabled: !isOwner() || st.direct_locked}) + sitem({icon: "shield", k: "自動審核", v: "照下面的規則自動允許或先問你", sw: !!st.auto_review, swdata: 'data-sset="auto_review"', disabled: !isOwner()})
+ + sitem({icon: "zap", k: "一律放行", v: "你自己的對話裡,要允許的都自動答應(和聊天打 /always-approve 一樣);危險操作和「一律詢問」照樣擋", sw: !!st.always_approve, swdata: 'data-sset="always_approve"', disabled: !isOwner() || st.direct_locked})
+ + sitem({icon: "clock", k: "智慧模式:卡片沒人回答時", r: SMART_SECS.find((x) => x[0] === (st.smart_timeout_secs || 0))?.[1] || (st.smart_timeout_secs + " 秒後"), tap: isOwner() ? 1 : 0, data: 'data-s="smartsecs"'}));
h += rulesGroup("一律詢問(優先)", st.ask_rules, "ask") + rulesGroup("無需詢問直接允許", st.allow_rules, "allow");
// 直接操作 always asks about these three too (not written into the rules: turning it off leaves nothing behind).
- if (st.direct_mode) h += group("直接操作開著時也一定先問", ["刪除檔案或資料夾", "付款、購買或轉帳", "用我的帳號發文、留言,或傳訊息給別人"].map((r) => item({icon: "hand", k: r})).join(""));
+ if (st.direct_mode) h += group("直接操作開著時也一定先問", ["刪除檔案或資料夾", "付款、購買或轉帳", "用我的帳號發文、留言,或傳訊息給別人"].map((r) => sitem({icon: "hand", k: r})).join(""));
h += `
用一般的話寫,例如「付款前先問我」。兩邊都符合時先問。${st.direct_mode ? "直接操作開著:「一律詢問」照樣檢查,「直接允許」用不到。" : st.auto_review === false ? "自動審核關著時不會用這些規則。" : ""}
`;
}
if (kind === "integrations") {
const dot = (ok, on) => `
`;
h += group("訊息管道", (st.channels || []).map((c) => `
${dot(c.ok, c.enabled)}
${esc(c.kind)} · ${esc(c.name)}
由「${esc(c.bot)}」回覆${c.note ? " · " + esc(c.note) : ""}
${isOwner() ? `
` : ""}
`).join("") || `
還沒有。Telegram、Slack、Discord… 要在電腦上的 AnyBot 新增(需要輸入 Token)。
`);
- h += group("連接器(MCP)", ((st.mcp || []).map((m) => `
${dot(m.tools != null, m.enabled)}
${esc(m.name)}
${!m.enabled ? "已關閉" : m.tools != null ? `已連上,${m.tools} 個工具` : m.error ? esc(m.error) : "連線中…"}
${isOwner() ? `${m.enabled ? `
` : ""}
` : ""}
`).join("") || `
還沒有連接器
`) + (isOwner() ? item({icon: "plus", k: "從公用市集加入", v: "搜尋官方 MCP Registry 裡用網址連的連接器", tap: 1, data: 'data-mcpmarket="1"'}) : ""));
+ h += group("連接器(MCP)", ((st.mcp || []).map((m) => `
${dot(m.tools != null, m.enabled)}
${esc(m.name)}
${!m.enabled ? "已關閉" : m.tools != null ? `已連上,${m.tools} 個工具` : m.error ? esc(m.error) : "連線中…"}
${isOwner() ? `${m.enabled ? `
` : ""}
` : ""}
`).join("") || `
還沒有連接器
`) + (isOwner() ? sitem({icon: "plus", k: "從公用市集加入", v: "搜尋官方 MCP Registry 裡用網址連的連接器", tap: 1, data: 'data-mcpmarket="1"'}) : ""));
const skRows = (st.skills || []).map((k, i) => {
const tags = [...(k.resources && k.resources.length ? [`${k.resources.length} 檔`] : []), ...(k.steps ? [`可重播 ${k.steps} 步`] : [])].join(" · ");
- return `
${esc(k.name)}${tags ? ` ${esc(tags)}` : ""}
${esc(k.description)}
${isOwner() ? `
` : ""}
`;
+ return `
${ic("sparkles", 19)}
${esc(k.name)}${tags ? ` ${esc(tags)}` : ""}
${esc(k.description)}
${isOwner() ? `
` : ""}
`;
}).join("");
const skActions = isOwner()
- ? item({icon: "sparkles", k: "從技能市集加入", v: "內建繁中核心技能包與 Anthropic 官方開源技能", tap: 1, data: 'data-skillmarket="1"'}) +
- item({icon: "plus", k: "從 GitHub 或網址安裝技能", v: "支援 anthropics/skills 網址、owner/repo/path 或 SKILL.md 連結", tap: 1, data: 'data-skilladd="1"', chev: false})
+ ? sitem({icon: "sparkles", k: "從技能市集加入", v: "內建繁中核心技能包與 Anthropic 官方開源技能", tap: 1, data: 'data-skillmarket="1"'}) +
+ sitem({icon: "plus", k: "從 GitHub 或網址安裝技能", v: "支援 anthropics/skills 網址、owner/repo/path 或 SKILL.md 連結", tap: 1, data: 'data-skilladd="1"', chev: false})
: "";
h += group("技能", (skRows || `
還沒有技能。可從下方「技能市集」一鍵加入,或在聊天裡請 Bot 幫你建立。
`) + skActions);
}
if (kind === "computers") h += computersHtml(st);
+ // 語音: who hears you (聽) and who reads answers aloud (說) — on the brain, for every device.
+ if (kind === "voice") {
+ const V = st.voice || {};
+ const engine = (which, title, about) => {
+ const e = V[which] || {}, kindName = (VOICE_KINDS.find((k) => k[0] === e.kind) || VOICE_KINDS[0])[1];
+ let rows = sitem({icon: which === "listen" ? "mic" : "audio-lines", k: title, v: about, r: e.kind === "off" || !e.kind ? "關閉" : kindName + (e.ready ? "・可以用" : "・還不能用"), tap: isOwner() ? 1 : 0, data: `data-vk="${which}"`});
+ if (e.kind && e.kind !== "off") {
+ if (e.kind === "open_ai") rows += sitem({icon: "globe", k: "網址", r: e.base_url || "OpenAI", tap: 1, data: `data-vf="${which}:base_url"`});
+ rows += sitem({icon: "key", k: "金鑰", r: e.has_key ? "已設定" : "用「模型」裡同一家的", tap: 1, data: `data-vf="${which}:api_key"`});
+ rows += sitem({icon: "sparkles", k: "模型", r: e.model || "預設", tap: 1, data: `data-vf="${which}:model"`});
+ if (which === "speak") rows += sitem({icon: "smile-plus", k: "聲音", r: e.voice || "預設", tap: 1, data: `data-vf="speak:voice"`}) + (e.ready ? sitem({icon: "play", k: "試聽", tap: 1, data: 'data-vtest="1"', chev: false}) : "");
+ }
+ return group("", rows);
+ };
+ h += engine("listen", "聽(語音轉文字)", "語音輸入、語音聊天、會議錄音都用它") + engine("speak", "說(朗讀)", "把回答唸出來");
+ h += `
每台電腦和手機的錄音、朗讀都交給大腦,用這裡選的服務;金鑰只存在大腦,手機看不到。沒選服務時,麥克風和朗讀不會出現。
`;
+ }
if (kind === "vault") h += `
${ic("lock", 28)}
保險庫裡的密碼、卡號和聯絡資訊,只在電腦上的 AnyBot 管理。
Bot 用到時由 AnyBot 直接填進網頁,不會交給模型,也不會經過手機。
`;
if (kind === "account") {
- h += group("這台 AnyBot", item({icon: "monitor", k: "名稱", r: st.host || S.hostName}) + item({icon: "info", k: "你的角色", r: isOwner() ? "擁有者" : "管理員"}));
- if (st.devices) h += group("直接連線的手機", st.devices.map((d, i) => item({icon: "smartphone", k: d.name, v: d.last_seen ? "上次使用 " + ago(d.last_seen * 1000) : "登入於 " + ago(d.created * 1000), tap: 1, data: `data-dev="${i}"`})).join("") || `
沒有
`);
+ h += group("這台 AnyBot", sitem({icon: "monitor", k: "名稱", r: st.host || S.hostName}) + sitem({icon: "info", k: "你的角色", r: isOwner() ? "擁有者" : "管理員"}));
+ if (st.devices) h += group("直接連線的手機", st.devices.map((d, i) => sitem({icon: "smartphone", k: d.name, v: d.last_seen ? "上次使用 " + ago(d.last_seen * 1000) : "登入於 " + ago(d.created * 1000), tap: 1, data: `data-dev="${i}"`})).join("") || `
沒有
`);
const acts = [];
- if (S.relay) acts.push(item({icon: "bell", k: "通知", v: "Bot 需要你允許、或做完事時,手機跳通知", tap: 1, data: 'data-s="push"'}));
- if (S.relay) acts.push(item({icon: "shield", k: "兩步驗證", v: "登入要密碼+驗證器 App 的六位碼", tap: 1, data: 'data-s="2fa"'}));
- if (S.relay) acts.push(item({icon: "smartphone", k: "登入的裝置", v: "看看有哪些裝置登著,可逐台踢掉", tap: 1, data: 'data-s="devices"'}));
- if (S.relay && owner()) acts.push(item({icon: "plus", k: "加一台電腦", v: "Linux、伺服器當 Bot 的手腳", tap: 1, data: 'data-s="pair"'}));
- if (S.relay) acts.push(item({icon: "refresh", k: "切換到別台 AnyBot", tap: 1, data: 'data-s="host"'}));
- acts.push(item({icon: "log-out", k: "登出這支手機", tap: 1, data: 'data-s="out"', danger: true, chev: false}));
+ if (S.relay) acts.push(sitem({icon: "bell", k: "通知", v: "Bot 需要你允許、或做完事時,手機跳通知", tap: 1, data: 'data-s="push"'}));
+ if (S.relay) acts.push(sitem({icon: "shield", k: "兩步驗證", v: "登入要密碼+驗證器 App 的六位碼", tap: 1, data: 'data-s="2fa"'}));
+ if (S.relay) acts.push(sitem({icon: "smartphone", k: "登入的裝置", v: "看看有哪些裝置登著,可逐台踢掉", tap: 1, data: 'data-s="devices"'}));
+ if (S.relay && owner()) acts.push(sitem({icon: "plus", k: "加一台電腦", v: "Linux、伺服器當 Bot 的手腳", tap: 1, data: 'data-s="pair"'}));
+ if (S.relay) acts.push(sitem({icon: "refresh", k: "切換到別台 AnyBot", tap: 1, data: 'data-s="host"'}));
+ acts.push(sitem({icon: "log-out", k: "登出這支手機", tap: 1, data: 'data-s="out"', danger: true, chev: false}));
h += group("這支手機", acts.join(""));
}
if (kind === "updates") {
- h += group("", item({icon: "info", k: "版本", v: st.built ? `${stamp(st.built)} 建置` : "", r: st.version || ""}) + (st.newer ? item({icon: "download", k: "有新版", v: "電腦上的 AnyBot 已經下載新版,重新啟動就會換上"}) : item({icon: "circle-check", k: "已是最新版"})));
+ h += group("", sitem({icon: "info", k: "版本", v: st.built ? `${stamp(st.built)} 建置` : "", r: st.version || ""}) + (st.newer ? sitem({icon: "download", k: "有新版", v: "電腦上的 AnyBot 已經下載新版,重新啟動就會換上"}) : sitem({icon: "circle-check", k: "已是最新版"})));
+ if (isOwner()) h += group("自動", sitem({icon: "refresh", k: "你不在時自動更新", v: "有新版時,等你離開電腦再換上", sw: st.auto_update !== false, swdata: 'data-sset="auto_update"'}) + sitem({icon: "target", k: "園丁報告", v: "每天、每週整理 Bot 卡住和做錯的地方,給你看要不要改", sw: st.garden_reports !== false, swdata: 'data-sset="garden_reports"'}));
h += `
Bot 的電腦的更新在「電腦」裡。
`;
- h += group("這支手機", item({icon: "smartphone", k: "畫面", v: fitWords(), tap: 1, data: 'data-ruler="1"'}));
+ h += group("這支手機", sitem({icon: "smartphone", k: "畫面", v: fitWords(), tap: 1, data: 'data-ruler="1"'}));
h += `
畫面看起來被切到、上面糊糊的、下面空一塊時,按「畫面」打開量尺截圖給我們。
`;
}
el.innerHTML = h + `
`;
+ const sq = $("set-q");
+ if (sq) sq.oninput = () => {
+ S.setQ = sq.value.trim(); clearTimeout(S.setT);
+ S.setT = setTimeout(async () => {
+ const q = S.setQ;
+ const v = q ? await act("settings_find", {q}, false) : null;
+ if (q !== S.setQ || cur().v !== "list" || cur().arg.kind !== "settings") return;
+ S.setHits = v ? v.hits || [] : null;
+ const pos = sq.selectionStart; drawSettings("settings", true); const n = $("set-q"); if (n) { n.focus(); n.setSelectionRange(pos, pos); }
+ }, 200);
+ };
el.querySelectorAll("[data-ruler]").forEach((x) => x.onclick = ruler);
if (quiet) el.scrollTop = sc;
wireSettings(kind, st);
@@ -3312,17 +3851,17 @@ function computersHtml(st) {
const steps = f.steps && f.steps.n ? `平均每步 ${Math.round(f.steps.total_ms / f.steps.n)} ms(${f.steps.n} 步)` : "";
// (Not looked at yet: undefined. Nothing to look at — no Docker, no box yet: null.)
const upd = f.update === undefined ? "檢查中…" : f.update === null ? (box.available ? `還沒建立(建立時是 v${box.version})` : "沒有 Docker,現在沒有這台電腦") : f.update ? `有新版(v${box.version})。檔案和登入都會留著` : `已是 v${box.version}`;
- h += group("", item({icon: "download", k: "更新 Bot 的電腦", v: upd, tap: isOwner() && f.update ? 1 : 0, data: 'data-bx="update"'}) +
- item({icon: "alarm-clock", k: "自動更新", r: box.auto_update || "關", tap: isOwner() ? 1 : 0, data: 'data-bx="auto"'}) +
- item({icon: "shield", k: "容器隔離", v: running_rt && running_rt !== rt.slice(0, 2) ? `目前是${running_rt};按更新後改成${rt}` : (f.gvisor === false && box.runtime !== "runsc" ? "這台 Docker 主機沒有 gVisor" : ""), r: rt, tap: isOwner() && (f.gvisor || box.runtime === "runsc") ? 1 : 0, data: 'data-bx="runtime"'}) +
- item({icon: "hard-drive", k: "上次快照", r: box.snapshot || "還沒有"}) +
- (steps ? item({icon: "activity", k: "速度", r: steps}) : "") +
- (st.docker_host ? item({icon: "server", k: "Docker 主機", v: st.docker_host}) : ""));
- h += group("", item({icon: "sparkles", k: "請 Bot 提出清理方案", v: "先列出用量最大的地方,不會直接刪除", tap: 1, data: 'data-bx="clean"'}) +
- (isOwner() ? item({icon: "refresh", k: box.snapshot ? "從快照復原" : "重設電腦", v: box.snapshot ? `回到 ${box.snapshot} 的快照(目前的內容會先存起來)` : "換一台全新的電腦(檔案和登入會清除)", tap: 1, data: 'data-bx="reset"', danger: true, chev: false}) : ""));
+ h += group("", sitem({icon: "download", k: "更新 Bot 的電腦", v: upd, tap: isOwner() && f.update ? 1 : 0, data: 'data-bx="update"'}) +
+ sitem({icon: "alarm-clock", k: "自動更新", r: box.auto_update || "關", tap: isOwner() ? 1 : 0, data: 'data-bx="auto"'}) +
+ sitem({icon: "shield", k: "容器隔離", v: running_rt && running_rt !== rt.slice(0, 2) ? `目前是${running_rt};按更新後改成${rt}` : (f.gvisor === false && box.runtime !== "runsc" ? "這台 Docker 主機沒有 gVisor" : ""), r: rt, tap: isOwner() && (f.gvisor || box.runtime === "runsc") ? 1 : 0, data: 'data-bx="runtime"'}) +
+ sitem({icon: "hard-drive", k: "上次快照", r: box.snapshot || "還沒有"}) +
+ (steps ? sitem({icon: "activity", k: "速度", r: steps}) : "") +
+ (st.docker_host ? sitem({icon: "server", k: "Docker 主機", v: st.docker_host}) : ""));
+ h += group("", sitem({icon: "sparkles", k: "請 Bot 提出清理方案", v: "先列出用量最大的地方,不會直接刪除", tap: 1, data: 'data-bx="clean"'}) +
+ (isOwner() ? sitem({icon: "refresh", k: box.snapshot ? "從快照復原" : "重設電腦", v: box.snapshot ? `回到 ${box.snapshot} 的快照(目前的內容會先存起來)` : "換一台全新的電腦(檔案和登入會清除)", tap: 1, data: 'data-bx="reset"', danger: true, chev: false}) : ""));
if ((box.log || []).length) h += `
紀錄
${esc(box.log.slice(-25).join("\n"))}
`;
const others = comps.filter((c) => c.kind !== "own");
- if (others.length) h += group("帳號裡的電腦", others.map((c) => item({icon: {this: "monitor", device: "laptop", ssh: "server"}[c.kind] || "monitor", k: c.name, v: (c.online ? "在線上" : "離線") + (c.person ? " · 你正在用的" : ""), tap: c.kind === "this" && S.mac ? 1 : 0, data: c.kind === "this" && S.mac ? 'data-bx="mac"' : ""})).join(""));
+ if (others.length) h += group("帳號裡的電腦", others.map((c) => sitem({icon: {this: "monitor", device: "laptop", ssh: "server"}[c.kind] || "monitor", k: c.name, v: (c.online ? "在線上" : "離線") + (c.person ? " · 你正在用的" : ""), tap: c.kind === "this" && S.mac ? 1 : 0, data: c.kind === "this" && S.mac ? 'data-bx="mac"' : ""})).join(""));
return h;
}
async function devicesSheet() {
@@ -3382,6 +3921,15 @@ function wireSettings(kind, st) {
if (!await act("setting", {key: k, value: x.checked})) x.checked = !x.checked; else again();
});
on("[data-addrule]", "onclick", async (x) => { const t = await ask(x.dataset.addrule === "ask" ? "一律詢問的規則" : "無需詢問的規則", "", x.dataset.addrule === "ask" ? "例如:發文、寄信、付款前先問我" : "例如:讀取網頁和檔案"); if (t && await act("setting", {key: "rule_add", list: x.dataset.addrule, value: t})) again(); });
+ on("[data-vk]", "onclick", (x) => { const w = x.dataset.vk, cur = ((st.voice || {})[w] || {}).kind || "off"; sheet(w === "listen" ? "聽(語音轉文字)" : "說(朗讀)", VOICE_KINDS.map(([k, n]) => ({label: n, check: cur === k, on: async () => { if (await act("voice", {which: w, kind: k})) again(); }}))); });
+ on("[data-vf]", "onclick", async (x) => {
+ const [w, f] = x.dataset.vf.split(":"), e = (st.voice || {})[w] || {};
+ const label = {base_url: "網址(以 /v1 結尾;空白=OpenAI 自己的)", api_key: "金鑰(空白=用「模型」裡同一家的)", model: "模型(空白=服務預設的)", voice: "聲音(空白=服務預設的)"}[f];
+ const val = await ask(label, f === "api_key" ? "" : e[f] || "");
+ if (val != null && await act("voice", {which: w, [f]: val}, "已更新")) again();
+ });
+ on("[data-vtest]", "onclick", () => speakText("你好,這是朗讀的聲音。"));
+ on("[data-docrm]", "onclick", async (x) => { if (await act("setting", {key: "doc_folder_remove", value: x.dataset.docrm}, "已移除")) again(); });
on("[data-rmrule]", "onclick", async (x) => { if (await act("setting", {key: "rule_remove", list: x.dataset.rmrule, value: x.dataset.r}, "已移除")) again(); });
on("[data-ch]", "onchange", async (x) => { if (!await act("channel", {id: +x.dataset.ch, enabled: x.checked})) x.checked = !x.checked; else again(); });
on("[data-chrm]", "onclick", async (x) => { if (await confirmSheet("移除這個管道?", "", "移除") && await act("channel", {id: +x.dataset.chrm, remove: true}, "已移除")) again(); });
@@ -3407,6 +3955,10 @@ function wireSettings(kind, st) {
if (r) { toast(r.text || (r.ok ? "已登入" : "沒有登入成功")); again(); }
}}, ...(p.ready ? [{icon: "trash", label: "登出 ChatGPT", danger: true, on: async () => { if (await confirmSheet("登出 ChatGPT?", "用 ChatGPT 方案的 Bot 會沒辦法回答,直到再登入。", "登出") && await act("chatgpt", {action: "logout"})) again(); }}] : [])] : []),
{icon: "sparkles", label: "新 Bot 預設模型…", x: p.default_model || "", on: async () => { const m = await ask("新 Bot 預設用的模型", p.default_model || ""); if (m != null && await act("provider", {provider: p.key, default_model: m}, "已更新")) again(); }},
+ // 服務網址, 測試連線並取得模型清單, and a local model's 看圖小幫手 — as on the computer.
+ ...(p.account ? [] : [{icon: "globe", label: "服務網址…", x: p.base_url ? "自訂" : "預設", on: async () => { const u = await ask("服務網址(空白=預設)", p.base_url || "", p.default_url || ""); if (u != null && await act("provider", {provider: p.key, base_url: u}, "已更新網址")) again(); }}]),
+ {icon: "refresh", label: p.testing ? "正在測試連線…" : "測試連線並取得模型清單", x: p.status ? p.status.slice(0, 18) : p.known ? `記住 ${p.known} 個` : "", on: async () => { if (await act("provider", {provider: p.key, fetch: true})) { setTimeout(again, 2500); setTimeout(again, 8000); } }},
+ ...(p.local ? [{icon: "eye", label: p.cloud_eyes ? "看不到圖時請雲端模型看:開" : "看不到圖時請雲端模型看:關", x: "", on: async () => { if (await act("provider", {provider: p.key, cloud_eyes: !p.cloud_eyes}, p.cloud_eyes ? "圖片不會離開了" : "看不到的圖會給雲端模型看")) again(); }}] : []),
...(p.ready && p.needs_key ? [{icon: "trash", label: "清除金鑰", danger: true, on: async () => { if (await confirmSheet(`清除 ${p.label} 的金鑰?`, "用這個服務的 Bot 會沒辦法回答,直到再設定一把。", "清除") && await act("provider", {provider: p.key, key: ""}, "已清除")) again(); }}] : []),
]);
});
@@ -3477,11 +4029,20 @@ function wireSettings(kind, st) {
});
on("[data-s]", "onclick", async (x) => {
const k = x.dataset.s;
- if (k === "theme") sheet("主題", [["system", "跟隨系統"], ["light", "淺色"], ["dark", "深色"]].map(([v, n]) => ({label: n, check: st.theme === v, on: async () => { if (await app("update_settings", {theme: v})) again(); }})));
+ if (k === "accentcolor") sheet("強調色(會回到自訂的顏色)", (st.accents || []).map((a) => ({label: "● " + a.name, check: !st.style && st.shell_accent === a.key, on: async () => { if (await act("setting", {key: "shell_accent", value: a.key})) again(); }})));
+ else if (k === "contrast") sheet("對比", [[0.85, "柔和"], [1, "標準"], [1.2, "鮮明"]].map(([v, n]) => ({label: n, check: Math.abs((st.shell_contrast || 1) - v) < 0.06, on: async () => { if (await act("setting", {key: "shell_contrast", value: v})) again(); }})));
+ else if (k === "lang") sheet("語言(選單和 Bot 回答)", [["auto", "自動偵測"], ...(st.languages || [])].map(([v, n]) => ({label: n, check: (st.language || "auto") === v, on: async () => { if (await act("setting", {key: "language", value: v})) again(); }})));
+ else if (k === "smartsecs") sheet("智慧模式:卡片沒人回答時", SMART_SECS.map(([v, n]) => ({label: n, check: (st.smart_timeout_secs || 0) === v, on: async () => { if (await act("setting", {key: "smart_timeout_secs", value: v})) again(); }})));
+ else if (k === "embed") sheet("用意思找記憶", [["local", "本機模型(在這台電腦上算)"], ["ollama", "Ollama"], ["off", "關閉"]].map(([v, n]) => ({label: n, check: (st.embed || "local") === v, on: async () => { if (await act("setting", {key: "embed", value: v})) again(); }})));
+ else if (k === "docadd") { const f = await ask("資料夾路徑(那台電腦上的)", "", "例如:~/Documents/筆記"); if (f && await act("setting", {key: "doc_folder_add", value: f}, "已加入")) again(); }
+ else if (k === "style") { if (await app("update_settings", {style: x.dataset.style}, 0, false)) { toast("換好了"); again(); } }
+ else if (k === "theme") sheet("主題", [["system", "跟隨系統"], ["light", "淺色"], ["dark", "深色"]].map(([v, n]) => ({label: n, check: st.theme === v, on: async () => { if (await app("update_settings", {theme: v})) again(); }})));
else if (k === "accent") sheet("聊天的顏色", [["quiet", "安靜(淡灰泡泡)"], ["bot_color", "跟著 Bot"], ["black", "只用黑色"]].map(([v, n]) => ({label: n, check: (st.accent || "quiet") === v, on: async () => { if (await app("update_settings", {accent: v})) again(); }})));
else if (k === "tz") {
const zones = [...new Set([TZ, "Asia/Taipei", "Asia/Tokyo", "Asia/Shanghai", "Asia/Hong_Kong", "Asia/Singapore", "Europe/London", "America/New_York", "America/Los_Angeles", "UTC"].filter(Boolean))];
- sheet("時區", zones.map((z) => ({label: z + (z === TZ ? "(這支手機)" : ""), check: st.timezone === z, on: async () => { if (await app("update_settings", {timezone: z})) again(); }})));
+ sheet("時區", zones.map((z) => ({label: z + (z === TZ ? "(這支手機)" : ""), check: st.timezone === z, on: async () => { if (await app("update_settings", {timezone: z})) again(); }}))
+ // (Any IANA name, as on the computer: Europe/Berlin, Australia/Sydney…)
+ .concat([{icon: "pen", label: "其他時區…", on: async () => { const z = await ask("時區(例如 Europe/Berlin)", st.timezone || ""); if (z && z !== st.timezone && await app("update_settings", {timezone: z.trim()})) again(); }}]));
}
else if (k === "phonetheme") sheet("這支手機的外觀", THEMES.map(([v, n]) => ({label: n, check: phoneTheme() === v, on: () => { try { localStorage.setItem("anybot.theme", v); } catch (_) {} applyTheme(); drawSettings(kind, true); }})));
else if (k === "push") notifySheet();
@@ -3493,8 +4054,8 @@ function wireSettings(kind, st) {
});
on("[data-bx]", "onclick", async (x) => {
const k = x.dataset.bx, box = st.box || {};
- if (k === "open") openBox(false);
- else if (k === "take") openBox(true);
+ if (k === "open") pickBoxBot(false);
+ else if (k === "take") pickBoxBot(true);
else if (k === "mac") go("screen");
else if (k === "wake") { await act("box", {op: "wake"}, "正在喚醒…"); again(); }
else if (k === "snapshot") { await act("box", {op: "snapshot"}, "正在儲存快照…"); again(); }
@@ -3554,7 +4115,7 @@ function pageToc(root) {
}
$("b-pagemore").onclick = () => {
const v = S.pageData; if (!v) return;
- const items = [{icon: "copy", label: "複製 Markdown", on: () => copyText(v.body)}];
+ const items = [{icon: "copy", label: "複製 Markdown", on: () => copyText(v.body)}, {icon: "download", label: "存成檔案(.md)", on: () => saveText(v.body, (v.title || "頁面").replace(/[\\/:*?"<>|]/g, "_") + ".md")}];
if ((v.versions || []).length) items.push({icon: "history", label: "其他版本", on: () => sheet("版本", [{label: `第 ${v.latest} 版(最新)`, check: v.revision === v.latest, on: () => openPage(v.id)}, ...v.versions.map((x) => ({label: `第 ${x.revision} 版`, x: x.at, check: v.revision === x.revision, on: () => openPage(v.id, x.revision)}))])});
if (isOwner()) items.push({sep: true}, {icon: "trash", label: "刪除頁面", danger: true, on: async () => { if (await confirmSheet(`刪除「${v.title}」?`, "", "刪除") && await act("delete_page", {id: v.id}, "已刪除頁面")) back(); }});
sheet(v.title, items);
@@ -3705,13 +4266,34 @@ function saveFile(path, name, att, bot) {
$("b-filesave").innerHTML = ic("download", 20);
$("b-filesave").onclick = () => { if (S.file) saveFile(S.file.path, S.file.name, S.file.att, S.file.bot); };
const isDark = () => document.documentElement.dataset.theme === "dark" || (!document.documentElement.dataset.theme && matchMedia("(prefers-color-scheme: dark)").matches);
+// A drawn chart as a picture: an SVG kept as an SVG image — only ever shown in an
![]()
, where it
+// runs nothing (safeBlob turns SVG into a download, so the picture showed broken).
+const DIAGRAMS = new Map();
+async function chartUrl(r) {
+ if (/^image\/svg\+xml/i.test(r.headers.get("Content-Type") || "")) return URL.createObjectURL(new Blob([await r.text()], {type: "image/svg+xml"}));
+ return URL.createObjectURL(await safeBlob(r));
+}
async function loadCharts() {
+ for (const el of document.querySelectorAll(".chart[data-mermaid]")) {
+ // (The answer still being written: its diagram is drawn when it is whole.)
+ const m = el.closest(".m");
+ if (m && !m.nextElementSibling && el.closest("#msgs") && (bot(S.open) || {}).busy) continue;
+ const src = el.dataset.mermaid, key = (isDark() ? "d:" : "l:") + src; el.removeAttribute("data-mermaid");
+ try {
+ const r = await api(base() + "api/diagram", {json: {src, dark: isDark()}, raw: true});
+ if (!r.ok) { if (r.status === 422) DIAGRAMS.set(key, "fail"); throw new Error(); }
+ const u = await chartUrl(r);
+ DIAGRAMS.set(key, u);
+ if (DIAGRAMS.size > 60) { const old = DIAGRAMS.keys().next().value, v = DIAGRAMS.get(old); DIAGRAMS.delete(old); if (v !== "fail") URL.revokeObjectURL(v); }
+ el.innerHTML = `

`;
+ } catch (_) { el.innerHTML = `
${esc(src)}
`; }
+ }
for (const el of document.querySelectorAll(".chart[data-src]")) {
const src = el.dataset.src; el.removeAttribute("data-src");
try {
const r = await api(base() + src + (src.includes("?") ? "&" : "?") + "dark=" + (isDark() ? 1 : 0), {raw: true});
if (!r.ok) throw new Error();
- el.innerHTML = `
)})
`;
+ el.innerHTML = `
})
`;
} catch (_) { el.innerHTML = `
這張圖畫不出來
`; }
}
}
@@ -3981,6 +4563,13 @@ function pageMd(text, id, rev) {
while (i < L.length && !L[i].trim().startsWith("```")) body.push(L[i++]);
i++;
if (lang === "mermaid" && id) { out.push(`
`); continue; }
+ // (A diagram in a chat: drawn by the brain from its words, as the computer draws it.)
+ if (lang === "mermaid") {
+ // (Drawn once: a chat is redrawn on every change, and the picture must not blink or be asked for again.)
+ const src = body.join("\n"), had = DIAGRAMS.get((isDark() ? "d:" : "l:") + src);
+ out.push(had === "fail" ? `
${esc(src)}
` : had ? `
` : `
`);
+ continue;
+ }
// ```details
: folded under one quiet line (細節 without a title); the inside is the page's Markdown.
if (lang === "details") { const title = t.replace(/^```\s*details/i, "").trim() || "細節"; out.push(`${esc(title)}
${pageMd(body.join("\n"), id, rev)}
`); continue; }
if (lang === "chart") { const html = chartMd(body); if (html) { out.push(html); continue; } }
@@ -3996,7 +4585,7 @@ function pageMd(text, id, rev) {
});
if (items.length) { out.push(``); continue; }
}
- out.push(`${esc(body.join("\n"))}
`); continue;
+ out.push(`${esc(body.join("\n"))}
`); continue;
}
const h = t.match(/^(#{1,6})\s+(.*)$/);
if (h) { const n = Math.min(h[1].length + 1, 4); out.push(`${inl(h[2])}`); i++; continue; }
@@ -4039,19 +4628,34 @@ function pageMd(text, id, rev) {
// The bots' computer: its live screen shown over the app (screen.html embedded), where you
// can also take over. Its ✕ posts a close; a back gesture closes it too.
let boxOpen = false;
-function openBox(control) {
- const b = bot(S.open) || S.bots.find((x) => x.primary) || {};
+// From 設定 › 電腦 (no chat open): whose screen — each bot has its own, plus the shared desktop.
+function pickBoxBot(control) {
+ const bots = S.bots.filter((b) => !b.members);
+ if (bots.length <= 1) return openBox(control);
+ sheet(control ? "接管哪個 Bot 的螢幕?" : "看哪個 Bot 的螢幕?", [...bots.map((b) => ({icon: "monitor", label: b.name + " 的螢幕", on: () => openBox(control, b.id)})), {icon: "monitor", label: "共用的桌面", on: () => openBox(control, 0)}]);
+}
+function openBox(control, which) {
+ const b = which === undefined ? (bot(S.open) || S.bots.find((x) => x.primary) || {}) : which ? bot(which) || {} : {};
const own = (b.computers || []).find((c) => c.kind === "own");
const at = S.relay ? "host=" + encodeURIComponent(S.host) : "lan=1";
boxOpen = true;
history.pushState({box: 1}, "");
- $("boxframe").src = "screen#" + at + "&name=" + encodeURIComponent(own ? own.name : "Bot 的電腦") + (b.id ? "&bot=" + b.id : "") + (control ? "&control=1" : "") + "&embed=1";
+ newBoxFrame("screen#" + at + "&name=" + encodeURIComponent(own ? own.name : "Bot 的電腦") + (b.id ? "&bot=" + b.id : "") + (control ? "&control=1" : "") + "&embed=1");
$("boxwrap").style.display = "block";
}
function closeBox() {
boxOpen = false;
$("boxwrap").style.display = "none";
- $("boxframe").src = "about:blank";
+ newBoxFrame("");
+}
+// A fresh frame each time, never a new address in the same one: an iframe that navigates adds
+// to the page's back history, and after the first open and close 返回 (and the screen's ✕) went
+// back inside the frame instead of closing it — the takeover screen stayed and could not be left.
+function newBoxFrame(url) {
+ const old = $("boxframe"), f = old.cloneNode(false);
+ f.removeAttribute("src");
+ if (url) f.src = url;
+ old.replaceWith(f);
}
window.addEventListener("message", (e) => {
if (e.origin !== location.origin || !e.data) return;
@@ -4067,11 +4671,11 @@ async function frames(run) {
try {
const r = await api(base() + "api/screen/mac", {raw: true});
if (S.frameRun !== run) return;
- if (!r.ok) { const v = await r.json().catch(() => ({})); $("stage").innerHTML = `${esc(v.error || "看不到畫面")}
`; $("screen-live").textContent = ""; await nap(1500); continue; }
+ if (!r.ok) { const v = await r.json().catch(() => ({})); $("stage").innerHTML = `${esc(v.error || "看不到畫面")}
`; $("screen-live").textContent = ""; macShowPad(); await nap(1500); continue; }
S.size = (r.headers.get("X-Size") || "0x0").split("x").map(Number);
const url = URL.createObjectURL(await safeBlob(r));
let img = $("stage").querySelector("img");
- if (!img) { $("stage").innerHTML = ""; img = document.createElement("img"); img.draggable = false; $("stage").appendChild(img); bindStage(img); }
+ if (!img) { $("stage").innerHTML = ""; img = document.createElement("img"); img.draggable = false; $("stage").appendChild(img); bindStage(img); img.onload = () => { img.onload = null; macShowPad(); }; }
img.src = url; if (lastUrl) URL.revokeObjectURL(lastUrl); lastUrl = url;
$("screen-live").innerHTML = `即時`;
await nap(700);
@@ -4083,25 +4687,131 @@ function point(img, e) {
const w = S.size[0] || img.naturalWidth, h = S.size[1] || img.naturalHeight;
return {x: Math.round((e.clientX - r.left) / r.width * w), y: Math.round((e.clientY - r.top) / r.height * h), cx: e.clientX - $("stage").getBoundingClientRect().left, cy: e.clientY - $("stage").getBoundingClientRect().top};
}
+// Without the touchpad: a tap clicks where it lands, a long press right-clicks, two quick taps
+// are a double click.
function bindStage(img) {
- let pressTimer = null, long = false;
- img.addEventListener("pointerdown", (e) => { long = false; pressTimer = setTimeout(() => { long = true; tap(img, e, "right"); }, 550); });
- img.addEventListener("pointerup", (e) => { clearTimeout(pressTimer); if (!long) tap(img, e, S.right ? "right" : "left"); });
+ let pressTimer = null, long = false, last = 0;
+ img.addEventListener("pointerdown", (e) => { if (MAC.padOn) return; long = false; pressTimer = setTimeout(() => { long = true; tap(img, e, "right"); }, 550); });
+ img.addEventListener("pointerup", (e) => {
+ clearTimeout(pressTimer);
+ if (MAC.padOn || long) return;
+ const t = Date.now();
+ if (t - last < 320) { const p = point(img, e); screenInput({kind: "click", x: p.x, y: p.y, count: 2, modifiers: MAC.mods ? MAC.mods.list() : []}); last = 0; return; }
+ last = t;
+ tap(img, e, "left");
+ });
img.addEventListener("pointercancel", () => clearTimeout(pressTimer));
- img.addEventListener("dblclick", (e) => { const p = point(img, e); screenInput({kind: "click", x: p.x, y: p.y, count: 2}); });
}
function tap(img, e, button) {
const p = point(img, e);
const d = document.createElement("div"); d.className = "tapdot"; d.style.left = p.cx + "px"; d.style.top = p.cy + "px"; $("stage").appendChild(d); setTimeout(() => d.remove(), 600);
- screenInput({kind: "click", x: p.x, y: p.y, button});
+ screenInput({kind: "click", x: p.x, y: p.y, button, modifiers: MAC.mods ? MAC.mods.list() : []});
+ MAC.mods?.used();
}
async function screenInput(body) { try { await api(base() + "api/screen/mac", {json: body}); } catch (e) { toast(e.message); } }
-document.querySelectorAll("[data-key]").forEach((b) => b.onclick = () => screenInput({kind: "key", key: b.dataset.key}));
-document.querySelectorAll("[data-scroll]").forEach((b) => b.onclick = () => screenInput({kind: "scroll", x: Math.round(S.size[0] / 2), y: Math.round(S.size[1] / 2), direction: b.dataset.scroll, amount: 5}));
-$("k-type").onclick = () => { $("typebar").classList.toggle("on"); if ($("typebar").classList.contains("on")) $("typein").focus(); };
-$("b-type").onclick = () => { const t = $("typein").value; if (!t) return; $("typein").value = ""; screenInput({kind: "type", text: t}); };
+
+// 虛擬觸控板 and the key bar on this Mac's screen (mobile/trackpad.js, shared with the bots'
+// computer): the pointer lives in the shown picture's pixels and is sent in the screenshot's.
+const MAC = {padOn: localStorage.getItem("anybot.pad") !== "0", pad: null, mods: null, T: null, path: null, moveAt: 0, moveTimer: 0};
+const MAC_KEY = {Delete: "forwarddelete", BackSpace: "backspace", Return: "return", PageUp: "pageup", PageDown: "pagedown", "[": "bracketleft", "]": "bracketright"};
+const macKey = (k) => MAC_KEY[k] || k.toLowerCase();
+function macShot(x, y) {
+ const img = $("stage").querySelector("img");
+ if (!img || !img.clientWidth) return {x: 0, y: 0};
+ const w = S.size[0] || img.naturalWidth, h = S.size[1] || img.naturalHeight;
+ return {x: Math.round(x / img.clientWidth * w), y: Math.round(y / img.clientHeight * h)};
+}
+function macPlace(x, y) {
+ const img = $("stage").querySelector("img");
+ if (!img) return;
+ const ir = img.getBoundingClientRect(), wr = $("mac-pad").getBoundingClientRect();
+ $("mac-ptr").style.left = (ir.left - wr.left + x) + "px";
+ $("mac-ptr").style.top = (ir.top - wr.top + y) + "px";
+}
+function macPress(key, extra = []) {
+ const list = [...new Set([...(MAC.mods ? MAC.mods.list() : []), ...extra])];
+ screenInput({kind: "key", key: [...list, macKey(key)].join("+")});
+ MAC.mods?.used();
+}
+async function macTools() {
+ if (!MAC.T) {
+ try { MAC.T = await import("./trackpad.js"); } catch (_) { MAC.padOn = false; renderMacBar(); return; }
+ const T = MAC.T;
+ MAC.mods = T.modState(() => renderMacBar());
+ MAC.pad = T.trackpad($("mac-pad"), {
+ bounds() { const img = $("stage").querySelector("img"); return img ? {w: img.clientWidth || 1, h: img.clientHeight || 1} : {w: 1, h: 1}; },
+ move(x, y) {
+ if (MAC.path) { const p = macShot(x, y), l = MAC.path[MAC.path.length - 1]; if (Math.hypot(p.x - l.x, p.y - l.y) > 10 && MAC.path.length < 80) MAC.path.push(p); return; }
+ // (At most every 150 ms, the last place always sent.)
+ clearTimeout(MAC.moveTimer);
+ const go = () => { MAC.moveAt = Date.now(); const p = macShot(x, y); screenInput({kind: "move", x: p.x, y: p.y}); };
+ if (Date.now() - MAC.moveAt > 150) go(); else MAC.moveTimer = setTimeout(go, 150);
+ },
+ down(x, y) { MAC.path = [macShot(x, y)]; },
+ up(x, y) {
+ const path = MAC.path || []; MAC.path = null;
+ path.push(macShot(x, y));
+ if (path.length >= 2) screenInput({kind: "drag", path, modifiers: MAC.mods.list()});
+ MAC.mods.used();
+ },
+ click(x, y, button, count) { const p = macShot(x, y); screenInput({kind: "click", x: p.x, y: p.y, button, count, modifiers: MAC.mods.list()}); MAC.mods.used(); },
+ scroll(x, y, dx, dy) { if (!dy) return; const p = macShot(x, y); screenInput({kind: "scroll", x: p.x, y: p.y, direction: dy > 0 ? "down" : "up", amount: Math.min(20, Math.abs(dy) * 2)}); },
+ show: macPlace,
+ });
+ $("mac-combos").innerHTML = T.COMBOS.mac.map(([name, ms, k], i) => ``).join("");
+ }
+ macShowPad();
+ renderMacBar();
+}
+function macShowPad() {
+ const on = MAC.padOn && !!MAC.pad && !!$("stage").querySelector("img");
+ $("mac-pad").classList.toggle("on", on);
+ $("mac-ptr").classList.toggle("on", on);
+ if (MAC.pad) MAC.pad.enabled = on;
+ if (on && !MAC.centered) { MAC.centered = true; MAC.pad.center(); macTip(); }
+}
+function macTip() {
+ const n = Number(localStorage.getItem("anybot.padTip") || 0);
+ if (n >= 3) return;
+ localStorage.setItem("anybot.padTip", String(n + 1));
+ $("mac-tip").innerHTML = "一指移動游標・點一下按・點兩下按住拖曳・兩指捲動・兩指點右鍵";
+ $("mac-tip").classList.add("on");
+ setTimeout(() => $("mac-tip").classList.remove("on"), 5000);
+}
+// 觸控板 | ⌘ ⌥ ⌃ ⇧ | Esc Tab ← ↑ ↓ → ⌫ Del ⏎ … | 快捷鍵 ⌨ 打字
+function renderMacBar() {
+ const T = MAC.T;
+ const b = (attrs, label, cls = "") => ``;
+ $("mac-bar").innerHTML = b('data-pad="1"', "觸控板", MAC.padOn ? "on" : "") + ''
+ + (T ? T.MODS.mac.map(([m, l]) => b(`data-mod="${m}"`, l, MAC.mods.get(m))).join("") + '' + T.KEYS.map(([k, l]) => b(`data-key="${k}"`, esc(l))).join("") + '' : "")
+ + (T ? b('data-combos="1"', "快捷鍵", $("mac-combos").classList.contains("on") ? "on" : "") : "")
+ + b('data-kb="1"', "⌨ 打字", $("typebar").classList.contains("on") ? "on" : "");
+}
+$("mac-bar").onclick = (e) => {
+ const t = e.target.closest("button");
+ if (!t) return;
+ if (t.dataset.pad) { MAC.padOn = !MAC.padOn; localStorage.setItem("anybot.pad", MAC.padOn ? "1" : "0"); macShowPad(); }
+ else if (t.dataset.mod) MAC.mods.tap(t.dataset.mod);
+ else if (t.dataset.key) macPress(t.dataset.key);
+ else if (t.dataset.combos) $("mac-combos").classList.toggle("on");
+ else if (t.dataset.kb) { $("typebar").classList.toggle("on"); if ($("typebar").classList.contains("on")) $("typein").focus(); }
+ renderMacBar();
+};
+$("mac-combos").onclick = (e) => {
+ const c = e.target.closest("[data-combo]");
+ if (!c || !MAC.T) return;
+ const [, ms, k] = MAC.T.COMBOS.mac[Number(c.dataset.combo)];
+ macPress(k, ms);
+ navigator.vibrate?.(8);
+};
+$("b-type").onclick = () => {
+ const t = $("typein").value; if (!t) return; $("typein").value = "";
+ // A modifier held and one letter typed: that shortcut (⌘, then c → ⌘C), not the letter.
+ if (MAC.mods && MAC.mods.list().length && [...t].length === 1) macPress(t);
+ else screenInput({kind: "type", text: t});
+};
$("typein").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); $("b-type").click(); } });
-$("k-right").onclick = () => { S.right = !S.right; $("k-right").textContent = "右鍵:" + (S.right ? "開" : "關"); };
+window.addEventListener("resize", () => { if (MAC.pad && $("mac-pad").classList.contains("on")) { const p = MAC.pad.pos; macPlace(p.x, p.y); } });
// ---------- 傳送: a file or a few words to another device of the account ----------
// The brain carries it (src/drops.rs): to a computer it lands in 下載/AnyBot (words: on its
diff --git a/mobile/screen.html b/mobile/screen.html
index 34dc527..5e1406b 100644
--- a/mobile/screen.html
+++ b/mobile/screen.html
@@ -66,8 +66,38 @@
background: #0e0e0e; border: 1px solid var(--line); border-radius: 10px; padding: 0 10px; outline: none;
}
#type input:focus { border-color: var(--accent); }
- .key-group { display: flex; gap: 4px; flex-wrap: wrap; }
- .key-group button { height: 28px; padding: 0 9px; border-radius: 8px; font-size: 12px; }
+ /* 虛擬觸控板: a layer over the picture that takes the fingers; the pointer drawn on it. */
+ #pad { position: absolute; inset: 0; z-index: 5; display: none; touch-action: none; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
+ #pad.on { display: block; }
+ #ptr { position: absolute; z-index: 6; width: 20px; height: 20px; margin: -2px 0 0 -3px; pointer-events: none; display: none; filter: drop-shadow(0 1px 2px rgba(0,0,0,0.6)); }
+ #ptr.on { display: block; }
+ #tip {
+ position: absolute; z-index: 7; left: 50%; bottom: 12px; transform: translateX(-50%); max-width: calc(100% - 24px);
+ background: rgba(30, 29, 27, 0.92); border: 1px solid var(--line); border-radius: 14px; padding: 9px 12px;
+ font-size: 12.5px; line-height: 1.6; color: var(--text); pointer-events: none; opacity: 0; transition: opacity 0.3s;
+ }
+ #tip.on { opacity: 1; }
+ #tip b { font-weight: 600; color: var(--accent); }
+ /* The key bar: modifiers you tap (once: the next key; twice: locked), and the keys a phone lacks. */
+ #bar {
+ display: none; gap: 6px; padding: 8px 10px; padding-bottom: max(8px, env(safe-area-inset-bottom));
+ background: var(--bar); border-top: 1px solid var(--line); overflow-x: auto; scrollbar-width: none; flex: none;
+ }
+ #bar::-webkit-scrollbar { display: none; }
+ #bar.on { display: flex; }
+ #bar button { height: 36px; min-width: 40px; padding: 0 10px; border-radius: 10px; flex: none; font-size: 13px; }
+ #bar .sep { width: 1px; background: var(--line); margin: 4px 2px; flex: none; }
+ #bar button.once { background: rgba(216, 131, 102, 0.22); border-color: var(--accent); color: var(--accent); }
+ #bar button.lock { background: var(--accent); border-color: var(--accent); color: #fff; }
+ #bar button.on { background: var(--text); border-color: var(--text); color: var(--bar); }
+ #combos {
+ display: none; grid-template-columns: repeat(3, 1fr); gap: 6px; padding: 10px; background: var(--bar);
+ border-top: 1px solid var(--line); max-height: 40vh; overflow-y: auto; flex: none;
+ }
+ #combos.on { display: grid; }
+ #combos button { height: auto; min-height: 48px; flex-direction: column; gap: 2px; border-radius: 12px; padding: 6px 4px; }
+ #combos button small { color: var(--dim); font-size: 11px; font-weight: 400; letter-spacing: 0.5px; }
+ body.has-bar #type { padding-bottom: 8px; }
@@ -77,25 +107,19 @@
Bot 的電腦
連線中…
-