5465 lines
434 KiB
HTML
5465 lines
434 KiB
HTML
<!doctype html>
|
||
<html lang="zh-Hant">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content">
|
||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||
<meta name="mobile-web-app-capable" content="yes">
|
||
<meta name="color-scheme" content="light dark">
|
||
<meta name="format-detection" content="telephone=no">
|
||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||
<meta name="apple-mobile-web-app-title" content="AnyBot">
|
||
<meta name="theme-color" content="#1e1d1b" media="(prefers-color-scheme: dark)">
|
||
<meta name="theme-color" content="#faf9f6" media="(prefers-color-scheme: light)">
|
||
<link rel="manifest" href="manifest.webmanifest">
|
||
<link rel="icon" href="icon.svg" type="image/svg+xml">
|
||
<link rel="icon" href="icon-192.png" type="image/png" sizes="192x192">
|
||
<link rel="apple-touch-icon" href="icon-180.png">
|
||
<title>AnyBot</title>
|
||
<style>
|
||
/* The desktop app's colours (src/theme.rs, from the original's stylesheet), as on a phone: the
|
||
sidebar is the home, the chat is pushed on top, 對話詳細資訊 and 設定 are pushed on that. */
|
||
:root{
|
||
--pane:#faf9f6;--chrome:#f7f6f2;--side:#f2f0eb;--elev:#fff;--hover:#25221f0d;--active:#25221f15;
|
||
--primary:#25221f;--on-primary:#fefcfa;--text:#25221f;--text2:#25221fb0;--text3:#25221f85;--text4:#25221f66;
|
||
--line:#25221f1a;--line2:#25221f14;--focus:#c06244;--accent:#c06244;--accent-ink:#a84f33;
|
||
--danger:#b42a2a;--ok:#2e7d3f;--warn:#b07f2e;
|
||
--bubble-user:#25221f;--bubble-user-ink:#fefcfa;--bubble-bot:#25221f0d;--card:#fff;--attention:#d9a441;--attention-bg:#f6ecd9;
|
||
--spec:#ffffff59;--shadow:0 2px 8px -1px #241f1a0d,0 1px 2px #241f1a08,0 0 0 1px #e0ddd40a;
|
||
/* 圖表色板(與桌面版 theme.rs chart_cat 同序): 一個暖家族轉色相,低飽和 */
|
||
--cat1:#c06244;--cat2:#4f6f92;--cat3:#3e7c77;--cat4:#8a7a33;--cat5:#8a5a78;--cat6:#7a746c;
|
||
--grid:#25221f10;--up:#2e7d3f;
|
||
--font:-apple-system,BlinkMacSystemFont,"SF Pro Text","PingFang TC","Noto Sans TC","Segoe UI",system-ui,sans-serif;
|
||
--mono:ui-monospace,SFMono-Regular,Menlo,monospace;
|
||
--safe-b:env(safe-area-inset-bottom);--safe-t:env(safe-area-inset-top);
|
||
/* One design spec for desktop and phone (src/theme.rs has the same names and numbers). */
|
||
--fs-caption:12px;--fs-small:13px;--fs-ui:14px;--fs-read:16px;--fs-h3:18px;--fs-h2:22px;--fs-h1:28px;
|
||
--lh-read:1.7;
|
||
--sp-1:4px;--sp-2:8px;--sp-3:12px;--sp-4:16px;--sp-5:24px;--sp-6:32px;
|
||
--r-s:6px;--r-m:10px;--r-l:14px;
|
||
/* Answers and pages read in the same calm sans as the interface (Apple's way; they were in a serif). */
|
||
--font-read:var(--font);
|
||
/* Floating shadows, the sheet's backdrop, the black stage under a screen, words on a strong fill. */
|
||
--shade:#00000024;--scrim:#00000066;--stage:#000;--on-stage:#ffffff99;--on-color:#fff;
|
||
}
|
||
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){
|
||
--pane:#1e1d1b;--chrome:#1b1a18;--side:#191817;--elev:#262422;--hover:#f2f0eb0f;--active:#f2f0eb14;
|
||
--primary:#f2f0eb;--on-primary:#1e1d1b;--text:#f2f0eb;--text2:#f2f0eba8;--text3:#f2f0eb8a;--text4:#f2f0eb66;
|
||
--line:#f2f0eb1a;--line2:#f2f0eb14;--focus:#d88366;--accent:#d88366;--accent-ink:#e2977d;
|
||
--danger:#e26e6e;--bubble-user:#f2f0eb2e;--bubble-user-ink:#f2f0eb;--bubble-bot:#f2f0eb0a;--card:#262422;--attention:#d9a441;--attention-bg:#38311f;
|
||
--spec:#ffffff0d;--shadow:none;
|
||
--cat1:#d88366;--cat2:#7f9dc0;--cat3:#6fae9c;--cat4:#c2b060;--cat5:#b78aa4;--cat6:#a09a92;--grid:#f2f0eb14;--up:#6fb97d;
|
||
--shade:#00000073;--scrim:#0000008c;--stage:#000;--on-stage:#ffffff99;--on-color:#fff;
|
||
}}
|
||
:root[data-theme="dark"]{
|
||
--pane:#1e1d1b;--chrome:#1b1a18;--side:#191817;--elev:#262422;--hover:#f2f0eb0f;--active:#f2f0eb14;
|
||
--primary:#f2f0eb;--on-primary:#1e1d1b;--text:#f2f0eb;--text2:#f2f0eba8;--text3:#f2f0eb8a;--text4:#f2f0eb66;
|
||
--line:#f2f0eb1a;--line2:#f2f0eb14;--focus:#d88366;--accent:#d88366;--accent-ink:#e2977d;
|
||
--danger:#e26e6e;--bubble-user:#f2f0eb2e;--bubble-user-ink:#f2f0eb;--bubble-bot:#f2f0eb0a;--card:#262422;--attention:#d9a441;--attention-bg:#38311f;
|
||
--spec:#ffffff0d;--shadow:none;
|
||
--cat1:#d88366;--cat2:#7f9dc0;--cat3:#6fae9c;--cat4:#c2b060;--cat5:#b78aa4;--cat6:#a09a92;--grid:#f2f0eb14;--up:#6fb97d;
|
||
--shade:#00000073;--scrim:#0000008c;--stage:#000;--on-stage:#ffffff99;--on-color:#fff;
|
||
}
|
||
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
|
||
html,body{margin:0;height:100%;background:var(--pane);color:var(--text);font:var(--fs-ui)/1.47 var(--font);-webkit-font-smoothing:antialiased;overscroll-behavior:none}
|
||
button{font:inherit;color:inherit;background:none;border:0;padding:0;cursor:pointer}
|
||
input,textarea,select{font:inherit;color:var(--text)}
|
||
a{color:var(--accent-ink)}
|
||
.ic{flex:none;vertical-align:-3px}
|
||
.app{height:100dvh;display:flex;flex-direction:column;overflow:hidden}
|
||
.view{flex:1;display:none;flex-direction:column;min-height:0;background:var(--pane)}
|
||
.view.on{display:flex}
|
||
/* A message that just arrived slides up into place (screens slide in with in-fwd / in-back). */
|
||
@keyframes msgIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
|
||
.m.fresh{animation:msgIn .18s ease-out}
|
||
@media (prefers-reduced-motion:reduce){.m.fresh{animation:none}}
|
||
.scroll{flex:1;overflow-y:auto;-webkit-overflow-scrolling:touch;min-height:0}
|
||
|
||
/* ---- bars ---- */
|
||
.bar{display:flex;align-items:center;gap:4px;padding:calc(var(--safe-t) + 4px) 6px 4px;min-height:52px;background:var(--pane);flex:none}
|
||
.bar h1{font-size:var(--fs-h3);font-weight:600;margin:0;flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.bar h1 small{font-size:var(--fs-caption);font-weight:400;color:var(--text3);margin-left:6px}
|
||
.ib{width:44px;height:44px;border-radius:var(--r-m);display:grid;place-items:center;color:var(--text2);flex:none}
|
||
.ib:active,.ib.on{background:var(--hover)}
|
||
.ib .ic{vertical-align:0}
|
||
.island{flex:1;min-width:0;display:flex;align-items:center;gap:9px;height:40px;padding:0 10px 0 4px;border-radius:var(--r-m)}
|
||
.island:active{background:var(--hover)}
|
||
.island .t{min-width:0;flex:1;text-align:left}
|
||
.island .n{font-size:var(--fs-ui);font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:flex;align-items:center;gap:4px}
|
||
.island .s{font-size:var(--fs-caption);color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.island .s.busy{color:var(--ok)}
|
||
.island .s.wait{color:var(--warn)}
|
||
|
||
/* ---- avatars ---- */
|
||
.av{width:36px;height:36px;flex:none;position:relative;display:grid;place-items:center}
|
||
.av svg{width:100%;height:100%}
|
||
.av.lg{width:64px;height:64px}
|
||
.av.sm{width:30px;height:30px}
|
||
.av .dot{position:absolute;right:-1px;bottom:-1px;width:11px;height:11px;border-radius:50%;border:2px solid var(--side)}
|
||
.dot.busy{background:var(--ok)}.dot.wait{background:var(--warn)}.dot.unread{background:var(--accent)}.dot.err{background:var(--danger)}
|
||
|
||
/* ---- home = the sidebar ---- */
|
||
#v-home{background:var(--side)}
|
||
#v-home .bar{background:var(--side);border-bottom:0}
|
||
.me{width:32px;height:32px;border-radius:50%;background:var(--active);display:grid;place-items:center;font-size:var(--fs-small);font-weight:600;color:var(--text2);flex:none}
|
||
.searchbox{margin:0 12px 6px;display:none;align-items:center;gap:8px;background:var(--hover);border-radius:var(--r-m);padding:0 10px;height:36px}
|
||
.searchbox.on{display:flex}
|
||
.searchbox .ib{width:36px;height:36px}
|
||
.searchbox input{flex:1;border:0;background:none;outline:0;font-size:var(--fs-ui);min-width:0}
|
||
.quick{display:flex;gap:8px;padding:2px 12px 8px;overflow-x:auto;scrollbar-width:none}
|
||
.quick::-webkit-scrollbar{display:none}
|
||
.quick button{flex:none;display:flex;align-items:center;gap:6px;height:36px;padding:0 14px;border-radius:999px;background:var(--elev);font-size:var(--fs-small);color:var(--text2)}
|
||
.quick button b{font-weight:600;color:var(--text)}
|
||
.quick button .st{width:7px;height:7px;border-radius:50%}
|
||
.sec{display:flex;align-items:center;gap:6px;padding:14px 18px 4px;font-size:var(--fs-caption);font-weight:600;color:var(--text3)}
|
||
.sec .ic{color:var(--text3)}
|
||
.sec .n{font-weight:400}
|
||
.sec button{margin-left:auto;color:var(--text3);font-size:var(--fs-caption);font-weight:400;display:flex;align-items:center;gap:2px}
|
||
.rows{padding:0 8px}
|
||
.row{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:var(--r-m);min-height:56px;position:relative}
|
||
.row:active,.row.sel{background:var(--active)}
|
||
.row .mid{flex:1;min-width:0}
|
||
.row .nm{font-size:var(--fs-ui);font-weight:500;display:flex;align-items:center;gap:6px;min-width:0}
|
||
.row .nm span.t{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.row .pv{font-size:var(--fs-small);color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.row .pv.busy{color:var(--ok)}.row .pv.wait{color:var(--warn)}
|
||
.row .tm{font-size:var(--fs-caption);color:var(--text4);align-self:flex-start;margin-top:4px;flex:none}
|
||
.row .more{width:44px;height:44px;margin-right:-8px;border-radius:var(--r-m);display:grid;place-items:center;color:var(--text3);flex:none}
|
||
.pill{font-size:var(--fs-caption);font-weight:500;padding:1px 7px;border-radius:999px;background:var(--active);color:var(--text2);flex:none}
|
||
.pill.acc{background:color-mix(in srgb,var(--accent) 16%,transparent);color:var(--accent-ink)}
|
||
.pill.ok{background:color-mix(in srgb,var(--ok) 16%,transparent);color:var(--ok)}
|
||
.pill.warn{background:color-mix(in srgb,var(--warn) 18%,transparent);color:var(--warn)}
|
||
.empty{padding:40px 24px;text-align:center;color:var(--text3);font-size:var(--fs-ui);line-height:1.6}
|
||
|
||
/* ---- chat ---- */
|
||
#v-chat{position:relative}
|
||
.msgs{padding:12px 14px 8px;display:flex;flex-direction:column;gap:2px;max-width:760px;margin:0 auto;width:100%}
|
||
.dsep{align-self:center;font-size:var(--fs-caption);color:var(--text3);padding:12px 0 6px}
|
||
.m{display:flex;flex-direction:column;max-width:100%;margin:3px 0;position:relative}
|
||
.m.user{align-items:flex-end}
|
||
.m.bot{align-items:flex-start}
|
||
.bub{max-width:min(86%,560px);padding:7px 12px;border-radius:var(--r-l);font-size:var(--fs-read);line-height:1.5;word-wrap:break-word;overflow-wrap:anywhere;
|
||
background-image:linear-gradient(to bottom,var(--spec),transparent);box-shadow:inset 0 .5px 0 var(--spec),inset 0 0 0 .5px var(--line2)}
|
||
/* The chat takes its bot's colour (--bot, set when the chat opens; a black bot keeps the plain bubble). */
|
||
.m.user .bub{background-color:var(--bot,var(--bubble-user));color:var(--bot-ink,var(--bubble-user-ink));white-space:pre-wrap;border-radius:var(--r-l) var(--r-l) var(--r-s) var(--r-l)}
|
||
.quiet .m.user .bub{background-color:var(--hover);color:var(--text)}
|
||
.m.user.woke .bub{background-color:var(--hover);color:var(--text)}
|
||
details.dt{margin:var(--sp-3) 0}details.dt>summary{font-size:var(--fs-small);color:var(--text2);cursor:pointer;list-style:none}
|
||
details.dt>summary::-webkit-details-marker{display:none}details.dt>summary::before{content:"▸ "}details.dt[open]>summary::before{content:"▾ "}
|
||
details.dt>.dt-in{padding-left:var(--sp-4);margin-top:var(--sp-2)}
|
||
/* The bot's words sit on the page like a document; only an error gets a bubble. */
|
||
.m.bot .bub{background-color:transparent;padding:0;max-width:100%;border-radius:0;box-shadow:none;background-image:none}
|
||
.m.bot.err .bub{color:var(--danger);background-color:var(--bubble-bot);padding:7px 12px;border-radius:var(--r-l);font-family:var(--font);font-size:var(--fs-ui);line-height:1.5}
|
||
/* ---- Reading: the bot's answers and pages read like a document (Claude's warmth, Notion's
|
||
clarity) — serif text, quiet blocks. The person's own messages and the interface stay sans. ---- */
|
||
.m.bot .bub,.page{font-family:var(--font-read);font-size:var(--fs-read);line-height:var(--lh-read)}
|
||
:is(.bub,.page,.tk-a)>:first-child{margin-top:0}
|
||
:is(.bub,.page,.tk-a) p{margin:0 0 .75em}
|
||
:is(.bub,.page,.tk-a) :is(ul,ol){margin:0 0 .75em;padding-left:1.4em}
|
||
:is(.bub,.page,.tk-a) li{margin:0 0 6px}
|
||
:is(.bub,.page,.tk-a) li:last-child{margin-bottom:0}
|
||
:is(.bub,.page,.tk-a) li>:is(ul,ol,p,blockquote,pre,.tw){margin:.35em 0 0}
|
||
:is(.bub,.page,.tk-a) li.task{list-style:none;margin-left:-1.2em}
|
||
:is(.bub,.page) :is(h2,h3,h4){font-family:var(--font-read);font-weight:600;line-height:1.35;color:var(--text)}
|
||
.bub h2{font-size:var(--fs-h3);margin:1.2em 0 .4em}
|
||
.bub :is(h3,h4){font-size:var(--fs-read);margin:1.1em 0 .3em}
|
||
.tk-a :is(h2,h3,h4){font-size:var(--fs-ui);margin:.8em 0 .3em}
|
||
:is(.bub,.page,.tk-a) code{font-family:var(--mono);font-size:var(--fs-small);background:var(--hover);padding:1px 5px;border-radius:var(--r-s)}
|
||
:is(.bub,.page,.tk-a) pre{margin:0 0 .75em;padding:var(--sp-3) var(--sp-4);border-radius:var(--r-m);background:var(--hover);overflow-x:auto;font:var(--fs-small)/1.55 var(--mono)}
|
||
/* 複製程式碼: a small button on each code block (the whole message's 複製 is in its menu). */
|
||
pre.cb{position:relative}
|
||
pre.cb .cpy{position:absolute;top:4px;right:4px;width:30px;height:30px;border-radius:var(--r-s);display:grid;place-items:center;color:var(--text3);background:var(--elev);opacity:.85}
|
||
:is(.bub,.page,.tk-a) pre code{background:none;padding:0;border-radius:0;font:inherit}
|
||
:is(.bub,.page,.tk-a) blockquote{margin:0 0 .75em;padding-left:var(--sp-3);border-left:2px solid var(--line);color:var(--text2)}
|
||
:is(.bub,.page,.tk-a) hr{border:0;border-top:1px solid var(--line);margin:var(--sp-5) 0}
|
||
/* Tables: no vertical lines, no stripes — a hairline under the header and under each row;
|
||
numbers line up on the right. */
|
||
:is(.bub,.page,.tk-a) .tw{overflow-x:auto;margin:0 0 .75em}
|
||
:is(.bub,.page,.tk-a) table{border-collapse:collapse;font-family:var(--font);font-size:var(--fs-ui);line-height:1.5}
|
||
:is(.bub,.page,.tk-a) :is(th,td){border:0;border-bottom:1px solid var(--line2);padding:var(--sp-2) var(--sp-3);text-align:left;vertical-align:top}
|
||
:is(.bub,.page,.tk-a) th{font-size:var(--fs-small);font-weight:600;color:var(--text2);background:none;border-bottom-color:var(--line)}
|
||
:is(.bub,.page,.tk-a) :is(th,td).num{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
|
||
/* Call-outs ([!NOTE]…, the page's 結論): one quiet tint for every kind; only the icon says which. */
|
||
:is(.bub,.page,.tk-a) .call{margin:0 0 .75em;padding:var(--sp-3) var(--sp-4);border-radius:var(--r-m);background:var(--hover)}
|
||
.call .ct{display:flex;align-items:center;gap:6px;font-family:var(--font);font-size:var(--fs-small);font-weight:600;color:var(--text2);margin-bottom:var(--sp-1)}
|
||
/* (k-…: a plain "note" class would also pick up the app's .note look.) */
|
||
.call.k-note .ct .ic{color:var(--cat2)}.call.k-tip .ct .ic{color:var(--ok)}.call.k-warning .ct .ic{color:var(--warn)}
|
||
.call.k-important .ct .ic,.call.k-verdict .ct .ic{color:var(--accent)}
|
||
:is(.bub,.page,.tk-a) :is(p,ul,ol,pre,blockquote,.tw,.call,hr,.stats,.chartcard):last-child{margin-bottom:0}
|
||
.m.user .bub a{color:inherit;text-decoration:underline}
|
||
.who{font-size:var(--fs-caption);color:var(--text3);margin:6px 0 2px 4px}
|
||
.tag{font-size:var(--fs-caption);color:var(--text3);margin:4px 4px 2px;display:flex;align-items:center;gap:4px}
|
||
.meta{font-size:var(--fs-caption);color:var(--text4);margin:3px 6px 0;display:flex;align-items:center;gap:6px;flex-wrap:wrap}
|
||
.meta button{color:var(--text3);display:grid;place-items:center;width:36px;height:36px;border-radius:var(--r-m)}
|
||
.meta button:active{background:var(--hover)}
|
||
.reacts{display:flex;gap:4px;flex-wrap:wrap;margin:3px 4px 0}
|
||
.reacts button{font-size:var(--fs-small);padding:1px 8px;min-height:28px;border-radius:999px;background:var(--hover)}
|
||
.quote{font-size:var(--fs-small);color:var(--text2);border-left:2px solid var(--line);padding-left:8px;margin:0 0 4px;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;white-space:normal}
|
||
/* steps (the desktop's outline rows) */
|
||
.steps{display:flex;flex-direction:column;gap:4px;margin:4px 0;max-width:min(92%,560px);width:100%}
|
||
.step,.fold{border-radius:var(--r-m);background:var(--hover);font-size:var(--fs-small);overflow:hidden}
|
||
.step>.h,.fold{display:flex;align-items:center;gap:7px;padding:7px 10px;min-height:34px;width:100%;text-align:left}
|
||
.step .l{font-weight:600;flex:none;max-width:45%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.step .d{color:var(--text3);flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.step .chev{color:var(--text4);transition:transform .15s}
|
||
.step.open .chev{transform:rotate(90deg)}
|
||
.step .body{display:none;padding:0 10px 9px;border-top:.5px solid var(--line2)}
|
||
.step.open .body{display:block}
|
||
.step .body pre{margin:8px 0 0;white-space:pre-wrap;word-break:break-word;font:var(--fs-caption)/1.5 var(--mono);color:var(--text2);max-height:260px;overflow:auto}
|
||
.step .body .k{font-size:var(--fs-caption);color:var(--text3);margin-top:8px}
|
||
.st-i{display:grid;place-items:center;width:16px;color:var(--text3)}
|
||
.step.done .st-i{color:var(--ok)}.step.failed .st-i{color:var(--danger)}.step.waiting .st-i{color:var(--warn)}.step.running .st-i{color:var(--accent)}
|
||
.step.running .st-i svg{animation:spin 1.2s linear infinite}
|
||
@keyframes spin{to{transform:rotate(360deg)}}
|
||
.fold{color:var(--text2)}
|
||
.fold .ic:last-child{margin-left:auto;color:var(--text4)}
|
||
.typing{display:flex;gap:4px;padding:11px 14px;border-radius:var(--r-l);background:var(--bubble-bot);width:fit-content}
|
||
.typing i{width:5px;height:5px;border-radius:50%;background:var(--text3);animation:blink 1.2s infinite}
|
||
.typing i:nth-child(2){animation-delay:.2s}.typing i:nth-child(3){animation-delay:.4s}
|
||
@keyframes blink{0%,80%,100%{opacity:.3}40%{opacity:1}}
|
||
.working{display:flex;align-items:center;gap:8px;margin:6px 0;max-width:100%}
|
||
.working[data-wturn]{cursor:pointer}
|
||
.presence{font-size:var(--fs-small);color:var(--text3);margin:6px 4px;min-width:0;overflow-wrap:anywhere;background:linear-gradient(90deg,var(--text3) 30%,var(--text) 50%,var(--text3) 70%);background-size:200% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:shimmer 2s linear infinite}
|
||
@keyframes shimmer{to{background-position:-200% 0}}
|
||
.summary{align-self:stretch;margin:8px 0;padding:10px 12px;border-radius:var(--r-m);background:var(--hover);font-size:var(--fs-small);color:var(--text2)}
|
||
.summary b{display:flex;align-items:center;gap:6px;color:var(--text);font-weight:500}
|
||
.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}
|
||
.talk .tk-h b{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||
.talk .av.xs{width:18px;height:18px;display:inline-flex}.talk .av.xs svg{width:18px;height:18px}
|
||
.talk .tk-q{color:var(--text2);margin-top:4px;white-space:pre-wrap;overflow-wrap:anywhere}
|
||
.talk .tk-st{display:flex;gap:5px;align-items:center;color:var(--text2);font-size:var(--fs-small);margin-top:6px;min-width:0;overflow-wrap:anywhere}.talk .tk-st.err{color:var(--danger)}
|
||
.talk .tk-ok{display:flex;gap:5px;align-items:center;color:var(--ok);font-size:var(--fs-small);margin-top:6px}.talk .tk-a{margin-top:2px;min-width:0;max-width:100%;overflow-wrap:anywhere}
|
||
/* Answers in these cards are markdown: code and tables scroll inside, never past the card. */
|
||
.talk .tk-go{color:var(--text3);font-size:var(--fs-caption);margin-top:6px;padding:0}
|
||
.talk.branch .tk-h span{margin:0 2px 0 0}.br-log{margin-top:6px;color:var(--text3);font-size:var(--fs-caption)}.br-log summary{cursor:pointer}
|
||
.card,.pcard,.filec{border-radius:var(--r-l);background:none;box-shadow:inset 0 0 0 .5px var(--line);max-width:min(92%,420px);width:100%;margin:4px 0;overflow:hidden}
|
||
.card{padding:10px 12px;font-size:var(--fs-small)}
|
||
.card .t{font-weight:600;font-size:var(--fs-ui)}.card .s{color:var(--text3);margin-bottom:4px}
|
||
.card .r{display:flex;justify-content:space-between;gap:10px;padding:3px 0;border-top:.5px solid var(--line2)}
|
||
.card .r span:first-child{color:var(--text3)}
|
||
.pcard .top{padding:12px 14px 6px}
|
||
.pcard .top .t{font-weight:600;margin-bottom:4px}
|
||
.pcard .top .l{font-size:var(--fs-small);color:var(--text2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.pcard .foot{display:flex;align-items:center;gap:10px;padding:9px 14px;border-top:.5px solid var(--line2)}
|
||
.pcard .foot .n{font-size:var(--fs-small);font-weight:500}.pcard .foot .x{font-size:var(--fs-caption);color:var(--text3)}
|
||
.filec{display:flex;align-items:center;gap:8px;padding:8px 10px;min-width:180px;width:auto;text-decoration:none;color:var(--text)}
|
||
.filec .fn{font-size:var(--fs-small);font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.attimg{max-width:min(78%,320px);margin:4px 0;border-radius:var(--r-l);overflow:hidden;box-shadow:inset 0 0 0 .5px var(--line)}
|
||
.attimg img{display:block;width:100%;max-height:320px;object-fit:cover}
|
||
.attimg .wait{padding:20px;font-size:var(--fs-caption);color:var(--text3)}
|
||
/* 交付確認: one quiet mark under a file the bot handed over (✓ in the chat, ✓✓ shown on a device, accent once opened). */
|
||
.dlv{display:inline-flex;align-items:center;background:none;border:0;padding:2px 6px;margin:-2px 0 0;min-height:24px;color:var(--text3)}
|
||
.dlv .ic+.ic{margin-left:-7px}.dlv.opened{color:var(--accent)}
|
||
.dlv-list{padding:0 16px 12px}.dlv-list .r{display:flex;gap:8px;align-items:baseline;padding:8px 0;border-top:.5px solid var(--line);font-size:var(--fs-small)}
|
||
.dlv-list .r b{font-weight:600}.dlv-list .r .w{color:var(--text3);margin-left:auto;white-space:nowrap}.dlv-list .r.failed span{color:var(--danger)}
|
||
/* 完成宣稱關卡: a quiet 「未驗證」 under a reply AnyBot couldn't verify (tap: why). */
|
||
.unv{display:inline-flex;align-items:center;gap:4px;align-self:flex-start;background:none;border:0;padding:2px 6px;margin:2px 0 0;min-height:24px;color:var(--text3);font-size:var(--fs-caption)}
|
||
.plink,.flink{cursor:pointer;color:var(--accent-ink);text-decoration:underline;text-decoration-color:color-mix(in srgb,var(--accent-ink) 40%,transparent)}
|
||
/* empty chat */
|
||
.intro{display:flex;flex-direction:column;align-items:center;text-align:center;padding:36px 16px 10px;gap:6px}
|
||
.intro .hi{font-size:var(--fs-h2);font-weight:600;margin-top:8px}
|
||
.intro .sub{font-size:var(--fs-ui);color:var(--text3)}
|
||
.sugs{display:flex;flex-direction:column;gap:6px;padding:14px 16px;max-width:520px;margin:0 auto;width:100%}
|
||
.sug{display:flex;align-items:center;gap:12px;padding:11px 12px;min-height:52px;border-radius:var(--r-m);background:var(--elev);text-align:left}
|
||
.sug .ic{color:var(--text2)}
|
||
.sug .tt{font-size:var(--fs-ui);font-weight:500}.sug .dd{font-size:var(--fs-caption);color:var(--text3)}
|
||
/* the dock: approvals, queued steering, attachments, the composer */
|
||
/* --kb: the iOS keyboard floats over the page; the script measures it and lifts the composer. */
|
||
.dock{flex:none;padding:6px 10px calc(var(--safe-b) + 8px + var(--kb,0px));background:linear-gradient(to bottom,transparent,var(--chrome) 40%)}
|
||
/* 需要你: yellow is the one colour for what waits for the person. */
|
||
/* Tall cards (long reasons, many choices) scroll inside the card: the composer stays on screen. */
|
||
.ask{max-width:560px;margin:0 auto 8px;padding:14px 16px;border-radius:var(--r-l);background:var(--attention-bg);box-shadow:inset 0 0 0 1px var(--attention);max-height:min(48dvh,420px);overflow-y:auto;overscroll-behavior:contain}
|
||
.ask .q{font-weight:600;font-size:var(--fs-ui)}
|
||
.ask .why{font-size:var(--fs-small);color:var(--text2);margin:4px 0 10px;white-space:pre-wrap;overflow-wrap:anywhere}
|
||
.ask .thumb{width:100%;border-radius:var(--r-m);margin:2px 0 10px;display:block;background:var(--hover);min-height:60px}
|
||
.ask .btns{display:flex;flex-wrap:wrap;gap:8px}
|
||
.ask .all{display:block;margin-top:10px;font-size:var(--fs-small);color:var(--text3)}
|
||
/* 問題卡: one question at a time — choices to tap, a field for your own answer */
|
||
.ask .asknum{font-size:var(--fs-caption);color:var(--text2);margin-bottom:2px}
|
||
.ask .opt{display:flex;align-items:center;gap:10px;width:100%;min-height:44px;margin:0 0 6px;padding:8px 12px;border:0;border-radius:var(--r-m);background:var(--elev);box-shadow:inset 0 0 0 1px var(--line);color:var(--text);font:inherit;font-size:var(--fs-ui);text-align:left}
|
||
.ask .opt.on{box-shadow:inset 0 0 0 2px var(--text)}
|
||
.ask .opt i{flex:none;width:18px;height:18px;border-radius:50%;box-shadow:inset 0 0 0 1.5px var(--text3)}
|
||
.ask .opt.many i{border-radius:var(--r-s)}
|
||
.ask .opt.on i{background:var(--text);box-shadow:none;position:relative}
|
||
.ask .opt.on i::after{content:"";position:absolute;left:6px;top:2.5px;width:4px;height:9px;border:solid var(--elev);border-width:0 2px 2px 0;transform:rotate(45deg)}
|
||
.ask .own{display:block;width:100%;box-sizing:border-box;min-height:44px;margin:0 0 10px;padding:8px 12px;border:0;border-radius:var(--r-m);background:var(--elev);box-shadow:inset 0 0 0 1px var(--line);color:var(--text);font:inherit;font-size:var(--fs-read)}
|
||
.ask .btn[disabled]{opacity:.45}
|
||
.btn{height:40px;padding:0 16px;border-radius:999px;background:var(--hover);font-weight:500;font-size:var(--fs-ui);display:inline-flex;align-items:center;justify-content:center;gap:6px}
|
||
:focus-visible{outline:2px solid var(--focus);outline-offset:2px}
|
||
.btn.main{background:var(--primary);color:var(--on-primary)}
|
||
.btn.no{color:var(--danger)}
|
||
.btn.sm{height:34px;padding:0 12px;font-size:var(--fs-small);border-radius:999px}
|
||
.btn:disabled{opacity:.45}
|
||
/* 目標 and 計畫 while they are on: one row of small chips (no line each); a tap opens that one's line below. */
|
||
.modes{max-width:560px;margin:0 auto 6px;display:flex;gap:6px}
|
||
.modes:empty{display:none}
|
||
.mode{position:relative;display:inline-flex;align-items:center;gap:4px;height:28px;padding:0 9px;border-radius:999px;background:var(--hover);font-size:var(--fs-small);color:var(--text2)}
|
||
/* (28 px to look at, 44 px to tap.) */
|
||
.mode::after{content:"";position:absolute;inset:-8px -2px}
|
||
.mode.on .ic{color:var(--accent)}
|
||
.mode.open{box-shadow:inset 0 0 0 1px var(--text3)}
|
||
/* 問題卡: in the chat, after the newest message (it scrolls with it), as tall as its content. */
|
||
#askq{padding:0 14px}
|
||
#askq .ask{max-height:none;overflow:visible;margin:4px auto 14px}
|
||
.goalbar{max-width:560px;margin:0 auto 6px;display:flex;align-items:center;gap:8px;font-size:var(--fs-small);color:var(--text2);background:var(--hover);border-radius:var(--r-m);padding:5px 6px 5px 11px}
|
||
.goalbar .t{flex:1;min-width:0;display:flex;align-items:center;gap:6px}
|
||
.goalbar .t span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||
.goalbar.on .t .ic{color:var(--accent)}
|
||
.goalbar button{flex:none;font-size:var(--fs-small);color:var(--text2);padding:4px 8px;border-radius:var(--r-s)}
|
||
/* 計畫 (/plan): the plan handed in, as a card — waiting on you (accent edge), followed (its steps tick), or past. */
|
||
.card.plan .t{display:flex;align-items:center;gap:6px}.card.plan .t .st{margin-left:auto;font-weight:400;font-size:var(--fs-small);color:var(--text3)}
|
||
.card.plan.wait{box-shadow:inset 0 0 0 1px var(--accent)}.card.plan.wait .t .st{color:var(--accent)}
|
||
.card.plan .sum{margin:4px 0 2px;color:var(--text)}.card.plan.past .sum{color:var(--text2)}
|
||
.card.plan ol{margin:6px 0 0;padding-left:22px}.card.plan li{padding:2px 0}.card.plan li::marker{color:var(--text3)}
|
||
.card.plan li .d{display:block;color:var(--text3);font-size:var(--fs-small)}.card.plan li.done{color:var(--text3);list-style-type:"✓ "}.card.plan li.now{list-style-type:"▸ "}.card.plan li.now::marker{color:var(--accent)}.card.plan li.skip{color:var(--text3);text-decoration:line-through;list-style-type:"– "}
|
||
.card.plan .x{margin-top:6px;color:var(--text2);font-size:var(--fs-small)}
|
||
.msgs .note{align-self:center;display:flex;gap:6px;max-width:min(560px,100%);margin:6px 0;padding:7px 12px;border-radius:var(--r-m);background:var(--hover);color:var(--text2)}
|
||
.msgs .note .ic{flex:none;margin-top:2px;color:var(--text3)}
|
||
.queued{max-width:560px;margin:0 auto 6px;font-size:var(--fs-small);color:var(--text2);background:var(--hover);border-radius:var(--r-m);padding:7px 11px;overflow-wrap:anywhere}
|
||
.chips{display:flex;gap:6px;flex-wrap:wrap;max-width:760px;margin:0 auto}
|
||
.chip{display:inline-flex;align-items:center;gap:5px;font-size:var(--fs-small);padding:4px 6px 4px 10px;border-radius:999px;background:var(--elev);margin-bottom:6px;max-width:100%}
|
||
.chip span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:180px}
|
||
.chip button{display:grid;place-items:center;width:28px;height:28px;margin:-4px -2px;border-radius:50%;color:var(--text3)}
|
||
/* 記憶: the composer's suggestions, the tag under a message, the memory tab */
|
||
.memchips{display:flex;gap:6px;flex-wrap:nowrap;overflow-x:auto;scrollbar-width:none;align-items:center;max-width:760px;margin:0 auto}
|
||
.memchips::-webkit-scrollbar{display:none}
|
||
.memchips>*{flex:none}
|
||
.memchips:not(:empty){margin-bottom:6px}
|
||
.memchips .lbl{font-size:var(--fs-caption);color:var(--text3);display:inline-flex;gap:4px;align-items:center}
|
||
.mchip{font-size:var(--fs-small);padding:4px 10px;border-radius:999px;box-shadow:inset 0 0 0 .5px var(--line);color:var(--text2);max-width:220px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.mchip.on{background:color-mix(in srgb,var(--accent) 14%,transparent);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--accent) 55%,transparent);color:var(--text)}
|
||
.slash{max-width:760px;margin:0 auto 6px;padding:4px;max-height:min(272px,38vh);overflow-y:auto;border-radius:var(--r-l);background:var(--elev);box-shadow:0 6px 24px -6px var(--shade)}
|
||
.slash:empty{display:none}
|
||
.slash .hd{font-size:var(--fs-caption);color:var(--text3);padding:6px 10px 4px}
|
||
.slash button{display:flex;align-items:center;gap:8px;width:100%;min-height:44px;padding:6px 10px;border-radius:var(--r-m);text-align:left}
|
||
.slash button.on{background:var(--active)}
|
||
.slash b{flex:none;max-width:62%;font-size:var(--fs-ui);font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.slash span{min-width:0;font-size:var(--fs-small);color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.memtok{font-size:var(--fs-caption);color:var(--text3)}
|
||
.carried{font-size:var(--fs-caption);color:var(--text3);margin:3px 6px 0;display:inline-flex;gap:4px;align-items:center}
|
||
.carried-list{font-size:var(--fs-small);color:var(--text2);background:var(--hover);border-radius:var(--r-m);padding:8px 12px;margin:4px 4px 0;max-width:85%;line-height:1.5;white-space:pre-wrap;word-break:break-word}
|
||
.memhead{padding:10px 18px 0;font-size:var(--fs-small);color:var(--text3);line-height:1.7}
|
||
.memhead b{color:var(--text);font-weight:600;margin:0 12px 0 3px}
|
||
.memhead .sub{font-size:var(--fs-caption)}
|
||
.memsearch{display:flex;gap:8px;padding:10px 12px 6px}
|
||
.memsearch input{flex:1;min-width:0;height:40px;border-radius:999px;padding:0 14px;background:var(--elev);font-size:var(--fs-read);color:var(--text);border:0;outline:none}
|
||
.memsearch button{flex:none;height:40px;padding:0 14px;border-radius:999px;background:var(--elev);font-size:var(--fs-ui);color:var(--accent-ink);display:inline-flex;gap:4px;align-items:center}
|
||
.memfilters{display:flex;gap:6px;padding:4px 12px 10px;overflow-x:auto;scrollbar-width:none}
|
||
.memfilters::-webkit-scrollbar{display:none}
|
||
.memfilters button{flex:none;height:30px;padding:0 12px;border-radius:999px;font-size:var(--fs-small);color:var(--text2);box-shadow:inset 0 0 0 .5px var(--line)}
|
||
.memfilters button.on{background:var(--active);color:var(--text);font-weight:500;box-shadow:none}
|
||
.mcard{margin:0 12px 8px;padding:11px 14px 8px;border-radius:var(--r-l);background:var(--elev)}
|
||
.mcard.pin{box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--accent) 45%,transparent)}
|
||
.mcard .mt{font-size:var(--fs-ui);white-space:pre-wrap;word-break:break-word;line-height:1.5}
|
||
.mcard .mm{font-size:var(--fs-caption);color:var(--text3);margin-top:6px;display:flex;align-items:center;gap:6px;flex-wrap:wrap}
|
||
.mcard .mm .pinned{color:var(--accent-ink);display:inline-flex;gap:3px;align-items:center}
|
||
.mcard .ma{display:flex;gap:2px;justify-content:flex-end;margin-top:4px}
|
||
.mcard .ma button{height:30px;padding:0 10px;border-radius:999px;font-size:var(--fs-small);color:var(--text2)}
|
||
.mcard .ma button:active{background:var(--hover)}
|
||
.msugg{margin:0 12px 10px;padding:12px 14px;border-radius:var(--r-l);background:var(--hover);font-size:var(--fs-small);color:var(--text2);line-height:1.5}
|
||
.msugg .h{font-weight:600;color:var(--text);display:flex;gap:6px;align-items:center}
|
||
.msugg .sr{margin-top:10px;word-break:break-word}
|
||
.msugg .acts{display:flex;gap:6px;margin-top:6px;flex-wrap:wrap}
|
||
.msugg .acts button{height:30px;padding:0 12px;border-radius:999px;font-size:var(--fs-small);color:var(--accent-ink);background:var(--elev)}
|
||
.memmore{display:flex;justify-content:space-between;align-items:center;padding:4px 18px 12px;font-size:var(--fs-caption);color:var(--text3)}
|
||
.memmore button{color:var(--accent-ink);font-size:var(--fs-small)}
|
||
.quoting{max-width:760px;margin:0 auto 6px;display:flex;align-items:center;gap:8px;font-size:var(--fs-small);color:var(--text2);border-left:3px solid var(--line);padding-left:8px}
|
||
.quoting span{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.composer{max-width:760px;margin:0 auto;display:flex;align-items:flex-end;gap:4px;background:var(--elev);border-radius:var(--r-l);padding:6px;box-shadow:inset 0 0 0 1px var(--line),0 2px 10px -2px var(--shade)}
|
||
.composer:focus-within{box-shadow:inset 0 0 0 1px var(--text4),0 2px 10px -2px var(--shade)}
|
||
.composer.tall{border-radius:var(--r-l)}
|
||
.composer textarea{flex:1;border:0;outline:0;background:none;resize:none;font-size:var(--fs-read);line-height:22px;max-height:140px;min-height:28px;padding:3px 4px}
|
||
.cbtn{width:36px;height:36px;border-radius:50%;display:grid;place-items:center;flex:none;color:var(--text2)}
|
||
.cbtn.plus{background:none}
|
||
.cbtn.go{background:var(--bot,var(--primary));color:var(--bot-ink,var(--on-primary))}
|
||
.cbtn.go:disabled{opacity:.35}
|
||
.cbtn.rec{color:var(--danger)}
|
||
.cbtn .ic{vertical-align:0}
|
||
.down{position:absolute;right:16px;bottom:96px;width:36px;height:36px;border-radius:50%;background:var(--elev);box-shadow:inset 0 0 0 .5px var(--line),0 4px 12px var(--shade);display:none;place-items:center;color:var(--text2);z-index:2}
|
||
.down.on{display:grid}
|
||
|
||
/* ---- details, editor, lists ---- */
|
||
.hero{display:flex;flex-direction:column;align-items:center;gap:6px;padding:18px 16px 6px;text-align:center}
|
||
.hero .n{font-size:var(--fs-h2);font-weight:600}
|
||
.hero .d{font-size:var(--fs-small);color:var(--text3);max-width:320px}
|
||
.tabs{display:flex;gap:4px;padding:8px 12px;overflow-x:auto;scrollbar-width:none;flex:none;position:sticky;top:0;background:var(--pane);z-index:1}
|
||
.tabs::-webkit-scrollbar{display:none}
|
||
.tabs button{flex:none;height:32px;padding:0 13px;border-radius:999px;font-size:var(--fs-ui);color:var(--text2)}
|
||
.tabs button.on{background:var(--active);color:var(--text);font-weight:500}
|
||
.group{margin:8px 12px 14px;border-radius:var(--r-l);background:var(--elev);overflow:hidden}
|
||
.gt{font-size:var(--fs-caption);font-weight:600;color:var(--text3);padding:12px 18px 4px;display:flex;align-items:center;gap:6px}
|
||
.gt button{margin-left:auto;font-weight:500;color:var(--accent-ink);font-size:var(--fs-small)}
|
||
.item{display:flex;align-items:center;gap:12px;padding:11px 14px;min-height:48px;border-top:.5px solid var(--line2);width:100%;text-align:left}
|
||
.item:first-child{border-top:0}
|
||
/* 任務: one card per task (the bot, its words, its state, where, the last sign of life, files, evidence) */
|
||
.tk{display:flex;gap:12px;align-items:flex-start;padding:12px 14px;border-top:.5px solid var(--line2);width:100%;text-align:left}
|
||
.tk:first-child{border-top:0}
|
||
.tk:active{background:var(--hover)}
|
||
.tk .mid{flex:1;min-width:0}
|
||
.tk .hd{display:flex;align-items:center;gap:8px;font-size:var(--fs-caption);color:var(--text3)}
|
||
.tk .hd .who{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||
.tk .st{flex:none;font-size:var(--fs-caption);font-weight:600;padding:2px 8px;border-radius:999px;background:var(--hover);color:var(--text2)}
|
||
.tk .st.go{color:var(--accent-ink)}.tk .st.wait{color:var(--warn);background:var(--attention-bg)}.tk .st.bad{color:var(--danger)}.tk .st.good{color:var(--up)}
|
||
.tk .tx{font-size:var(--fs-ui);color:var(--text);margin:3px 0 2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||
.tk .ln{font-size:var(--fs-caption);color:var(--text3);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:1.6}
|
||
.tk .ln.why{color:var(--text2)}.tk .ln.why.bad{color:var(--danger)}
|
||
.tk .ln .dlv{padding:0 2px;min-height:0;margin:0;vertical-align:-2px}.tk .ln .dlv.failed{color:var(--danger);font-weight:700}
|
||
.m.lit .bub{box-shadow:0 0 0 2px var(--accent)}
|
||
button.item:active,.item.tap:active{background:var(--hover)}
|
||
.item .ic{color:var(--text2)}
|
||
.item .mid{flex:1;min-width:0}
|
||
.item .k{font-size:var(--fs-ui)}
|
||
.item .v{font-size:var(--fs-small);color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.item .r{font-size:var(--fs-ui);color:var(--text3);flex:none;max-width:45%;text-align:right;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.item.danger .k,.item.danger .ic{color:var(--danger)}
|
||
.item .chev{color:var(--text4)}
|
||
.note{font-size:var(--fs-small);color:var(--text3);padding:6px 18px 10px;line-height:1.55;white-space:pre-wrap;overflow-wrap:anywhere}
|
||
.sw{position:relative;width:46px;height:28px;flex:none}
|
||
.sw input{opacity:0;position:absolute;inset:0;margin:0}
|
||
.sw i{position:absolute;inset:0;border-radius:999px;background:var(--active);transition:.15s}
|
||
.sw i::after{content:"";position:absolute;left:3px;top:3px;width:22px;height:22px;border-radius:50%;background:var(--on-color);box-shadow:0 1px 3px var(--shade);transition:.15s}
|
||
.sw input:checked+i{background:var(--primary)}
|
||
.sw input:checked+i::after{background:var(--on-primary)}
|
||
.sw input:checked+i::after{transform:translateX(18px)}
|
||
.sw input:disabled+i{opacity:.4}
|
||
.field{display:block;width:100%;border:0;outline:0;background:var(--hover);border-radius:var(--r-m);padding:10px 12px;font-size:var(--fs-read);resize:vertical}
|
||
.field:focus{box-shadow:0 0 0 2px color-mix(in srgb,var(--focus) 45%,transparent)}
|
||
textarea.field{min-height:96px;line-height:1.5}
|
||
.form{padding:10px 14px;display:flex;flex-direction:column;gap:8px}
|
||
.form label{font-size:var(--fs-small);color:var(--text3);margin-top:4px}
|
||
.row2{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
|
||
.shapes{display:grid;grid-template-columns:repeat(6,1fr);gap:8px;padding:10px 14px}
|
||
.shapes button{aspect-ratio:1;border-radius:var(--r-m);padding:6px;background:var(--hover);min-width:0}
|
||
.shapes button svg{display:block;width:100%;height:100%}
|
||
.btnrow{display:flex;flex-wrap:wrap;gap:8px;padding:12px 14px}
|
||
.shapes button.on{box-shadow:0 0 0 2px var(--focus)}
|
||
.colors{display:flex;gap:10px;flex-wrap:wrap;padding:4px 14px 14px}
|
||
.colors button{width:30px;height:30px;border-radius:50%;box-shadow:inset 0 0 0 1px var(--line)}
|
||
.colors button.on{box-shadow:0 0 0 2px var(--pane),0 0 0 4px var(--focus)}
|
||
.thumbbox{margin:12px 14px 4px;border-radius:var(--r-l);overflow:hidden;background:var(--stage);aspect-ratio:16/10;display:grid;place-items:center;color:var(--on-stage);font-size:var(--fs-small)}
|
||
.thumbbox img{width:100%;height:100%;object-fit:contain;display:block}
|
||
.files{display:grid;grid-template-columns:repeat(3,1fr);gap:4px;padding:6px 12px}
|
||
.files .f{aspect-ratio:1;border-radius:var(--r-s);overflow:hidden;background:var(--hover);display:grid;place-items:center;font-size:var(--fs-caption);color:var(--text3);padding:6px;text-align:center;word-break:break-all}
|
||
.files .f img{width:100%;height:100%;object-fit:cover}
|
||
.log{font:var(--fs-caption)/1.5 var(--mono);color:var(--text2);white-space:pre-wrap;padding:10px 14px;max-height:280px;overflow:auto}
|
||
.kv{display:flex;justify-content:space-between;gap:10px;padding:4px 0}
|
||
|
||
/* ---- sheets ---- */
|
||
.sheet-bg{position:fixed;inset:0;background:var(--scrim);display:none;align-items:flex-end;justify-content:center;z-index:20}
|
||
.sheet-bg.on{display:flex}
|
||
.sheet{width:100%;max-width:560px;max-height:88dvh;overflow-y:auto;background:var(--pane);border-radius:var(--r-l) var(--r-l) 0 0;padding:6px 0 calc(var(--safe-b) + 10px);animation:up .18s ease-out}
|
||
@keyframes up{from{transform:translateY(30px);opacity:.6}}
|
||
.sheet .grab{width:36px;height:5px;border-radius:999px;background:var(--active);margin:4px auto 6px}
|
||
.sheet .st{font-size:var(--fs-small);color:var(--text3);text-align:center;padding:4px 16px 8px}
|
||
.sheet .opt{display:flex;align-items:center;gap:12px;width:100%;padding:13px 20px;font-size:var(--fs-ui);text-align:left}
|
||
.sheet .opt:active{background:var(--hover)}
|
||
.sheet .opt .ic{color:var(--text2)}
|
||
.sheet .opt.danger,.sheet .opt.danger .ic{color:var(--danger)}
|
||
.sheet .opt .ck{margin-left:auto;color:var(--accent)}
|
||
.sheet .sep{height:1px;background:var(--line2);margin:var(--sp-1) 20px}
|
||
.sheet .opt .x{margin-left:auto;font-size:var(--fs-small);color:var(--text3)}
|
||
.drop-to{display:flex;gap:6px;flex-wrap:wrap}
|
||
.drop-to button{height:32px;padding:0 12px;border-radius:999px;font-size:var(--fs-small);box-shadow:inset 0 0 0 .5px var(--line);color:var(--text2)}
|
||
.drop-to button.on{background:var(--primary);color:var(--on-primary);box-shadow:none}
|
||
.drop-to button.off{color:var(--text3)}
|
||
.drop-row{display:flex;align-items:center;gap:10px;padding:9px 18px}
|
||
.drop-row .ic{flex:none;color:var(--text3)}
|
||
.drop-row .dw{flex:1;min-width:0}
|
||
.drop-row .dn{font-size:var(--fs-ui);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.drop-row .ds{font-size:var(--fs-caption);color:var(--text3);line-height:1.4}
|
||
.drop-row .ds.bad{color:var(--danger)}
|
||
.drop-row .btn{flex:none}
|
||
.drop-bar{height:4px;border-radius:999px;background:var(--line);overflow:hidden;margin-top:4px}
|
||
.drop-bar i{display:block;height:100%;background:var(--primary)}
|
||
.sheet .grp{font-size:var(--fs-caption);font-weight:600;color:var(--text3);padding:12px 20px 4px}
|
||
.emojis{display:grid;grid-template-columns:repeat(8,1fr);gap:6px;padding:6px 16px 10px}
|
||
.emojis button{font-size:var(--fs-h2);height:44px;min-width:0;border-radius:var(--r-m);background:var(--hover)}
|
||
/* 選取文字: the message alone on a sheet, where the phone's own selecting works. */
|
||
.seltext{-webkit-user-select:text;user-select:text;-webkit-touch-callout:default;cursor:text;overflow-wrap:anywhere}
|
||
.sheet .seltext.page{padding-bottom:var(--sp-3)}
|
||
.seltext.mine{padding:var(--sp-2) 18px var(--sp-3);white-space:pre-wrap;font-size:var(--fs-read);line-height:1.5}
|
||
.seltext .quote{display:block;-webkit-line-clamp:none;overflow:visible}
|
||
/* A short notice floating under the title bar: frosted glass (what is under it blurs, so it
|
||
reads as above the page, not one more card on it), a hairline, a soft shadow, the card's
|
||
corners. It was a black capsule, and two or three lines swelled it into an oval. */
|
||
.toast{position:fixed;left:50%;top:calc(var(--safe-t) + 60px);transform:translate(-50%,-10px);width:max-content;max-width:min(360px,calc(100vw - 32px));background:color-mix(in srgb,var(--elev) 78%,transparent);-webkit-backdrop-filter:blur(18px) saturate(1.6);backdrop-filter:blur(18px) saturate(1.6);color:var(--text);padding:11px 16px;border-radius:var(--r-l);box-shadow:inset 0 0 0 .5px var(--line),0 12px 32px -8px var(--shade),0 2px 6px -2px var(--shade);font-size:var(--fs-ui);line-height:1.5;text-align:left;opacity:0;pointer-events:none;transition:opacity .2s,transform .2s;z-index:40}
|
||
.toast.on{opacity:1;transform:translate(-50%,0)}
|
||
.net{position:fixed;left:50%;top:calc(var(--safe-t) + 64px);transform:translate(-50%,-12px);background:var(--elev);color:var(--text2);border:1px solid var(--line);box-shadow:0 2px 10px #0000001a;padding:5px 12px;border-radius:999px;font-size:var(--fs-small);opacity:0;pointer-events:none;transition:.2s;z-index:39;white-space:nowrap}
|
||
.net.on{opacity:1;transform:translate(-50%,0)}
|
||
|
||
/* ---- sign in ---- */
|
||
.login{max-width:360px;margin:auto;padding:24px;display:flex;flex-direction:column;gap:10px;width:100%}
|
||
.login .logo{width:72px;height:72px;margin:0 auto 8px;display:block}
|
||
.login h2{text-align:center;margin:0;font-size:var(--fs-h2)}
|
||
.login p{text-align:center;color:var(--text3);margin:0 0 8px;font-size:var(--fs-ui)}
|
||
.login .err{color:var(--danger);font-size:var(--fs-small);text-align:center;min-height:18px}
|
||
.link{color:var(--accent-ink);font-size:var(--fs-ui);text-align:center;padding:6px}
|
||
/* ---- connecting: the icon the app opened with stays in the middle, breathing, rings spreading
|
||
out from it — no words (a screen reader still hears 正在連線) ---- */
|
||
.gate{margin:auto;position:relative;width:96px;height:96px}
|
||
.gate img{position:relative;z-index:1;width:100%;height:100%;display:block;border-radius:22%;box-shadow:0 6px 24px #0000001f}
|
||
.gate::before,.gate::after{content:"";position:absolute;inset:0;border-radius:22%;background:color-mix(in srgb,var(--text3) 24%,transparent);opacity:0}
|
||
@media (prefers-reduced-motion: no-preference){
|
||
.gate img{animation:breathe 2s ease-in-out infinite}
|
||
.gate::before,.gate::after{animation:ripple 2s cubic-bezier(.2,.6,.3,1) infinite}
|
||
.gate::after{animation-delay:1s}
|
||
}
|
||
@keyframes breathe{50%{transform:scale(1.045)}}
|
||
@keyframes ripple{0%{opacity:.6;transform:scale(1)}100%{opacity:0;transform:scale(1.8)}}
|
||
.vh{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
|
||
|
||
/* ---- page viewer ---- */
|
||
.page{padding:var(--sp-2) 18px 40px;max-width:760px;margin:0 auto}
|
||
.page h1.pt{font-family:var(--font-read);font-weight:600;font-size:var(--fs-h1);line-height:1.3;margin:var(--sp-3) 0 var(--sp-1)}
|
||
.page .mt{font-family:var(--font);font-size:var(--fs-caption);color:var(--text3);margin-bottom:var(--sp-4)}
|
||
.page h2{font-size:var(--fs-h2);margin:1.6em 0 .5em}
|
||
.page h3{font-size:var(--fs-h3);margin:1.4em 0 .4em}
|
||
.page h4{font-size:var(--fs-read);margin:1.2em 0 .3em}
|
||
.page :is(h2,h3,h4){scroll-margin-top:var(--sp-3)}
|
||
/* The one-line conclusion: a lead paragraph, no box. */
|
||
.page .sum{font-size:var(--fs-read);line-height:1.8;color:var(--text);margin:0 0 1em}
|
||
.page .old,.page .chg{font-family:var(--font);font-size:var(--fs-small);color:var(--text2);background:var(--hover);padding:var(--sp-2) var(--sp-3);border-radius:var(--r-m);margin:0 0 var(--sp-4)}
|
||
/* 目錄: one quiet line that opens to a plain list (only with 3+ headings). */
|
||
.toc{margin:0 0 var(--sp-4);font-family:var(--font)}
|
||
.toc summary{cursor:pointer;list-style:none;display:inline-flex;align-items:center;gap:var(--sp-1);padding:var(--sp-1) 0;font-size:var(--fs-small);color:var(--text3)}
|
||
.toc summary::-webkit-details-marker{display:none}
|
||
.toc summary .ic{transition:transform .15s}
|
||
.toc[open] summary .ic{transform:rotate(90deg)}
|
||
.toc ol{list-style:none;margin:var(--sp-1) 0 0;padding:0}
|
||
.toc li{margin:0}
|
||
.toc button{display:block;width:100%;text-align:left;padding:6px 0;font-size:var(--fs-ui);line-height:1.45;color:var(--text2)}
|
||
.toc li.sub button{padding-left:var(--sp-4);color:var(--text3)}
|
||
/* ---- 檔案: a chat file shown as the desktop shows it, and the takeover screen over all ---- */
|
||
.fimg{padding:16px 12px 40px;text-align:center}
|
||
.fimg img{max-width:100%;border-radius:var(--r-m)}
|
||
.ftext{padding:14px 16px 40px;font:var(--fs-small)/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;word-break:break-word;color:var(--text2)}
|
||
.fmedia{padding:28px 18px;display:grid;gap:12px;place-items:center}
|
||
.fmedia audio,.fmedia video{width:100%;max-width:560px;border-radius:var(--r-m)}
|
||
.fdl{display:grid;place-items:center;gap:14px;padding:64px 24px;color:var(--text2);text-align:center;line-height:1.6}
|
||
.pager{display:flex;align-items:center;justify-content:center;gap:14px;padding:8px 12px;padding-bottom:max(8px,var(--safe-b));border-top:1px solid var(--line);background:var(--pane);flex:none}
|
||
.pager span{font-size:var(--fs-small);color:var(--text2);min-width:72px;text-align:center}
|
||
.boxwrap{position:fixed;inset:0;z-index:50;background:var(--stage);display:none}
|
||
.boxwrap iframe{width:100%;height:100%;border:0;display:block}
|
||
.page .stats{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:8px;margin:12px 0}
|
||
.page .stat{border:.5px solid var(--line);border-radius:var(--r-l);background:none;padding:11px 13px;font-family:var(--font)}
|
||
.page .stat .k{font-size:var(--fs-caption);color:var(--text3)}.page .stat .v{font-size:var(--fs-h2);font-weight:650;line-height:1.2}.page .stat .v.long{font-size:var(--fs-read);font-weight:600}.page .stat .s{font-size:var(--fs-caption);color:var(--text2)}
|
||
.page .stat .v.up,.page .stat .s.up{color:var(--up)}.page .stat .v.dn,.page .stat .s.dn{color:var(--danger)}
|
||
.page ul.steps{list-style:none;padding:0}
|
||
.page ul.steps li{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:6px 0}
|
||
.page ul.steps .dot{width:18px;height:18px;border-radius:50%;border:2px solid var(--line);display:grid;place-items:center;font-size:var(--fs-caption)}
|
||
.page ul.steps li.done .dot{background:var(--ok);border-color:var(--ok);color:var(--on-color)}
|
||
.page ul.steps li.now .dot{border-color:var(--accent)}
|
||
.page ul.steps .nt{flex-basis:100%;padding-left:26px;font-size:var(--fs-small);color:var(--text3)}
|
||
.page .chart{margin:12px 0;border:.5px solid var(--line);border-radius:var(--r-l);overflow:hidden;background:var(--elev)}
|
||
.page .chart img{width:100%;display:block}
|
||
.page .chart .wait{padding:18px;font-size:var(--fs-small);color:var(--text3)}
|
||
/* ```chart 原生 SVG 卡(與桌面版圖表卡同款) */
|
||
.chartcard{margin:12px 0 .75em;border:.5px solid var(--line);border-radius:var(--r-l);background:none;padding:12px 12px 8px;max-width:100%;font-family:var(--font);line-height:1.45}
|
||
.bub .chartcard,.talk .chartcard{margin:6px 0;padding:8px 8px 6px}
|
||
.chartcard .ct2{font-size:var(--fs-ui);font-weight:600;line-height:1.4;margin:2px 2px 6px}
|
||
.chartcard svg{width:100%;height:auto;display:block;margin:0 auto}
|
||
/* The numbers under the chart (desktop: the same table). */
|
||
.chartcard .ctab{overflow-x:auto;margin:8px 0 2px}
|
||
.chartcard .ctab table{border-collapse:collapse;width:100%;font-size:var(--fs-small);line-height:1.45}
|
||
.chartcard .ctab th{font-weight:600;font-size:var(--fs-small);color:var(--text2);background:none;border:0;border-bottom:1px solid var(--line);padding:6px var(--sp-3);text-align:right;white-space:nowrap}
|
||
.chartcard .ctab td{border:0;border-bottom:1px solid var(--line2);padding:6px var(--sp-3);text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap;color:var(--text)}
|
||
.chartcard .ctab th:first-child,.chartcard .ctab td:first-child{text-align:left}
|
||
.chartcard .ctab td:first-child{color:var(--text2);white-space:normal;overflow-wrap:anywhere}
|
||
|
||
/* ---- this Mac's screen ---- */
|
||
.stage{flex:1;position:relative;background:var(--stage);display:flex;align-items:center;justify-content:center;overflow:hidden;touch-action:none}
|
||
.stage img{max-width:100%;max-height:100%;user-select:none;-webkit-user-select:none}
|
||
.stage .msg{color:var(--on-stage);font-size:var(--fs-ui);padding:20px;text-align:center}
|
||
.stage .tapdot{position:absolute;width:26px;height:26px;margin:-13px 0 0 -13px;border-radius:50%;background:color-mix(in srgb,var(--accent) 53%,transparent);pointer-events:none;animation:fade .6s forwards}
|
||
@keyframes fade{to{opacity:0;transform:scale(1.8)}}
|
||
.tools{display:flex;gap:6px;padding:8px 10px calc(var(--safe-b) + 8px);overflow-x:auto;flex:none;background:var(--chrome);scrollbar-width:none}
|
||
.tools::-webkit-scrollbar{display:none}
|
||
.tools .btn{flex:none;height:36px;min-width:40px;padding:0 10px;border-radius:var(--r-m)}
|
||
.tools .sep{width:1px;background:var(--line);margin:4px 2px;flex:none}
|
||
.tools .btn.once{background:color-mix(in srgb,var(--accent) 18%,transparent);color:var(--accent-ink)}
|
||
.tools .btn.lock{background:var(--accent);color:var(--on-color)}
|
||
.tools .btn.on{background:var(--primary);color:var(--on-primary)}
|
||
/* 所有檔案: a search, the kinds with their counts, pictures in a grid, the rest as rows. */
|
||
.lib-top{position:sticky;top:0;z-index:2;background:var(--pane);padding:var(--sp-3) var(--sp-4) var(--sp-2)}
|
||
.lib-tabs{padding:0;position:static;background:none;margin-top:var(--sp-2)}
|
||
.lib-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:4px;margin:var(--sp-2) var(--sp-4) var(--sp-3)}
|
||
.lib-pic{aspect-ratio:1;border-radius:var(--r-m);overflow:hidden;background:var(--hover);padding:0}
|
||
.lib-pic img{width:100%;height:100%;object-fit:cover;display:block}
|
||
.item.gone{opacity:.5}.item.gone .v{color:var(--danger)}
|
||
/* 日程: 即將執行, then a group a day — a row a time: when, what, how it went. */
|
||
.item.sch .sch-t{width:44px;flex:none;font-size:var(--fs-small);color:var(--text2);font-variant-numeric:tabular-nums;display:flex;align-items:center}
|
||
.item.sch .av.sm{width:26px;height:26px}.item.sch .av.sm svg{width:26px;height:26px}
|
||
.item.sch .r{display:flex;align-items:center;gap:4px;font-size:var(--fs-caption);white-space:nowrap}
|
||
.item.sch .r.good{color:var(--ok)}.item.sch .r.bad{color:var(--danger)}.item.sch .r.go{color:var(--accent-ink)}
|
||
.item.sch.todo{opacity:.55}
|
||
/* 工作流: a card each (run / stop at the right, the 等你確認 under it); one opened: its steps as a
|
||
line from top to bottom, each with how this run (or the last) went there. */
|
||
.wf-card{padding:12px 16px;border-bottom:1px solid var(--line2);cursor:pointer}
|
||
.wf-card:last-child{border-bottom:0}
|
||
.wf-row{display:flex;align-items:center;gap:12px}
|
||
.wf-row .mid{flex:1;min-width:0}.wf-row .k{font-size:var(--fs-ui);font-weight:500}.wf-row .v{font-size:var(--fs-small);color:var(--text3);line-height:1.5}
|
||
.wf-i{width:30px;height:30px;border-radius:var(--r-m);background:var(--hover);display:grid;place-items:center;flex:none;color:var(--text2)}
|
||
.wf-i.big{width:36px;height:36px}
|
||
.wf-ask{display:flex;align-items:center;gap:8px;margin-top:10px;padding:10px 12px;border-radius:var(--r-m);background:var(--attention-bg);font-size:var(--fs-small)}
|
||
.wf-ask span{flex:1;min-width:0}
|
||
.wf-head{display:flex;align-items:center;gap:12px;margin:var(--sp-3) var(--sp-4) 0}
|
||
.wf-head .v{flex:1;min-width:0;font-size:var(--fs-small);color:var(--text3)}
|
||
.wf-head + .wf-ask{margin:var(--sp-3) var(--sp-4) 0}
|
||
.wf-steps{margin:0 var(--sp-4);padding:4px 0;background:var(--elev);border-radius:var(--r-l)}
|
||
.wf-step{display:flex;gap:12px;padding:10px 14px;position:relative}
|
||
.wf-step:not(:last-child)::after{content:"";position:absolute;left:28px;top:44px;bottom:-6px;width:2px;background:var(--line)}
|
||
.wf-step .mid{flex:1;min-width:0}.wf-step .k{font-size:var(--fs-ui);font-weight:500}.wf-step .v{font-size:var(--fs-small);color:var(--text2);line-height:1.5;white-space:pre-line;overflow:hidden;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical}
|
||
.wf-step .v.out{color:var(--text3);margin-top:4px;padding-left:8px;border-left:2px solid var(--line)}
|
||
.wf-step.good .wf-i{background:color-mix(in srgb,var(--ok) 16%,transparent);color:var(--ok)}
|
||
.wf-step.go .wf-i{background:color-mix(in srgb,var(--accent) 16%,transparent);color:var(--accent-ink)}
|
||
.wf-step.wait .wf-i{background:var(--attention-bg);color:var(--warn)}
|
||
.wf-step.bad .wf-i{background:color-mix(in srgb,var(--danger) 14%,transparent);color:var(--danger)}
|
||
.wf-step.skip,.wf-step.todo{opacity:.5}
|
||
.pill.good{background:color-mix(in srgb,var(--ok) 16%,transparent);color:var(--ok)}
|
||
.pill.go{background:color-mix(in srgb,var(--accent) 16%,transparent);color:var(--accent-ink)}
|
||
.pill.wait{background:var(--attention-bg);color:var(--warn)}
|
||
.pill.bad{background:color-mix(in srgb,var(--danger) 14%,transparent);color:var(--danger)}
|
||
/* 風格 gallery: four little pictures a row, the one worn ringed in the accent. */
|
||
.tpl-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin:0 var(--sp-4) var(--sp-2)}
|
||
.tpl{display:flex;flex-direction:column;align-items:center;gap:5px;padding:0;min-width:0}
|
||
.tpl .pic{position:relative;width:100%;aspect-ratio:1.25;border-radius:var(--r-m);border:1px solid;overflow:hidden;display:block}
|
||
.tpl.on .pic{box-shadow:0 0 0 2px var(--pane),0 0 0 4px var(--accent)}
|
||
.tpl .pic i{position:absolute;display:block;border-radius:999px}
|
||
.tpl .pic .sd{left:0;top:0;bottom:0;width:26%;border-radius:0;display:flex;flex-direction:column;gap:4px;padding:6px 4px}
|
||
.tpl .pic .sd b{display:block;height:3px;border-radius:999px}
|
||
.tpl .pic .ln{left:34%;top:14%;width:50%;height:3px}.tpl .pic .ln.s{top:24%;width:36%}
|
||
.tpl .pic .bb{right:8%;top:42%;width:38%;height:9px}
|
||
.tpl .pic .dt{right:8%;bottom:10%;width:8px;height:8px}
|
||
.tpl .nm{font-size:var(--fs-caption);color:var(--text2)}.tpl.on .nm{color:var(--text);font-weight:600}
|
||
/* 風格's chat backdrop: dots, a grid or waves in the page's faintest line colour, behind the chat. */
|
||
html[data-backdrop="dots"] #scroller{background-image:radial-gradient(var(--grid) 1.3px,transparent 1.5px);background-size:22px 22px}
|
||
html[data-backdrop="grid"] #scroller{background-image:linear-gradient(var(--grid) 1px,transparent 1px),linear-gradient(90deg,var(--grid) 1px,transparent 1px);background-size:24px 24px}
|
||
html[data-backdrop="waves"] #scroller{background-image:radial-gradient(circle at 50% 100%,transparent 13.5px,var(--grid) 14px,var(--grid) 14.6px,transparent 15.2px);background-size:32px 16px}
|
||
/* 個人資料與用量: one strip of big numbers, the year's dots, a big number and bars. */
|
||
.me-figs{display:grid;grid-template-columns:repeat(4,1fr);gap:4px;margin:var(--sp-3) var(--sp-4) 0;padding:var(--sp-3) var(--sp-2);background:var(--elev);border-radius:var(--r-l)}
|
||
.me-figs div{display:flex;flex-direction:column;align-items:center;gap:2px;min-width:0}
|
||
.me-figs b{font-size:var(--fs-h3);font-weight:600;white-space:nowrap}
|
||
.me-figs span{font-size:var(--fs-caption);color:var(--text3);white-space:nowrap}
|
||
.me-card{margin:0 var(--sp-4);padding:var(--sp-3) var(--sp-4);background:var(--elev);border-radius:var(--r-l)}
|
||
.me-heat{width:100%;height:auto;display:block}
|
||
.me-note{font-size:var(--fs-caption);color:var(--text3);margin-top:var(--sp-2);line-height:1.5}
|
||
.me-seg{display:flex;gap:2px;padding:3px;background:var(--active);border-radius:999px;margin:var(--sp-1) 0 var(--sp-3)}
|
||
.me-seg button{flex:1;height:30px;border-radius:999px;font-size:var(--fs-small);color:var(--text2)}
|
||
.me-seg button.on{background:var(--elev);color:var(--text);font-weight:600}
|
||
.me-hero{font-size:var(--fs-small);color:var(--text3)}
|
||
.me-hero b{font-size:var(--fs-h1);font-weight:600;color:var(--text);margin-right:4px}
|
||
.me-bars{width:100%;height:84px;display:block;margin:var(--sp-3) 0 var(--sp-4);border-bottom:1px solid var(--grid)}
|
||
.me-split{display:flex;height:10px;border-radius:999px;overflow:hidden;background:var(--hover);margin-bottom:var(--sp-2)}
|
||
.me-split i{display:block;height:100%}
|
||
.me-row{display:flex;align-items:center;gap:10px;min-height:36px}
|
||
.me-dot{width:8px;height:8px;border-radius:50%;flex:none}
|
||
.me-av{width:22px;height:22px;flex:none;display:grid}.me-av svg{width:22px;height:22px}
|
||
.me-name{flex:1;min-width:0;font-size:var(--fs-small);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.me-bar{width:70px;height:6px;border-radius:999px;background:var(--hover);overflow:hidden;flex:none}.me-bar i{display:block;height:100%;background:var(--accent)}
|
||
.me-n{font-size:var(--fs-small);color:var(--text2);white-space:nowrap}
|
||
/* 虛擬觸控板 over this Mac's screen: a layer that takes the fingers, and the pointer drawn on it. */
|
||
.stagewrap{flex:1;min-height:0;position:relative;display:flex}
|
||
.pad{position:absolute;inset:0;display:none;touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}
|
||
.pad.on{display:block}
|
||
.ptr{position:absolute;width:20px;height:20px;margin:-2px 0 0 -3px;pointer-events:none;display:none;filter:drop-shadow(0 1px 2px #0009)}
|
||
.ptr.on{display:block}
|
||
.padtip{position:absolute;left:50%;bottom:12px;transform:translateX(-50%);max-width:calc(100% - 24px);background:var(--elev);border-radius:var(--r-l);padding:9px 12px;font-size:var(--fs-small);line-height:1.6;box-shadow:0 2px 10px -2px var(--shade);pointer-events:none;opacity:0;transition:opacity .3s}
|
||
.padtip.on{opacity:1}
|
||
.padtip b{font-weight:600;color:var(--accent-ink)}
|
||
.combos{display:none;grid-template-columns:repeat(3,1fr);gap:6px;padding:10px;background:var(--chrome);max-height:40vh;overflow-y:auto;flex:none}
|
||
.combos.on{display:grid}
|
||
.combos .btn{height:auto;min-height:48px;flex-direction:column;gap:2px;border-radius:var(--r-l);padding:6px 4px}
|
||
.combos .btn small{color:var(--text3);font-size:var(--fs-caption);font-weight:400}
|
||
.typebar{display:none;gap:6px;padding:8px 10px 0;background:var(--chrome)}
|
||
.typebar.on{display:flex}
|
||
.typebar input{flex:1}
|
||
.live{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--ok);margin-right:5px}
|
||
.pair-code{font:600 var(--fs-h1)/1.2 var(--mono);text-align:center;letter-spacing:4px;padding:10px}
|
||
.pair-line{display:block;font:var(--fs-caption)/1.5 var(--mono);background:var(--hover);padding:10px;border-radius:var(--r-m);margin:6px 16px;word-break:break-all}
|
||
/* ---- feels installed (a PWA on every phone) ---- */
|
||
:root{--safe-l:env(safe-area-inset-left,0px);--safe-r:env(safe-area-inset-right,0px)}
|
||
/* 頂天立地 (fit() below): on an iPhone that gives a home-screen app a status bar less at the bottom
|
||
(the system draws that strip, in the page's colour), what meets it is the page's colour too. */
|
||
html.fit-short .dock{background:linear-gradient(to bottom,transparent,var(--pane) 40%)}
|
||
html.fit-short .tools{background:var(--pane)}
|
||
/* 畫面量尺 (設定 › 更新 › 畫面): where the frost ends at the top, where the page ends at the bottom. */
|
||
#ruler{position:fixed;inset:0;z-index:99;background:color-mix(in srgb,var(--pane) 55%,transparent);font:var(--fs-caption)/1.3 var(--font);color:var(--text)}
|
||
#ruler .info{position:absolute;left:16px;right:16px;top:40%;transform:translateY(-50%);background:var(--elev);border:1px solid var(--line);border-radius:var(--r-l);padding:14px 16px;white-space:pre-wrap}
|
||
#ruler .past{position:absolute;left:0;right:0;bottom:-80px;height:80px;background:var(--danger);color:var(--on-color);display:grid;place-items:center;font-weight:600}
|
||
/* No font inflation when the phone turns sideways. */
|
||
html{-webkit-text-size-adjust:100%;text-size-adjust:100%}
|
||
/* A phone on its side with a notch: every screen paints edge to edge, its content stays clear of it. */
|
||
.view{padding-left:var(--safe-l);padding-right:var(--safe-r)}
|
||
.sheet{padding-left:var(--safe-l);padding-right:var(--safe-r)}
|
||
.boxwrap{padding:0 var(--safe-r) 0 var(--safe-l)}
|
||
/* Lists bounce on their own; the page behind them never moves. */
|
||
.scroll,.sheet{overscroll-behavior:contain}
|
||
/* Controls are not text: a long press doesn't select a button's label, and a tap answers at once. */
|
||
button,.row,.ib,.island,.opt,.chip,.tab,label.sw,[role="button"]{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;touch-action:manipulation}
|
||
/* (Under 16 px, iPhone zooms the page into the field and leaves it there.) */
|
||
.searchbox input{font-size:var(--fs-read)}
|
||
/* Screens slide like an app's: a new one comes in from the right, going back comes from the left. */
|
||
@media (prefers-reduced-motion: no-preference){
|
||
.view.in-fwd{animation:in-fwd .28s cubic-bezier(.22,.8,.24,1)}
|
||
.view.in-back{animation:in-back .28s cubic-bezier(.22,.8,.24,1)}
|
||
}
|
||
@keyframes in-fwd{from{transform:translateX(32%);opacity:.35}}
|
||
@keyframes in-back{from{transform:translateX(-14%);opacity:.6}}
|
||
/* The iPhone home-screen app has no browser to swipe back with: the edge swipe moves the screen. */
|
||
.view.dragging{transition:none!important;box-shadow:-12px 0 24px var(--shade)}
|
||
/* Put AnyBot on the home screen (shown once, until installed or dismissed). */
|
||
.install{margin:2px 12px 8px;padding:12px 14px;border-radius:var(--r-l);background:var(--elev);display:none;gap:12px;align-items:center}
|
||
.install.on{display:flex}
|
||
.install img{width:44px;height:44px;border-radius:var(--r-m);flex:none}
|
||
.install .mid{flex:1;min-width:0}
|
||
.install b{display:block;font-size:var(--fs-ui);font-weight:600}
|
||
.install span{display:block;font-size:var(--fs-small);color:var(--text3);line-height:1.45;margin-top:2px}
|
||
.install .x{width:30px;height:30px;border-radius:50%;display:grid;place-items:center;color:var(--text3);flex:none}
|
||
.install .btn{flex:none}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="app">
|
||
<!-- outside, until the first real connection: nothing inside is shown half-loaded -->
|
||
<section class="view on" id="v-gate">
|
||
<div class="scroll" style="display:flex">
|
||
<div class="gate" role="status"><img src="icon-192.png" alt=""><span class="vh">正在連線</span></div>
|
||
</div>
|
||
</section>
|
||
|
||
<!-- sign in -->
|
||
<section class="view" id="v-login">
|
||
<div class="scroll" style="display:flex">
|
||
<div class="login">
|
||
<img class="logo" src="icon-192.png" alt="AnyBot">
|
||
<h2 id="login-title">登入 AnyBot</h2>
|
||
<p id="login-desc">用手機和你的 Bot 聊天、核准它要做的事,也能看著它的電腦。</p>
|
||
<input class="field" id="f-user" placeholder="帳號" autocomplete="username" autocapitalize="off">
|
||
<input class="field" id="f-pass" type="password" placeholder="密碼" autocomplete="current-password">
|
||
<input class="field" id="f-invite" placeholder="邀請碼(伺服器有設定才需要)" autocapitalize="off" style="display:none">
|
||
<button class="btn main" id="b-login" style="height:44px;border-radius:var(--r-m)">登入</button>
|
||
<div class="err" id="login-err"></div>
|
||
<button class="link" id="b-mode" style="display:none">還沒有帳號?建立一個</button>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<!-- which AnyBot (an account with several) -->
|
||
<section class="view" id="v-hosts">
|
||
<div class="bar"><h1>選擇要連的 AnyBot</h1><button class="ib" id="b-out1" title="登出" aria-label="登出"></button></div>
|
||
<div class="scroll"><div class="rows" id="hosts" style="padding-top:8px"></div></div>
|
||
</section>
|
||
|
||
<!-- home: the sidebar -->
|
||
<section class="view" id="v-home">
|
||
<div class="bar">
|
||
<button class="me" id="b-me" title="帳戶選單">A</button>
|
||
<h1>AnyBot<small id="host-name"></small></h1>
|
||
<button class="ib" id="b-search" title="搜尋" aria-label="搜尋"></button>
|
||
<button class="ib" id="b-newbot" title="新 Bot" aria-label="新 Bot"></button>
|
||
</div>
|
||
<div class="searchbox" id="searchbox"><span id="search-ic"></span><input id="search" placeholder="搜尋 Bot" enterkeyhint="search"><button class="ib" id="b-search-x" aria-label="關閉搜尋"></button></div>
|
||
<div class="install" id="install"></div>
|
||
<div class="quick" id="quick"></div>
|
||
<div class="scroll" id="home"></div>
|
||
</section>
|
||
|
||
<!-- one chat -->
|
||
<section class="view" id="v-chat">
|
||
<div class="bar">
|
||
<button class="ib" data-back title="返回" aria-label=""></button>
|
||
<button class="island" id="island" title="查看對話詳細資訊"><div class="av sm" id="isl-av"></div><div class="t"><div class="n"><span id="isl-name"></span><span id="isl-chev"></span></div><div class="s" id="isl-sub"></div></div></button>
|
||
<button class="ib" id="b-newchat" title="開始新對話" aria-label="開始新對話"></button>
|
||
<button class="ib" id="b-chatmore" title="更多"></button>
|
||
</div>
|
||
<div class="scroll" id="scroller"><div class="msgs" id="msgs"></div><div id="askq"></div></div>
|
||
<button class="down" id="b-down" title="到最新的訊息"></button>
|
||
<div class="dock">
|
||
<div id="ask"></div>
|
||
<div class="modes" id="modes"></div>
|
||
<div id="goalbar"></div>
|
||
<div id="planbar"></div>
|
||
<div id="alwaysbar"></div>
|
||
<div id="queued"></div>
|
||
<div class="quoting" id="quoting" style="display:none"></div>
|
||
<div class="chips" id="chips"></div>
|
||
<div class="memchips" id="memchips"></div>
|
||
<div class="slash" id="slash"></div>
|
||
<div class="composer" id="composer">
|
||
<button class="cbtn plus" id="b-plus" title="輸入框操作"></button>
|
||
<input type="file" id="file" multiple hidden>
|
||
<input type="file" id="camera" accept="image/*" capture="environment" hidden>
|
||
<textarea id="input" rows="1" placeholder="傳訊息…" enterkeyhint="send"></textarea>
|
||
<button class="cbtn" id="b-mic" title="開始語音輸入"></button>
|
||
<button class="cbtn go" id="b-send" title="傳送訊息" aria-label="傳送訊息"></button>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<!-- 對話詳細資訊 -->
|
||
<section class="view" id="v-details">
|
||
<div class="bar">
|
||
<button class="ib" data-back title="關閉" aria-label=""></button>
|
||
<h1>對話詳細資訊</h1>
|
||
<button class="ib" id="b-botset" title="Bot 設定"></button>
|
||
</div>
|
||
<div class="scroll" id="details"></div>
|
||
</section>
|
||
|
||
<!-- Bot 設定 -->
|
||
<section class="view" id="v-botset">
|
||
<div class="bar"><button class="ib" data-back title="返回" aria-label=""></button><h1 id="botset-title">Bot 設定</h1></div>
|
||
<div class="scroll" id="botset"></div>
|
||
</section>
|
||
|
||
<!-- a list screen: 例行任務 / 頁面 / 電腦 / 設定 and its sections -->
|
||
<section class="view" id="v-list">
|
||
<div class="bar"><button class="ib" data-back title="返回" aria-label=""></button><h1 id="list-title"></h1><span id="list-act"></span></div>
|
||
<div class="scroll" id="list"></div>
|
||
</section>
|
||
|
||
<!-- a page -->
|
||
<section class="view" id="v-page">
|
||
<div class="bar">
|
||
<button class="ib" data-back title="返回" aria-label=""></button>
|
||
<h1 id="page-name">頁面</h1>
|
||
<button class="ib" id="b-pagemore" title="更多"></button>
|
||
</div>
|
||
<div class="scroll" id="pscroll"><div class="page" id="page"></div></div>
|
||
</section>
|
||
|
||
<!-- 檔案: a chat file's preview (image / PDF pages / text / sheet / media) -->
|
||
<section class="view" id="v-file">
|
||
<div class="bar">
|
||
<button class="ib" data-back title="返回" aria-label=""></button>
|
||
<h1 id="file-name">檔案</h1>
|
||
<button class="ib" id="b-filesave" title="儲存"></button>
|
||
</div>
|
||
<div class="scroll" id="filebody"><div class="empty">載入中…</div></div>
|
||
<div class="note" id="file-meta" style="display:none;padding:8px 14px"></div>
|
||
<div class="pager" id="filepager" style="display:none">
|
||
<button class="btn sm" id="f-prev">‹ 上一頁</button><span id="f-at"></span><button class="btn sm" id="f-next">下一頁 ›</button>
|
||
</div>
|
||
</section>
|
||
|
||
<!-- this Mac's screen -->
|
||
<section class="view" id="v-screen">
|
||
<div class="bar"><button class="ib" data-back title="返回" aria-label=""></button><h1>這台 Mac</h1><span class="pill" id="screen-live"></span></div>
|
||
<div class="stagewrap"><div class="stage" id="stage"><div class="msg">載入中…</div></div><div class="pad" id="mac-pad"></div><svg class="ptr" id="mac-ptr" viewBox="0 0 20 20"><path d="M3 2 L3 16 L7 12.5 L9.6 18 L12 17 L9.5 11.6 L14.5 11.6 Z" fill="#fff" stroke="#111" stroke-width="1.2" stroke-linejoin="round"/></svg><div class="padtip" id="mac-tip"></div></div>
|
||
<div class="combos" id="mac-combos"></div>
|
||
<div class="typebar" id="typebar"><input class="field" id="typein" placeholder="要打的字(會打進目前的視窗)" enterkeyhint="send"><button class="btn main" id="b-type">送出</button></div>
|
||
<div class="tools" id="mac-bar"></div>
|
||
</section>
|
||
</div>
|
||
<div class="toast" id="toast"></div>
|
||
<div class="net" id="net" role="status" aria-live="polite">連線中斷,正在重新連線…</div>
|
||
<!-- one sheet for every menu and picker -->
|
||
<div class="sheet-bg" id="sheet"><div class="sheet" id="sheet-in"></div></div>
|
||
<!-- 接管: the bot's computer, screen.html embedded over the app (its ✕ posts a close) -->
|
||
<div class="boxwrap" id="boxwrap"><iframe id="boxframe" title="Bot 的電腦" allow="clipboard-write"></iframe></div>
|
||
<script>
|
||
"use strict";
|
||
// Lucide icons (ISC licence), the set the desktop app uses.
|
||
const LUCIDE = {
|
||
"workflow": '<rect width="8" height="8" x="3" y="3" rx="2"/><path d="M7 11v4a2 2 0 0 0 2 2h4"/><rect width="8" height="8" x="13" y="13" rx="2"/>',
|
||
"send": '<path d="M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"/><path d="m21.854 2.147-10.94 10.939"/>',
|
||
"image": '<rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/>',
|
||
"file": '<path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/>',
|
||
"file-text": '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>',
|
||
"circle-check": '<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>',
|
||
"circle-alert": '<circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/>',
|
||
"circle-x": '<circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>',
|
||
"loader": '<path d="M12 2v4"/><path d="m16.2 7.8 2.9-2.9"/><path d="M18 12h4"/><path d="m16.2 16.2 2.9 2.9"/><path d="M12 18v4"/><path d="m4.9 19.1 2.9-2.9"/><path d="M2 12h4"/><path d="m4.9 4.9 2.9 2.9"/>',
|
||
"minus": '<path d="M5 12h14"/>',
|
||
"x": '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
|
||
"plus": '<path d="M5 12h14"/><path d="M12 5v14"/>',
|
||
"check": '<path d="M20 6 9 17l-5-5"/>',
|
||
"search": '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>',
|
||
"chevron-left": '<path d="m15 18-6-6 6-6"/>',
|
||
"chevron-right": '<path d="m9 18 6-6-6-6"/>',
|
||
"chevron-down": '<path d="m6 9 6 6 6-6"/>',
|
||
"chevron-up": '<path d="m18 15-6-6-6 6"/>',
|
||
"ellipsis": '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',
|
||
"settings": '<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>',
|
||
"star": '<path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"/>',
|
||
"pin": '<path d="M12 17v5"/><path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"/>',
|
||
"folder": '<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>',
|
||
"trash": '<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>',
|
||
"reply": '<polyline points="9 14 4 9 9 4"/><path d="M20 20v-7a4 4 0 0 0-4-4H4"/>',
|
||
"smile-plus": '<path d="M22 11v1a10 10 0 1 1-9-10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" x2="9.01" y1="9" y2="9"/><line x1="15" x2="15.01" y1="9" y2="9"/><path d="M16 5h6"/><path d="M19 2v6"/>',
|
||
"audio-lines": '<path d="M2 10v3"/><path d="M6 6v11"/><path d="M10 3v18"/><path d="M14 8v7"/><path d="M18 5v13"/><path d="M22 10v3"/>',
|
||
"mic": '<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" x2="12" y1="19" y2="22"/>',
|
||
"arrow-up": '<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>',
|
||
"arrow-down": '<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>',
|
||
"stop": '<rect width="10" height="10" x="7" y="7" rx="1.5" fill="currentColor" stroke="none"/>',
|
||
"play": '<polygon points="6 3 20 12 6 21 6 3"/>',
|
||
"pause": '<rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>',
|
||
"pen": '<path d="M12 20h9"/><path d="M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z"/>',
|
||
"copy": '<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
|
||
"text-cursor": '<path d="M17 22h-1a4 4 0 0 1-4-4V6a4 4 0 0 1 4-4h1"/><path d="M7 22h1a4 4 0 0 0 4-4v-1"/><path d="M7 2h1a4 4 0 0 1 4 4v1"/>',
|
||
"refresh": '<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/>',
|
||
"history": '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>',
|
||
"monitor": '<rect width="20" height="14" x="2" y="3" rx="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/>',
|
||
"laptop": '<path d="M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z"/><path d="M20.054 15.987H3.946"/>',
|
||
"cloud": '<path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/>',
|
||
"server": '<rect width="20" height="8" x="2" y="2" rx="2" ry="2"/><rect width="20" height="8" x="2" y="14" rx="2" ry="2"/><line x1="6" x2="6.01" y1="6" y2="6"/><line x1="6" x2="6.01" y1="18" y2="18"/>',
|
||
"target": '<circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/>',
|
||
"alarm-clock": '<circle cx="12" cy="13" r="8"/><path d="M12 9v4l2 2"/><path d="M5 3 2 6"/><path d="m22 6-3-3"/><path d="M6.38 18.7 4 21"/><path d="M17.64 18.67 20 21"/>',
|
||
"sparkles": '<path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/>',
|
||
"calendar": '<path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/>',
|
||
"list-checks": '<path d="m3 17 2 2 4-4"/><path d="m3 7 2 2 4-4"/><path d="M13 6h8"/><path d="M13 12h8"/><path d="M13 18h8"/>',
|
||
"camera": '<path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/>',
|
||
"paperclip": '<path d="m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"/>',
|
||
"log-out": '<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" x2="9" y1="12" y2="12"/>',
|
||
"bell": '<path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/>',
|
||
"clock": '<circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>',
|
||
"circle-dot": '<circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="1"/>',
|
||
"palette": '<path d="M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z"/><circle cx="13.5" cy="6.5" r=".5" fill="currentColor"/><circle cx="17.5" cy="10.5" r=".5" fill="currentColor"/><circle cx="6.5" cy="12.5" r=".5" fill="currentColor"/><circle cx="8.5" cy="7.5" r=".5" fill="currentColor"/>',
|
||
"moon": '<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>',
|
||
"shield": '<path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/>',
|
||
"plug": '<path d="M12 22v-5"/><path d="M9 8V2"/><path d="M15 8V2"/><path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"/>',
|
||
"users": '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
|
||
"bookmark": '<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/>',
|
||
"power": '<path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/>',
|
||
"share": '<path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" x2="12" y1="2" y2="15"/>',
|
||
"download": '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>',
|
||
"globe": '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
|
||
"key": '<circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/>',
|
||
"lock": '<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>',
|
||
"message": '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',
|
||
"hand": '<path d="M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2"/><path d="M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2"/><path d="M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8"/><path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"/>',
|
||
"zap": '<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>',
|
||
"lightbulb": '<path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"/><path d="M9 18h6"/><path d="M10 22h4"/>',
|
||
"activity": '<path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"/>',
|
||
"eye": '<path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"/><circle cx="12" cy="12" r="3"/>',
|
||
"hard-drive": '<line x1="22" x2="2" y1="12" y2="12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/><line x1="6" x2="6.01" y1="16" y2="16"/><line x1="10" x2="10.01" y1="16" y2="16"/>',
|
||
"info": '<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>',
|
||
"smartphone": '<rect width="14" height="20" x="5" y="2" rx="2" ry="2"/><path d="M12 18h.01"/>',
|
||
"terminal": '<polyline points="4 17 10 11 4 5"/><line x1="12" x2="20" y1="19" y2="19"/>',
|
||
"brain": '<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/><path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"/>',
|
||
"keyboard": '<path d="M10 8h.01"/><path d="M12 12h.01"/><path d="M14 8h.01"/><path d="M16 12h.01"/><path d="M18 8h.01"/><path d="M6 8h.01"/><path d="M7 16h10"/><path d="M8 12h.01"/><rect width="20" height="16" x="2" y="4" rx="2"/>',
|
||
"bot": '<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/>',
|
||
};
|
||
function ic(name, size = 18) { return `<svg class="ic" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${LUCIDE[name] || ""}</svg>`; }
|
||
const $ = (id) => document.getElementById(id);
|
||
function esc(s) { return String(s ?? "").replace(/[&<>"']/g, (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); }
|
||
// (No network is told once, by the line at the top — not again by every request that failed.)
|
||
// (A longer one stays longer: time to read it — 2.6 s, and more for each word past a short line.)
|
||
function toast(t) { if (t === OFFLINE_MSG) return netDown(true); const e = $("toast"); e.textContent = t; e.classList.add("on"); clearTimeout(toast.t); toast.t = setTimeout(() => e.classList.remove("on"), Math.min(7000, 2600 + Math.max(0, String(t).length - 16) * 70)); }
|
||
const nap = (ms) => new Promise((r) => setTimeout(r, ms));
|
||
// Times as the desktop's sidebar shows them: 剛剛 / 5 分鐘 / 3 小時 / 昨天 / 4 天 / 11/5.
|
||
function ago(ms) {
|
||
if (!ms) return "";
|
||
const s = (Date.now() - ms) / 1000;
|
||
if (s < 60) return "剛剛";
|
||
if (s < 3600) return Math.floor(s / 60) + " 分鐘";
|
||
const d = new Date(ms), now = new Date();
|
||
if (d.toDateString() === now.toDateString()) return Math.floor(s / 3600) + " 小時";
|
||
const y = new Date(now); y.setDate(now.getDate() - 1);
|
||
if (d.toDateString() === y.toDateString()) return "昨天";
|
||
if (s < 7 * 86400) return Math.ceil(s / 86400) + " 天";
|
||
return `${d.getMonth() + 1}/${d.getDate()}`;
|
||
}
|
||
function clock(ms) { return ms ? new Date(ms).toLocaleTimeString("zh-TW", {hour: "numeric", minute: "2-digit"}) : ""; }
|
||
// "2026-11-11 13:52" in this phone's time zone (the brain may be a server running in UTC).
|
||
function stamp(ms) {
|
||
if (typeof ms !== "number") return String(ms ?? "");
|
||
const d = new Date(ms), p = (n) => String(n).padStart(2, "0");
|
||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
||
}
|
||
function dayLabel(ms) {
|
||
const d = new Date(ms), now = new Date(), y = new Date(now); y.setDate(now.getDate() - 1);
|
||
if (d.toDateString() === now.toDateString()) return "今天";
|
||
if (d.toDateString() === y.toDateString()) return "昨天";
|
||
return d.getFullYear() === now.getFullYear() ? `${d.getMonth() + 1} 月 ${d.getDate()} 日` : `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}`;
|
||
}
|
||
// The words selected inside el ("" when nothing is, or the selection is somewhere else).
|
||
function selIn(el) {
|
||
const s = getSelection();
|
||
if (!el || !s || s.isCollapsed || !String(s).trim()) return "";
|
||
for (let k = 0; k < s.rangeCount; k++) if (s.getRangeAt(k).intersectsNode(el)) return String(s);
|
||
return "";
|
||
}
|
||
// Plain words of a message for a one-line preview (no Markdown marks).
|
||
function plain(t) { return String(t || "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/[*_`#>]/g, "").replace(/\s+/g, " ").trim(); }
|
||
|
||
// 外觀 of this phone: follow it, or light or dark by hand.
|
||
// 外觀 of this phone: the computer's (設定 › 一般 › 外觀 › 主題, the default), the phone's own, or light
|
||
// or dark by hand.
|
||
const THEMES = [["", "跟著電腦"], ["system", "跟著手機"], ["light", "淺色"], ["dark", "深色"]];
|
||
// What the computer said last (kept, so the next start wears it before the brain answers).
|
||
const DESK = {theme: ""};
|
||
function phoneTheme() { try { return localStorage.getItem("anybot.theme") || ""; } catch (_) { return ""; } }
|
||
function applyTheme() {
|
||
const pick = phoneTheme();
|
||
const t = pick === "light" || pick === "dark" ? pick : pick === "system" ? "" : ["light", "dark"].includes(DESK.theme) ? DESK.theme : "";
|
||
if (t) document.documentElement.dataset.theme = t; else delete document.documentElement.dataset.theme;
|
||
if (typeof barColor === "function") barColor();
|
||
}
|
||
// The computer's colours (底色, 強調色, 對比 — theme::shell, light and dark) as this page's CSS
|
||
// variables. Only names and #hex colours go in; an older brain sends none and the built-in 紙 stays.
|
||
function paletteCss(p) {
|
||
if (!p || typeof p !== "object") return "";
|
||
const block = (o) => Object.entries(o && typeof o === "object" ? o : {}).filter(([k, v]) => /^[a-z0-9-]{2,20}$/.test(k) && /^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(String(v))).map(([k, v]) => `--${k}:${v}`).join(";");
|
||
const l = block(p.light), d = block(p.dark);
|
||
if (!l || !d) return "";
|
||
return `:root{${l}}:root[data-theme="light"]{${l}}@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){${d}}}:root[data-theme="dark"]{${d}}`;
|
||
}
|
||
function applyPalette(p) {
|
||
const css = paletteCss(p);
|
||
let el = document.getElementById("desk-palette");
|
||
if (!el) { el = document.createElement("style"); el.id = "desk-palette"; document.head.appendChild(el); }
|
||
// The 風格's chat backdrop (dots, a grid, waves), drawn in the page's own faint line colour.
|
||
const bd = p && ["dots", "grid", "waves"].includes(p.backdrop) ? p.backdrop : "";
|
||
if (bd) document.documentElement.dataset.backdrop = bd; else delete document.documentElement.dataset.backdrop;
|
||
if (el.textContent === css) return;
|
||
el.textContent = css;
|
||
try { if (css) localStorage.setItem("anybot.palette", JSON.stringify(p)); else localStorage.removeItem("anybot.palette"); } catch (_) {}
|
||
if (typeof barColor === "function") barColor();
|
||
}
|
||
try { DESK.theme = localStorage.getItem("anybot.desk-theme") || ""; applyPalette(JSON.parse(localStorage.getItem("anybot.palette") || "null")); } catch (_) {}
|
||
applyTheme();
|
||
// The phone switching light/dark while open: the status bar follows.
|
||
try { matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => barColor()); } catch (_) {}
|
||
|
||
const S = { voice: {},
|
||
relay: localStorage.getItem("anybot.relay") === "1", token: localStorage.getItem("anybot.token") || "", host: localStorage.getItem("anybot.host") || "",
|
||
version: 0, bots: [], approvals: [], pages: [], tasks: [], jumpAt: 0, models: [], hostName: "", mac: false, box: "", boxOn: false, role: "owner",
|
||
prevShown: 0, prevFirst: "", answer: null, sc: "",
|
||
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,
|
||
};
|
||
const owner = () => S.role !== "member";
|
||
const isOwner = () => S.role === "owner";
|
||
const bot = (id) => S.bots.find((b) => b.id === id);
|
||
function base() { return S.relay ? "h/" + encodeURIComponent(S.host) + "/" : ""; }
|
||
|
||
// A request that hears nothing back in this long is given up: a connection that died without
|
||
// saying so (Wi-Fi to cellular, a lift, back from the background) never fails by itself.
|
||
const WAIT_MS = 60000;
|
||
// The network, not the brain, said no: worth trying again (502–504: the account server can't
|
||
// reach the computer right now).
|
||
const OFFLINE_MSG = "連不上,網路好像斷了";
|
||
function offline() { const e = new Error(OFFLINE_MSG); e.transient = true; return e; }
|
||
// Requests that change something (a message, an upload, an answer), on their way: the page is not
|
||
// swapped for a new build under them (swapWhenAway).
|
||
let writing = 0;
|
||
async function api(path, opts = {}) {
|
||
const writes = (opts.method || (opts.body || opts.json !== undefined ? "POST" : "GET")) !== "GET";
|
||
if (writes) writing++;
|
||
try { return await apiOnce(path, opts); } finally { if (writes) writing--; }
|
||
}
|
||
async function apiOnce(path, opts) {
|
||
const headers = Object.assign({}, opts.headers || {});
|
||
if (S.token) headers.Authorization = "Bearer " + S.token;
|
||
// (An upload has no deadline: a photo on a slow line takes what it takes.)
|
||
const ms = opts.timeout !== undefined ? opts.timeout : opts.body && opts.json === undefined ? 0 : WAIT_MS;
|
||
if (opts.json !== undefined) { headers["Content-Type"] = "application/json"; opts.body = JSON.stringify(opts.json); }
|
||
const ctl = new AbortController();
|
||
const timer = ms ? setTimeout(() => ctl.abort(), ms) : 0;
|
||
if (opts.signal) { if (opts.signal.aborted) ctl.abort(); else opts.signal.addEventListener("abort", () => ctl.abort(), {once: true}); }
|
||
let r, t;
|
||
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);
|
||
// (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) { 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); 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.
|
||
const resting = new Set();
|
||
function rest(ms) { return new Promise((done) => { const end = () => { clearTimeout(t); resting.delete(end); done(); }; const t = setTimeout(end, ms); resting.add(end); }); }
|
||
function wake() { [...resting].forEach((end) => end()); }
|
||
const backoff = (n, cap) => Math.min(cap, 1000 * 2 ** Math.min(n, 5)) * (0.6 + Math.random() * 0.4);
|
||
// 「連線中斷」 at the top, only once it has lasted a moment (a single lost request doesn't flash it).
|
||
let netTimer = 0;
|
||
function netDown(down, 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("");
|
||
// Words to a bot that survive a bad network: the same id on every try, so the brain takes them once
|
||
// even when an answer was lost on the way back.
|
||
async function deliver(path, body, retrying) {
|
||
body.id = body.id || mkId();
|
||
for (let n = 0; ; n++) {
|
||
try { const v = await api(path, {json: body, timeout: 20000}); netDown(false); return v; }
|
||
catch (e) {
|
||
if (!e.transient || !S.token || n >= 7) throw e;
|
||
netDown(true); if (retrying) retrying();
|
||
await rest(backoff(n, 10000));
|
||
}
|
||
}
|
||
}
|
||
// One of the desktop's actions (api/act/<what>), with its answer as a toast.
|
||
async function act(what, body, ok) {
|
||
try {
|
||
const v = await api(base() + "api/act/" + what, {json: body || {}});
|
||
if (ok !== false) toast(ok || v.text || "好了");
|
||
return v;
|
||
} catch (e) { toast(e.message); return null; }
|
||
}
|
||
const app = (name, args, b, ok) => act("app", {bot: b || S.open || 0, name, args}, ok);
|
||
|
||
// A bot's face as in the app (src/avatar.rs): its shape in its colour, two slanted oval eyes.
|
||
const color = (c) => (/^#[0-9a-f]{6}$/i.test(String(c || "")) ? c : "#1c1c1c");
|
||
function avatarSvg(shape, hex) {
|
||
const col = color(hex), P = Math.PI, f = (n) => n.toFixed(3);
|
||
const pts = (a) => `<polygon points="${a.map(([x, y]) => f(x) + "," + f(y)).join(" ")}"/>`;
|
||
const circ = (x, y, r) => `<circle cx="${f(x)}" cy="${f(y)}" r="${f(r)}"/>`;
|
||
const range = (n) => [...Array(n).keys()];
|
||
let body;
|
||
switch (shape) {
|
||
case "squircle": body = `<rect x="-0.92" y="-0.92" width="1.84" height="1.84" rx="0.42"/>`; break;
|
||
case "capsule": body = `<rect x="-0.675" y="-1" width="1.35" height="2" rx="0.66"/>`; break;
|
||
case "egg": body = pts(range(48).map((i) => { const t = i / 48 * 2 * P; return [0.8 * Math.cos(t), 0.08 + (Math.sin(t) < 0 ? 1 : 0.86) * Math.sin(t)]; })); break;
|
||
case "hex": body = pts(range(6).map((i) => { const a = i / 6 * 2 * P + P / 6; return [Math.cos(a), Math.sin(a)]; })); break;
|
||
case "gem": body = pts([[-0.55, -0.8], [0.55, -0.8], [1, -0.2], [0, 1], [-1, -0.2]]); break;
|
||
case "arch": body = pts(range(25).map((i) => { const a = P + i / 24 * P; return [0.85 * Math.cos(a), -0.15 + 0.85 * Math.sin(a)]; }).concat([[0.85, 1], [-0.85, 1]])); break;
|
||
case "shield": body = pts([[-0.85, -0.9], [0.85, -0.9], [0.85, 0.05], [0.5, 0.65], [0, 1], [-0.5, 0.65], [-0.85, 0.05]]); break;
|
||
case "pebble": body = `<ellipse rx="1" ry="0.78" transform="rotate(-14.3)"/>`; break;
|
||
case "cloud": body = circ(-0.45, 0.15, 0.55) + circ(0.45, 0.15, 0.55) + circ(0, -0.2, 0.65) + circ(0, 0.35, 0.55); break;
|
||
case "heart": body = circ(-0.45, -0.25, 0.55) + circ(0.45, -0.25, 0.55) + pts([[-0.97, -0.1], [0.97, -0.1], [0, 1]]); break;
|
||
case "star": body = pts(range(10).map((i) => { const a = -P / 2 + i * P / 5, r = i % 2 ? 0.48 : 1.05; return [r * Math.cos(a), 0.08 + r * Math.sin(a)]; })); break;
|
||
case "blob": body = pts(range(40).map((i) => { const a = i / 40 * 2 * P, r = 0.92 + 0.08 * Math.sin(3 * a); return [r * Math.cos(a), r * Math.sin(a)]; })); break;
|
||
default: body = circ(0, 0, 0.95);
|
||
}
|
||
const rgb = [1, 3, 5].map((i) => parseInt(col.slice(i, i + 2), 16));
|
||
const eye = rgb[0] + rgb[1] + rgb[2] > 600 ? "#1c1c1c" : "#fcfcfc";
|
||
const eyes = [-0.27, 0.27].map((x) => `<ellipse cx="${x}" cy="0.02" rx="0.11" ry="0.22" transform="rotate(-20 ${x} 0.02)"/>`).join("");
|
||
// A near-black bot gets a hairline edge: in dark it was only two eyes floating on the page.
|
||
const edge = rgb[0] + rgb[1] + rgb[2] < 150 ? ` style="stroke:var(--line)" stroke-width="0.08"` : "";
|
||
return `<svg viewBox="-1.1 -1.1 2.2 2.2" aria-hidden="true"><g fill="${col}"${edge}>${body}</g><g fill="${eye}">${eyes}</g></svg>`;
|
||
}
|
||
const face = (b, cls = "") => `<div class="av ${cls}">${avatarSvg(b.shape, b.color)}</div>`;
|
||
|
||
// ---------- the one sheet: menus, pickers, forms ----------
|
||
// opts: [{icon, label, x (right text), check, danger, on: fn}] or html; a tap runs on() and closes.
|
||
function sheet(title, items, html) {
|
||
const el = $("sheet-in");
|
||
el.innerHTML = `<div class="grab"></div>${title ? `<div class="st">${esc(title)}</div>` : ""}` + (html || "") +
|
||
(items || []).map((o, i) => o.sep ? `<div class="sep"></div>` : o.group ? `<div class="grp">${esc(o.group)}</div>` : `<button class="opt ${o.danger ? "danger" : ""}" data-i="${i}">${o.icon ? ic(o.icon, 20) : ""}<span>${esc(o.label)}</span>${o.check ? `<span class="ck">${ic("check", 18)}</span>` : o.x ? `<span class="x">${esc(o.x)}</span>` : ""}</button>`).join("");
|
||
el.querySelectorAll(".opt[data-i]").forEach((b) => b.onclick = () => { const o = items[+b.dataset.i]; if (!o.keep) closeSheet(); o.on && o.on(); });
|
||
$("sheet").classList.add("on");
|
||
return el;
|
||
}
|
||
function closeSheet() { $("sheet").classList.remove("on"); }
|
||
// (A drag that selects words on the sheet and lets go over the dim part is not a tap on it.)
|
||
let sheetDown = null;
|
||
$("sheet").addEventListener("pointerdown", (e) => { sheetDown = e.target; });
|
||
$("sheet").onclick = (e) => { if (e.target.id === "sheet" && (!sheetDown || sheetDown.id === "sheet")) closeSheet(); };
|
||
// A question with a text answer (prompt() looks out of place on a phone).
|
||
function ask(title, value = "", placeholder = "", multi = false) {
|
||
return new Promise((done) => {
|
||
const el = sheet(title, [], `<div class="form">${multi ? `<textarea class="field" id="ask-in" placeholder="${esc(placeholder)}">${esc(value)}</textarea>` : `<input class="field" id="ask-in" value="${esc(value)}" placeholder="${esc(placeholder)}">`}<div class="row2" style="justify-content:flex-end;margin-top:6px"><button class="btn" id="ask-no">取消</button><button class="btn main" id="ask-ok">好</button></div></div>`);
|
||
const input = el.querySelector("#ask-in"); setTimeout(() => input.focus(), 50);
|
||
el.querySelector("#ask-no").onclick = () => { closeSheet(); done(null); };
|
||
el.querySelector("#ask-ok").onclick = () => { closeSheet(); done(input.value.trim()); };
|
||
if (!multi) input.onkeydown = (e) => { if (e.key === "Enter" && !e.isComposing) el.querySelector("#ask-ok").click(); };
|
||
});
|
||
}
|
||
// (`icon`: the yes button's, when a trash can or a check is the wrong picture — 登出 is log-out.)
|
||
function confirmSheet(title, note, yes, danger = true, icon = "") {
|
||
return new Promise((done) => {
|
||
sheet(title, [{label: yes, danger, icon: icon || (danger ? "trash" : "check"), on: () => done(true)}, {label: "取消", on: () => done(false)}], note ? `<div class="note" style="text-align:center">${esc(note)}</div>` : "");
|
||
});
|
||
}
|
||
|
||
// ---------- screens: a stack, the phone's back gesture goes back ----------
|
||
const NAV = [];
|
||
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();
|
||
// 交付確認: back in the chat (from a preview), what is in view now counts as shown.
|
||
if (v === "chat" && was !== "chat") setTimeout(() => document.querySelectorAll("#msgs [data-att]").forEach(seenCheck), 0);
|
||
// 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}); }
|
||
barColor();
|
||
}
|
||
// Android's status bar (and the browser's own bar) in the colour of the top of the screen showing.
|
||
function barColor() {
|
||
const top = document.querySelector(".view.on .bar") || document.querySelector(".view.on") || document.body;
|
||
const c = getComputedStyle(top).backgroundColor;
|
||
if (!c || c === "rgba(0, 0, 0, 0)") return;
|
||
document.querySelectorAll('meta[name="theme-color"]').forEach((m) => m.setAttribute("content", c));
|
||
// (stripColor is in the last script: not there yet while this one first runs.)
|
||
if (typeof stripColor === "function") stripColor();
|
||
}
|
||
function go(v, arg = {}, replace = false) {
|
||
S.dir = replace ? "" : "in-fwd";
|
||
if (replace && NAV.length) NAV[NAV.length - 1] = {v, arg}; else NAV.push({v, arg});
|
||
if (replace) history.replaceState({n: NAV.length}, ""); else history.pushState({n: NAV.length}, "");
|
||
draw(v, arg);
|
||
}
|
||
function back() { if (NAV.length > 1) history.back(); else go("home", {}, true); }
|
||
window.addEventListener("popstate", () => {
|
||
if (!S.token) return;
|
||
if (boxOpen) { closeBox(); return; } // the takeover overlay sits above the stack; back closes it
|
||
NAV.pop();
|
||
if (!NAV.length) { NAV.push({v: "home", arg: {}}); history.pushState({n: 1}, ""); }
|
||
const t = NAV[NAV.length - 1];
|
||
S.dir = S.swiped ? "" : "in-back"; S.swiped = false;
|
||
closeSheet();
|
||
draw(t.v, t.arg);
|
||
});
|
||
document.querySelectorAll("[data-back]").forEach((b) => { b.innerHTML = ic("chevron-left", 24); b.onclick = back; });
|
||
function draw(v, arg) {
|
||
show(v);
|
||
if (v === "home") renderHome();
|
||
else if (v === "chat") openChat(arg.bot, arg.at);
|
||
else if (v === "details") renderDetails(arg.bot, arg.tab);
|
||
else if (v === "botset") renderBotset(arg.bot);
|
||
else if (v === "list") renderList(arg);
|
||
else if (v === "page") openPage(arg.id, arg.rev);
|
||
else if (v === "screen") { startFrames(); macTools(); }
|
||
}
|
||
const cur = () => NAV[NAV.length - 1] || {v: "home", arg: {}};
|
||
|
||
// ---------- sign in ----------
|
||
async function hello(tries = 0) {
|
||
// Still outside: the login and the bot list wait until this answers. A remembered way in
|
||
// (account or phone password) only labels the wait — it does not open the app on a dead line.
|
||
if (!S.entered) show("gate");
|
||
const known = localStorage.getItem("anybot.relay");
|
||
try { const v = await api("api/hello", {timeout: 12000}); S.relay = v.app === "anybot-relay"; localStorage.setItem("anybot.relay", S.relay ? "1" : "0"); netDown(false); }
|
||
catch (e) {
|
||
if (!e.transient) S.relay = false;
|
||
else {
|
||
if (known !== null) S.relay = known === "1";
|
||
netDown(true);
|
||
if (!S.entered) { await rest(backoff(tries, 15000)); return hello(tries + 1); }
|
||
}
|
||
}
|
||
$("f-user").style.display = S.relay ? "" : "none";
|
||
$("b-mode").style.display = S.relay ? "" : "none";
|
||
$("login-desc").textContent = S.relay ? "用你的 AnyBot 帳號登入。在哪裡都能用,電腦不用開任何連接埠。" : "輸入這台 AnyBot 的手機密碼(在 AnyBot 設定 › 手機與帳號 設定)。";
|
||
if (!S.token) return show("login");
|
||
if (S.relay) return pickHost();
|
||
start();
|
||
}
|
||
let signingUp = false;
|
||
$("b-mode").onclick = () => {
|
||
signingUp = !signingUp;
|
||
$("f-invite").style.display = signingUp ? "" : "none";
|
||
$("b-login").textContent = signingUp ? "建立帳號並登入" : "登入";
|
||
$("b-mode").textContent = signingUp ? "已經有帳號?登入" : "還沒有帳號?建立一個";
|
||
$("login-title").textContent = signingUp ? "建立 AnyBot 帳號" : "登入 AnyBot";
|
||
$("f-pass").placeholder = signingUp ? "密碼(至少 8 個字)" : "密碼";
|
||
};
|
||
$("b-login").onclick = async () => {
|
||
const b = $("b-login"); b.disabled = true; $("login-err").textContent = "";
|
||
const device = (navigator.userAgent.match(/iPhone|iPad|Android|Mac|Windows/) || ["手機"])[0];
|
||
try {
|
||
if (S.relay && signingUp) await api("relay/signup", {json: {user: $("f-user").value.trim(), password: $("f-pass").value, invite: $("f-invite").value.trim()}});
|
||
const v = await api(S.relay ? "relay/login" : "api/login", {json: {user: $("f-user").value.trim(), password: $("f-pass").value, device}});
|
||
if (v.need_2fa) {
|
||
// 開了两步验证:密码只是第一步,验证器 App 上的六位数(或一张恢复码)才换来通行证。
|
||
const code = (prompt("Two-step 验证:输入 App 上的六位验证码(没有 App 可用一张恢复码)") || "").trim();
|
||
if (!code) throw new Error("已取消");
|
||
const v2 = await api("relay/2fa/verify", {json: {challenge: v.challenge, code}});
|
||
v.token = v2.token;
|
||
}
|
||
S.token = v.token; localStorage.setItem("anybot.token", S.token); $("f-pass").value = "";
|
||
if (S.relay) await pickHost(); else start();
|
||
} catch (e) { $("login-err").textContent = e.message; }
|
||
b.disabled = false;
|
||
};
|
||
$("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");
|
||
// 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.winAt = 0; S.oldCopy = false; S.chatSig = ""; KEEP.clear();
|
||
if (expired) $("login-err").textContent = "登入已失效,請重新登入" + (lost ? `(還沒送出的 ${lost} 則訊息已清掉)` : "");
|
||
}
|
||
// 登出這支手機, from the 帳戶選單 or 設定 › 手機與帳號: the same question both ways (the menu's
|
||
// used to say nothing of the messages still waiting to go, which go with it).
|
||
async function askSignOut() {
|
||
const n = OUT.filter((x) => !x.sentAt).length;
|
||
if (await confirmSheet("要登出這支手機嗎?", n ? `還沒送出的 ${n} 則訊息會跟著清掉。` : "", "登出", true, "log-out")) signOut();
|
||
}
|
||
$("b-out1").innerHTML = ic("log-out", 20);
|
||
$("b-out1").onclick = () => signOut();
|
||
|
||
// The list waits for a brain that is restarting (or a computer that woke up): it looks again
|
||
// every few seconds and goes in by itself.
|
||
let hostRetry = null;
|
||
async function pickHost() {
|
||
clearTimeout(hostRetry);
|
||
let me;
|
||
const pre = EARLY.me; EARLY.me = null;
|
||
try { me = await (pre || api("relay/me", {timeout: 15000})); netDown(false); } catch (e) { if (e.transient) netDown(true); else toast(e.message); if (S.token) hostRetry = setTimeout(pickHost, 3000); return; }
|
||
const all = me.hosts || [];
|
||
const byId = Object.fromEntries(all.map((h) => [h.id, h]));
|
||
// A link or an old choice that isn't one of this account's AnyBots is forgotten.
|
||
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);
|
||
try { await api("relay/invites", {json: {host: inv.host, accept: !!yes}}); } catch (e) { toast(e.message); }
|
||
if (yes) return pickHost();
|
||
}
|
||
const target = (id) => (byId[id] && byId[id].uses && byId[byId[id].uses]) ? byId[id].uses : id;
|
||
const hosts = all.filter((h) => !(h.uses && byId[h.uses]));
|
||
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) toHost(used[0].id);
|
||
if (S.host) {
|
||
const t = target(S.host);
|
||
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) { 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);
|
||
}
|
||
|
||
// ---------- live state ----------
|
||
const TZ = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || ""; } catch (_) { return ""; } })();
|
||
// The first state is in: now the list (or the chat a link asked for) is drawn, already filled.
|
||
function enter() {
|
||
if (S.entered) return;
|
||
S.entered = true;
|
||
netDown(false);
|
||
if (!NAV.length) { NAV.push({v: "home", arg: {}}); history.replaceState({n: 1}, ""); }
|
||
// (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));
|
||
}
|
||
if (S.sc && !S.open) {
|
||
const want = S.sc === "unread" ? S.bots.find((b) => b.unread) : (S.bots.find((b) => b.primary) || S.bots[0]);
|
||
S.sc = "";
|
||
if (want) S.open = want.id;
|
||
}
|
||
if (S.open && cur().v !== "chat") go("chat", {bot: S.open});
|
||
else { const t = cur(); draw(t.v, t.arg); }
|
||
}
|
||
async function start() {
|
||
if (S.polling) return;
|
||
if (!S.entered) show("gate");
|
||
S.polling = true;
|
||
let fails = 0;
|
||
while (S.token) {
|
||
pollCtl = new AbortController();
|
||
try {
|
||
// 單趟同步: when a chat is open, the state poll carries its messages too — sent only
|
||
// when their signature changed, 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 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;
|
||
// (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 || ""; 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)) 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) { takeKept(c); 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() {
|
||
// 視窗起點:分頁後這條持有從哪條訊息起,服務端從那裡算 diff(開頁只拿最新 30 條;
|
||
// 已翻到最頂時 w0=0,持有整串)。
|
||
const win = S.msgs.length && S.msgs[0].index >= 0 ? "&w0=" + S.msgs[0].index : "";
|
||
const open = S.open && (S.view === "chat" || !S.entered) ? "&bot=" + S.open + "&chat_sig=" + encodeURIComponent(S.chatSig) + "&chat_delta=1" + win : "";
|
||
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.
|
||
const POLL_MS = 45000;
|
||
// A remembered way in: relay/me and the first state set off at once, beside api/hello, instead
|
||
// of one after the other — each used only when it is the very request that would have been made.
|
||
// (Still in only once the state is here.)
|
||
const EARLY = {me: null, state: null};
|
||
function setOff() {
|
||
const known = localStorage.getItem("anybot.relay");
|
||
if (!S.token || known === null) return;
|
||
S.relay = known === "1";
|
||
if (S.relay) { EARLY.me = api("relay/me", {timeout: 15000}); EARLY.me.catch(() => {}); }
|
||
if (!S.relay || S.host) { const path = statePath(), ctl = new AbortController(); EARLY.state = {path, ctl, p: api(path, {timeout: POLL_MS, signal: ctl.signal})}; EARLY.state.p.catch(() => {}); }
|
||
}
|
||
function callOffEarly() { if (EARLY.state) EARLY.state.ctl.abort(); EARLY.state = null; }
|
||
let pollCtl = null;
|
||
// Back in front, or the network is back: ask now — not after a request on a connection that may
|
||
// have died meanwhile, or the rest of a back-off.
|
||
function kick() {
|
||
if (!S.token) return;
|
||
callOffEarly();
|
||
if (S.polling && pollCtl) pollCtl.abort();
|
||
wake();
|
||
}
|
||
// What changed, over the state this page holds: keys left out are as they were, and a bot that
|
||
// is only {id, same} too.
|
||
function mergeState(prev, v) {
|
||
const m = Object.assign({}, prev, v);
|
||
delete m.base;
|
||
m.chat = v.chat;
|
||
if (v.bots) {
|
||
const had = new Map((prev.bots || []).map((b) => [b.id, b]));
|
||
m.bots = v.bots.map((b) => (b.same ? had.get(b.id) : b));
|
||
if (m.bots.some((b) => !b)) return null;
|
||
}
|
||
return m;
|
||
}
|
||
function apply(v) {
|
||
S.bots = v.bots || []; S.approvals = v.approvals || []; S.hostName = v.host || ""; S.mac = !!v.mac;
|
||
S.box = v.box || ""; S.boxOn = !!v.box_available; S.pages = v.pages || []; S.tasks = v.tasks || []; S.models = v.models || []; S.sections = v.sections || null; S.pinOrder = v.pin_order || null; S.always = !!v.always; S.role = v.role || "owner";
|
||
S.voice = v.voice || {}; micShown(); appBadge();
|
||
// The computer's 外觀 (an older brain sends neither: the built-in look stays).
|
||
if (v.palettes) applyPalette(v.palettes);
|
||
if (typeof v.theme === "string" && v.theme !== DESK.theme) { DESK.theme = v.theme; try { localStorage.setItem("anybot.desk-theme", v.theme); } catch (_) {} applyTheme(); }
|
||
// Still on the gate: keep what arrived (so the list and an opened chat are full the moment
|
||
// we go in) but don't draw the inside yet.
|
||
if (!S.entered) {
|
||
const c = v.chat;
|
||
if (c && c.bot === S.open && c.messages && c.from === undefined) { S.msgs = takeWhole(c.messages); S.chatSig = c.sig || ""; mergeDeliveries(S.msgs, c.deliveries); }
|
||
return;
|
||
}
|
||
// An approval answered from a notification banner, and a home-screen shortcut (主要 Bot, 未讀).
|
||
if (S.answer && S.token) {
|
||
const a = S.answer; S.answer = null;
|
||
// (from: "notice" — a notification's buttons answer only a request to allow, never a hand-off.)
|
||
api(base() + `api/bots/${a.bot}/answer`, {json: {answer: a.answer, call: a.call, from: "notice"}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message));
|
||
}
|
||
if (S.sc && !S.open) {
|
||
const want = S.sc === "unread" ? S.bots.find((b) => b.unread) : (S.bots.find((b) => b.primary) || S.bots[0]);
|
||
S.sc = "";
|
||
if (want) { S.open = want.id; go("chat", {bot: want.id}); }
|
||
}
|
||
const t = cur();
|
||
if (t.v === "home") renderHome();
|
||
else if (t.v === "chat") {
|
||
chatHead(); renderDock();
|
||
const c = v.chat;
|
||
// (A poll that left before the person switched chats carries the old chat: ignore it.)
|
||
// 串流降頻:開著聊天時服務端每秒最多重發一次聊天(最小的差量是一整條訊息),被擋時過一秒再問。
|
||
if (c && c.bot === S.open && c.throttled) chatLater();
|
||
// 交付確認不在訊息裡:只有 ✓ mark 動了,蓋上新的就好,不重畫整串。
|
||
// (Whether it is working moves without the chat: a turn that ended after its last words came
|
||
// drops 「正在…」 and gets its time and buttons. What it is doing only changes that line's words.)
|
||
else if (c && c.bot === S.open && c.unchanged) {
|
||
if (mergeDeliveries(S.msgs, c.deliveries) || S.drawnBusy !== busyKey()) renderMsgs();
|
||
else { const p = $("msgs").querySelector(".working .presence"), st = (bot(S.open) || {}).status; if (p && st && p.textContent !== st) p.textContent = st; }
|
||
}
|
||
// Only where it differs from what this page holds: drop the first few (the oldest left the
|
||
// window), keep the next `from`, then the new ones. Told against another list: all of it again.
|
||
else if (c && c.bot === S.open && c.messages && c.from !== undefined) { if (c.base === S.chatSig) applyChat(takePart(c), c.sig, c.deliveries); else loadChat(); }
|
||
else if (c && c.bot === S.open && c.messages) applyChat(takeWhole(c.messages), c.sig, c.deliveries);
|
||
else loadChat();
|
||
}
|
||
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);
|
||
else if (t.v === "list" && t.arg.kind === "tasks") listTasks($("list"));
|
||
settingsChanged();
|
||
}
|
||
|
||
// ---------- home: the sidebar ----------
|
||
$("b-search").innerHTML = ic("search", 20); $("b-newbot").innerHTML = ic("plus", 22); $("search-ic").innerHTML = ic("search", 16); $("b-search-x").innerHTML = ic("x", 16);
|
||
$("b-search").onclick = () => { $("searchbox").classList.add("on"); $("search").focus(); };
|
||
$("b-search-x").onclick = () => { $("search").value = ""; S.search = ""; S.hits = null; $("searchbox").classList.remove("on"); renderHome(); };
|
||
// 搜尋 finds bots by name, and (the owner's) words in every chat — past conversations and file
|
||
// names too — as on the computer: a tap opens that chat at that message.
|
||
let searchTimer = 0, searchSeq = 0;
|
||
$("search").oninput = () => {
|
||
S.search = $("search").value.trim().toLowerCase();
|
||
S.hits = null; clearTimeout(searchTimer);
|
||
if (S.search && owner()) searchTimer = setTimeout(searchChats, 300);
|
||
renderHome();
|
||
};
|
||
async function searchChats() {
|
||
const q = S.search, seq = ++searchSeq;
|
||
const v = await act("search", {q: $("search").value.trim()}, false);
|
||
if (seq !== searchSeq || q !== S.search) return;
|
||
S.hits = v || {hits: [], more: false};
|
||
renderHome();
|
||
}
|
||
function hitsHtml() {
|
||
if (!S.search || !S.hits) return "";
|
||
const hits = S.hits.hits || [];
|
||
if (!hits.length) return `<div class="empty" style="padding-top:12px">聊天裡也沒有找到</div>`;
|
||
return `<div class="sec">${ic("message", 13)}聊天裡 <span class="n">${hits.length}${S.hits.more ? "+" : ""}</span></div><div class="rows">${hits.map((h, i) => {
|
||
const b = bot(h.bot) || {};
|
||
const where = h.thread != null ? `<span class="pill">過去的對話</span>` : "";
|
||
const what = (h.file ? "📎 " + h.file + " " : "") + (h.snippet || "");
|
||
return `<div class="row" data-hit="${i}"><div class="av">${avatarSvg(b.shape, b.color)}</div><div class="mid"><div class="nm"><span class="t">${esc(h.bot_name || b.name || "")}</span>${where}</div><div class="pv">${esc(what)}</div></div><div class="tm">${ago(h.at)}</div></div>`;
|
||
}).join("")}</div>`;
|
||
}
|
||
async function openHit(i) {
|
||
const h = ((S.hits || {}).hits || [])[i];
|
||
if (!h) return;
|
||
if (h.thread != null) {
|
||
if (!await confirmSheet("回到這段對話?", `「${h.thread_title || "對話"}」會換回來,現在的對話留在「過去的對話」裡。`, "回到這段對話", false)) return;
|
||
try { await api(base() + `api/bots/${h.bot}/restore`, {json: {index: h.thread}}); } catch (e) { toast(e.message); return; }
|
||
}
|
||
go("chat", {bot: h.bot, at: h.at});
|
||
}
|
||
function botState(b) {
|
||
const waiting = S.approvals.find((a) => a.bot === b.id);
|
||
if (waiting) return {cls: "wait", dot: "wait", text: waiting.kind === "question" ? "等你回答:" + waiting.reason : "等你處理:" + (waiting.kind === "handoff" ? waiting.reason : waiting.title)};
|
||
if (b.busy) return {cls: "busy", dot: "busy", text: b.status || "工作中…"};
|
||
return {cls: "", dot: b.unread ? "unread" : "", text: plain(b.last) || b.description || "還沒有訊息"};
|
||
}
|
||
function botRow(b) {
|
||
const st = botState(b);
|
||
return `<div class="row" data-bot="${b.id}">${`<div class="av">${avatarSvg(b.shape, b.color)}${st.dot ? `<span class="dot ${st.dot}"></span>` : ""}</div>`}<div class="mid"><div class="nm"><span class="t">${esc(b.name)}</span>${b.members ? '<span class="pill">群組</span>' : ""}</div><div class="pv ${st.cls}">${esc(st.text)}</div></div><div class="tm">${ago(b.time)}</div><button class="more" data-botmenu="${b.id}" title="更多" aria-label="更多操作">${ic("ellipsis", 18)}</button></div>`;
|
||
}
|
||
function renderHome() {
|
||
installHint();
|
||
$("host-name").textContent = S.hostName ? "· " + S.hostName : "";
|
||
$("b-me").textContent = (S.hostName || "A").slice(0, 1).toUpperCase();
|
||
const q = S.search;
|
||
const match = (b) => !q || (b.name + " " + (b.description || "")).toLowerCase().includes(q);
|
||
const bots = S.bots.filter(match);
|
||
// Shortcuts the desktop keeps beside the chat: routines, pages, computers.
|
||
const routines = S.bots.reduce((n, b) => n + (b.routines || []).length, 0);
|
||
const main = S.bots.find((b) => b.primary) || S.bots[0];
|
||
const comps = (main && main.computers) || [];
|
||
const on = comps.filter((c) => c.online).length;
|
||
const tn = taskAttention();
|
||
$("quick").innerHTML = owner() ? [
|
||
`<button data-q="tasks" aria-label="任務${tn ? `,${tn} 件要看` : ""}">${ic("circle-check", 15)} 任務${tn ? ` <b>${tn}</b>` : ""}</button>`,
|
||
`<button data-q="schedule">${ic("calendar", 15)} 日程</button>`,
|
||
`<button data-q="workflows">${ic("workflow", 15)} 工作流</button>`,
|
||
`<button data-q="routines">${ic("alarm-clock", 15)} 例行任務 <b>${routines}</b></button>`,
|
||
`<button data-q="pages">${ic("file-text", 15)} 頁面 <b>${S.pages.length}</b></button>`,
|
||
`<button data-q="files">${ic("folder", 15)} 檔案</button>`,
|
||
`<button data-q="computers"><span class="st" style="background:${on ? "var(--ok)" : "var(--text4)"}"></span> 電腦 <b>${on}/${comps.length}</b></button>`,
|
||
isOwner() ? `<button data-q="settings">${ic("settings", 15)} 設定</button>` : "",
|
||
].join("") : "";
|
||
$("b-newbot").style.display = isOwner() ? "" : "none";
|
||
$("quick").querySelectorAll("[data-q]").forEach((b) => b.onclick = () => go("list", {kind: b.dataset.q}));
|
||
if (!S.bots.length) { $("home").innerHTML = `<div class="empty">還沒有 Bot。按右上角的 + 建立第一個。</div>`; return; }
|
||
if (!bots.length) {
|
||
$("home").innerHTML = (q && S.hits && (S.hits.hits || []).length ? "" : `<div class="empty">${q && owner() && !S.hits ? "找找看聊天裡…" : "沒有相符的 Bot"}</div>`) + hitsHtml();
|
||
$("home").querySelectorAll("[data-hit]").forEach((r) => r.onclick = () => openHit(+r.dataset.hit));
|
||
return;
|
||
}
|
||
// The sidebar's sections: 主要 Bot, 已釘選的 Bot, the person's own sections, then Bot.
|
||
const primary = bots.filter((b) => b.primary);
|
||
// (In the desktop's order, which the owner can change from a bot's ⋯ › 更多.)
|
||
const pinAt = (b) => { const i = (S.pinOrder || []).indexOf(b.id); return i < 0 ? 1e9 : i; };
|
||
const pinned = bots.filter((b) => !b.primary && b.pinned).sort((a, b) => pinAt(a) - pinAt(b));
|
||
const rest = bots.filter((b) => !b.primary && !b.pinned);
|
||
// The desktop's 分區 in its order (null = 未分區), empty ones too.
|
||
const order = S.sections || [...new Set(rest.map((b) => b.folder).filter(Boolean)), null];
|
||
const folders = order.filter((f) => f != null);
|
||
let folded = {}; try { folded = JSON.parse(localStorage.getItem("anybot.folded") || "{}"); } catch (_) {}
|
||
const sec = (title, icon, list, key, extra = "", keep = false) => list.length || keep ? `<div class="sec" data-fold="${esc(key)}">${icon ? ic(icon, 13) : ""}${esc(title)} <span class="n">${list.length}</span>${extra}${key ? `<button ${extra ? 'style="margin-left:6px"' : ""}>${ic(folded[key] ? "chevron-right" : "chevron-down", 14)}</button>` : ""}</div>${folded[key] ? "" : `<div class="rows">${list.map(botRow).join("")}</div>`}` : "";
|
||
let h = sec("主要 Bot", "star", primary, "") + sec("已釘選的 Bot", "pin", pinned, "");
|
||
for (const f of order) {
|
||
if (f == null) h += sec(folders.length ? "未分區" : "Bot", "", rest.filter((b) => !folders.includes(b.folder)), folders.length ? "loose" : "");
|
||
else h += sec(f, "folder", rest.filter((b) => b.folder === f), "f:" + f, isOwner() ? `<button data-fmenu="${esc(f)}" style="margin-left:auto">${ic("ellipsis", 15)}</button>` : "", !q);
|
||
}
|
||
$("home").innerHTML = h + hitsHtml() + `<div style="height:calc(var(--safe-b) + 24px)"></div>`;
|
||
$("home").querySelectorAll("[data-hit]").forEach((r) => r.onclick = () => openHit(+r.dataset.hit));
|
||
$("home").querySelectorAll(".row[data-bot]").forEach((r) => {
|
||
r.onclick = (e) => { if (e.target.closest("[data-botmenu]")) return; go("chat", {bot: +r.dataset.bot}); };
|
||
let t = null; r.addEventListener("touchstart", () => { t = setTimeout(() => { t = "long"; botMenu(+r.dataset.bot); }, 520); }, {passive: true});
|
||
r.addEventListener("touchend", (e) => { if (t === "long") e.preventDefault(); clearTimeout(t); }); r.addEventListener("touchmove", () => clearTimeout(t), {passive: true});
|
||
});
|
||
$("home").querySelectorAll("[data-botmenu]").forEach((b) => b.onclick = (e) => { e.stopPropagation(); botMenu(+b.dataset.botmenu); });
|
||
// 分區's menu: rename it, or delete it (its bots go back to 未分區; nothing is deleted).
|
||
$("home").querySelectorAll("[data-fmenu]").forEach((b) => b.onclick = (e) => {
|
||
e.stopPropagation();
|
||
const f = b.dataset.fmenu;
|
||
sheet(f, [
|
||
{icon: "arrow-up", label: "往上移", on: () => act("section_move", {folder: f, by: -1}, false)},
|
||
{icon: "arrow-down", label: "往下移", on: () => act("section_move", {folder: f, by: 1}, false)},
|
||
{icon: "pen", label: "重新命名分區", on: async () => { const n = await ask("分區名稱", f); if (n && n !== f) app("rename_group", {group: f, new_name: n}); }},
|
||
{icon: "trash", label: "刪除分區", danger: true, on: async () => { if (await confirmSheet(`刪除分區「${f}」?`, "裡面的 Bot 會移到未分區,不會刪除任何 Bot。", "刪除分區")) app("delete_group", {group: f}); }},
|
||
]);
|
||
});
|
||
$("home").querySelectorAll(".sec[data-fold]").forEach((s) => { if (!s.dataset.fold) return; s.onclick = () => { folded[s.dataset.fold] = !folded[s.dataset.fold]; try { localStorage.setItem("anybot.folded", JSON.stringify(folded)); } catch (_) {} renderHome(); }; });
|
||
}
|
||
// The sidebar row's menu, as on the desktop.
|
||
function botMenu(id) {
|
||
const b = bot(id); if (!b || !owner()) return;
|
||
// What is used often first; the rest under 「更多…」 (a tap on the row already opens the chat).
|
||
const items = [{icon: "info", label: "對話詳細資訊", on: () => go("details", {bot: id})}];
|
||
const more = [{icon: b.unread ? "check" : "bell", label: b.unread ? "標示為已讀" : "標示為未讀", on: () => b.unread ? api(base() + `api/bots/${id}/read`, {json: {}}).then(() => toast("已標示為已讀")).catch((e) => toast(e.message)) : act("bot", {bot: id, key: "unread", value: true}, "已標示為未讀")}];
|
||
// (Changing bots is the owner's; an admin opens, reads and restarts them.)
|
||
if (isOwner()) items.push({icon: "pin", label: b.pinned ? "取消釘選" : "釘選", on: () => act("bot", {bot: id, key: "pinned", value: !b.pinned}, b.pinned ? "已取消釘選" : "已釘選")}, {icon: "folder", label: "移至分區", on: () => moveToFolder(b)});
|
||
// 團隊: whether teammates may use this bot (they see its chat, pages and files).
|
||
if (isOwner() && !b.members) more.push({icon: "users", label: b.team ? "不再分享給團隊成員" : "分享給團隊成員", on: () => act("bot", {bot: id, key: "team", value: !b.team}, b.team ? "團隊成員看不到這個 Bot 了" : "團隊成員現在可以使用這個 Bot")});
|
||
if (!b.primary && isOwner()) more.push({icon: "star", label: "設為主要 Bot", on: () => act("bot", {bot: id, key: "primary", value: true}, "已設為主要 Bot")});
|
||
// 已釘選的 Bot in another order (the desktop drags them; here one step at a time).
|
||
const pins = (S.pinOrder || []).filter((x) => { const y = bot(x); return y && y.pinned && !y.primary; });
|
||
const at = pins.indexOf(id);
|
||
if (isOwner() && b.pinned && at > 0) more.push({icon: "arrow-up", label: "釘選裡往前移", on: () => act("bot", {bot: id, key: "pin_at", value: at - 1}, false)});
|
||
if (isOwner() && b.pinned && at >= 0 && at < pins.length - 1) more.push({icon: "arrow-down", label: "釘選裡往後移", on: () => act("bot", {bot: id, key: "pin_at", value: at + 1}, false)});
|
||
// 分享: the bot as a file (another AnyBot imports it), or this chat as Markdown.
|
||
if (isOwner()) more.push({icon: "share", label: "匯出 Bot 檔案(.anybot)", on: () => exportAs("export_bot", id)});
|
||
more.push({icon: "refresh", label: "重新啟動這個 Bot", on: () => act("restart_bot", {bot: id})});
|
||
items.push({icon: "ellipsis", label: "更多…", on: () => sheet(b.name, more)});
|
||
if (isOwner()) items.push({sep: true}, {icon: "trash", label: "刪除 Bot", danger: true, on: () => deleteBot(b)});
|
||
sheet(b.name, items);
|
||
}
|
||
async function moveToFolder(b) {
|
||
if (!S.sections && !S.settings) await loadSettings();
|
||
const folders = S.sections ? S.sections.filter((f) => f != null) : (S.settings && S.settings.folders) || [];
|
||
sheet("移至分區", [
|
||
...folders.map((f) => ({icon: "folder", label: f, check: b.folder === f, on: () => app("move_to_group", {group: f, bots: [b.name]}, b.id)})),
|
||
{icon: "minus", label: "未分區", check: !b.folder, on: () => app("move_to_group", {group: "", bots: [b.name]}, b.id)},
|
||
{icon: "plus", label: "新增分區…", on: async () => { const n = await ask("新增分區", "", "例如:文宣組"); if (n) app("move_to_group", {group: n, bots: [b.name]}, b.id); }},
|
||
]);
|
||
}
|
||
async function deleteBot(b) {
|
||
if (!await confirmSheet(`刪除「${b.name}」?`, "這會刪除它和它的聊天記錄。此操作無法復原。", "刪除")) return;
|
||
if (await act("delete_bot", {bot: b.id}, `已刪除「${b.name}」`)) { if (S.open === b.id) { S.open = 0; go("home", {}, true); } }
|
||
}
|
||
// 新 Bot: 建立 Bot / 從範本建立 / 建立群組聊天 / 新增分區.
|
||
$("b-newbot").onclick = async () => {
|
||
if (!isOwner()) return;
|
||
if (!S.settings) loadSettings();
|
||
sheet("新 Bot", [
|
||
{icon: "bot", label: "建立 Bot", on: async () => { const n = await ask("新 Bot 的名字", "", "例如:研究助理"); if (n) newBotDone(await app("create_bot", {name: n})); }},
|
||
{icon: "sparkles", label: "從範本建立", on: templates},
|
||
{icon: "users", label: "建立群組聊天", on: groupChat},
|
||
{icon: "folder", label: "新增分區", on: async () => { const n = await ask("新增分區", "", "例如:文宣組"); if (n) app("create_group", {name: n}); }},
|
||
{icon: "download", label: "匯入 Bot 檔案(.anybot)", on: importBot},
|
||
]);
|
||
};
|
||
// A file the brain made (a bot, a transcript): saved on the phone — the share sheet where there
|
||
// is one (iPhone: 儲存到檔案, AirDrop…), else a download.
|
||
async function exportAs(what, id) {
|
||
const v = await act(what, {bot: id}, false);
|
||
if (!v || !v.content) return;
|
||
const file = new File([v.content], v.filename || "AnyBot.txt", {type: what === "export_bot" ? "application/json" : "text/markdown"});
|
||
try { if (navigator.canShare && navigator.canShare({files: [file]})) { await navigator.share({files: [file]}); return; } } catch (e) { if (e.name === "AbortError") return; }
|
||
const a = document.createElement("a"); a.href = URL.createObjectURL(file); a.download = file.name; document.body.appendChild(a); a.click(); a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(a.href), 4000);
|
||
toast("已存成「" + file.name + "」");
|
||
}
|
||
async function saveText(text, name) {
|
||
const file = new File([text], name, {type: "text/markdown"});
|
||
try { if (navigator.canShare && navigator.canShare({files: [file]})) { await navigator.share({files: [file]}); return; } } catch (e) { if (e.name === "AbortError") return; }
|
||
const a = document.createElement("a"); a.href = URL.createObjectURL(file); a.download = name; document.body.appendChild(a); a.click(); a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(a.href), 4000);
|
||
toast("已存成「" + name + "」");
|
||
}
|
||
function importBot() {
|
||
const pick = document.createElement("input"); pick.type = "file"; pick.accept = ".anybot,application/json";
|
||
pick.onchange = async () => {
|
||
const f = pick.files && pick.files[0]; if (!f) return;
|
||
const v = await act("import_bot", {content: await f.text()}, false);
|
||
if (v && v.ok !== false) { toast(v.text || "已匯入"); newBotDone(v); }
|
||
};
|
||
pick.click();
|
||
}
|
||
function newBotDone(v) { if (v && v.bot) setTimeout(() => go("chat", {bot: v.bot}), 400); }
|
||
async function templates() {
|
||
if (!S.settings) await loadSettings();
|
||
const t = (S.settings && S.settings.templates) || [];
|
||
const el = sheet("從範本建立", [], t.map((x, i) => `<button class="opt" data-t="${i}"><div class="av sm">${avatarSvg(x.shape, x.color)}</div><span style="min-width:0"><div>${esc(x.name)}</div><div style="font-size:var(--fs-small);color:var(--text3)">${esc(x.description)}</div></span></button>`).join(""));
|
||
el.querySelectorAll("[data-t]").forEach((b) => b.onclick = async () => { closeSheet(); newBotDone(await app("create_bot", {template: t[+b.dataset.t].name})); });
|
||
}
|
||
function groupChat() {
|
||
const cands = S.bots.filter((b) => !b.members);
|
||
const pick = new Set(cands.slice(0, 3).map((b) => b.id));
|
||
const draw = () => {
|
||
const el = sheet("建立群組聊天", [], `<div class="note">選幾個 Bot,它們會依序回答同一則訊息;打「@名字」可以只叫某幾個回答。</div>` + cands.map((b) => `<button class="opt" data-m="${b.id}"><div class="av sm">${avatarSvg(b.shape, b.color)}</div><span>${esc(b.name)}</span>${pick.has(b.id) ? `<span class="ck">${ic("check", 18)}</span>` : ""}</button>`).join("") + `<div class="form"><button class="btn main" id="gc-ok" ${pick.size ? "" : "disabled"}>建立</button></div>`);
|
||
el.querySelectorAll("[data-m]").forEach((b) => b.onclick = () => { const id = +b.dataset.m; pick.has(id) ? pick.delete(id) : pick.add(id); draw(); });
|
||
el.querySelector("#gc-ok").onclick = async () => { closeSheet(); newBotDone(await act("group_chat", {members: [...pick]}, "已建立群組聊天")); };
|
||
};
|
||
draw();
|
||
}
|
||
// 帳戶選單 (the desktop's account menu): 設定, this phone's look and notifications, more.
|
||
$("b-me").onclick = () => {
|
||
const items = [];
|
||
if (isOwner()) items.push({icon: "settings", label: "設定", on: () => go("list", {kind: "settings"})});
|
||
items.push({icon: "moon", label: "這支手機的外觀", x: (THEMES.find((t) => t[0] === phoneTheme()) || THEMES[0])[1], on: () => {
|
||
sheet("這支手機的外觀", THEMES.map(([k, n]) => ({label: n, check: phoneTheme() === k, on: () => { try { localStorage.setItem("anybot.theme", k); } catch (_) {} applyTheme(); }})));
|
||
}});
|
||
if (isOwner()) items.push({icon: "send", label: "傳送到其他裝置", on: dropsSheet});
|
||
items.push({icon: "bell", label: "通知", on: notifySheet});
|
||
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: () => { toHost(""); S.entered = false; NAV.length = 0; show("gate"); kick(); pickHost(); }});
|
||
items.push({icon: "log-out", label: "登出這支手機", danger: true, on: askSignOut});
|
||
sheet(S.hostName || "AnyBot", items);
|
||
};
|
||
</script>
|
||
<script>
|
||
"use strict";
|
||
// ---------- chat ----------
|
||
$("isl-chev").innerHTML = ic("chevron-right", 14);
|
||
$("b-newchat").innerHTML = ic("pen", 19); $("b-chatmore").innerHTML = ic("ellipsis", 20);
|
||
$("b-plus").innerHTML = ic("plus", 16); $("b-mic").innerHTML = ic("mic", 18); $("b-down").innerHTML = ic("arrow-down", 18);
|
||
const ST = {waiting: "circle-alert", running: "loader", done: "circle-check", denied: "minus", failed: "circle-x"};
|
||
// What the bot is doing, in the words the desktop uses (its status line, or a waiting question).
|
||
function chatSub(b) {
|
||
const a = S.approvals.find((x) => x.bot === b.id);
|
||
if (a) return ["wait", a.kind === "handoff" ? "需要你的輸入" : a.kind === "question" ? "等你回答" : "需要你核准"];
|
||
if (b.busy) return ["busy", b.status || "工作中…"];
|
||
return ["", b.model || ""];
|
||
}
|
||
function chatHead() {
|
||
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);
|
||
$("isl-sub").className = "s " + cls; $("isl-sub").textContent = text;
|
||
$("input").placeholder = "傳訊息給 " + b.name;
|
||
$("b-newchat").style.display = owner() ? "" : "none";
|
||
}
|
||
$("island").onclick = () => go("details", {bot: S.open});
|
||
// 存在這支手機上的(這個網址自己的儲存空間,登出就全部清掉):每台電腦上次的狀態、看過的聊天、
|
||
// 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, S.winAt);
|
||
}
|
||
// 看過的聊天(最多 12 份,每台電腦各自記):回到它先畫上次看到的,再只拿有變的部分。
|
||
const CHATS = new Map();
|
||
const chatKey = (id) => S.host + ":" + id;
|
||
function toHost(h) {
|
||
if (h === S.host) return;
|
||
keepNow();
|
||
if (S.chatSig) keepChat(S.open, S.msgs, S.chatSig, S.winAt);
|
||
S.open = 0; S.msgs = []; S.winAt = 0; S.oldCopy = false; 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, winAt) {
|
||
if (!id || !sig) return;
|
||
// (Each kept with its own name and when it was last seen: found again by its prefix. With how
|
||
// many of its messages are from before the brain's window — 載入更早 — or the next answer,
|
||
// told against that window, lands in the wrong place.)
|
||
const k = chatKey(id), was = CHATS.get(k), c = {k, msgs, sig, winAt: winAt || 0, t: Date.now()};
|
||
const same = was && was.sig === sig && was.winAt === c.winAt && (was.msgs || []).length === msgs.length && Date.now() - (was.t || 0) <= 3600000;
|
||
if (!same) KEEP.put("chat:" + k, c);
|
||
CHATS.delete(k); CHATS.set(k, same ? was : c);
|
||
while (CHATS.size > 12) { const old = CHATS.keys().next().value; CHATS.delete(old); KEEP.del("chat:" + old); }
|
||
}
|
||
// What was typed and not sent stays with its bot, as on the computer: switching bots, or closing
|
||
// the page, does not lose it (kept on this phone, per AnyBot).
|
||
const draftKey = () => "anybot.drafts:" + (S.host || "lan");
|
||
function drafts() { try { return JSON.parse(localStorage.getItem(draftKey()) || "{}"); } catch (_) { return {}; } }
|
||
function keepDraft(id, text) {
|
||
if (!id) return;
|
||
const d = drafts();
|
||
if (text && text.trim()) d[id] = text; else delete d[id];
|
||
try { localStorage.setItem(draftKey(), JSON.stringify(d)); } catch (_) {}
|
||
}
|
||
function openChat(id, at) {
|
||
S.jumpAt = at || 0;
|
||
// (Whose words the box holds is kept on its own: a notification sets S.open before coming here.)
|
||
if (S.draftOf !== id) {
|
||
const box = $("input");
|
||
keepDraft(S.draftOf, box.value);
|
||
S.draftOf = id;
|
||
box.value = drafts()[id] || ""; box.style.height = "auto"; setTimeout(() => box.dispatchEvent(new Event("input")), 0);
|
||
}
|
||
if (S.open !== id) {
|
||
keepChat(S.open, S.msgs, S.chatSig, S.winAt);
|
||
S.msgs = []; S.winAt = 0; S.oldCopy = false; 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) takeKept(kept);
|
||
}
|
||
S.open = id;
|
||
// Your bubbles as 聊天的顏色 on the computer says (ob.bubble): "quiet" a light grey with the
|
||
// page's ink (the default), "bot" the bot's colour, "black". (An older AnyBot sends no field: its colour.)
|
||
const ob = bot(id) || {}, chat = $("v-chat");
|
||
const bubble = ob.bubble || "bot";
|
||
chat.classList.toggle("quiet", bubble === "quiet");
|
||
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();
|
||
renderMsgs(); $("scroller").scrollTop = $("scroller").scrollHeight; atEnd = true;
|
||
jumpTo();
|
||
loadChat(!at); renderDock();
|
||
api(base() + `api/bots/${id}/read`, {json: {}}).catch(() => {});
|
||
}
|
||
let loading = false, again = false;
|
||
async function loadChat(jump) {
|
||
if (!S.open) return;
|
||
if (loading) { again = true; return; }
|
||
loading = true;
|
||
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), from the
|
||
// window it holds (w0: 分頁後從最早那條的序號起)。
|
||
const w0 = S.msgs.length && S.msgs[0].index >= 0 ? (held ? "&" : "?") + "w0=" + S.msgs[0].index : "";
|
||
const v = await api(base() + "api/bots/" + id + (held ? "?chat_sig=" + encodeURIComponent(held) + "&chat_delta=1" + w0 : "?first=1"));
|
||
// 只有交付確認動了:蓋上新的,不重抓。(Not a return: it left `loading` set for good — from then
|
||
// on every chat opened, 表情 and the like only asked again later, and a chat showed what this
|
||
// phone kept until the next poll happened to carry it, 20–40 s on a quiet line; 11/20–11/23.)
|
||
if (v.unchanged && S.open === id && S.host === host) { if (mergeDeliveries(S.msgs, v.deliveries)) renderMsgs(); }
|
||
// (Another chat opened meanwhile, or the poll already brought a newer copy: not this answer.)
|
||
else if (S.open === id && S.chatSig === held && S.host === host) {
|
||
const msgs = v.from === undefined ? takeWhole(v.messages || []) : v.base === held ? takePart(v) : null;
|
||
if (msgs) {
|
||
const sc = $("scroller"); const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140;
|
||
mergeDeliveries(msgs, v.deliveries);
|
||
S.chatSig = v.sig || ""; S.chatLoaded = true; place(msgs, jump || near); keepSoon();
|
||
jumpTo();
|
||
} else { S.chatSig = ""; again = true; }
|
||
}
|
||
} catch (e) { toast(e.message); if (S.open === id && !S.chatLoaded && S.view === "chat") renderMsgs(); }
|
||
loading = false;
|
||
if (again) { again = false; loadChat(); }
|
||
// 任務 → a message older than what the phone keeps of the chat: the chat stays at its end.
|
||
else if (S.jumpAt && S.chatLoaded && S.open === id && !jumpTo()) { S.jumpAt = 0; toast("那則訊息太早了,手機上只留最近的訊息"); }
|
||
}
|
||
// 載入更早:開頁只拿最新 30 條,這裡一次往回補 60 條(序號去重,接在上方)——從大腦上整段聊天拿,
|
||
// 不只手機那份最新的。按了一定有回應:載入中、補上了、或「已是對話最開頭」(按鈕收起來)。
|
||
async function loadOlder(again) {
|
||
if (!S.open || !S.msgs.length || !(S.msgs[0].index > 0) || S.olderBusy) return;
|
||
const id = S.open, host = S.host, from = S.msgs[0].index, fromAt = S.msgs[0].at;
|
||
let moved = false;
|
||
S.olderBusy = true; renderMsgs();
|
||
try {
|
||
const v = await api(base() + `api/bots/${id}/older?from=${from}&count=60`);
|
||
if (S.open !== id || S.host !== host) return;
|
||
// (The chat's start moved while it was asked — an older message left the window as a bot
|
||
// worked, a new conversation: these are from before another start, and on top they would
|
||
// leave a hole that stays. Asked again from where it starts now, once.)
|
||
if (!S.msgs.length || S.msgs[0].index !== from || S.msgs[0].at !== fromAt) { moved = true; return; }
|
||
const have = new Set(S.msgs.map((m) => m.index));
|
||
const add = (v.messages || []).filter((m) => !have.has(m.index));
|
||
mergeDeliveries(add, v.deliveries);
|
||
if (!v.more) S.olderEnd = {bot: id, at: add.length ? add[0].index : S.msgs[0].index};
|
||
if (add.length) {
|
||
const sc = $("scroller"), keep = sc.scrollHeight - sc.scrollTop;
|
||
S.msgs = add.concat(S.msgs); S.winAt = (S.winAt || 0) + add.length;
|
||
S.olderBusy = false; renderMsgs();
|
||
sc.scrollTop = sc.scrollHeight - keep;
|
||
}
|
||
if (!v.more) toast("已是對話最開頭");
|
||
} catch (e) { toast(e.message); }
|
||
finally {
|
||
if (S.olderBusy) { S.olderBusy = false; if (S.open === id) renderMsgs(); }
|
||
if (moved && !again) loadOlder(true);
|
||
}
|
||
}
|
||
// What the brain sends is its window of the chat: the newest it publishes (PHONE_TAIL, steps'
|
||
// results left out), from where this page says its copy starts (w0). 載入更早 brings messages
|
||
// from before that window — S.winAt of them, held in front of it as long as the window still
|
||
// begins on a message this page has; the next answer used to put the window alone in their
|
||
// place, and what was just loaded went away again (11/23: one new message, and the chat was
|
||
// back to 120 with 「載入更早的對話」 on top).
|
||
function takeWhole(msgs) {
|
||
const f = msgs[0];
|
||
// (A copy kept by a page from before 11/23 may hold a hole the old way left — what it had loaded
|
||
// and the newest, with the middle gone: none of its front is kept, once.)
|
||
const old = S.oldCopy; S.oldCopy = false;
|
||
const j = f && !old ? S.msgs.findIndex((m) => m.index === f.index && m.role === f.role && (m.at || 0) === (f.at || 0)) : -1;
|
||
S.winAt = j > 0 ? j : 0;
|
||
return j > 0 ? S.msgs.slice(0, j).concat(msgs) : msgs;
|
||
}
|
||
// Only where the window differs: drop its first `drop` (the oldest left it), keep the next `from`,
|
||
// then the new ones — the ones held in front stay, and with them the ones that left the window
|
||
// (no gap between); with none in front, those leave as before (the first open stays small).
|
||
function takePart(c) {
|
||
const at = S.winAt || 0, win = S.msgs.slice(at), drop = c.drop || 0;
|
||
const pre = at ? S.msgs.slice(0, at).concat(win.slice(0, drop)) : [];
|
||
S.winAt = pre.length;
|
||
return pre.concat(win.slice(drop).slice(0, c.from), c.messages || []);
|
||
}
|
||
// A kept copy, as it was: one kept before it said how many were from before the window has no
|
||
// fingerprint to be told against — the next answer is whole, and placed by its first message.
|
||
function takeKept(c) {
|
||
S.msgs = c.msgs; S.winAt = c.winAt || 0; S.oldCopy = c.winAt === undefined; S.chatSig = S.oldCopy ? "" : c.sig;
|
||
}
|
||
// What 載入更早 brought stays — but not without end: once the person is back at the bottom (or
|
||
// the page isn't in view), more than HOLD held and some from before the window, those go from the
|
||
// top (the button comes back). A phone left open for days would otherwise draw thousands, every
|
||
// second while a bot works.
|
||
const HOLD = 300;
|
||
function trimFront(most) {
|
||
const cut = Math.min(S.winAt || 0, S.msgs.length - HOLD, most === undefined ? Infinity : most);
|
||
if (cut > 0) { S.msgs = S.msgs.slice(cut); S.winAt -= cut; }
|
||
}
|
||
// What the person is reading: the first message on screen (its place in the whole chat) and how
|
||
// far down it sits — read off what is drawn (S.drawn: a page not in view isn't drawn again, and
|
||
// S.msgs may have moved on since).
|
||
function anchorNow() {
|
||
const top = $("scroller").getBoundingClientRect().top, drawn = S.drawn || S.msgs;
|
||
for (const el of $("msgs").querySelectorAll("[data-msg]")) {
|
||
const r = el.getBoundingClientRect(), m = drawn[+el.dataset.msg];
|
||
if (m && r.bottom > top) return {index: m.index, off: r.top - top};
|
||
}
|
||
return null;
|
||
}
|
||
// Back to it once drawn: the end, or that message where it was.
|
||
function holdRead(a) {
|
||
const sc = $("scroller");
|
||
if (!a) return;
|
||
if (a.end) { sc.scrollTop = sc.scrollHeight; return; }
|
||
const p = S.msgs.findIndex((m) => m.index === a.index), el = p < 0 ? null : $("msgs").querySelector(`[data-msg="${p}"]`);
|
||
if (el) sc.scrollTop += el.getBoundingClientRect().top - sc.getBoundingClientRect().top - a.off;
|
||
}
|
||
// Out of view: where the person was, taken now — while it is away the page isn't drawn, and what
|
||
// moves meanwhile (the bar under the chat growing as a bot starts, the list changing) is no
|
||
// place to measure it from (it drifted, 11/23).
|
||
function outOfView() {
|
||
if (S.view !== "chat" || !S.open) { S.keepRead = null; return; }
|
||
const sc = $("scroller");
|
||
S.keepRead = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140 ? {end: true} : anchorNow();
|
||
}
|
||
// In view again: drawn as it is now, and held where the person was (or at the end).
|
||
function backInView() {
|
||
if (S.msgsStale) { renderMsgs(); holdRead(S.keepRead); }
|
||
S.keepRead = null;
|
||
}
|
||
// A new list in place. Back at the bottom it follows the end, and what 載入更早 brought past HOLD
|
||
// goes. Further up, the message being read stays where it is on screen, whatever changes above it
|
||
// — and above HOLD×2 (HOLD while the page isn't in view: a phone in a pocket, a bot at work) the
|
||
// top goes too, up to 20 above that message. Past HOLD×4 the top goes regardless — read at the very
|
||
// top while a bot writes for hours, the list still has an end (what is read may then go with it).
|
||
// Not in view, nothing is drawn: where to be is kept, and taken back when it is (backInView).
|
||
function place(msgs, follow) {
|
||
// (Out of view: where it was when it went — not measured again on a page that isn't drawn.)
|
||
const away = document.hidden && S.keepRead;
|
||
const a = away ? S.keepRead : follow ? {end: true} : anchorNow();
|
||
if (away) follow = !!a.end;
|
||
S.msgs = msgs;
|
||
const n = S.msgs.length, most = (a && !a.end ? S.msgs.findIndex((m) => m.index === a.index) : -1) - 20;
|
||
if (follow) trimFront();
|
||
else if (n > 4 * HOLD) trimFront(Math.max(most, n - 4 * HOLD));
|
||
else if (n > (document.hidden ? HOLD : 2 * HOLD)) trimFront(most);
|
||
renderMsgs();
|
||
if (document.hidden) { S.keepRead = a; return; }
|
||
holdRead(a);
|
||
}
|
||
// 表情 on a message from before the brain's window: the brain has it, but no answer will say so —
|
||
// that message isn't in the window. Its reactions as the brain now has them (asked, not guessed:
|
||
// another device may have changed them too).
|
||
async function reacted(v, index) {
|
||
const i = v ? S.msgs.findIndex((m) => m.index === index) : -1;
|
||
if (i >= 0 && i < (S.winAt || 0)) {
|
||
const id = S.open;
|
||
try {
|
||
const o = await api(base() + `api/bots/${id}/older?from=${index + 1}&count=1`);
|
||
// (Only one still in front of the window: one the window took meanwhile comes with it.)
|
||
const got = (o.messages || []).find((m) => m.index === index), k = S.open === id ? S.msgs.findIndex((m) => m.index === index) : -1;
|
||
if (got && k >= 0 && k < (S.winAt || 0)) { S.msgs[k].reactions = got.reactions || []; renderMsgs(); }
|
||
} catch (_) {}
|
||
}
|
||
loadChat();
|
||
}
|
||
// The state poll carried the open chat's messages along (single trip): take them as they come.
|
||
function applyChat(msgs, sig, deliveries) {
|
||
S.chatSig = sig || ""; S.chatLoaded = true;
|
||
const sc = $("scroller");
|
||
const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140;
|
||
mergeDeliveries(msgs, deliveries);
|
||
place(msgs, near); keepSoon();
|
||
jumpTo();
|
||
}
|
||
// 交付確認(✓ mark)與訊息分開送(服务端也分開放:别的装置回報檔案不該改到聊天指紋):
|
||
// 蓋在持有的那批 attachment 上;動過的回 true(要重畫)。
|
||
function mergeDeliveries(msgs, deliveries) {
|
||
if (!msgs || !deliveries || !deliveries.length) return false;
|
||
const by = new Map(deliveries.map((d) => [d.id, d]));
|
||
let moved = false;
|
||
msgs.forEach((m) => (m.attachments || []).forEach((a) => {
|
||
const d = by.get(a.id);
|
||
if (!d) return;
|
||
const seen = d.seen || [];
|
||
if (a.delivery !== d.delivery || (a.seen || []).length !== seen.length) { a.delivery = d.delivery; a.seen = seen; moved = true; }
|
||
}));
|
||
return moved;
|
||
}
|
||
// 串流時聊天每秒最多重發一次;被擋下來時,一秒後補問一次。
|
||
function chatLater() { clearTimeout(S._ct); S._ct = setTimeout(() => { if (S.token) kick(); }, 1300); }
|
||
// What a new chat offers (the desktop's 建議): the everyday jobs, one tap to start writing them.
|
||
const SUGGEST = [
|
||
["search", "海巡 Threads", "整理熱門討論和互動數", "幫我在 Threads 海巡「」最近的熱門討論,整理互動最多的 5 則(誰發的、在講什麼、讚數、連結)。"],
|
||
["pen", "寫一則貼文", "用你平常的語氣先寫草稿", "用我 Threads 帳號平常的語氣,幫我寫一則關於「」的貼文草稿,先給我看,不要發。"],
|
||
["monitor", "看我電腦的畫面", "截一張現在的畫面給你", "截一張我電腦現在的畫面給我看。"],
|
||
["list-checks", "幫我研究一件事", "查清楚現況和來源,整理成一頁", "幫我研究「」:查清楚現況和來源,整理成一頁。"],
|
||
["alarm-clock", "建立例行任務", "每天、每週自動做", "幫我建立一個例行任務:每天早上 9 點"],
|
||
];
|
||
function stepHtml(t, key) {
|
||
const open = S.openSteps[key];
|
||
const body = `<div class="body">${t.detail ? `<div class="k">內容</div><pre>${esc(t.detail)}</pre>` : ""}${t.result ? `<div class="k">結果</div><pre>${esc(t.result)}</pre>` : ""}${!t.detail && !t.result ? `<div class="k">(沒有更多內容)</div>` : ""}</div>`;
|
||
return `<div class="step ${t.status} ${open ? "open" : ""}" data-step="${esc(key)}"><button class="h"><span class="st-i">${ic(ST[t.status] || "minus", 14)}</span><span class="l">${esc(t.label)}</span><span class="d">${esc(t.detail || "")}</span><span class="chev">${ic("chevron-right", 13)}</span></button>${body}</div>`;
|
||
}
|
||
function thinkHtml(m) {
|
||
const key = "t" + m.index, open = S.openSteps[key];
|
||
return `<div class="step done ${open ? "open" : ""}" data-step="${key}"><button class="h"><span class="st-i">${ic("brain", 14)}</span><span class="l">思考過程</span><span class="d">${esc(plain(m.thinking).slice(0, 80))}</span><span class="chev">${ic("chevron-right", 13)}</span></button><div class="body"><pre>${esc(m.thinking)}</pre></div></div>`;
|
||
}
|
||
function attHtml(a) {
|
||
if (!a.path) return `<div class="filec">${ic(a.image ? "image" : "file", 16)}<span class="fn">${esc(a.name)}</span></div>`;
|
||
const att = a.id ? ` data-att="${esc(a.id)}" data-bot="${S.open}"` : "";
|
||
// (A picture already fetched is drawn from its copy: a redraw doesn't drop every picture to its
|
||
// name and grow the chat again under the newest message.)
|
||
const got = BLOBS["img:" + a.path] || FILES[a.path];
|
||
if (a.image) return `<div class="attimg" data-file="${esc(a.path)}" data-name="${esc(a.name)}"${att}>${got ? `<img alt="${esc(a.name)}" src="${got}">` : `<div class="wait">${ic("image", 14)} ${esc(a.name)}</div>`}</div>`;
|
||
return `<a class="filec" data-file="${esc(a.path)}" data-name="${esc(a.name)}"${att}>${ic("file", 18)}<span style="min-width:0"><div class="fn">${esc(a.name)}</div><div style="font-size:var(--fs-caption);color:var(--text3)">${esc(a.kind || "檔案")}${a.bytes ? " · " + kb(a.bytes) : ""} · 點一下開啟</div></span></a>`;
|
||
}
|
||
// 交付確認: the mark under a file the bot handed over; tapping it lists the devices (dlvSheet).
|
||
const DLV_TITLE = {chat: "已放進聊天", shown: "已在裝置上顯示", opened: "已點開"};
|
||
function dlvMark(a) {
|
||
if (!a.id || !a.path) return "";
|
||
const d = DLV_TITLE[a.delivery] ? a.delivery : "chat";
|
||
return `<button class="dlv ${d}" data-dlv="${esc(a.id)}" aria-label="交付狀態:${DLV_TITLE[d]}">${ic("check", 12)}${d !== "chat" ? ic("check", 12) : ""}</button>`;
|
||
}
|
||
function dlvSheet(id) {
|
||
const a = S.msgs.flatMap((m) => m.role === "user" ? [] : m.attachments || []).find((x) => x.id === id);
|
||
if (!a) return;
|
||
const d = DLV_TITLE[a.delivery] ? a.delivery : "chat";
|
||
const what = {shown: "顯示了", opened: "點開了", failed: "沒顯示出來"};
|
||
const rows = (a.seen || []).map((x) => `<div class="r ${x.kind === "failed" ? "failed" : ""}"><b>${esc(x.device)}</b><span>${esc(what[x.kind] || "")}${x.why ? ":" + esc(x.why) : ""}</span><span class="w">${x.at ? esc(dayLabel(x.at) + " " + clock(x.at)) : ""}</span></div>`).join("");
|
||
sheet(DLV_TITLE[d], [], `<div class="dlv-list"><div class="note" style="text-align:center">${esc(a.name)}</div>${rows || `<div class="r"><span>還沒有裝置回報顯示</span></div>`}</div>`);
|
||
}
|
||
// 完成宣稱關卡: under a reply that didn't match what its turn did; tapping it says why.
|
||
function unvMark(m, i) {
|
||
return (m.check || []).length ? `<button class="unv" data-unv="${i}" aria-label="未驗證:看原因">${ic("circle-alert", 12)}未驗證</button>` : "";
|
||
}
|
||
function unvSheet(i) {
|
||
const m = S.msgs[i];
|
||
if (!m || !(m.check || []).length) return;
|
||
sheet("未驗證", [], `<div class="dlv-list"><div class="note" style="text-align:center">AnyBot 核對這一輪實際做了什麼,跟這則回覆對不上</div>${m.check.map((c) => `<div class="r failed"><span>${esc(c.why)}</span></div>`).join("")}</div>`);
|
||
}
|
||
// A link to a place on the bot's computer (sandbox:, file://, a path): the chat's file of that
|
||
// name opens; otherwise it is said plainly that it can't open here.
|
||
function openDeadLink(name) {
|
||
let n = name || "";
|
||
try { n = decodeURIComponent(n); } catch (_) {}
|
||
const a = [...S.msgs].reverse().flatMap((m) => m.attachments || []).find((x) => x.path && n && x.name.toLowerCase() === n.toLowerCase());
|
||
if (a) openFile(a.path, a.name, a.id || "");
|
||
else toast("這個連結指到 Bot 電腦上的位置,手機打不開;聊天裡也沒有這個檔案");
|
||
}
|
||
// The device this page names for itself in 交付確認.
|
||
function deviceLabel() {
|
||
const ua = navigator.userAgent || "";
|
||
if (/iPad/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) return "iPad";
|
||
if (/iPhone|iPod/.test(ua)) return "iPhone";
|
||
if (/Android/.test(ua)) return "Android";
|
||
return /Mobi/.test(ua) ? "手機" : "瀏覽器";
|
||
}
|
||
// What this page did with a file the bot handed over, told once each while the page is open
|
||
// (not queued: one lost on a bad line is tried again only when it is drawn again). 一批一批送:
|
||
// 開一個舊聊天會把看到的檔案全報一次,一檔一個請求、每個都叫醒所有頁面,慢線上是一场風暴。
|
||
const SEEN_TOLD = new Set();
|
||
const SEEN_OUT = [];
|
||
let SEEN_TIMER = 0;
|
||
function seenTell(att, kind, why, bot) {
|
||
const k = att + ":" + kind;
|
||
if (!att || !bot || SEEN_TOLD.has(k)) return;
|
||
SEEN_TOLD.add(k);
|
||
SEEN_OUT.push({bot, att, kind, why: why || ""});
|
||
clearTimeout(SEEN_TIMER);
|
||
SEEN_TIMER = setTimeout(seenFlush, 800);
|
||
}
|
||
function seenFlush() {
|
||
clearTimeout(SEEN_TIMER);
|
||
const rs = SEEN_OUT.splice(0);
|
||
const byBot = new Map();
|
||
rs.forEach((r) => { if (!byBot.has(r.bot)) byBot.set(r.bot, []); byBot.get(r.bot).push({att: r.att, kind: r.kind, why: r.why}); });
|
||
byBot.forEach((reports, bot) => api(base() + `api/bots/${bot}/seen`, {json: {device: deviceLabel(), reports}, timeout: 15000})
|
||
.catch((e) => { if (e.transient) reports.forEach((r) => SEEN_TOLD.delete(r.att + ":" + r.kind)); }));
|
||
}
|
||
// Shown: drawn (a picture loaded), in view, the page in front.
|
||
function seenCheck(el) {
|
||
if (!el.dataset.att || document.hidden || S.view !== "chat" || !el.isConnected) return;
|
||
const r = el.getBoundingClientRect();
|
||
if (r.bottom <= 0 || r.top >= innerHeight || !r.width) return;
|
||
if (el.classList.contains("attimg")) { const img = el.querySelector("img"); if (!img || !img.complete || !img.naturalWidth) return; }
|
||
seenTell(el.dataset.att, "shown", "", +el.dataset.bot);
|
||
}
|
||
const seenObs = "IntersectionObserver" in window ? new IntersectionObserver((es) => es.forEach((e) => { if (e.isIntersecting) seenCheck(e.target); }), {threshold: 0.2}) : null;
|
||
function seenWatch() {
|
||
if (!seenObs) return;
|
||
seenObs.disconnect();
|
||
document.querySelectorAll("#msgs [data-att]").forEach((el) => seenObs.observe(el));
|
||
}
|
||
document.addEventListener("visibilitychange", () => { if (document.hidden) { if (SEEN_OUT.length) seenFlush(); return; } document.querySelectorAll("#msgs [data-att]").forEach(seenCheck); });
|
||
// A picture in the chat: shown once it has loaded in view; one the phone can't decode failed.
|
||
function seenImg(el) {
|
||
const img = el.querySelector("img");
|
||
if (!img || !el.dataset.att) return;
|
||
img.onload = () => seenCheck(el);
|
||
img.onerror = () => {
|
||
// (Its kept copy let go while it loaded — many pictures in one chat: not the picture's fault.)
|
||
if (BLOBS["img:" + el.dataset.file] !== img.src) { el.innerHTML = ""; loadFiles(); return; }
|
||
el.innerHTML = `<div class="wait">這張圖讀不到</div>`;
|
||
// (Once more first: a picture whose kept copy was let go while it loaded isn't unreadable.)
|
||
if (!SEEN_RETRIED.has(el.dataset.att)) { SEEN_RETRIED.add(el.dataset.att); delete BLOBS["img:" + el.dataset.file]; loadFiles(); return; }
|
||
seenTell(el.dataset.att, "failed", "unreadable", +el.dataset.bot);
|
||
};
|
||
if (img.complete && img.naturalWidth) seenCheck(el);
|
||
}
|
||
// Couldn't be fetched: the brain said no (not a line that is down — that is nobody's failure).
|
||
const SEEN_RETRIED = new Set();
|
||
function seenFail(att, e, bot) {
|
||
if (!att || !e || e.transient || !e.status || e.status === 429) return;
|
||
seenTell(att, "failed", e.status === 404 ? "missing" : e.status === 422 ? "unreadable" : "error", bot);
|
||
}
|
||
const kb = (n) => n >= 1048576 ? (n / 1048576).toFixed(1) + " MB" : Math.max(1, Math.round(n / 1024)) + " KB";
|
||
function safeHttpUrl(u) {
|
||
const s = String(u || "").trim();
|
||
return /^https?:\/\//i.test(s) ? s : "";
|
||
}
|
||
/** 支線 (/btw): what it was asked, how it stands, its steps; a stop button while it works. */
|
||
function branchCard(r) {
|
||
const st = {checking: `${ic("loader", 13)} 先看看會不會跟主線正在做的事衝突…`, waiting: `等主線這一輪做完再開始:${esc(r.note || "")}`, running: `${ic("loader", 13)} ${esc(r.doing || "正在做…")}${r.steps ? `(${r.steps} 步)` : ""}`, done: `${ic("circle-check", 13)} 做完了`, failed: `沒有做完:${esc(r.note || "")}`, stopped: "已停止"}[r.state] || "";
|
||
const log = (r.log || []).length ? `<details class="br-log"><summary>看過程(${r.log.length})</summary>${r.log.map((l) => `<div>${esc(l)}</div>`).join("")}</details>` : "";
|
||
const stop = r.state === "running" && owner() ? `<button class="tk-go" data-brstop="${r.id}">停止支線</button>` : "";
|
||
return `<div class="talk branch"><div class="tk-h">${ic("activity", 13)}<span>支線</span><b>${esc(r.task)}</b></div><div class="tk-st ${r.state === "failed" ? "err" : ""}">${st}</div>${r.state === "done" && r.result ? `<div class="tk-a">${pageMd(r.result, 0)}</div>` : ""}${log}${stop}</div>`;
|
||
}
|
||
/** 同事之間: who asked whom (or handed what), and the answer once it is back — here, in the chat
|
||
* that asked. The colleague's own chat keeps the whole of it. */
|
||
function talkCard(t, status, from) {
|
||
const to = S.bots.find((b) => b.name === t.to);
|
||
const av = (b) => b ? `<span class="av xs">${avatarSvg(b.shape, b.color)}</span>` : "";
|
||
const me = S.bots.find((b) => b.name === from);
|
||
const q = (t.text || "").length > 400 ? t.text.slice(0, 400) + "…" : (t.text || "");
|
||
let tail;
|
||
if (status === "running" || status === "waiting") tail = `<div class="tk-st">${ic("loader", 13)} 「${esc(t.to)}」${to && to.busy && to.status ? ":" + esc(to.status) : "正在處理…"}</div>`;
|
||
else if (status === "done" && t.ask && t.answer) { const body = t.answer.includes("\n") ? t.answer.slice(t.answer.indexOf("\n") + 1) : t.answer; tail = `<div class="tk-ok">${ic("circle-check", 13)} 「${esc(t.to)}」的回答</div><div class="tk-a">${pageMd(body, 0)}</div>`; }
|
||
else if (status === "done") tail = `<div class="tk-st">${esc(t.answer || "已交給它,做完會回報到這裡")}</div>`;
|
||
else tail = `<div class="tk-st err">${esc(t.answer || "沒有完成")}</div>`;
|
||
return `<div class="talk"><div class="tk-h">${av(me)}<b>${esc(from)}</b>${ic("chevron-right", 12)}${av(to)}<b>${esc(t.to)}</b><span>${t.ask ? "問" : "交辦"}</span></div>${q ? `<div class="tk-q">${esc(q)}</div>` : ""}${tail}${to ? `<button class="tk-go" data-bot="${to.id}">「${esc(t.to)}」那邊的紀錄 ›</button>` : ""}</div>`;
|
||
}
|
||
/** 計畫: the plan a bot handed in (`state`: waiting, approved, changed, not_now; `live`: its steps as followed now). */
|
||
function planCard(p) {
|
||
if (!p || !p.summary) return "";
|
||
const st = {waiting: "等你決定", approved: p.live ? `照著做 · ${p.live.filter((s) => s.status === "done" || s.status === "skipped").length}/${p.live.length}` : "已核准", changed: "已修改,見下面新版", not_now: "沒有採用"}[p.state] || "";
|
||
const whole = p.state === "waiting" || p.state === "approved";
|
||
const cls = p.state === "waiting" ? " wait" : whole ? "" : " past";
|
||
let h = `<div class="card plan${cls}"><div class="t">${ic("list-checks", 15)}<span>計畫</span><span class="st">${esc(st)}</span></div><div class="sum">${esc(p.summary)}</div>`;
|
||
if (whole) {
|
||
const rows = p.live ? p.live.map((s) => ({title: s.title, detail: "", status: s.status})) : (p.steps || []);
|
||
h += "<ol>" + rows.map((s) => `<li class="${{done: "done", in_progress: "now", skipped: "skip"}[s.status] || ""}">${esc(s.title)}${s.detail && s.status !== "done" ? `<span class="d">${esc(s.detail)}</span>` : ""}</li>`).join("") + "</ol>";
|
||
if (p.check) h += `<div class="x">怎麼確認做對了:${esc(p.check)}</div>`;
|
||
if (p.notes) h += `<div class="x">注意:${esc(p.notes)}</div>`;
|
||
if (p.state === "waiting") h += `<div class="x">在下面的卡片選「開始照計畫做」,或寫下要改哪裡</div>`;
|
||
}
|
||
return h + "</div>";
|
||
}
|
||
function card(c) {
|
||
if (!c) return "";
|
||
const rows = (c.rows || []).map((r) => `<div class="r"><span>${esc(r.label)}</span><span>${esc(r.value)}</span></div>`).join("");
|
||
const link = safeHttpUrl(c.link);
|
||
return `<div class="card"><div class="t">${esc(c.title)}</div>${c.subtitle ? `<div class="s">${esc(c.subtitle)}</div>` : ""}${rows}${link ? `<div class="r"><a href="${esc(link)}" target="_blank" rel="noopener">來源</a><span></span></div>` : ""}</div>`;
|
||
}
|
||
const GLYPH = (h = 34) => `<svg width="${Math.round(h * .8)}" height="${h}" viewBox="0 0 24 30" style="flex:none"><rect x=".5" y=".5" width="23" height="29" rx="4" style="fill:var(--hover);stroke:var(--line)"/><path d="M5 7h9M5 11h6" style="stroke:var(--text3)" stroke-width="2" stroke-linecap="round"/><rect x="5" y="20" width="2.6" height="5" rx=".6" style="fill:var(--cat3)"/><rect x="9" y="18" width="2.6" height="7" rx=".6" style="fill:var(--cat4)"/><rect x="13" y="16" width="2.6" height="9" rx=".6" style="fill:var(--cat1)"/><rect x="17" y="14" width="2.6" height="11" rx=".6" style="fill:var(--cat2)"/></svg>`;
|
||
function pageCard(p) {
|
||
const lines = (p.preview || []).slice(0, 3).map((l, i, a) => `<div class="l" style="opacity:${1 - (i / Math.max(a.length, 1)) * .6}">${esc(l)}</div>`).join("");
|
||
// (The title once: the foot only says what it is and when.)
|
||
return `<div class="pcard" data-page="${p.id}"><div class="top"><div class="t">${esc(p.title)}</div>${lines}</div><div class="foot">${GLYPH(22)}<div class="x">頁面 · ${esc(p.updated)}${p.revision > 1 ? " · 已更新" : ""}</div></div></div>`;
|
||
}
|
||
// Whether the open bot is working (and says what it is doing): what the chat's foot shows of it.
|
||
function busyKey() { const b = bot(S.open) || {}; return `${!!b.busy}${!!b.status}`; }
|
||
function renderMsgs() {
|
||
// 分頁在背景(切到別的 App、鎖螢幕)時不重畫整串訊息:只記下要畫,回到前景再畫一次。
|
||
if (document.hidden) { S.msgsStale = true; return; }
|
||
S.msgsStale = false; S.drawnBusy = busyKey();
|
||
const b = bot(S.open) || {};
|
||
const busy = b.busy;
|
||
// A turn: the bot's messages between two of the person's. Its thinking and steps stay out of the
|
||
// chat, like the desktop's: 長按 (right-click) the answer or its ⋯ › 顯示步驟 shows them in place,
|
||
// under a 「收起」 line; while it works, the line by its face says what it is doing. A turn with
|
||
// nothing else to press (no words, files or cards) keeps one 「已完成 N 個步驟」 line instead.
|
||
const turns = []; let curT = null;
|
||
S.msgs.forEach((m, i) => {
|
||
if (m.role === "user" || m.summary || m.interrupted || m.note) { curT = null; return; }
|
||
if (!curT) { curT = {first: i, last: i, key: String(m.at || i), steps: 0, thinks: 0, said: false}; turns.push(curT); }
|
||
curT.last = i; curT.steps += (m.tools || []).filter((t) => !t.page && !t.card && !t.plan && !t.plan_update && !t.talk).length;
|
||
if (m.thinking) curT.thinks++;
|
||
if (m.text || (m.attachments || []).length || (m.tools || []).some((t) => t.page || t.card || t.plan || t.talk)) curT.said = true;
|
||
});
|
||
const turnOf = {}; turns.forEach((t) => { for (let i = t.first; i <= t.last; i++) turnOf[i] = t; });
|
||
S.turnOf = turnOf; // (for the message menu's 顯示步驟)
|
||
const lastTurn = turns[turns.length - 1];
|
||
const lastBot = [...S.msgs].reverse().find((m) => m.role !== "user" && m.text && !m.note);
|
||
const lastMsg = S.msgs[S.msgs.length - 1];
|
||
let day = "";
|
||
let h = "";
|
||
// 載入更早:開頁只有最新 30 條,這一鍵一次往回補 60 條。
|
||
const atStart = S.olderEnd && S.olderEnd.bot === S.open && S.msgs.length && S.msgs[0].index <= S.olderEnd.at;
|
||
if (S.msgs.length && S.msgs[0].index > 0 && !atStart) h += `<div class="dsep"><button class="btn sm" data-older="1" ${S.olderBusy ? "disabled" : ""}>${S.olderBusy ? "載入中…" : "載入更早的對話"}</button></div>`;
|
||
// A message that arrived since the last draw slides up into place; the whole history on
|
||
// opening a chat draws plain (no animation on every old message).
|
||
// (Another conversation of the same bot — its first message differs — draws plain too.)
|
||
const first = S.msgs.length ? String(S.msgs[0].at || "") + (S.msgs[0].text || "").slice(0, 40) : "";
|
||
const same = first === S.prevFirst; S.prevFirst = first;
|
||
const freshFrom = same && S.prevShown > 0 && S.msgs.length > S.prevShown ? S.prevShown : S.msgs.length;
|
||
S.prevShown = S.msgs.length;
|
||
const fr = (i) => (i >= freshFrom ? " fresh" : "");
|
||
S.msgs.forEach((m, i) => {
|
||
if (m.at) { const d = dayLabel(m.at); if (d !== day) { day = d; h += `<div class="dsep">${esc(d)}</div>`; } }
|
||
const reacts = (m.reactions || []).length ? `<div class="reacts">${m.reactions.map((e) => `<button data-react="${esc(e)}" data-i="${m.index}">${esc(e)}</button>`).join("")}</div>` : "";
|
||
if (m.summary) {
|
||
h += `<div class="summary" data-sum="1"><b>${ic("history", 15)} 較早的對話已整理成摘要 ${ic("chevron-down", 14)}</b><div class="tx">${esc(m.text)}</div></div>`;
|
||
return;
|
||
}
|
||
// Where AnyBot stopping cut a turn off: what it was doing, what may have run, and 「繼續」
|
||
// while it is the newest thing in the chat.
|
||
if (m.interrupted) {
|
||
const go = m === lastMsg && !busy && owner() ? `<button class="btn main sm" style="margin-top:8px" data-resume="1">繼續</button>` : "";
|
||
h += `<div class="summary open"><div class="tx">${esc(m.text)}</div>${go}</div>`;
|
||
return;
|
||
}
|
||
// 支線: its card where it was asked; its report handed to the running turn is one line.
|
||
if (m.branch && m.note) { h += branchCard(m.branch); return; }
|
||
if (m.branch && m.role === "user") { h += `<div class="note">${ic("activity", 13)}<span>支線的結果已交給正在做事的主線</span></div>`; return; }
|
||
// 目標: AnyBot's own line about the goal (met, paused…), not the bot's words.
|
||
if (m.note) {
|
||
// (A goal's lines wear the target; 「改用 ○○ 回答/繼續」 — another model, chosen or a
|
||
// backup taking over — the model's sparkle.)
|
||
h += `<div class="note">${ic(/^改用 .+ (回答|繼續)(/.test(m.text) ? "sparkles" : "target", 13)}<span>${esc(m.text)}</span></div>`;
|
||
return;
|
||
}
|
||
if (m.role === "user") {
|
||
const wt = m.wake ? wakeTag(m.text) : null;
|
||
const tag = wt ? `<div class="tag">${ic(wt.icon, 12)} ${esc(wt.label)}</div>` : "";
|
||
if (wt) m = {...m, text: wt.body};
|
||
const q = String(m.text || "").match(/^((?:>.*\n?)+)\n*([\s\S]*)$/);
|
||
const text = q ? q[2] : m.text;
|
||
const quote = q ? `<div class="quote">${esc(plain(q[1].replace(/^> ?/gm, "")).replace(/\|/g, " ").replace(/\s+/g, " ").trim())}</div>` : "";
|
||
const mems = m.memories || [];
|
||
const open = S.carried.has(String(m.at || i));
|
||
const carried = mems.length ? `<button class="carried" data-carried="${esc(String(m.at || i))}">${ic("bookmark", 12)} 帶了 ${mems.length} 條記憶 ${ic(open ? "chevron-up" : "chevron-down", 12)}</button>${open ? `<div class="carried-list">${mems.map((x) => "• " + esc(x)).join("<br>")}</div>` : ""}` : "";
|
||
h += `<div class="m user${wt ? " woke" : ""}${fr(i)}" data-msg="${i}">${tag}${m.text ? `<div class="bub">${quote}${esc(text)}</div>` : ""}${(m.attachments || []).map(attHtml).join("")}${reacts}${carried}</div>`;
|
||
return;
|
||
}
|
||
const t = turnOf[i];
|
||
const running = busy && t === lastTurn;
|
||
const unfolded = !!(t && S.unfold[t.key]);
|
||
// The turn's line, where its first thought or step would be (once per turn): 「收起」 while
|
||
// shown; the way in for a turn with nothing else to press.
|
||
const foldLine = () => {
|
||
if (!t || t.lined || !(unfolded || (!t.said && !running))) return "";
|
||
t.lined = true;
|
||
const what = unfolded ? (t.steps ? `收起 ${t.steps} 個步驟` : "收起思考過程") : t.steps ? `已完成 ${t.steps} 個步驟` : "思考過程";
|
||
return `<button class="fold" data-turn="${esc(t.key)}" aria-expanded="${unfolded}">${ic(t.steps ? "circle-check" : "brain", 14)} ${what} ${ic(unfolded ? "chevron-up" : "chevron-right", 13)}</button>`;
|
||
};
|
||
const thought = m.thinking ? foldLine() + (unfolded ? thinkHtml(m) : "") : "";
|
||
let steps = "", extra = "";
|
||
(m.tools || []).forEach((x, k) => {
|
||
if (x.page) { extra += pageCard(x.page); return; }
|
||
if (x.card) { extra += card(x.card); return; }
|
||
if (x.plan) { extra += planCard(x.plan); return; }
|
||
if (x.plan_update) return;
|
||
if (x.talk) { extra += talkCard(x.talk, x.status, m.author || (bot(S.open) || {}).name || ""); return; }
|
||
steps += foldLine();
|
||
if (unfolded) steps += stepHtml(x, m.index + ":" + k);
|
||
});
|
||
const end = t && i === t.last && !running;
|
||
const who = m.author ? `<div class="who">${esc(m.author)}</div>` : "";
|
||
const think = thought ? `<div class="steps">${thought}</div>` : "";
|
||
const bub = m.text ? `<div class="bub">${pageMd(m.text, 0)}</div>` : "";
|
||
const atts = (m.attachments || []).map((a) => attHtml(a) + dlvMark(a)).join("");
|
||
const meta = end && m.text ? `<div class="meta">${m.at ? esc(clock(m.at)) : ""}<button data-copy="${i}" title="複製">${ic("copy", 14)}</button>${owner() && m === lastBot && t === lastTurn ? `<button data-regen="1" title="重新產生">${ic("refresh", 14)}</button>` : ""}<button data-more="${i}" title="更多">${ic("ellipsis", 14)}</button></div>` : "";
|
||
const unv = running ? "" : unvMark(m, i);
|
||
const body = `${think}${bub}${steps ? `<div class="steps">${steps}</div>` : ""}${extra}${atts}${unv}${reacts}${meta}`;
|
||
// (A round whose thinking and steps are all behind the line takes no room.)
|
||
if (body) h += `<div class="m bot${fr(i)} ${m.error ? "err" : ""}" data-msg="${i}">${who}${body}</div>`;
|
||
});
|
||
// 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>` : "";
|
||
// (A tap on it shows the running turn's thinking and steps, like 顯示步驟 on an answer.)
|
||
const live = busy && lastTurn && lastTurn.last === S.msgs.length - 1 && (lastTurn.steps || lastTurn.thinks) ? lastTurn : null;
|
||
if (busy && b.status) h += `<div class="working"${live ? ` data-wturn="${esc(live.key)}"` : ""}>${face(b, "sm")}<div class="presence">${esc(b.status)}</div></div>`;
|
||
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 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());
|
||
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; S.drawn = S.msgs;
|
||
// (Diagrams in the answers: drawn by the brain once they are on the page.)
|
||
if ($("msgs").querySelector(".chart[data-mermaid]")) loadCharts();
|
||
renderSendBtn();
|
||
loadFiles();
|
||
seenWatch();
|
||
}
|
||
// Taps in the chat: steps, folds, summaries, copy, regenerate, resend, reactions, suggestions, pages.
|
||
$("msgs").addEventListener("click", async (e) => {
|
||
const od = e.target.closest("[data-older]"); if (od) { loadOlder(); return; }
|
||
// The end of a drag that selected words is not a tap: nothing folds, opens or goes.
|
||
if (!e.target.closest("button,a") && selIn(e.target)) return;
|
||
const dv = e.target.closest("[data-dlv]"); if (dv) { dlvSheet(dv.dataset.dlv); return; }
|
||
const uv = e.target.closest("[data-unv]"); if (uv) { unvSheet(+uv.dataset.unv); return; }
|
||
const fl = e.target.closest("a.flink"); if (fl) { e.preventDefault(); openDeadLink(fl.dataset.fname); return; }
|
||
const st = e.target.closest(".step .h");
|
||
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,[data-wturn]"); if (f) { const k = f.dataset.turn || f.dataset.wturn; S.unfold[k] = !S.unfold[k]; 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; }
|
||
// 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; }
|
||
if (e.target.closest("[data-regen]")) { regen(); return; }
|
||
if (e.target.closest("[data-resend]")) { act("reply", {bot: S.open}); return; }
|
||
if (e.target.closest("[data-resume]")) { act("resume", {bot: S.open}, "繼續中…"); return; }
|
||
const mo = e.target.closest("[data-more]"); if (mo) { msgMenu(+mo.dataset.more); return; }
|
||
const r = e.target.closest("[data-react]"); if (r) { act("react", {bot: S.open, index: +r.dataset.i, emoji: r.dataset.react}, false).then((v) => reacted(v, +r.dataset.i)); return; }
|
||
const sg = e.target.closest("[data-sugg]");
|
||
if (sg) {
|
||
const text = SUGGEST[+sg.dataset.sugg][3];
|
||
const input = $("input"); input.value = text; input.focus();
|
||
const at = text.indexOf("「」"); if (at >= 0) input.setSelectionRange(at + 1, at + 1);
|
||
input.dispatchEvent(new Event("input"));
|
||
}
|
||
});
|
||
// Long-press (or right-click) a message: its menu (the desktop's hover row). Words the person
|
||
// already selected keep the browser's own way to copy them: pressing or right-clicking on them
|
||
// opens no menu here; neither does a link (the browser's 複製連結).
|
||
(() => {
|
||
let t = null, at = null;
|
||
// The words selected in message m, when x, y is on them (a few px of slack for a finger).
|
||
const onSel = (m, x, y) => {
|
||
const s = selIn(m), sel = getSelection(); if (!s) return "";
|
||
for (let k = 0; k < sel.rangeCount; k++) for (const r of sel.getRangeAt(k).getClientRects()) if (x >= r.left - 4 && x <= r.right + 4 && y >= r.top - 4 && y <= r.bottom + 4) return s;
|
||
return "";
|
||
};
|
||
// Where the finger or mouse last went down (or came up), before the browser picks anything: a long
|
||
// press or a right-click that itself selects a word (Android, a Mac) still opens the menu, and so
|
||
// does one beside the selected words.
|
||
let was = {m: null, sel: ""};
|
||
const note = (e) => { const m = e.target.closest(".m[data-msg]"); was = {m, sel: onSel(m, e.clientX, e.clientY)}; };
|
||
$("msgs").addEventListener("pointerdown", note, true);
|
||
$("msgs").addEventListener("pointerup", note, true);
|
||
// (The word that press picked goes: the menu doesn't sit over a stray highlight, and the next
|
||
// press on it is a menu again.)
|
||
const open = (m) => { if (selIn(m)) getSelection().removeAllRanges(); msgMenu(+m.dataset.msg); };
|
||
$("msgs").addEventListener("touchstart", (e) => {
|
||
const m = e.target.closest(".m[data-msg]"), p = e.touches[0];
|
||
if (!m || e.target.closest("button,a,.step,.pcard") || onSel(m, p.clientX, p.clientY)) return;
|
||
at = m; t = setTimeout(() => { t = "long"; open(at); }, 480);
|
||
}, {passive: true});
|
||
$("msgs").addEventListener("touchend", (e) => { if (t === "long") e.preventDefault(); clearTimeout(t); t = null; });
|
||
$("msgs").addEventListener("touchmove", () => { clearTimeout(t); t = null; }, {passive: true});
|
||
$("msgs").addEventListener("contextmenu", (e) => {
|
||
const m = e.target.closest(".m[data-msg]");
|
||
if (!m || e.target.closest("a[href]") || (was.m === m ? was.sel : selIn(m))) return;
|
||
e.preventDefault(); open(m);
|
||
});
|
||
})();
|
||
// 選取文字: the message alone on a sheet, where the phone's own selecting works (press and hold a
|
||
// word, drag its ends, the system's 拷貝); in the chat a long press is the menu instead.
|
||
function selectSheet(i, m) {
|
||
if (!m || !m.text) return;
|
||
// What the chat shows (the answer's tables and code, your quote), while line i is still m.
|
||
const shown = (S.msgs[i] || {}).text === m.text && document.querySelector(`#msgs .m[data-msg="${i}"] .bub`);
|
||
const mine = m.role === "user";
|
||
const el = sheet("選取文字", [{icon: "check", label: "完成"}], `<div class="note">按住一個字開始選取,拖兩端調整範圍,再按系統跳出的「拷貝」(或「複製」)。電腦上用滑鼠拖曳,再按 ⌘C 或 Ctrl+C。</div><div class="seltext ${mine ? "mine" : "page"}">${shown ? shown.innerHTML : mine ? esc(m.text) : pageMd(m.text, 0)}</div>`);
|
||
el.scrollTop = 0;
|
||
}
|
||
async function copyText(t) { try { await navigator.clipboard.writeText(t || ""); toast("已複製"); } catch (_) { toast("這支手機不讓網頁複製"); } }
|
||
document.addEventListener("click", (e) => { const b = e.target.closest("[data-copycode]"); if (!b) return; e.stopPropagation(); copyText((b.parentElement.querySelector("code") || {}).textContent || ""); }, true);
|
||
const QUICK = ["👍", "❤️", "😂", "🎉", "👀", "🙏", "👌", "🔥"];
|
||
function msgMenu(i) {
|
||
const m = S.msgs[i]; if (!m) return;
|
||
const items = [];
|
||
if (m.text) items.push({icon: "copy", label: "複製", on: () => copyText(m.text)});
|
||
if (m.text) items.push({icon: "text-cursor", label: "選取文字", on: () => selectSheet(i, m)});
|
||
if (m.text && m.role !== "user" && S.voice.speak) items.push({icon: "audio-lines", label: "唸出來", on: () => speakText(m.text)});
|
||
if (m.text && owner()) items.push({icon: "reply", label: "引用回覆", on: () => { S.quote = {text: plain(m.text).slice(0, 300), raw: m.text}; renderQuote(); $("input").focus(); }});
|
||
if (m.text && owner() && m.role === "user") items.push({icon: "sparkles", label: "教我做(學這一回合)", on: () => app("skillify", {prompt: plain(m.text).slice(0, 200), at: m.at}, 0, "已存成技能,下次說名字就會照做")});
|
||
const lastBot = [...S.msgs].reverse().find((x) => x.role !== "user" && x.text);
|
||
if (m === lastBot && owner()) items.push({icon: "refresh", label: "重新產生這個回答", on: regen});
|
||
// 重新產生 kept what it replaced (on the brain): put it back.
|
||
if (m === lastBot && owner() && (bot(S.open) || {}).can_restore && !(bot(S.open) || {}).busy) items.push({icon: "history", label: "還原上一個答案", on: async () => { try { await api(base() + `api/bots/${S.open}/restore_answer`, {json: {}}); toast("還原了"); } catch (e) { toast(e.message); } }});
|
||
if (m.role === "user" && i === S.msgs.length - 1 && owner()) items.push({icon: "refresh", label: "重新傳送", on: () => act("reply", {bot: S.open})});
|
||
// 顯示步驟 (the desktop's ⋯ › 顯示步驟): this turn's thinking and steps, in place, from its top.
|
||
const t = m.role !== "user" && S.turnOf ? S.turnOf[i] : null;
|
||
if (t && (t.steps || t.thinks)) items.push({icon: t.steps ? "list-checks" : "brain", label: S.unfold[t.key] ? "隱藏步驟" : t.steps ? `顯示步驟(${t.steps})` : "顯示思考過程", on: () => {
|
||
S.unfold[t.key] = !S.unfold[t.key]; renderMsgs();
|
||
const f = S.unfold[t.key] && document.querySelector(`#msgs .fold[data-turn="${CSS.escape(t.key)}"]`);
|
||
if (f) f.scrollIntoView({block: "nearest"});
|
||
}});
|
||
const emojis = m.index != null && owner() ? `<div class="emojis">${QUICK.map((e) => `<button data-e="${e}">${e}</button>`).join("")}</div>` : "";
|
||
const el = sheet("", items, emojis);
|
||
el.querySelectorAll("[data-e]").forEach((b) => b.onclick = () => { closeSheet(); act("react", {bot: S.open, index: m.index, emoji: b.dataset.e}, false).then((v) => reacted(v, m.index)); });
|
||
}
|
||
async function regen() { try { await api(base() + `api/bots/${S.open}/regenerate`, {json: {}}); toast("重新產生中…"); } catch (e) { toast(e.message); } }
|
||
// The dock: what needs the person (允許 / 需要處理), what is queued, then the composer.
|
||
let thumbTimer = null;
|
||
function renderDock() {
|
||
const b = bot(S.open) || {};
|
||
const a = S.approvals.find((x) => x.bot === S.open);
|
||
clearInterval(thumbTimer);
|
||
if (a && a.kind === "question" && owner()) { $("ask").innerHTML = ""; renderQuestion(a); renderDockRest(b); return; }
|
||
ASKF = null;
|
||
$("askq").innerHTML = "";
|
||
if (!a) $("ask").innerHTML = "";
|
||
else if (!owner()) $("ask").innerHTML = `<div class="ask"><div class="q">${esc(a.title)}</div><div class="why">等擁有者或管理員決定</div></div>`;
|
||
else if (a.kind === "handoff") {
|
||
const own = /的電腦$/.test(a.computer || "") && S.boxOn;
|
||
$("ask").innerHTML = `<div class="ask"><div class="q">${ic("hand", 16)} 需要處理 · ${esc(a.computer || "")}</div><div class="why">${esc(a.reason)}</div>${own ? `<img class="thumb" id="hand-thumb" alt="">` : ""}<div class="btns"><button class="btn" data-screen="1">${ic("monitor", 15)} 接管</button><button class="btn main" data-a="once">我完成了</button><button class="btn" data-a="reject">跳過</button></div></div>`;
|
||
$("ask").querySelector("[data-screen]").onclick = () => openBox(true);
|
||
if (own) { const load = () => boxThumb($("hand-thumb"), b.id); load(); thumbTimer = setInterval(load, 3000); }
|
||
} else {
|
||
// 智慧模式開著時主按鈕是「這輪都准」(这一轮同类不再问,比「一律允許」小一格);否则主按鈕是「允許一次」。
|
||
const yes = a.can_scope ? `<button class="btn main" data-a="scope">這輪都准</button><button class="btn" data-a="once">允許一次</button>` : `<button class="btn main" data-a="once">允許一次</button>`;
|
||
$("ask").innerHTML = `<div class="ask"><div class="q">${esc(a.title)}</div><div class="why">${esc(a.reason)}</div><div class="btns" role="group" aria-label="審批選項">${yes}${a.can_always ? `<button class="btn" data-a="always">一律允許</button>` : (a.kind === "ask" ? `<span style="font-size:var(--fs-caption);color:var(--text3);align-self:center">這類操作有風險,每次都會問你</span>` : "")}<button class="btn no" data-a="reject">拒絕</button></div>${isOwner() ? `<a class="all" data-direct="1">${ic("zap", 13)} 全部允許,之後直接操作</a>` : ""}</div>`;
|
||
}
|
||
$("ask").querySelectorAll("button[data-a]").forEach((x) => x.onclick = async () => {
|
||
if (navigator.vibrate) navigator.vibrate(8);
|
||
$("ask").innerHTML = "";
|
||
// call: this card's key — the brain applies the answer only to the card drawn here, not
|
||
// one that took its place since.
|
||
try { await api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: {answer: x.dataset.a, call: a.key || ""}}); } catch (e) { toast(e.message); }
|
||
});
|
||
const d = $("ask").querySelector("[data-direct]");
|
||
if (d) d.onclick = async () => {
|
||
if (!await confirmSheet("打開「直接操作」?", "Bot 會直接做事,只有危險操作和你的「一律詢問」規則會停下來問你。", "打開", false)) return;
|
||
if (await act("setting", {key: "direct_mode", value: true}, "已打開直接操作")) api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: {answer: a.can_always ? "always" : "once", call: a.key || ""}}).catch(() => {});
|
||
};
|
||
renderDockRest(b);
|
||
}
|
||
// 問題卡: the bot's questions, one at a time. A choice is one tap (it moves on; on the last
|
||
// question it sends); several choices and typed answers have 下一題/送出.
|
||
let ASKF = null;
|
||
function askAnswer(q, i) {
|
||
const typed = (ASKF.typed[i] || "").trim();
|
||
const parts = (q.multiple || !typed) ? ASKF.picks[i].slice().sort((x, y) => x - y).map((k) => q.options[k]) : [];
|
||
if (typed) parts.push(typed);
|
||
return parts.join("、");
|
||
}
|
||
function renderQuestion(a, force) {
|
||
const qs = a.questions || [];
|
||
if (!qs.length) return;
|
||
// (A card is told apart by its key: call ids repeat, call_0 every round.)
|
||
if (!ASKF || ASKF.id !== (a.key || a.call_id)) {
|
||
ASKF = {id: a.key || a.call_id, step: 0, drawn: -1, picks: qs.map((q) => { const k = (q.options || []).indexOf(q.default); return k >= 0 && q.default ? [k] : []; }), typed: qs.map((q) => (q.options || []).length ? "" : (q.default || ""))};
|
||
}
|
||
// Drawn already: leave it, or what is being typed would be lost on every refresh.
|
||
if (!force && ASKF.drawn === ASKF.step && $("askq").querySelector(".own")) return;
|
||
const i = ASKF.step, q = qs[i], opts = q.options || [], last = i + 1 === qs.length;
|
||
ASKF.drawn = i;
|
||
const own = !!(ASKF.typed[i] || "").trim();
|
||
$("askq").innerHTML = `<div class="ask"><div class="asknum">${esc(a.title)}${qs.length > 1 ? ` · ${i + 1}/${qs.length}` : ""}</div><div class="q">${esc(q.question)}</div><div class="why">${q.multiple ? "可以選好幾個" : ""}</div>${opts.map((o, k) => `<button class="opt ${q.multiple ? "many" : ""} ${ASKF.picks[i].includes(k) && (q.multiple || !own) ? "on" : ""}" data-k="${k}"><i></i><span>${esc(o)}</span></button>`).join("")}<input class="own" enterkeyhint="${last ? "send" : "next"}" placeholder="${opts.length ? "自己回答" : "輸入回答"}" value="${esc(ASKF.typed[i])}"><div class="btns"><button class="btn main" data-go="next">${last ? "送出" : "下一題"}</button>${i > 0 ? `<button class="btn" data-go="back">上一題</button>` : ""}<button class="btn" data-go="skip">略過</button></div></div>`;
|
||
const box = $("askq"), field = box.querySelector(".own"), go = box.querySelector('[data-go="next"]');
|
||
// The chat comes to the card when it appears and at each next question.
|
||
// (Once laid out; a card taller than the screen shows its question, not its buttons.)
|
||
requestAnimationFrame(() => {
|
||
const sc = $("scroller"), top = box.getBoundingClientRect().top - sc.getBoundingClientRect().top + sc.scrollTop;
|
||
sc.scrollTo({top: box.offsetHeight > sc.clientHeight ? top : sc.scrollHeight, behavior: "smooth"});
|
||
});
|
||
const ready = () => { go.disabled = !askAnswer(q, i); };
|
||
ready();
|
||
// (With this card's key: an answer for these questions never reaches the next card.)
|
||
const send = async (body) => { ASKF = null; box.innerHTML = ""; try { await api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: Object.assign({call: a.key || ""}, body)}); } catch (e) { toast(e.message); } };
|
||
const next = () => {
|
||
if (!askAnswer(q, i)) return;
|
||
if (!last) { ASKF.step = i + 1; return renderQuestion(a, true); }
|
||
// Every question has its answer, or it goes back to the first without one.
|
||
const miss = qs.findIndex((x, k) => !askAnswer(x, k));
|
||
if (miss >= 0) { ASKF.step = miss; return renderQuestion(a, true); }
|
||
send({answer: "answered", text: JSON.stringify(qs.map((x, k) => askAnswer(x, k)))});
|
||
};
|
||
field.oninput = () => { ASKF.typed[i] = field.value; if (!q.multiple) box.querySelectorAll(".opt").forEach((x) => x.classList.toggle("on", !field.value.trim() && ASKF.picks[i].includes(+x.dataset.k))); ready(); };
|
||
field.onkeydown = (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); next(); } };
|
||
box.querySelectorAll(".opt").forEach((x) => x.onclick = () => {
|
||
const k = +x.dataset.k, picks = ASKF.picks[i];
|
||
if (q.multiple) { const at = picks.indexOf(k); if (at >= 0) picks.splice(at, 1); else picks.push(k); x.classList.toggle("on"); ready(); }
|
||
else { ASKF.picks[i] = [k]; ASKF.typed[i] = ""; next(); }
|
||
});
|
||
go.onclick = next;
|
||
const back = box.querySelector('[data-go="back"]');
|
||
if (back) back.onclick = () => { ASKF.step = i - 1; renderQuestion(a, true); };
|
||
box.querySelector('[data-go="skip"]').onclick = () => send({answer: "reject"});
|
||
}
|
||
// Which mode's line is open above the input ("goal", "plan" or none).
|
||
var MODE_OPEN = ""; // (var: openChat, above, clears it.)
|
||
function renderDockRest(b) {
|
||
// 目標 and 計畫: a chip each in one row (what it is on hover; the plan's 2/5 beside its icon).
|
||
// A tap opens that one's line: how it stands, and 清除目標/取消計畫 (sent as 「/goal clear」,
|
||
// 「/plan clear」, the brain's own commands).
|
||
const g = b.goal, pl = b.plan;
|
||
// (智慧模式一直開著:輸入列不再放它的 ✨。)
|
||
if (MODE_OPEN && !(MODE_OPEN === "goal" ? g : pl)) MODE_OPEN = "";
|
||
const gTip = g ? g.line + "\n\n目標:" + g.condition + (g.reason ? "\n最近一次檢查:" + g.reason : "") : "";
|
||
const pTip = pl ? pl.line + "\n\n要做的事:" + pl.task + (pl.steps ? "\n\n" + pl.steps : "") : "";
|
||
const count = pl ? (/\d+/\d+/.exec(pl.line) || [""])[0] : "";
|
||
const chip = (m, on, icon, tip, label, n) => `<button class="mode ${on ? "on" : ""} ${MODE_OPEN === m ? "open" : ""}" data-m="${m}" title="${esc(tip)}" aria-label="${label}" aria-expanded="${MODE_OPEN === m}">${ic(icon, 14)}${n ? `<span>${esc(n)}</span>` : ""}</button>`;
|
||
$("modes").innerHTML = (g ? chip("goal", g.active, "target", gTip, "目標", "") : "") + (pl ? chip("plan", true, "list-checks", pTip, "計畫", count) : "");
|
||
$("modes").querySelectorAll(".mode").forEach((x) => x.onclick = () => {
|
||
MODE_OPEN = MODE_OPEN === x.dataset.m ? "" : x.dataset.m; renderDockRest(b);
|
||
});
|
||
$("goalbar").innerHTML = g && MODE_OPEN === "goal" ? `<div class="goalbar ${g.active ? "on" : ""}"><div class="t" title="${esc(gTip)}">${ic("target", 14)}<span>${esc(g.line)}</span></div>${owner() ? `<button id="goal-x">清除目標</button>` : ""}</div>` : "";
|
||
if ($("goal-x")) $("goal-x").onclick = async () => {
|
||
try { await api(base() + `api/bots/${S.open}/send`, {json: {text: "/goal clear", attachments: []}}); toast("已清除目標"); loadChat(); } catch (e) { toast(e.message); }
|
||
};
|
||
$("planbar").innerHTML = pl && MODE_OPEN === "plan" ? `<div class="goalbar on"><div class="t" title="${esc(pTip)}">${ic("list-checks", 14)}<span>${esc(pl.line)}</span></div>${owner() ? `<button id="plan-x">取消計畫</button>` : ""}</div>` : "";
|
||
// 一律放行 is on (every chat: it is everyone's), with 關閉 — as the desktop's icon above the input.
|
||
$("alwaysbar").innerHTML = S.always ? `<div class="goalbar on"><div class="t">${ic("zap", 14)}<span>一律放行開著:要允許的都自動答應</span></div>${isOwner() ? `<button id="always-x">關閉</button>` : ""}</div>` : "";
|
||
if ($("always-x")) $("always-x").onclick = async () => { if (await act("setting", {key: "always_approve", value: false, bot: S.open}, false)) toast("一律放行關了"); };
|
||
if ($("plan-x")) $("plan-x").onclick = async () => {
|
||
try { await api(base() + `api/bots/${S.open}/send`, {json: {text: "/plan clear", attachments: []}}); toast("已取消計畫"); loadChat(); } catch (e) { toast(e.message); }
|
||
};
|
||
const q = b.queued || [];
|
||
$("queued").innerHTML = q.length ? `<div class="queued">${ic("history", 13)} 已排入:「${esc(q.join("」「"))}」,${esc(b.name)} 會在下一步看到</div>` : "";
|
||
renderSendBtn();
|
||
}
|
||
const BOXIMG = {};
|
||
// (Of this bot's own screen when it has one open; else the shared one.)
|
||
async function boxThumb(img, bot) {
|
||
if (!img) return;
|
||
try {
|
||
const r = await api(base() + "api/box/thumb" + (bot ? "?bot=" + bot : ""), {raw: true});
|
||
if (!r.ok) throw new Error();
|
||
const u = URL.createObjectURL(await safeBlob(r));
|
||
if (BOXIMG.last) URL.revokeObjectURL(BOXIMG.last);
|
||
BOXIMG.last = u; img.src = u;
|
||
} catch (_) { img.alt = "看不到畫面"; }
|
||
}
|
||
function renderQuote() {
|
||
const q = S.quote;
|
||
$("quoting").style.display = q ? "" : "none";
|
||
$("quoting").innerHTML = q ? `${ic("reply", 14)}<span>${esc(q.text)}</span><button class="cbtn" id="q-x">${ic("x", 14)}</button>` : "";
|
||
if (q) $("q-x").onclick = () => { S.quote = null; renderQuote(); };
|
||
}
|
||
const input = $("input");
|
||
input.addEventListener("input", () => { clearTimeout(S.draftTimer); S.draftTimer = setTimeout(() => keepDraft(S.draftOf, input.value), 400); });
|
||
input.addEventListener("input", () => {
|
||
input.style.height = "auto"; input.style.height = Math.min(input.scrollHeight, 140) + "px";
|
||
$("composer").classList.toggle("tall", input.scrollHeight > 40); renderSendBtn();
|
||
memSuggestSoon(); renderMemChips(); renderSlash();
|
||
});
|
||
// 技能: a / at the start of the input lists them — tap one, or ↑↓ and Enter/Tab on a keyboard;
|
||
// Esc closes the list until the / is gone. (First here: Enter picks instead of sending.)
|
||
input.addEventListener("keydown", (e) => {
|
||
const n = SL.hits.length;
|
||
if (!n || e.isComposing) return;
|
||
const k = e.key, stop = () => { e.preventDefault(); e.stopImmediatePropagation(); };
|
||
if (k === "ArrowDown" || k === "ArrowUp") { stop(); SL.lit = (SL.lit + (k === "ArrowDown" ? 1 : n - 1)) % n; SL.moved = true; renderSlash(); }
|
||
else if ((k === "Enter" && !e.shiftKey) || k === "Tab") { stop(); slashPick(SL.lit); }
|
||
else if (k === "Escape") { stop(); SL.closed = true; renderSlash(); }
|
||
});
|
||
input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && matchMedia("(pointer:fine)").matches) { e.preventDefault(); send(); } });
|
||
const SL = {hits: [], lit: 0, q: null, moved: false, closed: false, loading: false, fresh: false, at: false};
|
||
/** AnyBot's own / commands (goal.rs on the brain). */
|
||
const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "context", description: "這個對話用了模型可讀的多少"}, {name: "compact", description: "現在就把較早的對話整理成摘要"}, {name: "fork", description: "分岔:這段對話存一份到過去的對話,之後各走各的"}, {name: "rewind", description: "退回:把 Bot 改的檔案和對話退回之前說的某一句"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}];
|
||
/** What woke the bot, from the tag its message starts with (app::chat_ui::wake_tag on the
|
||
* desktop): [tag, icon, label], and the words after it. 監看's tag carries the command's number, so
|
||
* its words stay whole. (Every wake used to say 例行任務 — a 監看's lines, a colleague's message.) */
|
||
const WAKE_TAGS = [["[目標]", "target", "目標"], ["[例行任務]", "alarm-clock", "例行任務"], ["[觸發]", "zap", "觸發"], ["[訊息管道]", "message", "訊息管道"], ["[來自 Bot]", "bot", "來自其他 Bot"], ["[交付]", "circle-alert", "交付沒顯示"], ["[核對]", "circle-alert", "回覆沒對上"], ["⏰ ", "alarm-clock", "例行任務"], ["⚡ ", "zap", "觸發"], ["💬 ", "message", "訊息管道"], ["📨 ", "bot", "來自其他 Bot"]];
|
||
function wakeTag(text) {
|
||
const t = String(text || "");
|
||
for (const [tag, icon, label] of WAKE_TAGS) if (t.startsWith(tag)) return {icon, label, body: t.slice(tag.length)};
|
||
if (t.startsWith("[監看 ")) return {icon: "eye", label: "監看", body: t};
|
||
// A workflow's question: its tag, and the previous step's result cut short (whole on tap-and-hold → 複製).
|
||
const wf = t.match(/^[(工作流「[^」]*」第 \d+\/\d+ 步[^]]*)]/);
|
||
if (wf) {
|
||
let body = t.slice(wf[0].length).trim();
|
||
// (A step hands on 「上一步的結果:」; a 檢查 shows what it checks as 「結果:」.)
|
||
for (const mark of ["\n\n上一步的結果:", "\n\n結果:"]) {
|
||
const cut = body.indexOf(mark);
|
||
if (cut < 0) continue;
|
||
const last = body.slice(cut + mark.length).trim();
|
||
const short = last.split("\n").slice(0, 3).join("\n").slice(0, 160);
|
||
body = body.slice(0, cut) + mark + short + (short.length < last.length ? "…" : "");
|
||
break;
|
||
}
|
||
return {icon: "workflow", label: wf[1], body};
|
||
}
|
||
return null;
|
||
}
|
||
/** The skills a draft like 「/pp」 asks for, as the brain ranks them: name starts with it, name
|
||
* contains it, then description. None once a space ends the name, or while the bot works. */
|
||
function slashHits() {
|
||
const v = input.value;
|
||
// @點名: in a group chat an @ being typed at the end lists the members instead.
|
||
const at = atHits(v);
|
||
SL.at = at !== null;
|
||
if (at !== null) return SL.closed ? [] : at;
|
||
if (!v.startsWith("/")) { SL.closed = false; SL.fresh = false; return []; }
|
||
if (SL.closed || /\s/.test(v.slice(1))) return [];
|
||
// AnyBot's own commands first (the brain acts on them itself), then the skills. While it works
|
||
// only /btw (anything else typed then joins the running turn).
|
||
const working = !!(bot(S.open) || {}).busy;
|
||
const cmds = COMMANDS.filter((c) => c.name.startsWith(v.slice(1).toLowerCase()) && (!working || c.name === "btw"));
|
||
if (working) return cmds;
|
||
// Each new / asks the brain once more, so a skill added since (on the computer, from the
|
||
// market, or one a bot just learned) is there; what was known shows in the meantime.
|
||
if (!SL.fresh && owner() && !SL.loading) {
|
||
SL.fresh = SL.loading = true;
|
||
api(base() + "api/settings").then((st) => { S.settings = st; }).catch(() => {}).finally(() => { SL.loading = false; renderSlash(); });
|
||
}
|
||
// A bare 「/」: the commands only. A word after it also finds this bot's skills by it (a few).
|
||
if (!S.settings || v.length < 2) return cmds;
|
||
const q = v.slice(1).toLowerCase();
|
||
const mine = (bot(S.open) || {}).skills;
|
||
const rank = (k) => { const n = k.name.toLowerCase(); return n.startsWith(q) ? 0 : n.includes(q) ? 1 : (k.description || "").toLowerCase().includes(q) ? 2 : 3; };
|
||
return cmds.concat((S.settings.skills || []).filter((k) => k.enabled !== false && k.name && !COMMANDS.some((c) => c.name === k.name) && (!Array.isArray(mine) || mine.includes(k.name))).map((k) => [rank(k), k]).filter(([r]) => r < 3).sort((a, b) => a[0] - b[0]).slice(0, 6).map(([, k]) => k));
|
||
}
|
||
/** What is typed after an @ at the end of the input (names may hold spaces), or null: a new
|
||
* line or a long run of words ends it, and an @ glued to letters is an address. */
|
||
function atTyping(v) {
|
||
const i = Math.max(v.lastIndexOf("@"), v.lastIndexOf("@"));
|
||
if (i < 0 || (i > 0 && /[A-Za-z0-9]/.test(v[i - 1]))) return null;
|
||
const q = v.slice(i + 1);
|
||
return q.includes("\n") || [...q].length > 24 ? null : q;
|
||
}
|
||
/** Who fits the @ being typed (name starts with it, then contains it): a group's members, or in a
|
||
* bot's own chat the other bots. null when no @ is being typed (or it is working). */
|
||
function atHits(v) {
|
||
const b = bot(S.open) || {};
|
||
if (b.busy) return null;
|
||
const q = atTyping(v);
|
||
if (q === null) return null;
|
||
const s = q.trimStart().toLowerCase();
|
||
const names = b.members ? (b.member_names || []) : S.bots.filter((x) => !x.members && x.id !== b.id).map((x) => x.name);
|
||
return names.map((n) => [n.toLowerCase().startsWith(s) ? 0 : n.toLowerCase().includes(s) ? 1 : 2, n]).filter(([r]) => r < 2).sort((x, y) => x[0] - y[0])
|
||
.map(([, n]) => ({name: n, description: (S.bots.find((x) => x.name === n) || {}).description || ""}));
|
||
}
|
||
function renderSlash() {
|
||
const el = $("slash");
|
||
SL.hits = slashHits();
|
||
if (input.value !== SL.q) { SL.q = input.value; SL.lit = 0; }
|
||
if (!SL.hits.length) { el.innerHTML = ""; return; }
|
||
SL.lit = Math.min(SL.lit, SL.hits.length - 1);
|
||
const mark = SL.at ? "@" : "/";
|
||
el.innerHTML = `<div class="hd">${SL.at ? ((bot(S.open) || {}).members ? "點名成員" : "找其他 Bot 一起來") : "指令和技能"}</div>` + SL.hits.map((k, i) => `<button class="${i === SL.lit ? "on" : ""}" data-sl="${i}"><b>${mark}${esc(k.name)}</b><span>${esc(k.description || "")}</span></button>`).join("");
|
||
el.querySelectorAll("[data-sl]").forEach((x) => {
|
||
// Keep the caret (and the phone's keyboard) in the input while a row is pressed.
|
||
x.onpointerdown = x.onmousedown = (e) => e.preventDefault();
|
||
x.onclick = () => slashPick(+x.dataset.sl);
|
||
});
|
||
if (SL.moved) { SL.moved = false; const on = el.querySelector(".on"); if (on) on.scrollIntoView({block: "nearest"}); }
|
||
}
|
||
function slashPick(i) {
|
||
const k = SL.hits[i];
|
||
if (!k) return;
|
||
if (SL.at) {
|
||
// The name being typed is completed, whatever came before it stays.
|
||
const v = input.value, i = Math.max(v.lastIndexOf("@"), v.lastIndexOf("@"));
|
||
input.value = v.slice(0, i + 1) + k.name + " ";
|
||
} else input.value = "/" + k.name + " ";
|
||
input.focus(); input.setSelectionRange(input.value.length, input.value.length);
|
||
input.dispatchEvent(new Event("input"));
|
||
}
|
||
function renderSendBtn() {
|
||
const b = bot(S.open) || {};
|
||
const empty = !input.value.trim() && !S.pending.length;
|
||
const stop = empty && b.busy && owner();
|
||
$("b-send").innerHTML = ic(stop ? "stop" : "arrow-up", 16);
|
||
$("b-send").title = stop ? "停止" : "傳送訊息";
|
||
$("b-send").disabled = empty && !stop;
|
||
}
|
||
$("b-send").onclick = send;
|
||
async function send() {
|
||
let text = input.value.trim();
|
||
const b = bot(S.open) || {};
|
||
if (!text && !S.pending.length) {
|
||
if (b.busy && owner()) { try { await api(base() + `api/bots/${S.open}/stop`, {json: {}}); toast("已停止"); } catch (e) { toast(e.message); } }
|
||
return;
|
||
}
|
||
if (S.quote) { text = S.quote.raw.split("\n").map((l) => "> " + l).join("\n") + "\n\n" + text; S.quote = null; renderQuote(); }
|
||
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();
|
||
// (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 = ""; keepDraft(S.open, ""); 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) {
|
||
// 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"${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();
|
||
}
|
||
// 語音輸入: record here; the brain's voice service (設定 › 語音) turns it into text, the same as
|
||
// on every screen. The mic shows only when the brain says it can hear.
|
||
const CAN_REC = !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia && window.MediaRecorder);
|
||
// The brain writes Mandarin in Traditional characters for a Traditional Chinese phone.
|
||
const UI_LANG = /^zh-(tw|hk|mo|hant)/i.test(navigator.language || "") ? "zh-TW" : (navigator.language || "");
|
||
let rec = null;
|
||
function micShown() { $("b-mic").style.display = S.voice.listen && CAN_REC ? "" : "none"; }
|
||
micShown();
|
||
$("b-mic").onclick = async () => {
|
||
if (rec) { rec.stop(); return; }
|
||
let stream;
|
||
try { stream = await navigator.mediaDevices.getUserMedia({audio: true}); } catch (_) { toast("沒有允許使用麥克風"); return; }
|
||
const type = ["audio/webm;codecs=opus", "audio/mp4", "audio/webm", "audio/ogg"].find((t) => MediaRecorder.isTypeSupported && MediaRecorder.isTypeSupported(t)) || "";
|
||
const r = new MediaRecorder(stream, type ? {mimeType: type} : {});
|
||
const chunks = [];
|
||
r.ondataavailable = (e) => { if (e.data && e.data.size) chunks.push(e.data); };
|
||
r.onstop = async () => {
|
||
stream.getTracks().forEach((t) => t.stop());
|
||
rec = null; $("b-mic").classList.remove("rec"); $("b-mic").title = "開始語音輸入";
|
||
const mime = r.mimeType || type || "audio/webm";
|
||
const ext = mime.includes("mp4") ? "m4a" : mime.includes("ogg") ? "ogg" : "webm";
|
||
const blob = new Blob(chunks, {type: mime});
|
||
if (blob.size < 1000) { toast("沒有錄到聲音"); return; }
|
||
toast("轉成文字中…");
|
||
try {
|
||
const v = await api(base() + "api/voice/transcribe?name=voice." + ext + "&ui=" + encodeURIComponent(UI_LANG), {method: "POST", body: blob, headers: {"Content-Type": "application/octet-stream"}});
|
||
if (!v.text) { toast("沒有聽到說話"); return; }
|
||
input.value = (input.value ? input.value + " " : "") + v.text; input.dispatchEvent(new Event("input"));
|
||
} catch (err) { toast(err.message); }
|
||
};
|
||
r.start(); rec = r;
|
||
$("b-mic").classList.add("rec"); $("b-mic").title = "停止並轉成文字"; toast("正在錄音…再按一次結束");
|
||
};
|
||
// 朗讀: the brain's voice service reads a message; the phone only plays it.
|
||
let player = null;
|
||
async function speakText(text) {
|
||
if (player) { player.pause(); player = null; }
|
||
// Made while the tap still counts, so the phone lets it play once the sound arrives.
|
||
const a = new Audio(); a.play().catch(() => {}); player = a;
|
||
toast("準備朗讀…");
|
||
try {
|
||
const r = await api(base() + "api/voice/speech", {json: {text}, raw: true});
|
||
if (!r.ok) { let e = ""; try { e = (await r.json()).error || ""; } catch (_) {} throw new Error(e || "HTTP " + r.status); }
|
||
const url = URL.createObjectURL(await safeBlob(r));
|
||
if (player !== a) { URL.revokeObjectURL(url); return; }
|
||
a.onended = () => URL.revokeObjectURL(url);
|
||
a.src = url; await a.play();
|
||
} catch (err) { toast(err.message || "朗讀失敗"); }
|
||
}
|
||
$("b-newchat").onclick = async () => {
|
||
if (!await confirmSheet("開始新對話?", "目前的對話會留在「過去的對話」裡。", "開始新對話", false)) return;
|
||
try { await api(base() + `api/bots/${S.open}/new`, {json: {}}); S.unfold = {}; toast("已開始新對話"); setTimeout(() => loadChat(true), 500); } catch (e) { toast(e.message); }
|
||
};
|
||
$("b-chatmore").onclick = () => {
|
||
const b = bot(S.open); if (!b) return;
|
||
const items = [
|
||
{icon: "info", label: "對話詳細資訊", on: () => go("details", {bot: b.id})},
|
||
{icon: "history", label: "過去的對話", x: String((b.threads || []).length || ""), on: () => threads(b)},
|
||
{icon: "copy", label: "複製整段對話", on: () => copyText(S.msgs.filter((m) => m.text && !m.summary).map((m) => (m.role === "user" ? "我:" : b.name + ":") + m.text).join("\n\n"))},
|
||
...(owner() ? [{icon: "download", label: "匯出文字記錄(.md)", on: () => exportAs("export_transcript", b.id)}] : []),
|
||
];
|
||
if (owner()) items.splice(1, 0, {icon: "refresh", label: "重新產生上一個回答", on: regen});
|
||
if (isOwner()) items.push({icon: "settings", label: "Bot 設定", on: () => go("botset", {bot: b.id})});
|
||
if (isOwner()) items.push({icon: "trash", label: "清除聊天記錄", danger: true, on: async () => { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) { await act("clear", {bot: b.id}); setTimeout(() => loadChat(true), 500); } }});
|
||
sheet(b.name, items);
|
||
};
|
||
function threads(b) {
|
||
const list = b.threads || [];
|
||
if (!list.length) { toast("還沒有過去的對話"); return; }
|
||
sheet("過去的對話", list.map((t) => ({icon: "message", label: t.title || "對話", x: ago(t.at), on: async () => {
|
||
if (!await confirmSheet("回到這段對話?", "現在的對話會留在「過去的對話」裡。", "回到這段對話", false)) return;
|
||
try { await api(base() + `api/bots/${b.id}/restore`, {json: {index: t.index}}); toast("已回到那段對話"); S.unfold = {}; setTimeout(() => loadChat(true), 700); } catch (e) { toast(e.message); }
|
||
}})));
|
||
}
|
||
// At the newest message, it stays in view while what is above it grows after being drawn (a
|
||
// picture that loads, a preview); scrolled up to read, nothing moves. (A question card taller
|
||
// than the screen is left where renderQuestion put it: its question, not its buttons.)
|
||
let atEnd = true;
|
||
$("scroller").addEventListener("scroll", () => { const sc = $("scroller"), left = sc.scrollHeight - sc.scrollTop - sc.clientHeight; atEnd = left < 140; $("b-down").classList.toggle("on", left > 400); });
|
||
if ("ResizeObserver" in window) new ResizeObserver(() => { const sc = $("scroller"); if (atEnd && S.view === "chat" && $("askq").offsetHeight <= sc.clientHeight && sc.scrollHeight - sc.scrollTop - sc.clientHeight > 1) sc.scrollTop = sc.scrollHeight; }).observe($("msgs"));
|
||
$("b-down").onclick = () => { const sc = $("scroller"); sc.scrollTo({top: sc.scrollHeight, behavior: "smooth"}); };
|
||
</script>
|
||
<script>
|
||
"use strict";
|
||
// ---------- 對話詳細資訊 (the desktop's panel beside the chat) ----------
|
||
$("b-botset").innerHTML = ic("settings", 20);
|
||
$("b-botset").onclick = () => go("botset", {bot: cur().arg.bot});
|
||
async function loadDetail(id) {
|
||
if (!owner()) return null;
|
||
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>`;
|
||
// 設定 rows all have a picture (as on the computer, src/icons.rs setting_icon): by the words in
|
||
// the name, first match wins; a name that matches none gets the sliders.
|
||
const SET_ICON = [[["上網"], "globe"], [["頁面"], "file-text"], [["合作", "同事"], "users"], [["電話", "簡訊"], "message"], [["Mac App"], "laptop"], [["管理 App"], "settings"], [["主題"], "moon"], [["風格", "強調色", "顏色", "外觀"], "palette"], [["頭像", "形狀"], "smile-plus"], [["語言", "時區"], "globe"], [["通知", "響一聲"], "bell"], [["記憶"], "brain"], [["資料夾", "文件", "檔案", "資料庫"], "folder"], [["金鑰", "Token", "密碼", "保險庫", "兩步"], "lock"], [["瀏覽器", "網址"], "globe"], [["更新", "版本", "重新啟動"], "refresh"], [["備份", "還原", "快照"], "history"], [["磁碟", "用量"], "hard-drive"], [["團隊", "成員", "分享"], "users"], [["帳號", "登入", "登出", "角色", "名稱"], "info"], [["手機", "裝置"], "smartphone"], [["語音", "聲音"], "audio-lines"], [["規則", "權限", "直接操作", "一律", "允許", "詢問", "審核", "隔離"], "shield"], [["連接器", "整合"], "plug"], [["管道"], "message"], [["技能"], "sparkles"], [["模型", "思考", "步驟"], "sparkles"], [["電腦", "螢幕", "Docker", "主機", "終端機"], "monitor"], [["例行"], "alarm-clock"], [["指示", "描述", "擅長", "不找"], "pen"], [["釘選"], "pin"], [["分區"], "folder"], [["主要"], "star"]];
|
||
const SMART_SECS = [[30, "30 秒後"], [60, "1 分鐘後"], [120, "2 分鐘後"], [300, "5 分鐘後"], [600, "10 分鐘後"]];
|
||
const VOICE_KINDS = [["off", "關閉"], ["open_ai", "OpenAI 相容"], ["xai", "xAI"], ["eleven_labs", "ElevenLabs"]];
|
||
const setIcon = (k) => (SET_ICON.find(([ws]) => ws.some((w) => String(k || "").includes(w))) || [0, "settings"])[1];
|
||
const sitem = (o) => item(o.icon || o.noIcon ? o : {...o, icon: setIcon(o.k)});
|
||
async function loadAudit(id) {
|
||
try { S.audit[id] = await api(base() + `api/bots/${id}/audit`); } catch (e) { S.audit[id] = {turns: []}; }
|
||
if (cur().v === "details" && S.tab === "audit") renderDetails(id, "audit", true);
|
||
}
|
||
|
||
async function renderDetails(id, tab, quiet) {
|
||
const b = bot(id); if (!b) { back(); return; }
|
||
S.tab = tab || S.tab || "activity";
|
||
// 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] || {};
|
||
const tabs = [["activity", "動態"], ...(isOwner() ? [["memory", "記憶"]] : []), ["routines", "例行任務"], ["library", "資料庫"], ["computer", "電腦"], ["audit", "稽核"]];
|
||
if (b.members) tabs.push(["members", "成員"]);
|
||
let h = `<div class="hero">${face(b, "lg")}<div class="n">${esc(b.name)}</div>${b.description ? `<div class="d">${esc(b.description)}</div>` : ""}</div>`;
|
||
h += `<div class="tabs">${tabs.map(([k, n]) => `<button data-tab="${k}" class="${S.tab === k ? "on" : ""}">${n}</button>`).join("")}</div>`;
|
||
h += `<div id="tab">${tabBody(b, d)}</div><div style="height:calc(var(--safe-b) + 24px)"></div>`;
|
||
const sc = $("details").scrollTop;
|
||
$("details").innerHTML = h;
|
||
if (quiet) $("details").scrollTop = sc;
|
||
$("details").querySelectorAll("[data-tab]").forEach((x) => x.onclick = () => { S.tab = x.dataset.tab; renderDetails(id, S.tab, true); });
|
||
wireDetails(b, d);
|
||
}
|
||
function tabBody(b, d) {
|
||
const a = S.approvals.find((x) => x.bot === b.id);
|
||
if (S.tab === "memory") { setTimeout(() => memTab(b.id), 0); return `<div id="memtab"><div class="note" style="padding:14px 18px">載入中…</div></div>`; }
|
||
if (S.tab === "activity") {
|
||
let h = "";
|
||
if (b.busy || a) h += group("進行中", (a ? item({icon: "hand", k: a.kind === "handoff" ? "需要你處理" : a.kind === "question" ? "等你回答" : "需要你核准", v: a.title, tap: 1, data: 'data-d="chat"'}) : "") + (b.busy ? item({icon: "loader", k: b.status || "工作中…", r: "", tap: 0}) + `<div class="form"><button class="btn no" data-d="stop">${ic("stop", 14)} 停止</button></div>` : ""));
|
||
h += group("建議", SUGGEST.slice(0, 3).map((x, k) => item({icon: x[0], k: x[1], v: x[2], tap: 1, data: `data-sg="${k}"`})).join(""));
|
||
if (isOwner()) h += group("記憶", item({icon: "bookmark", k: "記得的事和做過的事", v: (d.memories || []).length ? `記得 ${(d.memories || []).length} 件事 · 搜尋、釘選、整理` : "還沒有記得的事。在聊天裡說「記住…」", tap: 1, data: 'data-tab="memory"'}));
|
||
if (owner()) h += group("這個 Bot", item({icon: "sparkles", k: "模型", r: b.model || "", tap: 1, data: 'data-d="model"'}) + item({icon: "file-text", k: "指示", v: d.instructions ? d.instructions.slice(0, 120) + (d.instructions.length > 120 ? "…" : "") : "還沒有寫", tap: isOwner() ? 1 : 0, data: isOwner() ? 'data-d="instr"' : ""}) + item({icon: "history", k: "過去的對話", r: String((d.threads || []).length), tap: 1, data: 'data-d="threads"'}));
|
||
return h;
|
||
}
|
||
if (S.tab === "audit") {
|
||
const a = S.audit[b.id];
|
||
if (a === undefined) { loadAudit(b.id); return `<div class="note" style="padding:14px 16px">載入中…</div>`; }
|
||
if (!a.turns.length) return `<div class="empty">最近 30 天沒有工作紀錄。</div>`;
|
||
// 只看沒人看著時做的 (as on the computer): the turns a routine or another bot started.
|
||
const alone = !!S.auditAlone, turns = alone ? a.turns.filter((t) => t.who && t.who !== "person") : a.turns;
|
||
const OUT = {completed: "已結束", aborted: "被你停止", failed: "失敗"};
|
||
const ST = {done: "完成", running: "進行中…", waiting: "等核准", denied: "沒有完成(拒絕或停止)", failed: "失敗"};
|
||
const TI = {computer: "zap", menu_click: "zap", fill_form: "zap", wait_for: "clock", run_cmd: "zap", web_fetch: "globe", browser: "globe"};
|
||
let h = "";
|
||
h += `<div class="form" style="padding-bottom:0"><label style="display:flex;align-items:center;gap:8px;font-size:var(--fs-small);color:var(--text2)"><input type="checkbox" data-alone ${alone ? "checked" : ""}> 只看沒人看著時做的(例行任務和別的 Bot 叫它做的)</label></div>`;
|
||
if (!turns.length) h += `<div class="empty">最近 30 天沒有沒人看著時做的事。</div>`;
|
||
for (const t of [...turns].reverse()) {
|
||
const steps = t.steps.map((x) => {
|
||
if (x.type === "model") return item({icon: "sparkles", k: x.step === "assistant" ? "問模型" : x.step === "compaction" ? "整理長對話" : x.step, v: x.attempts > 1 ? `試了 ${x.attempts} 次(有重試)` : ""});
|
||
if (x.type === "tool") return item({icon: TI[x.name] || "zap", k: x.name, v: (x.args || "").slice(0, 200), r: ST[x.status] || x.status});
|
||
if (x.type === "queue") return item({icon: "message", k: "你插進來的話", v: x.text, r: x.state === "waiting" ? "排隊中" : x.state === "consumed" ? "已送達" : "已取消"});
|
||
return item({icon: "stop", k: "你按了停止"});
|
||
}).join("");
|
||
// 操作紀錄 (plan D5): who started it, how long, what failed, and what it looked at, wrote and ran.
|
||
const e = t.evidence;
|
||
const WHO = {routine: "例行任務", bot: "別的 Bot", person: "你"};
|
||
const secs = Math.round(((e && e.duration_ms) || 0) / 1000);
|
||
const dur = secs < 60 ? `${secs} 秒` : secs < 3600 ? `${Math.floor(secs / 60)} 分 ${secs % 60} 秒` : `${Math.floor(secs / 3600)} 小時 ${Math.floor(secs % 3600 / 60)} 分`;
|
||
const parts = e ? [["looked", "看了"], ["wrote", "寫了"], ["ran", "執行了"]].filter(([k]) => (e[k] || []).length).map(([k, w]) => `${w}:${e[k].slice(0, 4).join("、")}${e[k].length > 4 ? ` 等 ${e[k].length} 項` : ""}`) : [];
|
||
const sum = e ? item({icon: "activity", k: `${WHO[t.who] || "你"}發起 · ${dur}${e.failed ? ` · 失敗 ${e.failed} 步` : ""}`, v: parts.join("\n")}) : "";
|
||
h += group(`${plain(t.prompt || "(無訊息的回合)").slice(0, 24)} · ${ago(t.at)} · ${OUT[t.outcome] || "進行中…"}`, sum + steps); // (group() escapes the title itself)
|
||
}
|
||
return h;
|
||
}
|
||
if (S.tab === "routines") {
|
||
const rs = d.routines || [];
|
||
const list = rs.map((r) => item({icon: r.paused ? "pause" : "alarm-clock", k: r.title, v: (r.trigger ? "事件觸發:" + r.trigger : r.repeat) + " · " + r.when + (r.status ? "\n" + r.status : ""), tap: 1, data: `data-rt="${r.id}"`})).join("");
|
||
return group("", list || `<div class="note" style="padding:14px 16px">例行任務是這個 Bot 依排程重複執行的任務。按下面的新增,或在聊天中請它設定一個。</div>`) + (isOwner() ? `<div class="form"><button class="btn main" data-d="newrt">${ic("plus", 15)} 新增例行任務</button></div>` : "");
|
||
}
|
||
if (S.tab === "library") {
|
||
const pages = S.pages.filter((p) => p.bot === b.name);
|
||
const files = d.files || [];
|
||
const imgs = files.filter((f) => f.image), docs = files.filter((f) => !f.image);
|
||
let h = "";
|
||
if (pages.length) h += group("頁面", pages.map((p) => item({icon: "file-text", k: p.title, v: p.updated, tap: 1, data: `data-page="${p.id}"`})).join(""));
|
||
if (imgs.length) h += `<div class="gt">圖片 <span style="font-weight:400">${imgs.length}</span></div><div class="files">${imgs.map((f) => `<div class="f" data-file="${esc(f.path)}" data-img="1">${FILES[f.path] ? `<img src="${FILES[f.path]}">` : ic("image", 18)}</div>`).join("")}</div>`;
|
||
if (docs.length) h += group("檔案", docs.map((f) => `<a class="item tap" data-file="${esc(f.path)}" data-name="${esc(f.name)}">${ic("file", 19)}<div class="mid"><div class="k" style="font-size:var(--fs-ui);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(f.name)}</div><div class="v">${f.mine ? "你傳的" : "Bot 傳的"} · ${ago(f.at)}</div></div>${ic("download", 16)}</a>`).join(""));
|
||
return h || `<div class="empty">這段對話還沒有頁面或檔案</div>`;
|
||
}
|
||
if (S.tab === "computer") {
|
||
const comps = b.computers || [];
|
||
const own = comps.find((c) => c.kind === "own");
|
||
let h = "";
|
||
if (own) h += `<div class="gt">${esc(own.name)} <span class="pill ${S.boxOn && !/睡|暫停|關/.test(S.box) ? "ok" : ""}" style="margin-left:4px">${esc(S.boxOn ? S.box || "可以用" : "沒有 Docker")}</span></div><div class="group"><div class="thumbbox" style="margin:0;border-radius:0">${S.boxOn ? `<img id="box-thumb" alt="">` : "沒有畫面"}</div><div class="btnrow"><button class="btn main" data-d="openbox">${ic("monitor", 15)} 開啟電腦</button><button class="btn" data-d="takeover">${ic("hand", 15)} 接管</button><button class="btn" data-d="wake">${ic("power", 15)} 喚醒</button></div></div>`;
|
||
// Shown here, set in one place: Bot 設定 (the row goes there).
|
||
h += group("做事的電腦", item({icon: "monitor", k: "預設在這台做事", v: isOwner() ? "在 Bot 設定裡改" : "", r: b.computer || "", tap: isOwner() ? 1 : 0, data: isOwner() ? 'data-d="botsetcomp"' : ""}));
|
||
h += group("電腦", comps.map((c) => { const k = {own: "cloud", this: "monitor", device: "laptop", ssh: "server"}[c.kind] || "monitor"; return item({icon: k, k: c.name, v: (c.online ? "在線上" : "離線") + (c.person ? " · 你正在用的" : "") + (c.name === b.computer ? " · 預設" : ""), tap: c.kind === "this" && S.mac ? 1 : 0, data: c.kind === "this" && S.mac ? 'data-d="mac"' : ""}); }).join(""));
|
||
return h;
|
||
}
|
||
if (S.tab === "members") {
|
||
const ids = (d.members || []).map((m) => m.id);
|
||
return group("成員", S.bots.filter((x) => !x.members && x.id !== b.id).map((x) => `<button class="item" data-mem="${x.id}"><div class="av sm">${avatarSvg(x.shape, x.color)}</div><div class="mid"><div class="k">${esc(x.name)}</div></div>${ids.includes(x.id) ? `<span style="color:var(--accent)">${ic("check", 18)}</span>` : ""}</button>`).join("")) + `<div class="note">成員依序回答你的訊息,只回答自己擅長的部分;用「@名字」點名就只有被點到的回答,成員也會 @ 彼此接著說。</div>`;
|
||
}
|
||
return "";
|
||
}
|
||
function wireDetails(b, d) {
|
||
const el = $("details");
|
||
const on = (sel, fn) => el.querySelectorAll(sel).forEach((x) => x.onclick = (e) => fn(x, e));
|
||
on("[data-d]", async (x) => {
|
||
const k = x.dataset.d;
|
||
if (k === "chat") back();
|
||
else if (k === "stop") { try { await api(base() + `api/bots/${b.id}/stop`, {json: {}}); toast("已停止"); } catch (e) { toast(e.message); } }
|
||
else if (k === "remember") { const t = await ask("要它記住什麼?", "", "例如:之後的貼文都用輕鬆的語氣"); if (t && await app("remember", {fact: t}, b.id)) renderDetails(b.id, S.tab); }
|
||
else if (k === "model") modelSheet(b);
|
||
else if (k === "instr") editInstructions(b, d);
|
||
else if (k === "threads") threads(b);
|
||
else if (k === "newrt") routineForm(b, null);
|
||
else if (k === "openbox") openBox(false);
|
||
else if (k === "takeover") openBox(true);
|
||
else if (k === "wake") act("box", {op: "wake"}, "正在喚醒…");
|
||
else if (k === "botsetcomp") go("botset", {bot: b.id});
|
||
else if (k === "mac") go("screen");
|
||
});
|
||
on("[data-forget]", async (x) => { if (await app("forget", {what: x.dataset.forget}, b.id)) renderDetails(b.id, S.tab); });
|
||
el.querySelectorAll("[data-alone]").forEach((x) => x.onchange = () => { S.auditAlone = x.checked; 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]", (x) => oneAtATime(async () => {
|
||
if (!isOwner()) return;
|
||
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]}, "已更新成員")) { delete S.detail[b.id]; renderDetails(b.id, S.tab); }
|
||
}));
|
||
const t = $("box-thumb"); if (t) boxThumb(t, b.id);
|
||
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); } });
|
||
}
|
||
// ---------- 記憶 ----------
|
||
// The memories live on the brain: the composer asks which ones a draft may want (300 ms after
|
||
// typing stops; the strong ones come ticked), and the memory tab lists, searches and tidies them.
|
||
const memApi = (body) => api(base() + "api/memory", {json: body});
|
||
const KIND = {fact: "記得的事", event: "做過的事", rollup: "整理過的"};
|
||
const memDay = (ms) => ms ? new Date(ms).toLocaleDateString("zh-TW") : "";
|
||
S.carried = new Set();
|
||
S.memSug = {bot: 0, asked: "", hits: [], toggled: {}, timer: null};
|
||
function memOn(h) { const t = S.memSug.toggled[h.id]; return t === undefined ? !!h.pick : t; }
|
||
function memPicks() { const s = S.memSug; return s.bot === S.open && s.asked ? s.hits.filter(memOn).map((h) => h.text) : undefined; }
|
||
function memReset() { clearTimeout(S.memSug.timer); S.memSug = {bot: 0, asked: "", hits: [], toggled: {}, timer: null}; renderMemChips(); }
|
||
function renderMemChips() {
|
||
const s = S.memSug, el = $("memchips");
|
||
// (Not while the bot works: what is sent then joins the running turn, which carries none.)
|
||
const busy = (S.bots.find((x) => x.id === S.open) || {}).busy;
|
||
if (!isOwner() || busy || s.bot !== S.open || !s.hits.length || !input.value.trim()) { el.innerHTML = ""; return; }
|
||
const on = s.hits.filter(memOn), tok = on.reduce((a, h) => a + (h.tokens || 0), 0);
|
||
el.innerHTML = `<span class="lbl">${ic("bookmark", 13)} 帶入記憶</span>` + s.hits.map((h) => `<button class="mchip ${memOn(h) ? "on" : ""}" data-mc="${h.id}" title="${esc(h.text)}">${memOn(h) ? "✓ " : ""}${esc(h.text)}</button>`).join("") + `<span class="memtok">${on.length ? `帶 ${on.length} 條,約 ${tok} token` : "這次不帶"}</span>`;
|
||
el.querySelectorAll("[data-mc]").forEach((x) => x.onclick = () => { const h = s.hits.find((y) => y.id === +x.dataset.mc); if (h) { s.toggled[h.id] = !memOn(h); renderMemChips(); } });
|
||
}
|
||
function memSuggestSoon() {
|
||
const s = S.memSug; clearTimeout(s.timer);
|
||
if (!isOwner() || !S.open) return;
|
||
s.timer = setTimeout(async () => {
|
||
const q = input.value.trim(), bot = S.open;
|
||
if (q.length < 2) { Object.assign(s, {bot, asked: "", hits: [], toggled: {}}); renderMemChips(); return; }
|
||
if (q === s.asked && bot === s.bot) return;
|
||
try {
|
||
const v = await memApi({op: "suggest", bot, q});
|
||
if (S.open !== bot) return;
|
||
const keep = {}; (v.hits || []).forEach((h) => { if (s.bot === bot && s.toggled[h.id] !== undefined) keep[h.id] = s.toggled[h.id]; });
|
||
Object.assign(s, {bot, asked: q, hits: v.hits || [], toggled: keep});
|
||
renderMemChips();
|
||
} catch (_) {}
|
||
}, 300);
|
||
}
|
||
$("msgs").addEventListener("click", (e) => {
|
||
const c = e.target.closest("[data-carried]"); if (!c) return;
|
||
const k = c.dataset.carried; S.carried.has(k) ? S.carried.delete(k) : S.carried.add(k); renderMsgs();
|
||
});
|
||
// The memory tab.
|
||
const MEM_FILTERS = [["all", "全部"], ["fact", "記得的事"], ["event", "做過的事"], ["pinned", "釘選"], ["trash", "最近刪除"]];
|
||
/** `shelf`: the bot's own memories (its id) or 關於你 (0, what every bot knows about the person);
|
||
* left out, the one already open for this bot. */
|
||
function memTab(id, shelf) {
|
||
const el = $("memtab"); if (!el) return;
|
||
const want = shelf === undefined ? (S.mem && S.mem.owner === id ? S.mem.bot : id) : shelf;
|
||
if (!S.mem || S.mem.owner !== id || S.mem.bot !== want) S.mem = {bot: want, owner: id, filter: "all", q: "", limit: 60, items: [], total: 0, ov: null, kept: [], staleOpen: false};
|
||
const m = S.mem;
|
||
const shelves = [[id, "這個 Bot 自己的"], [0, "關於你(所有 Bot 共用)"]];
|
||
el.innerHTML = `<div class="memfilters">${shelves.map(([b, n]) => `<button class="${m.bot === b ? "on" : ""}" data-shelf="${b}">${n}</button>`).join("")}</div>`
|
||
+ (m.bot === 0 ? `<div class="note" style="padding:2px 18px 8px">每個 Bot 每次聊天都帶著這裡的事(最新的 40 條);Bot 記下關於你本人的事(名字、家人、住哪、喜好)時會放在這裡。</div>` : "")
|
||
+ `<div class="memhead" id="mem-head"></div><div class="memsearch"><input id="mem-q" type="search" placeholder="搜尋記憶(打字就找)" value="${esc(m.q)}"><button id="mem-add">${ic("plus", 15)} 新增</button></div><div class="memfilters" id="mem-filters"></div><div id="mem-sugg"></div><div id="mem-list"></div>`;
|
||
let t = null;
|
||
$("mem-q").oninput = () => { clearTimeout(t); t = setTimeout(() => { m.q = $("mem-q").value.trim(); m.limit = 60; memList(); memSugg(); }, 300); };
|
||
$("mem-add").onclick = async () => { const x = await ask(m.bot === 0 ? "所有 Bot 都要知道你什麼?" : "要它記住什麼?", "", m.bot === 0 ? "例如:我住台南,平日早上九點上班" : "例如:之後的貼文都用輕鬆的語氣"); if (x) memWrite({op: "add", text: x}); };
|
||
el.querySelectorAll("[data-shelf]").forEach((x) => x.onclick = () => memTab(id, +x.dataset.shelf));
|
||
memFilters(); memList(); memOverview();
|
||
}
|
||
function memFilters() {
|
||
const m = S.mem, el = $("mem-filters"); if (!el) return;
|
||
el.innerHTML = MEM_FILTERS.filter(([k]) => m.bot !== 0 || (k !== "event" && k !== "pinned")).map(([k, n]) => `<button class="${m.filter === k ? "on" : ""}" data-mf="${k}">${n}</button>`).join("");
|
||
el.querySelectorAll("[data-mf]").forEach((x) => x.onclick = () => { m.filter = x.dataset.mf; m.limit = 60; memFilters(); memList(); memSugg(); });
|
||
}
|
||
async function memOverview() {
|
||
const m = S.mem;
|
||
try { m.ov = await memApi({op: "overview", bot: m.bot}); } catch (e) { toast(e.message); return; }
|
||
const st = m.ov.stats || {}, n = (k) => st[k] || 0;
|
||
const files = (m.ov.files || []).map((f) => `${f.name} ${f.bytes > 1048576 ? (f.bytes / 1048576).toFixed(1) + " MB" : Math.max(1, Math.round(f.bytes / 1024)) + " KB"}`).join(" · ");
|
||
const head = $("mem-head");
|
||
if (head) head.innerHTML = m.bot === 0 ? `記得的事<b>${n("facts")}</b>最近刪除<b>${n("trash")}</b>` : `記得的事<b>${n("facts")}</b>做過的事<b>${n("events") + n("rollups")}</b>釘選<b>${n("pinned")}</b>最近刪除<b>${n("trash")}</b><div class="sub">釘選的每次都帶,其他的相關時才帶</div>`;
|
||
memSugg();
|
||
}
|
||
function memSugg() {
|
||
const m = S.mem, el = $("mem-sugg"); if (!el) return;
|
||
const s = (m.ov && m.ov.suggestions) || {};
|
||
const dupes = (s.dupes || []).filter((d) => !m.kept.includes(d[0].id + ":" + d[1].id)), stale = s.stale || [];
|
||
if (m.filter === "trash" || m.q || (!dupes.length && !stale.length && !s.old_events && !s.old_weeks)) { el.innerHTML = ""; return; }
|
||
let h = `<div class="msugg"><div class="h">${ic("sparkles", 15)} 整理建議</div>`;
|
||
dupes.forEach((d, i) => { h += `<div class="sr">這兩條很像:「${esc(d[0].text)}」/「${esc(d[1].text)}」<div class="acts"><button data-merge="${i}">合併(留下較新的)</button><button data-keep="${i}">兩條都留著</button></div></div>`; });
|
||
if (stale.length) h += `<div class="sr">${stale.length} 條記得的事半年沒被帶入過,可能過時了<div class="acts"><button data-stale="1">${m.staleOpen ? "收起" : "看看是哪些"}</button><button data-staleall="1">全部忘記</button></div>${m.staleOpen ? stale.map((x) => `<div class="sr" style="margin-top:6px">• ${esc(x.text)} <button class="plink" data-forget1="${x.id}">忘記</button></div>`).join("") : ""}</div>`;
|
||
if (s.old_events || s.old_weeks) h += `<div class="sr">${s.old_events ? `${s.old_events} 條做過的事超過 30 天,可以壓成每週一行` : ""}${s.old_events && s.old_weeks ? ";" : ""}${s.old_weeks ? `${s.old_weeks} 行每週的整理可以壓成每月一行` : ""}<div class="acts"><button data-tidy="1">現在整理</button></div><div style="font-size:var(--fs-caption);color:var(--text3);margin-top:4px">每晚也會自動整理;壓掉的原文在「最近刪除」放 30 天。</div></div>`;
|
||
el.innerHTML = h + "</div>";
|
||
el.querySelectorAll("[data-merge]").forEach((x) => x.onclick = () => { const d = dupes[+x.dataset.merge]; const [keep, drop] = d[0].created >= d[1].created ? [d[0], d[1]] : [d[1], d[0]]; memWrite({op: "merge", keep: keep.id, drop: [drop.id]}); });
|
||
el.querySelectorAll("[data-keep]").forEach((x) => x.onclick = () => { const d = dupes[+x.dataset.keep]; m.kept.push(d[0].id + ":" + d[1].id); memSugg(); });
|
||
el.querySelectorAll("[data-stale]").forEach((x) => x.onclick = () => { m.staleOpen = !m.staleOpen; memSugg(); });
|
||
el.querySelectorAll("[data-staleall]").forEach((x) => x.onclick = async () => { if (await confirmSheet(`忘記這 ${stale.length} 條?`, "30 天內可以在「最近刪除」還原。", "全部忘記")) memWrite({op: "forget", ids: stale.map((y) => y.id)}); });
|
||
el.querySelectorAll("[data-forget1]").forEach((x) => x.onclick = () => memWrite({op: "forget", id: +x.dataset.forget1}));
|
||
el.querySelectorAll("[data-tidy]").forEach((x) => x.onclick = () => memWrite({op: "tidy"}));
|
||
}
|
||
async function memList() {
|
||
const m = S.mem, el = $("mem-list"); if (!el) return;
|
||
const want = {op: "list", bot: m.bot, filter: m.filter, q: m.q, limit: m.limit};
|
||
let v; try { v = await memApi(want); } catch (e) { toast(e.message); return; }
|
||
if (S.mem !== m || m.q !== want.q || m.filter !== want.filter) return;
|
||
m.items = v.items || []; m.total = v.total || 0;
|
||
const trash = m.filter === "trash";
|
||
if (!m.items.length) {
|
||
el.innerHTML = `<div class="note" style="padding:14px 18px">${m.q ? "沒有找到相關的記憶。" : trash ? "最近刪除是空的。忘記、合併、壓縮掉的記憶會在這裡放 30 天。" : "還沒有記憶。在聊天裡說「記住…」,或按上面的新增。"}</div>`;
|
||
return;
|
||
}
|
||
el.innerHTML = m.items.map((x) => {
|
||
const meta = [x.pinned ? `<span class="pinned">${ic("pin", 12)} 釘選</span>` : "", KIND[x.kind] || "", memDay(x.created),
|
||
trash ? `${ago(x.deleted)}刪除${x.superseded_by ? "(被新的取代或壓縮)" : ""}` : m.bot === 0 ? "每個 Bot 都帶著" : (x.uses ? `帶過 ${x.uses} 次 · 上次 ${ago(x.last_used)}` : "還沒被帶入過")].filter(Boolean).join(" · ");
|
||
const acts = trash ? `<button data-restore="${x.id}">還原</button>` : `${m.bot === 0 ? "" : `<button data-pin="${x.id}">${x.pinned ? "取消釘選" : "釘選"}</button>`}<button data-edit="${x.id}">編輯</button><button data-forget="${x.id}">忘記</button>`;
|
||
return `<div class="mcard ${x.pinned ? "pin" : ""}"><div class="mt">${esc(x.text)}</div><div class="mm">${meta}</div><div class="ma">${acts}</div></div>`;
|
||
}).join("") + `<div class="memmore"><span>共 ${m.total} 條${m.q && v.ms != null ? `(搜尋 ${v.ms} 毫秒)` : ""}</span>${m.total > m.items.length ? `<button data-more="1">再顯示 ${Math.min(60, m.total - m.items.length)} 條</button>` : trash && m.total ? `<button data-empty="1">清空最近刪除</button>` : ""}</div>`;
|
||
const find = (id) => m.items.find((y) => y.id === +id);
|
||
el.querySelectorAll("[data-pin]").forEach((x) => x.onclick = () => { const y = find(x.dataset.pin); memWrite({op: "pin", id: y.id, on: !y.pinned}); });
|
||
el.querySelectorAll("[data-edit]").forEach((x) => x.onclick = async () => { const y = find(x.dataset.edit); const t = await ask("編輯記憶", y.text, "", true); if (t && t.trim() && t.trim() !== y.text) memWrite({op: "edit", id: y.id, text: t.trim()}); });
|
||
el.querySelectorAll("[data-forget]").forEach((x) => x.onclick = () => memWrite({op: "forget", id: +x.dataset.forget}));
|
||
el.querySelectorAll("[data-restore]").forEach((x) => x.onclick = () => memWrite({op: "restore", id: +x.dataset.restore}));
|
||
el.querySelectorAll("[data-more]").forEach((x) => x.onclick = () => { m.limit += 60; memList(); });
|
||
el.querySelectorAll("[data-empty]").forEach((x) => x.onclick = async () => { if (await confirmSheet("清空最近刪除?", "清掉以後就不能還原了。", "清空")) memWrite({op: "empty_trash"}); });
|
||
}
|
||
async function memWrite(body) {
|
||
const m = S.mem;
|
||
try { const v = await memApi(Object.assign({bot: m.bot}, body)); toast(v.text || "好了"); } catch (e) { toast(e.message); }
|
||
delete S.detail[m.owner];
|
||
memList(); memOverview();
|
||
}
|
||
|
||
// The model, as the desktop's composer picker: each ready provider's chat models, or any name.
|
||
function modelSheet(b) {
|
||
const items = [];
|
||
for (const p of S.models || []) {
|
||
items.push({group: p.label + (p.runs ? " · " + p.runs : "")});
|
||
for (const m of p.models || []) items.push({label: m, check: p.provider === b.provider && m === b.model, on: () => setBot(b, {provider: p.provider, model: m}, "之後用 " + m + " 回答")});
|
||
}
|
||
items.push({icon: "pen", label: "其他模型…", on: async () => { const m = await ask("模型名稱", b.model || "", "例如:grok-4.7"); if (m) setBot(b, {provider: b.provider, model: m}, "之後用 " + m + " 回答"); }});
|
||
sheet("模型", items);
|
||
}
|
||
async function setBot(b, body, ok) {
|
||
try { await api(base() + `api/bots/${b.id}/set`, {json: body}); toast(ok); delete S.detail[b.id]; } catch (e) { toast(e.message); }
|
||
}
|
||
function pickComputer(b, d) {
|
||
const list = (d.computers || []).map((c) => c.name);
|
||
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); }
|
||
}
|
||
// ---------- 例行任務 ----------
|
||
function routineSheet(b, r) {
|
||
if (!r) return;
|
||
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 () => { 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", "日"]];
|
||
function routineForm(b, r) {
|
||
const sc = (r && r.schedule) || {};
|
||
let freq = sc.once ? "once" : sc.frequency || "daily";
|
||
const dow = new Set(sc.daysOfWeek || sc.days_of_week || []);
|
||
if (freq === "weekly" && dow.size === 5 && !dow.has("SA") && !dow.has("SU")) freq = "workdays";
|
||
const el = sheet(r ? "編輯例行任務" : "新增例行任務", [], `<div class="form">
|
||
<label>名稱</label><input class="field" id="rt-title" value="${esc(r ? r.title : "")}" placeholder="例如:每天早上海巡">
|
||
<label>每次要做的事</label><textarea class="field" id="rt-prompt" placeholder="例如:海巡 Threads 上 AI 工具的熱門討論,整理 5 則">${esc(r ? r.prompt : "")}</textarea>
|
||
<label>多久一次</label><select class="field" id="rt-freq">${FREQ.map(([k, n]) => `<option value="${k}" ${k === freq ? "selected" : ""}>${n}</option>`).join("")}</select>
|
||
<div id="rt-days" class="row2" style="display:${freq === "weekly" ? "flex" : "none"}">${DAYS.map(([k, n]) => `<button class="btn sm ${dow.has(k) ? "main" : ""}" data-day="${k}">${n}</button>`).join("")}</div>
|
||
<div id="rt-mday" style="display:${freq === "monthly" ? "block" : "none"}"><label>每月幾號</label><input class="field" id="rt-md" type="number" min="1" max="31" value="${sc.monthDay || sc.month_day || 1}"></div>
|
||
<label>時間</label><input class="field" id="rt-time" type="time" value="${esc(sc.time || "09:00")}">
|
||
<div class="row2" style="justify-content:flex-end;margin-top:8px"><button class="btn" id="rt-no">取消</button><button class="btn main" id="rt-ok">${r ? "儲存" : "建立"}</button></div></div>`);
|
||
const days = new Set(dow);
|
||
el.querySelector("#rt-freq").onchange = (e) => { el.querySelector("#rt-days").style.display = e.target.value === "weekly" ? "flex" : "none"; el.querySelector("#rt-mday").style.display = e.target.value === "monthly" ? "block" : "none"; };
|
||
el.querySelectorAll("[data-day]").forEach((x) => x.onclick = () => { const k = x.dataset.day; days.has(k) ? days.delete(k) : days.add(k); x.classList.toggle("main"); });
|
||
el.querySelector("#rt-no").onclick = closeSheet;
|
||
el.querySelector("#rt-ok").onclick = async () => {
|
||
const title = el.querySelector("#rt-title").value.trim(), prompt = el.querySelector("#rt-prompt").value.trim();
|
||
const f = el.querySelector("#rt-freq").value, time = el.querySelector("#rt-time").value || "09:00";
|
||
if (!title || !prompt) { toast("名稱和要做的事都要填"); return; }
|
||
const schedule = {frequency: f === "workdays" ? "weekly" : f === "once" ? "daily" : f, time};
|
||
if (f === "workdays") schedule.daysOfWeek = ["MO", "TU", "WE", "TH", "FR"];
|
||
if (f === "weekly") { if (!days.size) { toast("選至少一天"); return; } schedule.daysOfWeek = DAYS.map((d) => d[0]).filter((k) => days.has(k)); }
|
||
if (f === "monthly") schedule.monthDay = Math.max(1, Math.min(31, +el.querySelector("#rt-md").value || 1));
|
||
if (f === "once") schedule.once = true;
|
||
closeSheet();
|
||
const ok = r ? await app("update_routine", {id: r.id, title, prompt, schedule}, b.id) : await app("create_routine", {title, prompt, schedule}, b.id);
|
||
if (ok) refreshAfter(b);
|
||
};
|
||
}
|
||
|
||
// ---------- 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); });
|
||
let d = S.detail[id] || await loadDetail(id) || {};
|
||
if (cur().v !== "botset") return;
|
||
const st = S.settings || {};
|
||
const CTX = [[32000, "32K"], [64000, "64K"], [128000, "128K"], [200000, "200K"], [400000, "400K"], [1000000, "1M"]];
|
||
// 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("基本", sitem({k: "名稱", r: b.name, tap: 1, data: 'data-e="name"'}) + sitem({k: "描述", v: d.description || "還沒有寫", tap: 1, data: 'data-e="desc"'}) + sitem({k: "指示", v: d.instructions ? d.instructions.slice(0, 160) + (d.instructions.length > 160 ? "…" : "") : "還沒有寫", tap: 1, data: 'data-e="instr"'}));
|
||
if (isOwner()) {
|
||
h += group("個人檔案", sitem({k: "擅長", v: d.strengths || "還沒有寫(同事會看到,知道什麼事找它)", tap: 1, data: 'data-e="strengths"'}) + sitem({k: "不找它做的事", v: d.not_for || "還沒有寫", tap: 1, data: 'data-e="not_for"'}));
|
||
const ticks = (title, key, list, note) => (list || []).length ? group(title, list.map((x) => sitem({k: x.name, v: x.note || "", sw: !!x.on, swdata: `data-tick="${key}" data-key="${esc(x.key)}"`, disabled: !!x.fixed})).join("") + (note ? `<div class="note" style="padding:8px 16px">${note}</div>` : "")) : "";
|
||
h += ticks("能力", "abilities", d.abilities, "沒勾的工具不會給它,也不佔它每一輪的字數。");
|
||
h += ticks("會的技能", "skills", d.skills, "") .replace(/^(<div class="gt">會的技能)/, `$1<button data-allsk="1" style="margin-left:auto">${(d.skills || []).every((x) => x.on) ? "全不選" : "全選"}</button>`);
|
||
h += ticks("可以用的電腦", "may_use", (d.may_use || []).length > 1 ? d.may_use : [], "它自己的電腦一定可以用。");
|
||
}
|
||
h += `<div class="gt">頭像</div><div class="group"><div class="shapes">${(st.shapes || []).map((s) => `<button data-shape="${s}" class="${s === d.shape ? "on" : ""}">${avatarSvg(s, b.color)}</button>`).join("")}</div><div class="colors">${(st.colors || []).map((c) => `<button data-color="${c.key}" title="${esc(c.name)}" class="${c.key === d.color ? "on" : ""}" style="background:${c.hex}"></button>`).join("")}${isOwner() ? `<button data-color-own="1" title="自訂顏色" class="${/^#/.test(d.color || "") ? "on" : ""}" style="background:${/^#/.test(d.color || "") ? d.color : "conic-gradient(#e5484d,#f5a623,#46a758,#0090ff,#8e4ec6,#e5484d)"}"></button>` : ""}</div></div>`;
|
||
// (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) => `<div class="item">${ic("shield", 17)}<div class="mid"><div class="v" style="color:var(--text);font-size:var(--fs-ui)">${esc(r)}</div></div><button class="btn sm no" data-rule="${esc(r)}">移除</button></div>`).join("") || `<div class="note" style="padding:12px 16px">還沒有。在核准時選「一律允許」就會記在這裡。</div>`);
|
||
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("") + `<div class="note" style="padding:8px 16px">示範要在那台電腦上錄;Bot 在對話裡會照著做。</div>`);
|
||
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 + `<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(); });
|
||
// 自訂顏色: 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
|
||
// 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; }
|
||
if (!await act("bot", {bot: id, key: k, value: x.checked}, false)) x.checked = !x.checked; else refresh();
|
||
});
|
||
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(); }
|
||
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});
|
||
else if (k === "clear") { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) act("clear", {bot: id}); }
|
||
else if (k === "delete") deleteBot(b);
|
||
});
|
||
}
|
||
</script>
|
||
<script>
|
||
"use strict";
|
||
// ---------- 設定 and the other lists ----------
|
||
async function loadSettings() {
|
||
if (!owner()) return null;
|
||
S.settingsOld = false;
|
||
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", "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 還沒有規則.) */
|
||
async function settingsChanged() {
|
||
S.settingsOld = true;
|
||
const t = cur();
|
||
if (t.v !== "list" || !SETTINGS_PAGES.includes(t.arg.kind)) return;
|
||
if (S.settingsLoading) { S.settingsAgain = true; return; }
|
||
S.settingsLoading = true;
|
||
try { do { S.settingsAgain = false; await loadSettings(); } while (S.settingsAgain); } finally { S.settingsLoading = false; }
|
||
if (cur().v === "list" && cur().arg.kind === t.arg.kind) drawSettings(t.arg.kind, true);
|
||
}
|
||
let listTimer = null;
|
||
function stopListTimer() { clearInterval(listTimer); listTimer = null; }
|
||
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] || "";
|
||
$("list-act").innerHTML = "";
|
||
const el = $("list");
|
||
stopListTimer();
|
||
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 = `<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);
|
||
}
|
||
}
|
||
// ---------- 所有檔案 ----------
|
||
// 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 = `<div class="empty">載入中…</div>`;
|
||
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 = `<div class="lib-top"><input class="field" id="lib-q" placeholder="搜尋檔案名稱" value="${esc(LIB.q)}" enterkeyhint="search"><div class="tabs lib-tabs">${LIB_KINDS.filter(([k]) => k === "all" || count(k)).map(([k, l]) => `<button data-lk="${k}" class="${LIB.kind === k ? "on" : ""}">${l} ${count(k)}</button>`).join("")}</div></div>`;
|
||
if (!all.length) h += `<div class="empty">還沒有檔案。<br>你傳給 Bot、Bot 交給你的檔案都會收在這裡。</div>`;
|
||
else if (!shown.length) h += `<div class="empty">沒有相符的檔案</div>`;
|
||
else {
|
||
const pics = shown.filter((f) => f.image && f.there), rest = shown.filter((f) => !(f.image && f.there));
|
||
if (pics.length) h += `<div class="lib-grid">${pics.slice(0, 120).map((f) => `<button class="lib-pic" data-lf="${esc(f.path)}" data-ln="${esc(f.name)}" title="${esc(f.name)}"><img alt="" loading="lazy" ${THUMBS.has(f.path) ? `src="${THUMBS.get(f.path)}"` : `data-thumb="${esc(f.path)}"`}></button>`).join("")}</div>`;
|
||
if (rest.length) h += group("", rest.slice(0, 300).map((f) => { const b = bot(f.bot) || {}; return `<button class="item ${f.there ? "" : "gone"}" ${f.there ? `data-lf="${esc(f.path)}" data-ln="${esc(f.name)}"` : "disabled"}>${ic(LIB_ICON[f.kind] || "file", 19)}<div class="mid"><div class="k">${esc(f.name)}</div><div class="v">${f.there ? "" : "不見了 · "}${esc([b.name || "", ago(f.at), fsize(f.bytes)].filter(Boolean).join(" · "))}</div></div></button>`; }).join(""));
|
||
}
|
||
h += `<div style="height:calc(var(--safe-b) + 24px)"></div>`;
|
||
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 = `<div class="empty">載入中…</div>`;
|
||
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 `<button class="item sch ${cls}" data-sch="${i.kind}:${i.id}:${i.bot}"><span class="sch-t">${showDay ? `<span class="av sm">${b.shape ? avatarSvg(b.shape, b.color) : ic("workflow", 14)}</span>` : esc(i.clock)}</span><div class="mid"><div class="k">${i.kind === "workflow" ? ic("workflow", 13) + " " : ""}${esc(i.title)}</div><div class="v">${esc((showDay ? "" : (b.name ? b.name + " · " : "")) + i.when)}</div></div><div class="r ${cls}">${showDay ? esc(right) : ic(icon, 16) + (word ? " " + esc(word) : "")}</div></button>`;
|
||
};
|
||
let h = group("即將執行", (v.coming || []).map((i) => row(i, true)).join("") || `<div class="note" style="padding:12px 16px">接下來兩週沒有排定的事</div>`);
|
||
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("") || `<div class="note" style="padding:12px 16px">這一天沒有排定的事</div>`);
|
||
}
|
||
h += `<div class="note">只放排程或事件自己跑的;你按的「立即執行」在各自的執行紀錄裡。新增:在聊天裡跟 Bot 說「每天早上 9 點幫我…」。</div><div style="height:calc(var(--safe-b) + 24px)"></div>`;
|
||
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 = `<div class="empty">載入中…</div>`;
|
||
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 `<div class="wf-ask">${ic("hand", 15)}<span>等你確認:${esc(r.asks || "要繼續嗎?")}</span><button class="btn main sm" data-wfdo="go" data-wf="${w.id}">繼續</button><button class="btn sm" data-wfdo="halt" data-wf="${w.id}">停止</button></div>`;
|
||
}
|
||
function drawWorkflows(el, wf) {
|
||
const list = S.wfs || [];
|
||
if (wf) {
|
||
const w = list.find((x) => x.id === wf);
|
||
if (!w) { el.innerHTML = `<div class="empty">找不到這個工作流(可能刪掉了)</div>`; 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 = `<div class="wf-head"><div class="v">${esc(w.when)}${w.next ? " · 下次 " + esc(w.next) : ""}</div>${isOwner() ? (w.live ? `<button class="btn" data-wfdo="stop" data-wf="${w.id}">${ic("stop", 15)} 停止</button>` : `<button class="btn main" data-wfdo="run" data-wf="${w.id}">${ic("play", 15)} 執行工作流</button>`) : ""}</div>`;
|
||
h += wfWaiting(w);
|
||
h += `<div class="gt">步驟${r ? `(${w.live ? "這一次" : "最近一次"}:${esc(r.words)})` : ""}</div><div class="wf-steps">${w.steps.map((st, i) => {
|
||
const s = stepOf(st.id), [cls, word] = stepLook(s, r, st.id);
|
||
return `<div class="wf-step ${cls}" ${s && s.output ? `data-wfout="${st.id}"` : ""}><span class="wf-i">${ic(WF_ICON[st.kind] || "circle-dot", 15)}</span><div class="mid"><div class="k">${esc(st.kind)}${st.bot ? ` · ${esc(st.bot)}` : ""}${word ? ` <span class="pill ${cls}">${esc(word)}</span>` : ""}</div>${st.words ? `<div class="v">${esc(st.words)}</div>` : ""}${s && s.output ? `<div class="v out">${esc(s.output.split("\n").slice(0, 3).join("\n"))}</div>` : ""}</div></div>`;
|
||
}).join("")}</div>`;
|
||
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("") || `<div class="note" style="padding:12px 16px">還沒有跑過</div>`);
|
||
h += `<div class="note">畫布在電腦上改;或在聊天裡請 Bot 改這個工作流。</div><div style="height:calc(var(--safe-b) + 24px)"></div>`;
|
||
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 ? `<div class="group">${list.map((w) => {
|
||
const st = w.live ? WF_STATE[w.live.state] || ["", ""] : null;
|
||
return `<div class="wf-card" data-wfopen="${w.id}"><div class="wf-row"><span class="wf-i big">${ic("workflow", 18)}</span><div class="mid"><div class="k">${esc(w.name)}${st ? ` <span class="pill ${st[0]}">${st[1]}</span>` : ""}</div><div class="v" style="white-space:pre-line">${esc(wfLine(w))}</div></div>${isOwner() ? (w.live ? `<button class="ib" data-wfdo="stop" data-wf="${w.id}" title="停止">${ic("stop", 18)}</button>` : `<button class="ib" data-wfdo="run" data-wf="${w.id}" title="執行">${ic("play", 18)}</button>`) : ""}</div>${wfWaiting(w)}</div>`;
|
||
}).join("")}</div>` : `<div class="empty">還沒有工作流。<br>在聊天裡請 Bot「做一個每天早上整理新聞的工作流」,或在電腦上畫。</div>`;
|
||
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 = `<div class="empty">正在算過去一年的用量…</div>`;
|
||
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 = `<div class="empty">讀不到用量:${esc(e.message)}</div>`; 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 = `<div class="me-figs">${figs.map(([v, l]) => `<div><b>${esc(v)}</b><span>${esc(l)}</span></div>`).join("")}</div>`;
|
||
// 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 `<circle cx="${Math.floor(k / 7) * cell + cell / 2}" cy="${(k % 7) * cell + cell / 2}" r="${cell * 0.38}" fill="${lv[Math.min(4, x[3] || 0)]}"><title>${esc(shortDate(x[0]))}:${wan(x[1])} token、${x[2]} 則訊息</title></circle>`; }).join("");
|
||
const busy = d.busiest && d.busiest.date ? `最活躍:${shortDate(d.busiest.date)}・${wan(d.busiest.tokens)} token` : "";
|
||
h += `<div class="gt">活動</div><div class="me-card"><svg class="me-heat" viewBox="0 0 ${W} ${H}" preserveAspectRatio="xMinYMid meet">${dots}</svg><div class="me-note">過去一年有 ${d.active_days || 0} 個活躍日${busy ? "・" + esc(busy) : ""}</div></div>`;
|
||
// 用量: 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) => `<div class="me-seg">${list.map(([v, l]) => `<button data-${key}="${v}" class="${v === cur ? "on" : ""}">${l}</button>`).join("")}</div>`;
|
||
h += `<div class="gt">用量</div><div class="me-card">${seg([["7", "7 天"], ["30", "30 天"], ["90", "90 天"], ["365", "一年"]], ME.span, "mespan")}`;
|
||
h += `<div class="me-hero"><b>${wan(u.tokens)}</b> token</div><div class="me-note" title="花費是模型服務自己回報的;沒回報的寫「未定價」,不是 0 元。">${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)}</div>`;
|
||
const daily = u.daily || [], max = Math.max(1, ...daily.map((x) => x[1] || 0)), bw = 100 / Math.max(1, daily.length);
|
||
h += `<svg class="me-bars" viewBox="0 0 100 40" preserveAspectRatio="none">${daily.map((x, i) => x[1] ? `<rect x="${i * bw + bw * 0.18}" y="${40 - Math.max(1.2, x[1] / max * 38)}" width="${bw * 0.64}" height="${Math.max(1.2, x[1] / max * 38)}" rx="0.6" fill="var(--accent)"><title>${esc(shortDate(x[0]))}:${wan(x[1])} token</title></rect>` : "").join("")}</svg>`;
|
||
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 += `<div class="me-note">這段時間沒有用量紀錄</div>`;
|
||
else {
|
||
if (ME.by === "model") h += `<div class="me-split">${rows.map((r, i) => `<i style="width:${(r.tokens || 0) / total * 100}%;background:${cat(i)}"></i>`).join("")}</div>`;
|
||
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" ? `<span class="me-av">${b ? avatarSvg(b.shape, b.color) : ""}</span>` : `<span class="me-dot" style="background:${cat(i)}"></span>`;
|
||
const bar = ME.by === "bot" ? `<span class="me-bar"><i style="width:${(r.tokens || 0) / top * 100}%"></i></span>` : "";
|
||
return `<div class="me-row">${mark}<span class="me-name">${esc(r.name)}</span>${bar}<span class="me-n">${wan(r.tokens)}・${Math.round((r.tokens || 0) / total * 100)}%</span></div>`;
|
||
}).join("");
|
||
}
|
||
h += `</div><div style="height:calc(var(--safe-b) + 24px)"></div>`;
|
||
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
|
||
// with the state (kept on this phone with the rest: the list draws from it offline too). Nothing
|
||
// in the chat: a quiet 任務 among the home's shortcuts, with how many need a look.
|
||
const TASK_CLS = {running: "go", following: "go", verifying: "go", waiting: "wait", failed: "bad", delivered: "good", confirmed: "good", verified: "good"};
|
||
const TASK_ACTIVE = ["running", "waiting", "following", "verifying"];
|
||
function taskAttention() {
|
||
const day = Date.now() - 864e5;
|
||
return (S.tasks || []).filter((t) => TASK_ACTIVE.includes(t.status) || (t.status === "failed" && Math.max(t.finished || 0, t.heartbeat || 0) > day)).length;
|
||
}
|
||
function since(ms) { const a = ago(ms); return /(分鐘|小時|天)$/.test(a) ? a + "前" : a; }
|
||
function taskFile(a) {
|
||
const d = {in_chat: "chat", shown: "shown", opened: "opened", failed: "failed"}[a.delivery] || "chat";
|
||
const mark = d === "failed" ? "!" : ic("check", 12) + (d !== "chat" ? ic("check", 12) : "");
|
||
return `${esc(a.name)}<span class="dlv ${d}" title="${esc(d === "failed" ? (a.device || "") + "顯示失敗:" + (a.why || "") : DLV_TITLE[d] || "")}">${mark}</span>`;
|
||
}
|
||
function taskCard(t) {
|
||
const b = bot(t.bot);
|
||
const facts = ["在 " + (t.computer || "—"), t.steps ? `${t.steps} 步${t.failed ? `(${t.failed} 步失敗)` : ""}` : "", "最後動靜 " + (since(Math.max(t.heartbeat || 0, t.at || 0)) || "剛剛")].filter(Boolean).join(" · ");
|
||
const active = TASK_ACTIVE.includes(t.status);
|
||
const doing = t.doing ? `<div class="ln">${active ? "現在" : "最後一步"}:${esc(t.doing)}</div>` : "";
|
||
const why = t.why && t.why !== t.doing ? `<div class="ln why ${t.status === "failed" ? "bad" : ""}">${esc(t.why)}</div>` : "";
|
||
const files = (t.artifacts || []).map(taskFile).join("、");
|
||
const foot = `${files ? "產物:" + files + " · " : ""}證據 <b class="lv">${esc(t.level || "")}</b>${t.kept ? " · 照紀錄(聊天裡已經沒有)" : ""}`;
|
||
return `<button class="tk" data-task="${t.bot}:${t.at}" data-status="${esc(t.status)}"><div class="av sm">${b ? avatarSvg(b.shape, b.color) : ""}</div><div class="mid"><div class="hd"><span class="who">${esc(b ? b.name : "已刪除的 Bot")} · ${esc(t.from || "")}${/[A-Za-z]$/.test(t.from || "") ? " " : ""}開的</span><span class="st ${TASK_CLS[t.status] || ""}">${esc(t.label || t.status)}</span></div><div class="tx">${esc(t.text || "")}</div><div class="ln">${esc(facts)}</div>${doing}${why}<div class="ln">${foot}</div></div></button>`;
|
||
}
|
||
function listTasks(el) {
|
||
const list = S.tasks || [], n = taskAttention();
|
||
const head = S.stale ? "離線中:顯示的是上次存在這支手機上的任務" : n ? `${n} 件進行中、等你或今天失敗` : "";
|
||
el.innerHTML = list.length
|
||
? `${head ? `<div class="gt">${esc(head)}</div>` : ""}<div class="group" id="tasks">${list.map(taskCard).join("")}</div><div class="note">狀態由 AnyBot 從步驟、回合結束和交付回報算出,不是 Bot 說的。證據 B:你親眼看到(按 👍、點開檔案);A:系統自己看到;C:別的 Bot 轉述;未驗:都沒有。</div>`
|
||
: `<div class="empty">還沒有任務。<br>交代 Bot 做一件事,它就會出現在這裡。</div>`;
|
||
el.querySelectorAll("[data-task]").forEach((x) => x.onclick = () => { const [b, at] = x.dataset.task.split(":").map(Number); if (bot(b)) go("chat", {bot: b, at}); else toast("這個 Bot 已經刪除了"); });
|
||
}
|
||
// 任務 → 那則訊息: 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;
|
||
// (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;
|
||
el.scrollIntoView({block: "center"}); atEnd = false;
|
||
el.classList.add("lit"); setTimeout(() => el.classList.remove("lit"), 1800);
|
||
return true;
|
||
}
|
||
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) {
|
||
const rs = (S.detail[b.id] || {}).routines || [];
|
||
if (!rs.length) continue;
|
||
h += `<div class="gt"><div class="av sm" style="width:20px;height:20px">${avatarSvg(b.shape, b.color)}</div>${esc(b.name)}</div><div class="group">${rs.map((r) => item({icon: r.paused ? "pause" : "alarm-clock", k: r.title, v: (r.trigger ? "事件觸發:" + r.trigger : r.repeat) + " · " + r.when, tap: 1, data: `data-rt="${b.id}:${r.id}"`})).join("")}</div>`;
|
||
}
|
||
el.innerHTML = (h || `<div class="empty">還沒有例行任務。<br>例行任務是 Bot 依排程重複執行的任務。</div>`) + (isOwner() ? `<div class="form"><button class="btn main" id="rt-new">${ic("plus", 15)} 新增例行任務</button></div>` : "");
|
||
el.querySelectorAll("[data-rt]").forEach((x) => x.onclick = () => { const [bid, rid] = x.dataset.rt.split(":").map(Number); const b = bot(bid); routineSheet(b, ((S.detail[bid] || {}).routines || []).find((r) => r.id === rid)); });
|
||
if ($("rt-new")) $("rt-new").onclick = () => {
|
||
const pick = (b) => routineForm(b, null);
|
||
if (S.bots.length === 1) pick(S.bots[0]);
|
||
else sheet("交給哪個 Bot?", S.bots.filter((b) => !b.members).map((b) => ({label: b.name, on: () => setTimeout(() => pick(b), 60)})));
|
||
};
|
||
}
|
||
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>`;
|
||
}
|
||
function rulesGroup(title, list, kind) {
|
||
return group(title, (list || []).map((r) => `<div class="item">${ic(kind === "ask" ? "hand" : "shield", 17)}<div class="mid"><div class="v" style="color:var(--text);font-size:var(--fs-ui)">${esc(r)}</div></div>${isOwner() ? `<button class="btn sm no" data-rmrule="${kind}" data-r="${esc(r)}">移除</button>` : ""}</div>`).join("") || `<div class="note" style="padding:12px 16px">還沒有規則</div>`, isOwner() ? `<button data-addrule="${kind}">${ic("plus", 14)} 新增</button>` : "");
|
||
}
|
||
function drawSettings(kind, quiet) {
|
||
const st = S.settings || {};
|
||
const el = $("list");
|
||
const sc = el.scrollTop;
|
||
let h = "";
|
||
if (kind === "settings") {
|
||
// 搜尋設定 (the computer's index): what matches stands where the pages were.
|
||
h += `<div style="padding:var(--sp-3) var(--sp-4) 0"><input class="field" id="set-q" placeholder="搜尋設定…" value="${esc(S.setQ || "")}" enterkeyhint="search"></div>`;
|
||
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("") || `<div class="note" style="padding:12px 16px">沒有符合的設定</div>`);
|
||
}
|
||
if (kind === "settings" && !(S.setQ && S.setHits)) {
|
||
h += group("", [
|
||
["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]) => 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 主題 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 += `<div class="gt">風格</div><div class="tpl-grid">${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 `<button class="tpl ${on ? "on" : ""}" data-s="style" data-style="${t.id}" title="${esc(t.about)}"><span class="pic" style="background-color:${c.pane};border-color:${c.line};${bd}"><i class="sd" style="background:${c.side}"><b style="background:${c.active}"></b><b style="background:${c.hover}"></b></i><i class="ln" style="background:${c.text3}"></i><i class="ln s" style="background:${c.text3}"></i><i class="bb" style="background:${c.bubble}"></i><i class="dt" style="background:${c.accent}"></i></span><span class="nm">${esc(t.name)}</span></button>`;
|
||
}).join("")}</div>${st.style ? "" : `<div class="note" style="padding-top:4px">現在是自訂的顏色(電腦上的強調色);點一個風格整套換,電腦和手機一起。</div>`}`;
|
||
}
|
||
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) => `<div class="item">${ic("folder", 19)}<div class="mid"><div class="k" style="font-size:var(--fs-small);word-break:break-all">${esc(f)}</div></div><button class="btn sm no" data-docrm="${esc(f)}">移除</button></div>`).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) => 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 += `<div class="note">金鑰只存在這台 AnyBot,手機寫得進去、看不到。</div>`;
|
||
}
|
||
if (kind === "perms") {
|
||
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) => sitem({icon: "hand", k: r})).join(""));
|
||
h += `<div class="note">用一般的話寫,例如「付款前先問我」。兩邊都符合時先問。${st.direct_mode ? "直接操作開著:「一律詢問」照樣檢查,「直接允許」用不到。" : st.auto_review === false ? "自動審核關著時不會用這些規則。" : ""}</div>`;
|
||
}
|
||
if (kind === "integrations") {
|
||
const dot = (ok, on) => `<span style="width:8px;height:8px;border-radius:50%;flex:none;background:${!on ? "var(--text4)" : ok ? "var(--ok)" : "var(--warn)"}"></span>`;
|
||
h += group("訊息管道", (st.channels || []).map((c) => `<div class="item">${dot(c.ok, c.enabled)}<div class="mid"><div class="k">${esc(c.kind)} · ${esc(c.name)}</div><div class="v">由「${esc(c.bot)}」回覆${c.note ? " · " + esc(c.note) : ""}</div></div>${isOwner() ? `<label class="sw"><input type="checkbox" ${c.enabled ? "checked" : ""} data-ch="${c.id}"><i></i></label><button class="ib" data-chrm="${c.id}" title="移除">${ic("trash", 16)}</button>` : ""}</div>`).join("") || `<div class="note" style="padding:12px 16px">還沒有。Telegram、Slack、Discord… 要在電腦上的 AnyBot 新增(需要輸入 Token)。</div>`);
|
||
h += group("連接器(MCP)", ((st.mcp || []).map((m) => `<div class="item">${dot(m.tools != null, m.enabled)}<div class="mid"><div class="k">${esc(m.name)}</div><div class="v">${!m.enabled ? "已關閉" : m.tools != null ? `已連上,${m.tools} 個工具` : m.error ? esc(m.error) : "連線中…"}</div></div>${isOwner() ? `${m.enabled ? `<button class="ib" data-mcpre="${esc(m.name)}" title="重新連線">${ic("refresh", 16)}</button>` : ""}<label class="sw"><input type="checkbox" ${m.enabled ? "checked" : ""} data-mcp="${esc(m.name)}"><i></i></label><button class="ib" data-mcprm="${esc(m.name)}" title="移除">${ic("trash", 16)}</button>` : ""}</div>`).join("") || `<div class="note" style="padding:12px 16px">還沒有連接器</div>`) + (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 `<div class="item">${ic("sparkles", 19)}<div class="mid" data-skill="${i}" style="cursor:pointer"><div class="k">${esc(k.name)}${tags ? ` <span class="pill" style="margin-left:4px">${esc(tags)}</span>` : ""}</div><div class="v">${esc(k.description)}</div></div>${isOwner() ? `<label class="sw"><input type="checkbox" ${k.enabled !== false ? "checked" : ""} data-sksw="${esc(k.name)}"><i></i></label>` : ""}</div>`;
|
||
}).join("");
|
||
const skActions = isOwner()
|
||
? 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 || `<div class="note" style="padding:12px 16px">還沒有技能。可從下方「技能市集」一鍵加入,或在聊天裡請 Bot 幫你建立。</div>`) + 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 += `<div class="note">每台電腦和手機的錄音、朗讀都交給大腦,用這裡選的服務;金鑰只存在大腦,手機看不到。沒選服務時,麥克風和朗讀不會出現。</div>`;
|
||
}
|
||
if (kind === "vault") h += `<div class="empty">${ic("lock", 28)}<br><br>保險庫裡的密碼、卡號和聯絡資訊,只在電腦上的 AnyBot 管理。<br>Bot 用到時由 AnyBot 直接填進網頁,不會交給模型,也不會經過手機。</div>`;
|
||
if (kind === "account") {
|
||
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("") || `<div class="note" style="padding:12px 16px">沒有</div>`);
|
||
const acts = [];
|
||
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("", 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 += `<div class="note">Bot 的電腦的更新在「電腦」裡。</div>`;
|
||
h += group("這支手機", sitem({icon: "smartphone", k: "畫面", v: fitWords(), tap: 1, data: 'data-ruler="1"'}));
|
||
h += `<div class="note">畫面看起來被切到、上面糊糊的、下面空一塊時,按「畫面」打開量尺截圖給我們。</div>`;
|
||
}
|
||
el.innerHTML = h + `<div style="height:calc(var(--safe-b) + 24px)"></div>`;
|
||
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);
|
||
}
|
||
function computersHtml(st) {
|
||
const box = st.box || {}, f = box.facts || {};
|
||
const main = S.bots.find((b) => b.primary) || S.bots[0] || {};
|
||
const comps = main.computers || [];
|
||
const own = comps.find((c) => c.kind === "own");
|
||
const running = box.available && /運作中|可以用|執行中|已開/.test(box.state || "") || (box.available && !/睡|暫停|關|沒有|失敗|建立中|喚醒中|更新/.test(box.state || ""));
|
||
let h = `<div class="gt">${esc(own ? own.name : "Bot 的電腦")} <span class="pill ${running ? "ok" : ""}" style="margin-left:4px">${esc(box.state || "")}</span></div><div class="group">`;
|
||
if (box.available) h += `<div class="thumbbox" style="margin:0;border-radius:0">${running ? `<img id="box-thumb" alt="">` : esc(box.state || "")}</div>`;
|
||
h += `<div class="btnrow"><button class="btn main" data-bx="open">${ic("monitor", 15)} 開啟電腦</button><button class="btn" data-bx="take">${ic("hand", 15)} 接管</button><button class="btn" data-bx="wake">${ic("power", 15)} 喚醒</button>${isOwner() ? `<button class="btn" data-bx="snapshot">${ic("hard-drive", 15)} 儲存快照</button>` : ""}<button class="btn" data-bx="disk">檢查用量</button></div>`;
|
||
if (box.note) h += `<div class="note" style="padding:0 16px 12px">${esc(box.note)}</div>`;
|
||
h += `</div>`;
|
||
if (box.disk) h += group("用量", `<div class="log">${esc(box.disk)}</div>`);
|
||
const rt = box.runtime === "runsc" ? "強隔離(gVisor)" : "標準";
|
||
const running_rt = f.running ? (f.running === "runsc" ? "強隔離" : "標準") : "";
|
||
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("", 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 += `<div class="gt">紀錄</div><div class="group"><div class="log">${esc(box.log.slice(-25).join("\n"))}</div></div>`;
|
||
const others = comps.filter((c) => c.kind !== "own");
|
||
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() {
|
||
let me;
|
||
try { me = await api("relay/me"); } catch (e) { toast(e.message); return; }
|
||
const ss = me.sessions || [];
|
||
const html = ss.map((d) => item({icon: "smartphone", k: d.device || "裝置", v: "上次使用 " + ago(d.last * 1000), r: d.id})).join("") || `<div class="note" style="padding:12px 16px">只有這支手機</div>`;
|
||
sheet("登入的裝置 (" + ss.length + ")", [
|
||
{icon: "log-out", label: "全部登出", danger: true, on: async () => {
|
||
if (!await confirmSheet("全部登出?", "包含這支手機。其他裝置要重新用密碼(和驗證碼)登入。", "全部登出", true, "log-out")) return;
|
||
await api("relay/sessions/logout", {json: {}}); signOut();
|
||
}},
|
||
], html + `<div class="note">踢掉某一台:按它的「裝置代號」。不知道是哪台就全部登出。</div>`);
|
||
// Tapping a device's id (the .r span) kicks just it.
|
||
sheet.devices = ss;
|
||
$("sheet-in").querySelectorAll(".item .r").forEach((el, i) => { el.style.textDecoration = "underline"; el.onclick = async (e) => {
|
||
e.stopPropagation();
|
||
const d = (sheet.devices || [])[i]; if (!d) return;
|
||
if (!await confirmSheet(`登出「${d.device || "裝置"}」?`, "那台手機要重新登入才能用。", "登出這台", true, "log-out")) return;
|
||
const v = await api("relay/sessions/drop", {json: {id: d.id}});
|
||
if (v.was_self) { signOut(); return; }
|
||
toast("已登出"); devicesSheet();
|
||
}; });
|
||
}
|
||
async function twoFaSheet() {
|
||
let me;
|
||
try { me = await api("relay/me"); } catch (e) { toast(e.message); return; }
|
||
if (!me.two_factor) {
|
||
if (!await confirmSheet("打開兩步驗證?", "之後登入要密碼,加驗證器 App(Google Authenticator、Authy、Apple 密碼…)的六位碼。會給你 8 個恢復碼——收好,遺失驗證器時用。", "開始設定", false)) return;
|
||
let v;
|
||
try { v = await api("relay/2fa/enroll", {json: {}}); } catch (e) { toast(e.message); return; }
|
||
const el = sheet("在驗證器 App 加入這組金鑰", [],
|
||
`<div class="form"><div class="note">金鑰(在 App 選「輸入設定金鑰」貼上)</div><input class="field" readonly value="${esc(v.secret)}">
|
||
<div class="note">恢復碼——只顯示這一次,先抄下來</div><textarea class="field" readonly rows="3" style="font-family:var(--mono)">${v.recovery_codes.join(" ")}</textarea>
|
||
<div class="note">App 加好金鑰後,輸入它現在顯示的六位碼</div><input class="field" id="2fa-in" inputmode="numeric" placeholder="123456" autocomplete="one-time-code">
|
||
<button class="btn main" id="2fa-ok">開啟兩步驗證</button></div>`);
|
||
el.querySelector("#2fa-ok").onclick = async () => {
|
||
const b = el.querySelector("#2fa-ok"); b.disabled = true;
|
||
try { await api("relay/2fa/verify", {json: {code: el.querySelector("#2fa-in").value.trim()}}); closeSheet(); toast("兩步驗證已開啟,恢復碼收好"); }
|
||
catch (e) { toast(e.message); b.disabled = false; }
|
||
};
|
||
return;
|
||
}
|
||
const code = await ask("關閉兩步驗證", "", "先輸入一個六位碼證明是你");
|
||
if (!code) return;
|
||
try { await api("relay/2fa/disable", {json: {code}}); toast("兩步驗證已關閉"); } catch (e) { toast(e.message); }
|
||
}
|
||
|
||
function wireSettings(kind, st) {
|
||
const el = $("list");
|
||
const on = (sel, ev, fn) => el.querySelectorAll(sel).forEach((x) => x[ev] = () => fn(x));
|
||
const again = async () => { await loadSettings(); if (cur().v === "list") drawSettings(cur().arg.kind, true); };
|
||
on("[data-go]", "onclick", (x) => go("list", {kind: x.dataset.go}));
|
||
on("[data-sset]", "onchange", async (x) => {
|
||
const k = x.dataset.sset;
|
||
if (k === "direct_mode" && x.checked && !await confirmSheet("打開「直接操作」?", "Bot 會直接做事,只有危險操作和你的「一律詢問」規則會停下來問你。", "打開", false)) { x.checked = false; return; }
|
||
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(); });
|
||
on("[data-mcp]", "onchange", async (x) => { if (!await act("mcp", {name: x.dataset.mcp, enabled: x.checked})) x.checked = !x.checked; else again(); });
|
||
on("[data-mcpre]", "onclick", async (x) => { if (await act("mcp", {name: x.dataset.mcpre, reconnect: true}, "重新連線中…")) { again(); setTimeout(again, 4000); } });
|
||
on("[data-mcprm]", "onclick", async (x) => { if (await confirmSheet("移除這個連接器?", "", "移除") && await act("mcp", {name: x.dataset.mcprm, remove: true}, "已移除")) again(); });
|
||
on("[data-prov]", "onclick", (x) => {
|
||
const p = st.providers[+x.dataset.prov];
|
||
sheet(p.label, [
|
||
...(p.needs_key || p.key === "Custom" ? [{icon: "key", label: p.ready && p.needs_key ? "換一把 API 金鑰…" : "設定 API 金鑰…", on: async () => { const k = await ask(p.label + " 的 API 金鑰", "", "貼上金鑰(存在這台 AnyBot,手機看不到)"); if (k && await act("provider", {provider: p.key, key: k}, "已設定金鑰")) again(); }}] : []),
|
||
// ChatGPT 方案: an account on the brain, not a key. The sign-in page opens here; the page it
|
||
// comes back to (127.0.0.1 on the brain) won't load on the phone, so its address is pasted back.
|
||
...(p.account ? [{icon: "key", label: p.ready ? "重新用 ChatGPT 登入…" : "使用 ChatGPT 繼續…", on: async () => {
|
||
// (Opened now, while the tap still counts: a window opened after waiting is blocked.)
|
||
const w = window.open("", "_blank");
|
||
if (!w) { toast("請允許這個網頁開新視窗,再按一次"); return; }
|
||
const v = await act("chatgpt", {action: "login"}, false);
|
||
if (!v || !v.url || !String(v.url).startsWith("https://auth.openai.com/")) { w.close(); if (v && v.text) toast(v.text); return; }
|
||
w.location = v.url;
|
||
const cb = await ask("登入並同意後,那一頁打不開的話,把它的網址整個貼在這裡", "", "http://127.0.0.1:1455/auth/callback?code=…");
|
||
if (!cb) return;
|
||
const r = await act("chatgpt", {action: "login", callback: cb}, false);
|
||
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(); }}] : []),
|
||
]);
|
||
});
|
||
on("[data-dev]", "onclick", async (x) => {
|
||
const d = st.devices[+x.dataset.dev];
|
||
if (await confirmSheet(`登出「${d.name}」?`, "那支手機要重新輸入密碼才能再連。如果是你現在用的這支,也會被登出。", "登出", true, "log-out") && await act("device_remove", {name: d.name, created: d.created}, "已登出那支手機")) again();
|
||
});
|
||
on("[data-sksw]", "onchange", async (x) => { if (!await act("skill", {name: x.dataset.sksw, enabled: x.checked})) x.checked = !x.checked; else again(); });
|
||
// 公用市集: the brain searches the official MCP Registry; a pick asks for what it needs (the
|
||
// key, an address part) and the brain adds it.
|
||
on("[data-mcpmarket]", "onclick", async () => {
|
||
const q = await ask("搜尋公用市集", "", "例如 notion、search、docs");
|
||
if (!q) return;
|
||
toast("搜尋中…");
|
||
let found;
|
||
try { found = (await api(base() + "api/mcp/registry?q=" + encodeURIComponent(q))).servers || []; } catch (e) { toast(e.message); return; }
|
||
if (!found.length) { toast("沒有找到,換個關鍵字試試(英文的比較多)"); return; }
|
||
const have = new Set((st.mcp || []).map((m) => m.what));
|
||
sheet(`公用市集:${q}`, found.map((e) => ({
|
||
icon: "plug",
|
||
label: e.title + (e.description ? " — " + e.description : ""),
|
||
x: e.note ? "還不支援" : have.has(e.url) ? "已加入" : e.header ? "要金鑰" : "",
|
||
on: async () => {
|
||
if (e.note) { toast(e.note); return; }
|
||
if (have.has(e.url)) { toast("已經加入過了"); return; }
|
||
let url = e.url, header = "";
|
||
for (const v of e.variables || []) {
|
||
const val = await ask(`網址裡的 ${v.name}`, (v.choices || [])[0] || "", v.description || "");
|
||
if (!val) return;
|
||
url = url.split("{" + v.name + "}").join(val);
|
||
}
|
||
if (e.header) {
|
||
const key = await ask(`${e.title} 的金鑰`, "", e.header.description || e.header.value);
|
||
if (!key) return;
|
||
header = `${e.header.name}: ${e.header.value.replace(/\{[^}]*\}/, key)}`;
|
||
}
|
||
if (await act("mcp", {add: {name: e.title, url, header}})) again();
|
||
},
|
||
})), `<div class="note" style="text-align:center">官方 MCP Registry 裡用網址連的連接器。要登入帳號(OAuth)的 AnyBot 還不支援,加入後連線時會說。</div>`);
|
||
});
|
||
on("[data-skillmarket]", "onclick", () => {
|
||
const installed = new Set((st.skills || []).map((s) => s.name));
|
||
const list = (st.skill_market || []).map((m) => ({
|
||
icon: m.remote ? "download" : "sparkles",
|
||
label: `${m.name}${m.title && m.title !== m.name ? " · " + m.title : ""}`,
|
||
x: installed.has(m.name) ? "已加入" : (m.remote ? "GitHub" : "內建"),
|
||
on: async () => {
|
||
if (installed.has(m.name)) { toast("已經加入過了"); return; }
|
||
if (m.remote) {
|
||
toast("正在從 GitHub 下載技能…");
|
||
if (await app("skill_install", {url: m.source}, 0, `已安裝技能「${m.name}」`)) again();
|
||
} else {
|
||
if (await act("skill", {builtin: m.name}, `已加入技能「${m.name}」`)) again();
|
||
}
|
||
},
|
||
}));
|
||
sheet("技能市集", list, `<div class="note" style="text-align:center">點一下即可安裝,所有 Bot 都能使用</div>`);
|
||
});
|
||
on("[data-skilladd]", "onclick", async () => {
|
||
const url = await ask("安裝技能", "", "GitHub 網址、owner/repo/path 或 SKILL.md 網址");
|
||
if (url && await app("skill_install", {url}, 0, "已安裝技能")) again();
|
||
});
|
||
on("[data-skill]", "onclick", (x) => {
|
||
const k = st.skills[+x.dataset.skill];
|
||
const filesHtml = (k.resources && k.resources.length) ? `<div style="font-size:var(--fs-caption);color:var(--text3)">隨附檔案:<code>${esc(k.resources.join("、"))}</code></div>` : "";
|
||
sheet("", isOwner() ? [{icon: "trash", label: "刪除技能", danger: true, on: async () => { if (await confirmSheet(`刪除技能「${k.name}」?`, "", "刪除") && await act("skill", {name: k.name, remove: true}, "已刪除技能")) again(); }}] : [],
|
||
`<div class="form"><div style="font-size:var(--fs-h3);font-weight:600">${esc(k.name)}</div><div style="color:var(--text3);font-size:var(--fs-small)">${esc(k.description)}</div>${filesHtml}<div style="white-space:pre-wrap;font-size:var(--fs-small);background:var(--hover);border-radius:var(--r-m);padding:10px 12px;max-height:50vh;overflow:auto">${esc(k.instructions)}</div></div>`);
|
||
});
|
||
on("[data-s]", "onclick", async (x) => {
|
||
const k = x.dataset.s;
|
||
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(); }}))
|
||
// (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();
|
||
else if (k === "2fa") twoFaSheet();
|
||
else if (k === "devices") devicesSheet();
|
||
else if (k === "pair") pair();
|
||
else if (k === "host") { toHost(""); S.entered = false; NAV.length = 0; show("gate"); kick(); pickHost(); }
|
||
else if (k === "out") askSignOut();
|
||
});
|
||
on("[data-bx]", "onclick", async (x) => {
|
||
const k = x.dataset.bx, box = st.box || {};
|
||
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(); }
|
||
else if (k === "disk") { await act("box", {op: "disk"}, "檢查中…"); setTimeout(again, 2500); }
|
||
else if (k === "update") { if (await confirmSheet("更新 Bot 的電腦?", "正在做的事會先停下來;檔案和登入都會留著,要幾分鐘。", "更新", false)) { await act("box", {op: "update"}, "更新已開始"); again(); } }
|
||
else if (k === "auto") sheet("自動更新", [{label: "關", check: !box.auto_update, on: async () => { if (await act("box", {op: "auto_update", value: ""})) again(); }}, {label: "每天在這個時間更新…", on: async () => { const t = await ask("每天幾點更新(有新版時)", box.auto_update || "03:00", "HH:MM"); if (t && await act("box", {op: "auto_update", value: t})) again(); }}]);
|
||
else if (k === "clean") {
|
||
const main = S.bots.find((b) => b.primary) || S.bots[0]; if (!main) return;
|
||
go("chat", {bot: main.id});
|
||
setTimeout(() => { input.value = "檢查「Bot 的電腦」的磁碟使用情況,並提出安全的清理方案供我核准。先列出用量最大的地方,不要直接刪除任何東西。"; input.dispatchEvent(new Event("input")); input.focus(); }, 300);
|
||
}
|
||
else if (k === "reset") {
|
||
const restore = !!box.snapshot;
|
||
if (await confirmSheet(restore ? "從快照復原?" : "重設電腦?", restore ? "會關閉目前的電腦,從上次的快照以最新版本開一台新的。目前電腦的內容會先存成快照,事後可以找回。正在做的事會先停下來。" : "還沒有快照:會換一台全新的電腦,裡面的檔案和登入資訊都會清除。正在做的事會先停下來。", restore ? "復原" : "重設")) { await act("box", {op: "reset"}, "已開始"); again(); }
|
||
}
|
||
else if (k === "runtime") sheet("容器隔離", [["runc", "標準", "容器和主機共用核心"], ["runsc", "強隔離(gVisor)", "電腦有自己的虛擬核心,Chromium 的沙盒打開"]].map(([v, n, d]) => ({label: n, x: d, check: (box.runtime || "runc") === v, on: async () => { if (await act("box", {op: "runtime", value: v}, "已設定;按「更新」重建後生效")) again(); }})));
|
||
});
|
||
const t = $("box-thumb"); if (t) boxThumb(t);
|
||
}
|
||
|
||
// ---------- 頁面 ----------
|
||
$("b-pagemore").innerHTML = ic("ellipsis", 20);
|
||
document.addEventListener("click", (e) => {
|
||
const el = e.target.closest && e.target.closest("[data-page]");
|
||
if (el && !e.defaultPrevented) { e.preventDefault(); go("page", {id: +el.dataset.page}); }
|
||
});
|
||
async function openPage(id, rev) {
|
||
S.page = id; $("pscroll").scrollTop = 0;
|
||
if (!rev) $("page").innerHTML = `<div class="empty">載入中…</div>`;
|
||
try {
|
||
const v = await api(base() + "api/pages/" + id + (rev ? "?rev=" + rev : ""));
|
||
S.pageData = v;
|
||
$("page-name").textContent = v.title;
|
||
const old = v.revision !== v.latest;
|
||
let head = `<h1 class="pt">${esc(v.title)}</h1><div class="mt">${esc(v.bot)} · 更新於 ${esc(v.updated)}${v.latest > 1 ? ` · 第 ${v.revision} 版` : ""}</div>`;
|
||
if (old) head += `<div class="old">你在看舊的版本。<a class="plink" data-page="${id}">回到最新版</a></div>`;
|
||
else if (v.summary) head += `<p class="sum">${esc(v.summary)}</p>`;
|
||
if (v.note && v.revision > 1) head += `<div class="chg">這一版更新了:${esc(v.note)}</div>`;
|
||
if ((v.kpis || []).length) head += `<div class="stats">${v.kpis.map((k) => `<div class="stat"><div class="k">${esc(k.label)}</div><div class="v${String(k.value || "").length > 10 ? " long" : ""}">${esc(k.value)}</div>${k.delta ? `<div class="s${trend(k.delta)}">${esc(k.delta)}</div>` : ""}</div>`).join("")}</div>`;
|
||
if (v.verdict) head += `<div class="call k-verdict"><div class="ct">${ic("circle-check", 15)}結論</div><p>${inl(v.verdict)}</p></div>`;
|
||
$("page").innerHTML = head + `<div class="toc-at"></div>` + pageMd(v.body, id, old ? v.revision : 0);
|
||
pageToc($("page"));
|
||
loadCharts();
|
||
} catch (e) { $("page").innerHTML = `<div class="empty">${esc(e.message)}</div>`; }
|
||
}
|
||
// 目錄: with 3+ headings, one quiet line 「目錄 · N 節」 that opens to the headings; a tap scrolls there.
|
||
function pageToc(root) {
|
||
const at = root.querySelector(".toc-at"); if (!at) return;
|
||
const all = [...root.children].filter((x) => /^H[2-4]$/.test(x.tagName)), lv = (h) => +h.tagName[1];
|
||
const top = Math.min(...all.map(lv)), hs = all.filter((h) => lv(h) <= top + 1);
|
||
if (hs.length < 3) { at.remove(); return; }
|
||
const toc = document.createElement("details");
|
||
toc.className = "toc";
|
||
toc.innerHTML = `<summary>${ic("chevron-right", 14)}目錄 · ${hs.length} 節</summary><ol>${hs.map((h, i) => `<li class="${lv(h) > top ? "sub" : ""}"><button data-toc="${i}">${esc(h.textContent)}</button></li>`).join("")}</ol>`;
|
||
toc.querySelectorAll("[data-toc]").forEach((b) => b.onclick = () => hs[+b.dataset.toc].scrollIntoView({block: "start", behavior: "smooth"}));
|
||
at.replaceWith(toc);
|
||
}
|
||
$("b-pagemore").onclick = () => {
|
||
const v = S.pageData; if (!v) return;
|
||
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);
|
||
};
|
||
// Files in a chat: pictures shown in place, every file opened as a preview (as the desktop
|
||
// shows it) — api/preview says what it is, api/preview/image decodes it, api/preview/pdf
|
||
// renders one page at a time. Saving is a button in the preview's own bar.
|
||
/** A fetched answer as a blob that can never run as a page of this site: a picture (no SVG),
|
||
* sound, video or PDF keeps its type; anything else (HTML, SVG, unknown) is plain bytes. The
|
||
* brain names the type, and a brain may be someone else's (a team). */
|
||
async function safeBlob(r) {
|
||
const b = await r.blob();
|
||
const t = String(b.type || "").split(";")[0].trim().toLowerCase();
|
||
const ok = /^(image\/(png|jpeg|gif|webp|bmp|avif|heic|x-icon)|audio\/[\w.+-]+|video\/[\w.+-]+|application\/pdf)$/.test(t);
|
||
return ok ? b : new Blob([b], {type: "application/octet-stream"});
|
||
}
|
||
/** Keep a fetched file's blob URL, and let the oldest go past 40 of them: a tab left open for
|
||
* days used to hold every picture, PDF page and recording it had ever shown. */
|
||
function keepBlob(map, key, url) {
|
||
map[key] = url;
|
||
const keys = Object.keys(map);
|
||
for (const old of keys.slice(0, Math.max(0, keys.length - 40))) { URL.revokeObjectURL(map[old]); delete map[old]; }
|
||
}
|
||
const FILES = {};
|
||
async function fileUrl(path) {
|
||
if (!FILES[path]) {
|
||
const r = await api(base() + "api/file?path=" + encodeURIComponent(path), {raw: true});
|
||
if (!r.ok) throw new Error("找不到這個檔案");
|
||
keepBlob(FILES, path, URL.createObjectURL(await safeBlob(r)));
|
||
}
|
||
return FILES[path];
|
||
}
|
||
// Raw GETs fetched with the login, kept as blob URLs (decoded images, PDF pages, media).
|
||
const BLOBS = {};
|
||
async function blobUrl(url, key) {
|
||
if (!BLOBS[key]) {
|
||
const r = await api(url, {raw: true});
|
||
if (!r.ok) { let m = "找不到這個檔案"; try { m = (await r.json()).error || m; } catch (_) {} const err = new Error(m); err.status = r.status; err.transient = [408, 429, 502, 503, 504].includes(r.status); throw err; }
|
||
keepBlob(BLOBS, key, URL.createObjectURL(await safeBlob(r)));
|
||
}
|
||
return BLOBS[key];
|
||
}
|
||
async function loadFiles() {
|
||
for (const el of document.querySelectorAll(".attimg[data-file]")) {
|
||
if (el.querySelector("img")) { seenImg(el); continue; }
|
||
// 預覽圖走 api/preview/image: it decodes TIFF/HEIC too, not only web formats.
|
||
const p = el.dataset.file;
|
||
try { const u = await blobUrl(base() + "api/preview/image?path=" + encodeURIComponent(p), "img:" + p); el.innerHTML = `<img alt="" src="${u}">`; seenImg(el); } catch (e) { el.innerHTML = `<div class="wait">這張圖讀不到</div>`; seenFail(el.dataset.att, e, +el.dataset.bot); }
|
||
}
|
||
}
|
||
document.addEventListener("click", async (e) => {
|
||
const img = e.target.closest && e.target.closest(".attimg[data-file]");
|
||
if (img) { e.preventDefault(); openFile(img.dataset.file, img.dataset.name, img.dataset.att); return; }
|
||
const f = e.target.closest && e.target.closest("a[data-file]");
|
||
if (!f) return;
|
||
e.preventDefault();
|
||
openFile(f.dataset.file, f.dataset.name, f.dataset.att);
|
||
});
|
||
// `att`: the id of a file the bot handed over (交付確認: opened, or couldn't be).
|
||
async function openFile(path, name, att) {
|
||
const f = {path, name: name || "檔案", page: 0, pages: 0, kind: "", data: null, att: att || "", bot: S.open};
|
||
S.file = f;
|
||
$("file-name").textContent = f.name;
|
||
$("filebody").innerHTML = `<div class="empty">載入中…</div>`;
|
||
$("file-meta").style.display = "none";
|
||
$("filepager").style.display = "none";
|
||
go("file", {});
|
||
try {
|
||
const v = await api(base() + "api/preview?path=" + encodeURIComponent(path));
|
||
if (S.file !== f) return; // the person left while it loaded
|
||
Object.assign(f, {kind: v.kind, pages: v.pages || 0, data: v});
|
||
drawFile(f);
|
||
// 產物核對(規格 §產物驗證):AnyBot 存副本時記的大小和 SHA-256,下載後可對。
|
||
const a = f.att ? (S.msgs || []).flatMap((m) => m.attachments || []).find((x) => x.id === f.att) : null;
|
||
const meta = a ? [a.bytes ? "大小 " + kb(a.bytes) : "", a.sha ? "SHA-256 " + a.sha + "(前 12 碼,下載後可用 shasum -a 256 核對)" : ""].filter(Boolean).join(" · ") : "";
|
||
$("file-meta").textContent = meta ? "檔案核對:" + meta : "";
|
||
$("file-meta").style.display = meta ? "" : "none";
|
||
// (Drawn here at once; a picture, PDF or recording says so when it is really shown, and a file
|
||
// with no preview only when it is saved to the phone.)
|
||
if (f.att && ["markdown", "html", "text", "sheet"].includes(f.kind)) seenTell(f.att, "opened", "", f.bot);
|
||
} catch (e) {
|
||
if (S.file === f) $("filebody").innerHTML = `<div class="empty">${esc(e.message)}</div>`;
|
||
seenFail(f.att, e, f.bot);
|
||
}
|
||
}
|
||
function drawFile(f) {
|
||
const v = f.data, body = $("filebody");
|
||
if (f.kind === "image") {
|
||
body.innerHTML = `<div class="fimg"><div class="empty">讀取中…</div></div>`;
|
||
blobUrl(base() + "api/preview/image?path=" + encodeURIComponent(f.path), "img:" + f.path)
|
||
.then((u) => {
|
||
if (S.file !== f) return;
|
||
body.innerHTML = `<div class="fimg"><img alt="" src="${u}"></div>`;
|
||
// 交付確認: a picture is opened once it is drawn — not when its preview is merely asked for.
|
||
const img = body.querySelector("img");
|
||
if (f.att) { img.onload = () => seenTell(f.att, "opened", "", f.bot); img.onerror = () => { if (BLOBS["img:" + f.path] === u) seenTell(f.att, "failed", "unreadable", f.bot); }; }
|
||
})
|
||
.catch((e) => { if (S.file === f) body.innerHTML = `<div class="empty">${esc(e.message)}</div>`; seenFail(f.att, e, f.bot); });
|
||
} else if (f.kind === "pdf") {
|
||
$("filepager").style.display = f.pages > 1 ? "flex" : "none";
|
||
pdfPage(f, 0);
|
||
} else if (f.kind === "markdown" || f.kind === "html") {
|
||
body.innerHTML = `<div class="page">${pageMd(v.text || "", 0, 0)}</div>`;
|
||
} else if (f.kind === "text") {
|
||
body.innerHTML = `<pre class="ftext">${esc(v.text || "")}</pre>`;
|
||
} else if (f.kind === "sheet") {
|
||
body.innerHTML = `<div class="page">` + (v.sheets || []).map((s) =>
|
||
`<h2>${esc(s.name)}</h2><div class="tw"><table><tbody>` +
|
||
(s.rows || []).map((r, i) => `<tr>${(r || []).map((c) => i === 0 ? `<th>${esc(c)}</th>` : `<td>${esc(c)}</td>`).join("")}</tr>`).join("") +
|
||
`</tbody></table></div>`).join("") + `</div>`;
|
||
} else if (f.kind === "audio" || f.kind === "video") {
|
||
body.innerHTML = `<div class="fmedia"><div class="empty">讀取中…</div></div>`;
|
||
blobUrl(base() + "api/file?path=" + encodeURIComponent(f.path), "file:" + f.path)
|
||
.then((u) => {
|
||
if (S.file !== f) return;
|
||
body.innerHTML = `<div class="fmedia">${f.kind === "audio" ? `<audio controls src="${u}"></audio>` : `<video controls src="${u}"></video>`}</div>`;
|
||
// 交付確認: opened once the phone can play it, not before.
|
||
const m = body.querySelector("audio,video");
|
||
if (f.att && m) { m.addEventListener("loadedmetadata", () => seenTell(f.att, "opened", "", f.bot), {once: true}); m.addEventListener("error", () => seenTell(f.att, "failed", "unreadable", f.bot), {once: true}); }
|
||
})
|
||
.catch((e) => { if (S.file === f) body.innerHTML = `<div class="empty">${esc(e.message)}</div>`; seenFail(f.att, e, f.bot); });
|
||
} else {
|
||
body.innerHTML = `<div class="fdl">${ic("file", 40)}<div>${esc(v.message || "這個檔案沒有預覽")}<br>${esc(f.name)}${v.bytes ? " · " + kb(v.bytes) : ""}</div><button class="btn main" id="f-get">儲存到手機</button></div>`;
|
||
$("f-get").onclick = () => saveFile(f.path, f.name, f.att, f.bot);
|
||
}
|
||
}
|
||
async function pdfPage(f, n) {
|
||
f.page = Math.max(0, Math.min(n, Math.max(0, f.pages - 1)));
|
||
$("f-at").textContent = (f.page + 1) + " / " + f.pages;
|
||
$("filebody").innerHTML = `<div class="empty">讀第 ${f.page + 1} 頁…</div>`;
|
||
try {
|
||
const u = await blobUrl(base() + "api/preview/pdf?path=" + encodeURIComponent(f.path) + "&page=" + f.page, f.path + "#" + f.page);
|
||
if (S.file === f) {
|
||
$("filebody").innerHTML = `<div class="fimg"><img alt="" src="${u}"></div>`;
|
||
// 交付確認: a PDF is opened once a page is drawn.
|
||
const img = $("filebody").querySelector("img");
|
||
if (f.att) img.onload = () => seenTell(f.att, "opened", "", f.bot);
|
||
}
|
||
} catch (e) { if (S.file === f) $("filebody").innerHTML = `<div class="empty">${esc(e.message)}</div>`; seenFail(f.att, e, f.bot); }
|
||
}
|
||
$("f-prev").onclick = () => { if (S.file) pdfPage(S.file, (S.file.page || 0) - 1); };
|
||
$("f-next").onclick = () => { if (S.file) pdfPage(S.file, (S.file.page || 0) + 1); };
|
||
// Saving a chat file (from the preview's bar): fetched with the login, handed to the phone.
|
||
function saveFile(path, name, att, bot) {
|
||
fileUrl(path).then((u) => {
|
||
if (att) seenTell(att, "opened", "", bot); const a = document.createElement("a"); a.href = u; a.download = name || "檔案"; document.body.appendChild(a); a.click(); a.remove(); }).catch((e) => toast(e.message));
|
||
}
|
||
$("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 <img>, 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 = `<img alt="圖表" src="${u}">`;
|
||
} catch (_) { el.innerHTML = `<pre><code>${esc(src)}</code></pre>`; }
|
||
}
|
||
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 = `<img alt="圖表" src="${await chartUrl(r)}">`;
|
||
} catch (_) { el.innerHTML = `<div class="wait">這張圖畫不出來</div>`; }
|
||
}
|
||
}
|
||
// Inline Markdown: code, bold, italics, strike, links (page:N opens the page).
|
||
function inl(s) {
|
||
return esc(s)
|
||
.replace(/`([^`]+)`/g, "<code>$1</code>")
|
||
.replace(/\*\*([^*]+)\*\*/g, "<b>$1</b>")
|
||
.replace(/(^|[^*])\*([^*\s][^*]*)\*/g, "$1<i>$2</i>")
|
||
.replace(/~~([^~]+)~~/g, "<s>$1</s>")
|
||
.replace(/\[([^\]]+)\]\(page:(\d+)\)/g, (_, t, id) => `<a class="plink" data-page="${id}">${t}</a>`)
|
||
// A place on the bot's computer (sandbox:, file://, a path): opens the chat's file of that name.
|
||
.replace(/\[([^\]]+)\]\(((?:sandbox:|file:)[^)\s]*|(?:\/(?!\/)|~\/|\.\.?\/)[^)\s]*|[A-Za-z]:[\\/][^)\s]*)\)/g, (_, t, u) => `<a class="flink" data-fname="${u.split(/[?#]/)[0].split(/[\/\\]/).pop()}">${t}</a>`)
|
||
.replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>')
|
||
.replace(/(^|[\s((::,、「])(https?:\/\/[^\s<))」,。]+)/g, '$1<a href="$2" target="_blank" rel="noopener">$2</a>');
|
||
}
|
||
const CALL = {note: "說明", tip: "提示", warning: "注意", important: "重要"};
|
||
// A call-out's icon: the one coloured thing in it (the tint is the same for every kind).
|
||
const CALL_IC = {note: "info", tip: "lightbulb", warning: "circle-alert", important: "zap"};
|
||
// A table column of numbers (amounts, %, counts) lines up on the right; a label column doesn't.
|
||
const NUM_CELL = /^[+\-−~≈約]?\s?[$€£¥]?\s?\d[\d,]*(\.\d+)?\s?(%|[萬億千元個次人台倍件kKMB×x])?$/;
|
||
function numCols(head, rows) {
|
||
return head.map((_, j) => {
|
||
if (!j) return false;
|
||
const vals = rows.map((r) => String(r[j] ?? "").replace(/[*`]/g, "").trim()).filter((v) => v && !/^[-—–]$|^N\/A$/i.test(v));
|
||
return vals.length > 0 && vals.every((v) => NUM_CELL.test(v));
|
||
});
|
||
}
|
||
// Markdown as the desktop draws it (pages and chat replies): headings, lists and tasks, tables,
|
||
// quotes and call-outs, code, Mermaid charts (pages: drawn by AnyBot), ```stats and ```steps.
|
||
/* ```chart → 原生 SVG,和桌面版同一套規則(解析照 src/pages.rs chart(),畫法照
|
||
src/app/markdown_ui.rs md_chart_card):長條依大小排序(標籤本身有順序(月/季/年/數字)
|
||
時不排);單系列長條把數字直接標在條上、不畫 y 軸,折線和多系列長條有 y 軸;多條線在
|
||
線尾標系列名;只留淡水平參考線;圖下附數據表;色板用 --cat1..6(同 theme.rs)。
|
||
圖照手機畫面的寬度畫:字是 --fs-caption(12 px),螢幕上就是 12 px(不會縮成 6 px)。 */
|
||
const CHART_KINDS = {bar: "bar", long: "bar", "長條": "bar", line: "line", "折線": "line", pie: "pie", "圓餅": "pie"};
|
||
const CHART_TEMPORAL = ["月", "年", "週", "周", "季", "Q1", "Q2", "Q3", "Q4", "q1", "q2", "q3", "q4", "W1", "W2", "W3", "W4", "今", "上週", "上季", "去年", "今年", "明年"];
|
||
// A cell's words: a link becomes its text; ** ` __ go (pages.rs plain()).
|
||
const chartPlain = (s) => String(s).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").split("**").join("").split("`").join("").split("__").join("");
|
||
// A number with spaces, thousands commas, % and trailing units stripped (pages.rs num()); null when it is not one.
|
||
function chartValue(s) {
|
||
const t = String(s).replace(/[ \t\n\r\f,]/g, "").replace(/[%元個次人台]+$/, "");
|
||
return /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(t) && isFinite(+t) ? +t : null;
|
||
}
|
||
// ```chart's text → {kind, title, labels, series: [[name, values]]}, or null (pages.rs chart()).
|
||
function chartParse(lines) {
|
||
let kind = "bar", title = "", labels = [], series = [], header = false;
|
||
for (const line of lines.map((l) => String(l).trim()).filter((l) => l && !l.startsWith("#"))) {
|
||
// The first line, before any data: [kind] [title] — or only a kind, or only a title.
|
||
if (!title && !labels.length && !series.length && !line.includes("|")) {
|
||
const sp = line.search(/\s/), k = CHART_KINDS[(sp < 0 ? line : line.slice(0, sp)).toLowerCase()];
|
||
if (k) { kind = k; title = sp < 0 ? "" : line.slice(sp + 1).trim(); } else title = line;
|
||
continue;
|
||
}
|
||
const cells = line.split("|").map((c) => chartPlain(c.trim()));
|
||
if (cells.length > 1 && line.endsWith("|")) cells.pop(); // (a closing | adds no empty column)
|
||
// `| 1月 | 2月` (first cell empty): the labels of a multi-series chart.
|
||
if (!cells[0] && !labels.length) { labels = cells.slice(1); header = true; continue; }
|
||
// A row: its name and the cells that are numbers (|---| and words are skipped).
|
||
const vals = cells.slice(1).map(chartValue);
|
||
if (cells[0] && vals.some((v) => v !== null)) series.push([cells[0], vals.filter((v) => v !== null)]);
|
||
}
|
||
// The plain 標籤 | 數值 form: each row became a one-value series — fold them into one.
|
||
if (!labels.length && series.length && series.every((s) => s[1].length === 1) && kind !== "pie") {
|
||
labels = series.map((s) => s[0]);
|
||
series = [["", series.map((s) => s[1][0])]];
|
||
}
|
||
const n = Math.max(labels.length, ...series.map((s) => s[1].length));
|
||
if (!series.length || !n) return null;
|
||
labels = Array.from({length: n}, (_, i) => labels[i] || String(i + 1));
|
||
// A missing cell is 0; a series of only zeros is left out.
|
||
series = series.map(([s, v]) => [s, Array.from({length: n}, (_, i) => v[i] ?? 0)]).filter((s) => s[1].some((x) => x !== 0));
|
||
if (!series.length) return null;
|
||
// A pie of one plain row is that row's slice (not a slice called 「1」).
|
||
if (kind === "pie" && !header && series.length === 1 && n === 1) labels = [series[0][0]];
|
||
return {kind, title, labels, series};
|
||
}
|
||
const chartNum = (v) => Math.abs(v) >= 10000 ? Math.round(v).toLocaleString("en-US") : String(Math.round(v * 100) / 100);
|
||
// About how wide a text is (CJK and full-width ≈ 1 em, the rest ≈ 0.6 em).
|
||
const chartTextW = (s, fs) => [...String(s)].reduce((a, ch) => a + (ch.codePointAt(0) >= 0x2e80 ? fs : fs * 0.6), 0);
|
||
const chartCut7 = (s) => { const cs = [...String(s)]; return cs.length > 7 ? cs.slice(0, 7).join("") + "…" : String(s); };
|
||
// A text cut with … to fit a width.
|
||
function chartFit(s, w, fs) {
|
||
if (chartTextW(s, fs) <= w) return String(s);
|
||
const cs = [...String(s)];
|
||
while (cs.length > 1 && chartTextW(cs.join("") + "…", fs) > w) cs.pop();
|
||
return cs.join("") + "…";
|
||
}
|
||
const chartCol = (i) => `var(--cat${i % 6 + 1})`;
|
||
// Round steps for the value axis, 0 always inside: 0 · 50 · 100 · 150.
|
||
function chartTicks(lo, hi) {
|
||
const raw = (hi - lo) / 4 || 1, mag = 10 ** Math.floor(Math.log10(raw));
|
||
const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw * (1 - 1e-9));
|
||
const out = [];
|
||
for (let k = Math.floor(lo / step + 1e-9); k <= Math.ceil(hi / step - 1e-9) && out.length < 12; k++) out.push(+(k * step).toPrecision(12));
|
||
return out.length >= 2 && isFinite(step) ? out : [lo, hi];
|
||
}
|
||
// Whether the value axis starts at 0 (src/pages.rs chart_from_zero): bars always; a line only when 0
|
||
// is within reach of its data (its lowest value is 0 or less, or no bigger than its spread) — a
|
||
// reading of 1,649–1,796 W drawn from 0 was a flat line pressed against the top.
|
||
function chartFromZero(c) {
|
||
if (c.kind !== "line") return true;
|
||
const all = c.series.flatMap((s) => s[1]).filter((v) => isFinite(v));
|
||
if (!all.length) return true;
|
||
const lo = Math.min(...all), hi = Math.max(...all);
|
||
return lo <= 0 || lo <= hi - lo;
|
||
}
|
||
// Bar and line.
|
||
function chartPlot(c, W) {
|
||
const FS = 12, line = c.kind === "line", single = c.series.length === 1, labelBars = single && !line;
|
||
const n = c.labels.length, ns = c.series.length, svg = [];
|
||
// A bar chart shows ranking, so bars go big → small — unless the labels carry their own order.
|
||
const temporal = (s) => CHART_TEMPORAL.some((k) => s.includes(k)) || /^\d/.test(s.trim());
|
||
const order = c.labels.map((_, i) => i);
|
||
if (!line && n >= 2 && !c.labels.every(temporal)) {
|
||
const tot = (k) => c.series.reduce((a, s) => a + (s[1][k] || 0), 0);
|
||
order.sort((a, b) => tot(b) - tot(a) || a - b);
|
||
}
|
||
const all = c.series.flatMap((s) => s[1]);
|
||
// Bars from 0; a line far from 0 fits its data (chartFromZero).
|
||
const z = chartFromZero(c) ? [0] : [];
|
||
const vmin = Math.min(...z, ...all), vmax = Math.max(...z, ...all);
|
||
const ticks = chartTicks(vmin, vmax), lo = ticks[0], hi = ticks[ticks.length - 1];
|
||
// The value axis on the left — except a single series of bars, which carries its own numbers.
|
||
const L = labelBars ? 4 : Math.ceil(Math.max(...ticks.map((t) => chartTextW(chartNum(t), FS)))) + 10;
|
||
// Several lines say their names at their ends: room on the right for them.
|
||
const ends = line && !single;
|
||
const R = ends ? Math.min(Math.ceil(Math.max(...c.series.map((s) => chartTextW(chartCut7(s[0]), FS)))) + 12, Math.round(W * 0.3)) : 6;
|
||
// Several series of bars: a legend on top (wrapping).
|
||
let legendH = 0;
|
||
if (!single && !line) {
|
||
let x = 4, y = FS + 1;
|
||
c.series.forEach((s, si) => {
|
||
const name = chartFit(s[0], W * 0.45, FS), w = Math.ceil(13 + chartTextW(name, FS) + 14);
|
||
if (x > 4 && x + w > W) { x = 4; y += FS + 6; }
|
||
svg.push(`<rect x="${x}" y="${y - 10}" width="9" height="9" rx="2" style="fill:${chartCol(si)}"/><text x="${x + 13}" y="${y}" style="font-size:var(--fs-caption);fill:var(--text2)">${esc(name)}</text>`);
|
||
x += w;
|
||
});
|
||
legendH = y + 6;
|
||
}
|
||
const top = Math.max(labelBars ? FS + 10 : 10, legendH + 10);
|
||
const bot = top + Math.round(Math.min(200, Math.max(140, W * 0.5)));
|
||
// A negative bar's number goes under it: room for that above the labels underneath.
|
||
const negRoom = labelBars && vmin < 0 ? FS + 6 : 0;
|
||
const H = bot + negRoom + FS + 16;
|
||
const Y = (v) => top + (bot - top) * (hi - v) / (hi - lo);
|
||
for (const t of ticks) {
|
||
const y = Y(t).toFixed(1);
|
||
svg.push(`<line x1="${L}" y1="${y}" x2="${W - R}" y2="${y}" style="stroke:var(--grid)" stroke-width="1"/>`);
|
||
if (!labelBars) svg.push(`<text x="${L - 6}" y="${(Y(t) + 4).toFixed(1)}" text-anchor="end" style="font-size:var(--fs-caption);fill:var(--text3)">${chartNum(t)}</text>`);
|
||
}
|
||
const x0 = L + (line ? 10 : 0), x1 = W - R - (line ? 10 : 0), gw = (x1 - x0) / n;
|
||
const X = (k) => line ? (n === 1 ? (x0 + x1) / 2 : x0 + (x1 - x0) * k / (n - 1)) : x0 + gw * (k + 0.5);
|
||
const slot = line ? (n === 1 ? x1 - x0 : (x1 - x0) / (n - 1)) : gw;
|
||
// A text centred on x, kept inside the picture (the first and last labels were cut in half).
|
||
const inside = (x, w) => Math.min(Math.max(x, w / 2 + 2), W - w / 2 - 2).toFixed(1);
|
||
// The labels underneath: every one that fits (crowded: every 2nd, 3rd…) — counting the ones
|
||
// pulled in from the edges, so no two touch.
|
||
const xl = order.map((i) => chartCut7(c.labels[i])), xw = xl.map((s) => chartTextW(s, FS)), xx = xl.map((_, k) => +inside(X(k), xw[k]));
|
||
const clash = (e) => { for (let k = e; k < n; k += e) if (xx[k] - xw[k] / 2 < xx[k - e] + xw[k - e] / 2 + 6) return true; return false; };
|
||
let every = Math.max(1, Math.ceil((Math.max(...xw) + 8) / slot));
|
||
while (every < n && clash(every)) every++;
|
||
xl.forEach((s, k) => {
|
||
if (!(k % every)) svg.push(`<text x="${xx[k].toFixed(1)}" y="${H - 8}" text-anchor="middle" style="font-size:var(--fs-caption);fill:var(--text3)">${esc(s)}</text>`);
|
||
});
|
||
if (!line) {
|
||
const bw = Math.max(2, Math.min(single ? 44 : 28, (gw * 0.7 - 2 * (ns - 1)) / ns)), y0 = Y(0);
|
||
order.forEach((i, k) => c.series.forEach((s, si) => {
|
||
const v = s[1][i], cx = X(k) + (si - (ns - 1) / 2) * (bw + 2), yv = Y(v);
|
||
svg.push(`<rect x="${(cx - bw / 2).toFixed(1)}" y="${Math.min(y0, yv).toFixed(1)}" width="${bw.toFixed(1)}" height="${Math.max(1, Math.abs(y0 - yv)).toFixed(1)}" rx="${Math.min(4, bw / 3).toFixed(1)}" style="fill:${chartCol(si)}"><title>${esc(c.labels[i])}${s[0] ? " · " + esc(s[0]) : ""} · ${chartNum(v)}</title></rect>`);
|
||
}));
|
||
if (labelBars) {
|
||
const vs = order.map((i) => chartNum(c.series[0][1][i]));
|
||
const vevery = Math.max(1, Math.ceil((Math.max(...vs.map((s) => chartTextW(s, FS))) + 4) / gw));
|
||
order.forEach((i, k) => {
|
||
if (k % vevery) return;
|
||
const v = c.series[0][1][i], yv = Y(v);
|
||
svg.push(`<text x="${inside(X(k), chartTextW(vs[k], FS))}" y="${(v >= 0 ? yv - 5 : yv + FS + 2).toFixed(1)}" text-anchor="middle" style="font-size:var(--fs-caption);fill:var(--text2)">${vs[k]}</text>`);
|
||
});
|
||
}
|
||
} else {
|
||
const names = [];
|
||
c.series.forEach((s, si) => {
|
||
const pts = order.map((i, k) => [X(k), Y(s[1][i])]);
|
||
svg.push(`<polyline points="${pts.map((p) => p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" ")}" fill="none" style="stroke:${chartCol(si)}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>`);
|
||
pts.forEach((p, k) => svg.push(`<circle cx="${p[0].toFixed(1)}" cy="${p[1].toFixed(1)}" r="3" style="fill:${chartCol(si)}"><title>${esc(c.labels[order[k]])}${s[0] ? " · " + esc(s[0]) : ""} · ${chartNum(s[1][order[k]])}</title></circle>`));
|
||
const last = pts[pts.length - 1];
|
||
if (ends && s[0].trim()) names.push({si, x: last[0] + 7, y: last[1] + 4});
|
||
});
|
||
// Names at the line ends, pushed apart when two lines end close together.
|
||
names.sort((a, b) => a.y - b.y);
|
||
for (let j = 1; j < names.length; j++) names[j].y = Math.max(names[j].y, names[j - 1].y + FS + 2);
|
||
const over = names.length ? Math.max(0, names[names.length - 1].y - (bot + 4)) : 0;
|
||
names.forEach((e) => svg.push(`<text x="${e.x.toFixed(1)}" y="${Math.max(FS, e.y - over).toFixed(1)}" font-weight="600" style="font-size:var(--fs-caption);fill:${chartCol(e.si)}">${esc(chartFit(chartCut7(c.series[e.si][0]), W - e.x - 2, FS))}</text>`));
|
||
}
|
||
return {svg: svg.join(""), H};
|
||
}
|
||
// Pie: slices of the positive values in their own order; the legend says value and share.
|
||
function chartPie(c, W) {
|
||
const FS = 12, one = c.series.length === 1;
|
||
const names = one ? c.labels : c.series.map((s) => s[0]);
|
||
const vals = (one ? c.series[0][1] : c.series.map((s) => s[1][0])).map((v) => Math.max(0, v));
|
||
const total = vals.reduce((a, b) => a + b, 0);
|
||
if (total <= 0) return {svg: "", H: 0};
|
||
const shown = vals.map((_, i) => i).filter((i) => vals[i] > 0);
|
||
const share = (i) => Math.round(vals[i] / total * 100);
|
||
const legend = shown.map((i) => `${chartCut7(names[i])} · ${chartNum(vals[i])} (${share(i)}%)`);
|
||
// (A legend row: the colour, a gap, the words, a little room on the right.)
|
||
const legW = Math.max(...legend.map((s) => chartTextW(s, FS))) + 20, rowH = FS + 9;
|
||
// The legend beside the pie when both fit; under it on a narrow phone. Every row is inside.
|
||
const side = W >= 144 + legW;
|
||
const r = Math.floor(side ? Math.max(60, Math.min(84, (W - legW - 24) / 2)) : Math.min(84, (W - 16) / 2));
|
||
const H = Math.ceil(side ? Math.max(2 * r + 16, shown.length * rowH + 16) : 2 * r + 24 + shown.length * rowH + 4);
|
||
const cx = side ? r + 8 : W / 2, cy = side ? H / 2 : r + 8, svg = [];
|
||
const pt = (a) => `${(cx + r * Math.cos(a)).toFixed(2)},${(cy + r * Math.sin(a)).toFixed(2)}`;
|
||
let a0 = -Math.PI / 2;
|
||
for (const i of shown) {
|
||
const sweep = vals[i] / total * Math.PI * 2, tip = `<title>${esc(names[i])} · ${chartNum(vals[i])} (${share(i)}%)</title>`;
|
||
// One slice (nearly) all the way round is a circle: an arc that ends where it starts draws nothing.
|
||
if (sweep > Math.PI * 2 - 1e-3) svg.push(`<circle cx="${cx}" cy="${cy}" r="${r}" style="fill:${chartCol(i)}">${tip}</circle>`);
|
||
else svg.push(`<path d="M${cx},${cy} L${pt(a0)} A${r},${r} 0 ${sweep > Math.PI ? 1 : 0} 1 ${pt(a0 + sweep)} Z" style="fill:${chartCol(i)};stroke:var(--elev)" stroke-width="2" stroke-linejoin="round">${tip}</path>`);
|
||
a0 += sweep;
|
||
}
|
||
const lx = side ? Math.round(2 * r + 24) : 8, ly = side ? cy - (shown.length - 1) * rowH / 2 : 2 * r + 24;
|
||
shown.forEach((i, k) => {
|
||
const y = ly + k * rowH;
|
||
svg.push(`<rect x="${lx}" y="${(y - 5).toFixed(1)}" width="9" height="9" rx="2" style="fill:${chartCol(i)}"/><text x="${lx + 14}" y="${(y + 4).toFixed(1)}" style="font-size:var(--fs-caption);fill:var(--text2)">${esc(chartFit(legend[k], W - lx - 18, FS))}</text>`);
|
||
});
|
||
return {svg: svg.join(""), H};
|
||
}
|
||
// The numbers behind the chart, under it (desktop: the same table) — readable without hovering.
|
||
function chartTable(c) {
|
||
const pie = c.kind === "pie", one = c.series.length === 1;
|
||
const labels = !pie || one ? c.labels : c.series.map((s) => s[0]);
|
||
const vals = !pie || one ? c.series[0][1] : c.series.map((s) => s[1][0]);
|
||
const total = Math.max(1e-9, vals.reduce((a, b) => a + b, 0));
|
||
const cols = pie ? ["項目", "數值", "佔比"] : one ? ["項目", c.series[0][0].trim() || "數值"] : ["項目", ...c.series.map((s) => s[0])];
|
||
const cell = (i, ci) => pie && ci === 2 ? Math.round(vals[i] / total * 100) + "%" : chartNum(pie || one ? vals[i] : c.series[ci - 1][1][i]);
|
||
const tbl = `<div class="ctab"><table><thead><tr>${cols.map((h) => `<th>${esc(h)}</th>`).join("")}</tr></thead><tbody>${labels.map((l, i) => `<tr><td>${esc(l)}</td>${cols.slice(1).map((_, k) => `<td>${cell(i, k + 1)}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`;
|
||
// Longer than CHART_TABLE_FOLD rows: folded into 「▸ 數據 · N 筆」 (the chart already shows them).
|
||
return labels.length > CHART_TABLE_FOLD ? `<details class="dt"><summary>數據 · ${labels.length} 筆</summary>${tbl}</details>` : tbl;
|
||
}
|
||
const CHART_TABLE_FOLD = 6;
|
||
function chartMd(lines) {
|
||
const c = chartParse(lines);
|
||
if (!c) return "";
|
||
// Drawn at this phone's width (and grows at most a third when the phone turns sideways).
|
||
const vw = typeof innerWidth === "number" && innerWidth > 0 ? innerWidth : 390;
|
||
const W = Math.round(Math.min(700, Math.max(296, vw - 64)));
|
||
const {svg, H} = c.kind === "pie" ? chartPie(c, W) : chartPlot(c, W);
|
||
const pic = H ? `<svg viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" style="max-width:${Math.round(W * 1.3)}px" role="img" aria-label="${esc(c.title || "圖表")}">${svg}</svg>` : "";
|
||
return `<div class="chartcard">${c.title ? `<div class="ct2">${esc(c.title)}</div>` : ""}${pic}${chartTable(c)}</div>`;
|
||
}
|
||
// ```stats: ↑/+ green, ↓/− red. The same rule as src/pages.rs stat_trend: + − - count only with
|
||
// something right after them (「-12%」 is down; a lone 「-」 is "no data", 「- 待補」 is neutral).
|
||
const trend = (t) => /^\s*(↑|\+(?=\S))/.test(t) ? " up" : /^\s*(↓|[−-](?=\S))/.test(t) ? " dn" : "";
|
||
function pageMd(text, id, rev) {
|
||
const L = String(text || "").replace(/\r/g, "").split("\n");
|
||
const out = []; let i = 0, chart = 0;
|
||
const cells = (l) => l.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim());
|
||
while (i < L.length) {
|
||
const l = L[i], t = l.trim();
|
||
if (!t) { i++; continue; }
|
||
const fence = t.match(/^```\s*([\w-]*)/);
|
||
if (fence) {
|
||
const lang = fence[1].toLowerCase(); const body = []; i++;
|
||
while (i < L.length && !L[i].trim().startsWith("```")) body.push(L[i++]);
|
||
i++;
|
||
if (lang === "mermaid" && id) { out.push(`<div class="chart" data-src="api/pages/${id}/chart/${chart++}${rev ? "?rev=" + rev : ""}"><div class="wait">圖表載入中…</div></div>`); 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" ? `<pre><code>${esc(src)}</code></pre>` : had ? `<div class="chart"><img alt="圖表" src="${had}"></div>` : `<div class="chart" data-mermaid="${esc(src)}"><div class="wait">圖表載入中…</div></div>`);
|
||
continue;
|
||
}
|
||
// ```details <title>: 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(`<details class="dt"><summary>${esc(title)}</summary><div class="dt-in">${pageMd(body.join("\n"), id, rev)}</div></details>`); continue; }
|
||
if (lang === "chart") { const html = chartMd(body); if (html) { out.push(html); continue; } }
|
||
if (lang === "stats") {
|
||
const tiles = body.map(cells).filter((c) => c.length >= 2 && c[0]).map((c) => `<div class="stat"><div class="k">${inl(c[0])}</div><div class="v${trend(c[1])}${c[1].length > 10 ? " long" : ""}">${inl(c[1])}</div>${c[2] ? `<div class="s${trend(c[2])}">${inl(c[2])}</div>` : ""}</div>`);
|
||
if (tiles.length) { out.push(`<div class="stats">${tiles.join("")}</div>`); continue; }
|
||
}
|
||
if (lang === "steps") {
|
||
const items = body.map((b) => b.trim().replace(/^[-*]\s*/, "").match(/^\[(x|X|✓|>|~|-| )\]\s*(.*)$/)).filter(Boolean).map((m) => {
|
||
const st = /[xX✓]/.test(m[1]) ? "done" : /[>~-]/.test(m[1]) ? "now" : "todo";
|
||
const [nm, nt] = m[2].split(/\s*\|\s*/, 2);
|
||
return `<li class="${st}"><span class="dot">${st === "done" ? "✓" : ""}</span><div class="nm">${inl(nm)}</div>${nt ? `<div class="nt">${inl(nt)}</div>` : ""}</li>`;
|
||
});
|
||
if (items.length) { out.push(`<ul class="steps">${items.join("")}</ul>`); continue; }
|
||
}
|
||
out.push(`<pre class="cb"><button class="cpy" data-copycode>${ic("copy", 14)}</button><code>${esc(body.join("\n"))}</code></pre>`); continue;
|
||
}
|
||
const h = t.match(/^(#{1,6})\s+(.*)$/);
|
||
if (h) { const n = Math.min(h[1].length + 1, 4); out.push(`<h${n}>${inl(h[2])}</h${n}>`); i++; continue; }
|
||
if (/^(-{3,}|\*{3,}|_{3,})$/.test(t)) { out.push("<hr>"); i++; continue; }
|
||
if (t.startsWith("|") && i + 1 < L.length && /^\|?\s*:?-{2,}/.test(L[i + 1].trim())) {
|
||
const head = cells(t); i += 2; const rows = [];
|
||
while (i < L.length && L[i].trim().startsWith("|")) rows.push(cells(L[i++]));
|
||
const num = numCols(head, rows), cls = (j) => num[j] ? ' class="num"' : "";
|
||
out.push(`<div class="tw"><table><thead><tr>${head.map((c, j) => `<th${cls(j)}>${inl(c)}</th>`).join("")}</tr></thead><tbody>${rows.map((r) => `<tr>${r.map((c, j) => `<td${cls(j)}>${inl(c)}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`);
|
||
continue;
|
||
}
|
||
if (t.startsWith(">")) {
|
||
const q = []; while (i < L.length && L[i].trim().startsWith(">")) q.push(L[i++].trim().replace(/^>\s?/, ""));
|
||
const c = (q[0] || "").match(/^\[!(NOTE|INFO|TIP|WARNING|CAUTION|IMPORTANT)\]\s*(.*)$/i);
|
||
if (c) {
|
||
const k = {info: "note", caution: "warning"}[c[1].toLowerCase()] || c[1].toLowerCase();
|
||
q[0] = c[2];
|
||
out.push(`<div class="call k-${k}"><div class="ct">${ic(CALL_IC[k], 15)}${CALL[k]}</div>${pageMd(q.join("\n"), id, rev)}</div>`);
|
||
} else out.push(`<blockquote>${pageMd(q.join("\n"), id, rev)}</blockquote>`);
|
||
continue;
|
||
}
|
||
if (/^([-*+•]|\d+[.)])\s+/.test(t)) {
|
||
// One list, the way Markdown reads it: items of one kind at this depth, with blank lines
|
||
// between them or not — a spaced-out 「1. … 2. … 3.」 was three lists of one, and every point
|
||
// read 1. — numbered from the first one's number. What is indented under an item is that
|
||
// item's: more of its words, or a list (or quote, code…) inside it — sub-points were flattened
|
||
// into the numbered ones.
|
||
const ordered = /^\d/.test(t), start = ordered ? parseInt(t, 10) : 1, items = [];
|
||
const kind = ordered ? /^\d+[.)]\s+/ : /^[-*+•]\s+/;
|
||
const indent = (x) => x.length - x.trimStart().length, base = indent(l);
|
||
const same = (x) => x.trim() && indent(x) < base + 2 && kind.test(x.trim());
|
||
while (i < L.length && same(L[i])) {
|
||
const head = L[i++].trim().replace(kind, ""), under = [];
|
||
for (;;) {
|
||
let j = i; while (j < L.length && !L[j].trim()) j++;
|
||
if (j < L.length && indent(L[j]) >= base + 2) { while (i <= j) under.push(L[i++]); } else break;
|
||
}
|
||
let j = i; while (j < L.length && !L[j].trim()) j++;
|
||
if (j > i && j < L.length && same(L[j])) i = j;
|
||
const task = head.match(/^\[( |x|X)\]\s+(.*)$/);
|
||
const words = task ? `${task[1] === " " ? "☐" : "☑"} ${inl(task[2])}` : inl(head);
|
||
const lines = under.filter((x) => x.trim()), cut = Math.min(...lines.map(indent));
|
||
const plain = lines.length === under.length && lines.every((x) => !/^(#{1,6}\s|```|>|\||([-*+•]|\d+[.)])\s)/.test(x.trim()));
|
||
const inner = !lines.length ? "" : plain ? lines.map((x) => "<br>" + inl(x.trim())).join("") : pageMd(under.map((x) => x.slice(Math.min(cut, indent(x)))).join("\n"), id, rev);
|
||
items.push(`<li${task ? ' class="task"' : ""}>${words}${inner}</li>`);
|
||
}
|
||
out.push(ordered ? `<ol${start !== 1 ? ` start="${start}"` : ""}>${items.join("")}</ol>` : `<ul>${items.join("")}</ul>`); continue;
|
||
}
|
||
const para = [];
|
||
while (i < L.length && L[i].trim() && !/^(#{1,6}\s|```|>|\||([-*+•]|\d+[.)])\s)/.test(L[i].trim())) para.push(L[i++].trim());
|
||
if (!para.length) { para.push(t); i++; }
|
||
out.push(`<p>${para.map(inl).join("<br>")}</p>`);
|
||
}
|
||
return out.join("");
|
||
}
|
||
|
||
// ---------- screens ----------
|
||
// 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;
|
||
// 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}, "");
|
||
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";
|
||
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;
|
||
if (e.data.anybotScreen === "close" && boxOpen) history.back();
|
||
});
|
||
// This Mac's screen: a picture at a time; taps click, long press right-clicks.
|
||
let lastUrl = null;
|
||
function startFrames() { stopFrames(); const run = S.frameRun = {}; frames(run); }
|
||
function stopFrames() { S.frameRun = null; }
|
||
async function frames(run) {
|
||
while (S.frameRun === run) {
|
||
if (document.hidden) { await nap(800); continue; }
|
||
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 = `<div class="msg">${esc(v.error || "看不到畫面")}</div>`; $("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); img.onload = () => { img.onload = null; macShowPad(); }; }
|
||
img.src = url; if (lastUrl) URL.revokeObjectURL(lastUrl); lastUrl = url;
|
||
$("screen-live").innerHTML = `<span class="live"></span>即時`;
|
||
await nap(700);
|
||
} catch (e) { $("screen-live").textContent = ""; await nap(1500); }
|
||
}
|
||
}
|
||
function point(img, e) {
|
||
const r = img.getBoundingClientRect();
|
||
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, 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));
|
||
}
|
||
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, 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); } }
|
||
|
||
// 虛擬觸控板 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) => `<button class="btn" data-combo="${i}">${esc(name)}<small>${esc(T.comboLabel(ms, k))}</small></button>`).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 = "<b>一指</b>移動游標・<b>點一下</b>按・<b>點兩下按住</b>拖曳・<b>兩指</b>捲動・<b>兩指點</b>右鍵";
|
||
$("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 = "") => `<button class="btn ${cls}" ${attrs}>${label}</button>`;
|
||
$("mac-bar").innerHTML = b('data-pad="1"', "觸控板", MAC.padOn ? "on" : "") + '<span class="sep"></span>'
|
||
+ (T ? T.MODS.mac.map(([m, l]) => b(`data-mod="${m}"`, l, MAC.mods.get(m))).join("") + '<span class="sep"></span>' + T.KEYS.map(([k, l]) => b(`data-key="${k}"`, esc(l))).join("") + '<span class="sep"></span>' : "")
|
||
+ (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(); } });
|
||
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
|
||
// clipboard); what was sent to the phone waits at the brain and is downloaded here.
|
||
const DROP = {to: "", targets: [], items: [], jobs: [], timer: 0};
|
||
const dropApi = (what, opts) => api(base() + "api/drop/" + what, opts);
|
||
const dropSize = (n) => n < 1024 ? n + " B" : n < 1048576 ? Math.round(n / 1024) + " KB" : n < 1073741824 ? (n / 1048576).toFixed(1) + " MB" : (n / 1073741824).toFixed(2) + " GB";
|
||
function dropAgo(ms) { const d = Math.max(0, (Date.now() - ms) / 1000); return d < 60 ? "剛剛" : d < 3600 ? Math.floor(d / 60) + " 分鐘前" : d < 86400 ? Math.floor(d / 3600) + " 小時前" : Math.floor(d / 86400) + " 天前"; }
|
||
function dropState(p) {
|
||
const pct = Math.min(100, Math.floor((p.sent || 0) * 100 / Math.max(1, p.bytes)));
|
||
switch (p.state) {
|
||
case "uploading": return ["正在交給大腦 " + pct + "%"];
|
||
case "waiting": return [/更新/.test(p.note || "") ? p.note : `等「${p.to_name}」開機上線,會自動送達`];
|
||
case "sending": return ["傳送中 " + pct + "%"];
|
||
case "ready": return [p.text ? "給手機的文字" : "可以下載(保留 7 天)"];
|
||
case "done": return [(p.to === "phone" && !p.text ? "已下載 · " : "已送達 · ") + dropAgo(p.at)];
|
||
default: return ["沒有送達:" + (p.note || "不知道原因"), true];
|
||
}
|
||
}
|
||
function dropDraw() {
|
||
const box = document.getElementById("drops"); if (!box) return false;
|
||
box.querySelector("#drop-to").innerHTML = DROP.targets.length ? DROP.targets.map((t) => `<button data-id="${esc(t.id)}" class="${t.id === DROP.to ? "on" : t.online ? "" : "off"}">${esc(t.name)}${t.online ? "" : " · 離線"}</button>`).join("") : `<span class="ds" style="color:var(--text3);font-size:var(--fs-small)">正在找帳號裡的裝置…</span>`;
|
||
box.querySelectorAll("#drop-to button").forEach((b) => b.onclick = () => { DROP.to = b.dataset.id; try { localStorage.setItem("anybot.dropto", DROP.to); } catch (_) {} dropDraw(); });
|
||
box.querySelector("#drop-jobs").innerHTML = DROP.jobs.map((j) => `<div class="drop-row"><div class="dw"><div class="dn">${esc(j.name)}</div><div class="ds">${dropSize(j.sent)} / ${dropSize(j.total)}</div><div class="drop-bar"><i style="width:${j.total ? Math.floor(j.sent * 100 / j.total) : 0}%"></i></div></div></div>`).join("");
|
||
box.querySelector("#drop-list").innerHTML = (DROP.items.length ? `<div class="grp">最近 7 天</div>` : "") + DROP.items.slice(0, 40).map((p, i) => {
|
||
const [st, bad] = dropState(p), mine = p.to === "phone";
|
||
const btns = (p.text ? `<button class="btn sm" data-copy="${i}">複製</button>` : mine && (p.state === "ready" || p.state === "done") ? `<button class="btn sm ${p.state === "ready" ? "main" : ""}" data-get="${i}">下載</button>` : "") + (bad ? `<button class="btn sm" data-retry="${i}">再試</button>` : "") + `<button class="btn sm" data-rm="${i}">${ic("x", 14)}</button>`;
|
||
return `<div class="drop-row">${ic(p.text ? "copy" : "file", 20)}<div class="dw"><div class="dn">${esc(p.name)}</div><div class="ds ${bad ? "bad" : ""}">${p.text ? "" : dropSize(p.bytes) + " · "}${esc(p.from)} → ${esc(p.to_name)} · ${esc(st)}</div></div>${btns}</div>`;
|
||
}).join("");
|
||
const at = (b, k) => DROP.items[+b.dataset[k]];
|
||
box.querySelectorAll("[data-copy]").forEach((b) => b.onclick = () => copyText(at(b, "copy").text));
|
||
box.querySelectorAll("[data-get]").forEach((b) => b.onclick = () => dropDownload(at(b, "get"), b));
|
||
box.querySelectorAll("[data-retry]").forEach((b) => b.onclick = async () => { try { await dropApi("retry", {json: {id: at(b, "retry").id}}); } catch (e) { toast(e.message); } dropRefresh(); });
|
||
box.querySelectorAll("[data-rm]").forEach((b) => b.onclick = async () => { const p = at(b, "rm"); DROP.items = DROP.items.filter((x) => x !== p); dropDraw(); try { await dropApi("remove", {json: {id: p.id}}); } catch (e) { toast(e.message); } });
|
||
return true;
|
||
}
|
||
async function dropRefresh() {
|
||
try {
|
||
const v = await dropApi("list");
|
||
DROP.items = v.items || [];
|
||
} catch (_) {}
|
||
clearTimeout(DROP.timer);
|
||
if (!dropDraw()) return;
|
||
const moving = DROP.jobs.length || DROP.items.some((p) => ["uploading", "sending", "waiting"].includes(p.state));
|
||
DROP.timer = setTimeout(dropRefresh, moving ? 1500 : 6000);
|
||
}
|
||
async function dropsSheet() {
|
||
sheet("傳送到其他裝置", [], `<div id="drops"><div class="form"><div class="drop-to" id="drop-to"></div><button class="btn main" id="drop-pick">${ic("arrow-up", 16)}選擇檔案或照片</button><textarea class="field" id="drop-text" style="min-height:56px" placeholder="或貼上一段文字、網址(電腦收到就在剪貼簿裡)"></textarea><button class="btn" id="drop-say">傳送文字</button></div><div id="drop-jobs"></div><div id="drop-list"></div><input type="file" id="drop-file" multiple hidden></div>`);
|
||
const box = document.getElementById("drops");
|
||
const need = () => { if (!DROP.to) { toast("先選要傳到哪一台"); return false; } return true; };
|
||
box.querySelector("#drop-pick").onclick = () => { if (need()) box.querySelector("#drop-file").click(); };
|
||
box.querySelector("#drop-file").onchange = (e) => { [...e.target.files].forEach(dropUpload); e.target.value = ""; };
|
||
box.querySelector("#drop-say").onclick = async () => {
|
||
const ta = box.querySelector("#drop-text"), text = ta.value.trim();
|
||
if (!text || !need()) return;
|
||
try { await dropApi("new", {json: {text, to: DROP.to}}); ta.value = ""; toast("已傳送"); } catch (e) { toast(e.message); }
|
||
dropRefresh();
|
||
};
|
||
dropDraw(); dropRefresh();
|
||
try {
|
||
const v = await dropApi("targets");
|
||
// (The phone itself isn't somewhere to send to from the phone.)
|
||
DROP.targets = (v.targets || []).filter((t) => t.id !== v.you);
|
||
let last = ""; try { last = localStorage.getItem("anybot.dropto") || ""; } catch (_) {}
|
||
if (!DROP.targets.some((t) => t.id === DROP.to)) DROP.to = (DROP.targets.find((t) => t.id === last) || DROP.targets.find((t) => t.online) || {id: ""}).id;
|
||
dropDraw();
|
||
} catch (e) { toast(e.message); }
|
||
}
|
||
// One file, handed to the brain in pieces (a piece that didn't get through is sent again from
|
||
// where the brain says it is).
|
||
async function dropUpload(f) {
|
||
const job = {name: f.name, total: f.size, sent: 0};
|
||
DROP.jobs.push(job); dropDraw();
|
||
let id = "";
|
||
try {
|
||
const v = await dropApi("new", {json: {name: f.name, bytes: f.size, to: DROP.to}});
|
||
id = v.id;
|
||
const step = v.chunk || 2097152;
|
||
let at = 0, stuck = 0;
|
||
while (at < f.size) {
|
||
let r = null;
|
||
try { r = await api(base() + `api/drop/chunk?id=${id}&at=${at}`, {method: "POST", body: f.slice(at, at + step), headers: {"Content-Type": "application/octet-stream"}, raw: true}); } catch (_) {}
|
||
if (r && r.ok) {
|
||
const have = (await r.json()).have;
|
||
stuck = have > at ? 0 : stuck + 1;
|
||
at = have;
|
||
} else if (r && r.status < 500) {
|
||
let m = ""; try { m = (await r.json()).error; } catch (_) {}
|
||
throw new Error(m || "大腦沒有收下");
|
||
} else { stuck++; await new Promise((ok) => setTimeout(ok, 2000)); }
|
||
if (stuck > 5) throw new Error("傳不過去:連線一直斷");
|
||
job.sent = at; dropDraw();
|
||
}
|
||
await dropApi("done", {json: {id}});
|
||
toast("「" + f.name + "」已交給大腦");
|
||
} catch (e) {
|
||
toast(e.message);
|
||
if (id) dropApi("remove", {json: {id}}).catch(() => {});
|
||
}
|
||
DROP.jobs.splice(DROP.jobs.indexOf(job), 1);
|
||
dropRefresh();
|
||
}
|
||
// What was sent to the phone: read from the brain in pieces, then saved (or shared, on a phone
|
||
// that can hand a file to another app).
|
||
async function dropDownload(p, btn) {
|
||
if (btn.disabled) return;
|
||
btn.disabled = true;
|
||
try {
|
||
const parts = [];
|
||
let at = 0;
|
||
while (at < p.bytes) {
|
||
const r = await api(base() + `api/drop/file?id=${p.id}&at=${at}&len=4194304`, {raw: true});
|
||
if (!r.ok) { let m = ""; try { m = (await r.json()).error; } catch (_) {} throw new Error(m || "下載不了"); }
|
||
const b = await r.arrayBuffer();
|
||
if (!b.byteLength) throw new Error("下載到一半斷了");
|
||
parts.push(b); at += b.byteLength;
|
||
btn.textContent = Math.floor(at * 100 / p.bytes) + "%";
|
||
}
|
||
const file = new File(parts, p.name, {type: "application/octet-stream"});
|
||
const u = URL.createObjectURL(file);
|
||
const a = document.createElement("a"); a.href = u; a.download = p.name; document.body.appendChild(a); a.click(); a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(u), 120000);
|
||
} catch (e) { toast(e.message); }
|
||
dropRefresh();
|
||
}
|
||
|
||
// ---------- 加一台電腦, notifications ----------
|
||
// A code for a new computer (ten minutes, once), as hands for this AnyBot.
|
||
async function pair() {
|
||
const el = sheet("加一台電腦", [], `<div class="note">Mac、任何 Linux(含沒有螢幕的)貼終端機那一行;Windows 貼 PowerShell 那一行。還沒裝會先裝好,並完成第一次配對,變成「${esc(S.hostName || "這台 AnyBot")}」的手腳。不用帳號密碼。</div><div class="pair-code" id="pair-code">······</div><code class="pair-line" id="pair-line" style="white-space:pre-wrap">正在產生…</code><div class="form"><button class="btn main" id="pair-copy">複製全部</button></div><div class="note" id="pair-left" style="text-align:center"></div>`);
|
||
try {
|
||
const v = await api("relay/pair", {json: {for: S.host}});
|
||
const line = `Windows PowerShell:\n$env:ANYBOT_NONINTERACTIVE='1'; $env:ANYBOT_MODE='hands'; $env:ANYBOT_PAIR_URL='${location.origin}'; $env:ANYBOT_PAIR_CODE='${v.code}'; irm https://code.30cm.net/daniel.w/AnyBot/raw/branch/main/install.ps1 | iex\n\nMac / Linux(任何發行版,沒有螢幕也可以):\ncurl -fsSL https://code.30cm.net/daniel.w/AnyBot/raw/branch/main/install.sh | sh -s -- hands ${location.origin} ${v.code}`;
|
||
el.querySelector("#pair-code").textContent = v.code.slice(0, 3) + " " + v.code.slice(3);
|
||
el.querySelector("#pair-line").textContent = line;
|
||
el.querySelector("#pair-copy").onclick = () => copyText(line);
|
||
const end = Date.now() + (v.expires_in || 600) * 1000;
|
||
clearInterval(S.pairTimer);
|
||
S.pairTimer = setInterval(() => {
|
||
const left = Math.max(0, Math.round((end - Date.now()) / 1000));
|
||
const e2 = document.getElementById("pair-left"); if (!e2) { clearInterval(S.pairTimer); return; }
|
||
e2.textContent = left ? `還有 ${Math.floor(left / 60)} 分 ${String(left % 60).padStart(2, "0")} 秒,只能用一次` : "過期了,關掉再按一次「加一台電腦」";
|
||
if (!left) clearInterval(S.pairTimer);
|
||
}, 1000);
|
||
} catch (e) { el.querySelector("#pair-line").textContent = "沒有拿到配對碼:" + e.message; }
|
||
}
|
||
const pushOK = () => S.relay && "serviceWorker" in navigator && "PushManager" in window && "Notification" in window;
|
||
function keyBytes(b64) { const s = atob(b64.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((b64.length + 3) % 4)); return Uint8Array.from(s, (c) => c.charCodeAt(0)); }
|
||
// What this phone is told about (the account server keeps the choice with this phone's subscription).
|
||
const KINDS = [["need", "需要你", "要你允許、回答問題,或接手一個步驟"], ["done", "做完了", "你不在電腦前時,Bot 做完一件事或達成目標"], ["routine", "例行任務暫停", "例行任務連續失敗、自己停下來了"], ["file", "收到傳來的檔案", "從其他裝置傳到這裡的檔案或文字"]];
|
||
async function pushSub() { const r = await navigator.serviceWorker.getRegistration(); return r && await r.pushManager.getSubscription(); }
|
||
async function notifySheet() {
|
||
if (!pushOK()) {
|
||
// Over plain http no browser offers notifications (no service worker, no push): say so, and
|
||
// how to get to https, instead of blaming the browser. The account server's own certificate
|
||
// (setup.sh's LAN mode serves it) lets a phone that trusts it open the https address.
|
||
if (S.relay && !window.isSecureContext) {
|
||
const ca = await fetch("anybot-ca.crt", {method: "HEAD", cache: "no-store"}).then((r) => r.ok && !/html/.test(r.headers.get("content-type") || "")).catch(() => false);
|
||
const https = "https://" + location.host + "/";
|
||
let h = `<div class="note">通知只能在 https 的網址開,這是瀏覽器的規定,跟用哪個瀏覽器無關。現在打開的是 <b>http://${esc(location.host)}</b>。</div>`;
|
||
h += ca
|
||
? `<div class="note">這台帳號伺服器有自己的憑證,手機信任它就能改用 https:<br>1. 用 Safari 打開 <a href="anybot-ca.crt">下載伺服器的憑證</a>,允許下載描述檔。<br>2. 到手機的 設定 › 一般 › VPN 與裝置管理 安裝它,再到 設定 › 一般 › 關於本機 › 憑證信任設定 把它打開。<br>3. 用 Safari 打開 <a href="${esc(https)}">${esc(https)}</a>,重新登入一次,分享 › 加入主畫面,從主畫面打開再來這裡開通知。</div>`
|
||
: `<div class="note">請管理帳號伺服器的人幫它加上 https(例如用自己的網域和正式憑證),再用 https 的網址打開。</div>`;
|
||
h += `<div class="note">長久的做法:帳號伺服器用有正式憑證的網址,手機什麼都不用裝。</div>`;
|
||
sheet("通知", [], h); return;
|
||
}
|
||
const why = !S.relay ? "直接連線(同一個網路)收不到推播:用 AnyBot 帳號登入的手機才收得到。" : navigator.standalone === false ? "iPhone 要先按分享 › 加入主畫面,從主畫面打開 AnyBot 才能開通知。" : "這個瀏覽器不支援通知。";
|
||
sheet("通知", [], `<div class="note">${why}</div>`); return;
|
||
}
|
||
// The switch shows what the account server has for this phone, and pressing it does what it
|
||
// shows: a subscription the phone kept but the server dropped (too many phones, an address the
|
||
// push service gave up on) reads 「關閉中」, and pressing it subscribes again. Server not
|
||
// reachable: the phone's own subscription, and the kinds and the test wait.
|
||
const all = KINDS.map((k) => k[0]);
|
||
const sub = await pushSub().catch(() => null);
|
||
let st = {on: false, kinds: all}, unknown = false;
|
||
if (sub) st = await api("relay/push/state", {json: {endpoint: sub.endpoint}}).catch(() => { unknown = true; return {on: true, kinds: all}; });
|
||
const blocked = Notification.permission === "denied";
|
||
// (The one switch for all of them is 設定 › 一般 › 通知總開關: off, this phone gets none either.)
|
||
const master = !(S.settings && S.settings.notify === false);
|
||
let h = master ? "" : `<div class="note">設定 › 一般 ›「通知總開關」關著:電腦和這支手機都不會通知。要收,先打開它。</div>`;
|
||
h += `<div class="group">` + item({icon: "bell", k: "這支手機的通知", v: blocked ? "被系統擋下了:到手機的設定 › 通知 › AnyBot 打開" : st.on ? "Bot 需要你時,會跳出通知" : "關閉中", sw: st.on && !blocked, swdata: 'data-push="1"', disabled: blocked}) + `</div>`;
|
||
if (unknown) h += `<div class="note">暫時連不上帳號伺服器:開關照這支手機上的設定;要通知哪幾種、送測試通知,等連上再試。</div>`;
|
||
else if (st.on) {
|
||
h += `<div class="grp">要通知我的事</div><div class="group">` + KINDS.map(([k, n, v]) => item({k: n, v, sw: st.kinds.includes(k), swdata: `data-kind="${k}"`})).join("") + `</div>`;
|
||
h += `<div class="form"><button class="btn" id="push-test">${ic("send", 16)}送一則測試通知</button></div>`;
|
||
}
|
||
h += `<div class="note">通知的圖示是 AnyBot 的貓;App 圖示上的數字是正在等你的 Bot。${navigator.standalone ? "聲音和橫幅樣式在 iPhone 的設定 › 通知 › AnyBot 調整。" : ""}</div>`;
|
||
const el = sheet("通知", [], h);
|
||
// This phone's subscription: the account server forgets it (best effort), then the phone.
|
||
const drop = async (s) => { if (!s) return; await api("relay/push/unsubscribe", {json: {endpoint: s.endpoint}}).catch(() => {}); await s.unsubscribe().catch(() => {}); };
|
||
const on = el.querySelector("[data-push]");
|
||
if (on) on.onchange = async () => {
|
||
const want = on.checked;
|
||
on.disabled = true;
|
||
try {
|
||
if (!want) {
|
||
await drop(await pushSub().catch(() => null));
|
||
if (navigator.clearAppBadge) navigator.clearAppBadge().catch(() => {});
|
||
toast("已關閉通知");
|
||
} else {
|
||
if (await Notification.requestPermission() !== "granted") { toast("沒有允許通知(可在手機的設定裡打開)"); notifySheet(); return; }
|
||
const r = await navigator.serviceWorker.register("sw.js"); await navigator.serviceWorker.ready;
|
||
const {key} = await api("relay/push/key");
|
||
// A subscription left on the phone (the server no longer has it, or it was made for
|
||
// another key) never rings: start a fresh one.
|
||
await drop(await r.pushManager.getSubscription());
|
||
const s2 = await r.pushManager.subscribe({userVisibleOnly: true, applicationServerKey: keyBytes(key)});
|
||
await api("relay/push/subscribe", {json: {...s2.toJSON(), kinds: all}}); toast("已開啟通知");
|
||
}
|
||
} catch (e) { toast("通知設定失敗:" + e.message); }
|
||
notifySheet();
|
||
};
|
||
const mine = async () => { const s2 = await pushSub(); if (!s2) throw new Error("這支手機還沒開通知"); return s2; };
|
||
el.querySelectorAll("[data-kind]").forEach((c) => c.onchange = async () => {
|
||
const kinds = [...el.querySelectorAll("[data-kind]")].filter((x) => x.checked).map((x) => x.dataset.kind);
|
||
try { const s2 = await mine(); await api("relay/push/kinds", {json: {endpoint: s2.endpoint, kinds}}); toast(kinds.length ? "已更新" : "這支手機現在不會收到 Bot 的通知"); }
|
||
catch (e) { toast("沒有存到:" + e.message); c.checked = !c.checked; }
|
||
});
|
||
const test = el.querySelector("#push-test");
|
||
if (test) test.onclick = async () => {
|
||
try { const s2 = await mine(); await api("relay/push/test", {json: {endpoint: s2.endpoint}}); toast("送出了,幾秒內會跳出來"); }
|
||
catch (e) { toast("沒有送出:" + e.message); }
|
||
};
|
||
}
|
||
// The number on the app's icon: bots waiting for you (允許、問題、需要你處理). The notifications set
|
||
// it while the app is closed; here it follows what the app shows.
|
||
function appBadge() {
|
||
if (!navigator.setAppBadge) return;
|
||
const n = new Set((S.approvals || []).map((a) => a.bot)).size;
|
||
(n ? navigator.setAppBadge(n) : navigator.clearAppBadge()).catch(() => {});
|
||
}
|
||
// ---------- installed like an app ----------
|
||
const installed = () => matchMedia("(display-mode: standalone)").matches || navigator.standalone === true;
|
||
window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); S.installPrompt = e; installHint(); });
|
||
window.addEventListener("appinstalled", () => { S.installPrompt = null; installHint(); toast("已安裝,之後從主畫面打開 AnyBot"); });
|
||
async function installApp() {
|
||
if (S.installPrompt) { const p = S.installPrompt; S.installPrompt = null; p.prompt(); await p.userChoice.catch(() => {}); installHint(); return; }
|
||
// (.note is a flex row: the steps are one block inside it, so the share icon stays in its line.)
|
||
sheet("加入主畫面", [], `<div class="note"><div>1. 按 Safari 下方的分享按鈕 ${ic("share", 15)}\n2. 選「加入主畫面」\n3. 之後從主畫面的 AnyBot 打開:全螢幕、沒有網址列,也能開通知。</div></div>`);
|
||
}
|
||
function installHint() {
|
||
const el = $("install"); if (!el) return;
|
||
let gone = false; try { gone = localStorage.getItem("anybot.install-hint") === "no"; } catch (_) {}
|
||
const can = !installed() && !gone && S.token && (S.installPrompt || navigator.standalone === false);
|
||
el.classList.toggle("on", !!can);
|
||
if (!can) { el.innerHTML = ""; return; }
|
||
el.innerHTML = `<img src="icon-180.png" alt=""><div class="mid"><b>把 AnyBot 裝成 App</b><span>全螢幕、從主畫面打開,Bot 需要你時會跳通知。</span></div><button class="btn main" id="install-go">${S.installPrompt ? "安裝" : "怎麼做"}</button><button class="x" id="install-no" title="不用了">${ic("x", 16)}</button>`;
|
||
$("install-go").onclick = installApp;
|
||
$("install-no").onclick = () => { try { localStorage.setItem("anybot.install-hint", "no"); } catch (_) {} installHint(); };
|
||
}
|
||
// The iPhone home-screen app has no browser around it, so no swipe from the left edge to go back:
|
||
// AnyBot does that itself (Android has its own back gesture; Safari in the browser has its own).
|
||
if (navigator.standalone === true) {
|
||
let el = null, sx = 0, sy = 0, dx = 0, t0 = 0;
|
||
document.addEventListener("touchstart", (e) => {
|
||
const t = e.touches[0];
|
||
el = null;
|
||
if (e.touches.length !== 1 || t.clientX > 22 || NAV.length < 2 || boxOpen || $("sheet").classList.contains("on")) return;
|
||
el = document.querySelector(".view.on"); sx = t.clientX; sy = t.clientY; dx = 0; t0 = performance.now();
|
||
}, {passive: true});
|
||
document.addEventListener("touchmove", (e) => {
|
||
if (!el) return;
|
||
const t = e.touches[0]; dx = Math.max(0, t.clientX - sx);
|
||
if (dx < 12 && Math.abs(t.clientY - sy) > 12) { el.classList.remove("dragging"); el.style.transform = ""; el = null; return; } // scrolling, not going back
|
||
el.classList.add("dragging"); el.style.transform = `translateX(${dx}px)`;
|
||
}, {passive: true});
|
||
const end = () => {
|
||
if (!el) return;
|
||
const v = el, goBack = dx > innerWidth * 0.33 || dx / Math.max(1, performance.now() - t0) > 0.45;
|
||
el = null;
|
||
v.classList.remove("dragging"); v.style.transition = "transform .2s cubic-bezier(.22,.8,.24,1)";
|
||
v.style.transform = goBack ? `translateX(${innerWidth}px)` : "";
|
||
setTimeout(() => { v.style.transition = ""; v.style.transform = ""; if (goBack) { S.swiped = true; back(); } }, 200);
|
||
};
|
||
document.addEventListener("touchend", end);
|
||
document.addEventListener("touchcancel", end);
|
||
}
|
||
// The page and its icons kept on this phone (sw.js), not only for notifications.
|
||
if ("serviceWorker" in navigator && window.isSecureContext) navigator.serviceWorker.register("sw.js").catch(() => {});
|
||
// A tapped notification opens that chat.
|
||
function openFromHash() {
|
||
const h = new URLSearchParams(location.hash.slice(1));
|
||
// (Only an id's shape; pickHost goes in only when it is one of this account's own.)
|
||
if (/^[A-Za-z0-9_-]{1,64}$/.test(h.get("host") || "")) { S.host = h.get("host"); localStorage.setItem("anybot.host", S.host); }
|
||
const b = +h.get("bot");
|
||
if (b) S.open = b;
|
||
// Tapping 允許/拒絕 on a notification: answer it once the token is in place.
|
||
const ans = h.get("answer");
|
||
// (With the request it was about: one that changed since is not answered by an old banner.)
|
||
// (A link with no key answers nothing: only a banner's own buttons carry one.)
|
||
if (ans && b && h.get("call") && (ans === "once" || ans === "reject")) S.answer = {bot: b, answer: ans, call: h.get("call")};
|
||
const sc = new URLSearchParams(location.search).get("sc");
|
||
if (sc) S.sc = sc;
|
||
if (location.hash || location.search) history.replaceState(null, "", location.pathname);
|
||
}
|
||
// A file or camera picker is open (it hides the page): what is picked must come back to this page.
|
||
let picking = false;
|
||
document.addEventListener("click", (e) => { if (e.target instanceof HTMLInputElement && e.target.type === "file") picking = true; }, true);
|
||
document.addEventListener("change", (e) => { if (e.target instanceof HTMLInputElement && e.target.type === "file") picking = false; }, true);
|
||
// What this page was opened with (a notification's chat and answer, a shortcut): a reload for a
|
||
// new build opens with it again.
|
||
const LAUNCH = location.search + location.hash;
|
||
openFromHash();
|
||
// A new build was kept while this page was in use: it is taken when the app goes to the
|
||
// background with nothing in hand (nothing typed, attached, on its way or being recorded, no
|
||
// 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.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();
|
||
}
|
||
if ("serviceWorker" in navigator) navigator.serviceWorker.addEventListener("message", (e) => {
|
||
// A new build of this page was just kept: still on the connecting screen, take it now (once a minute at
|
||
// most); already in, it is the one the next opening uses.
|
||
if (e.data && e.data.fresh) {
|
||
S.fresh = true;
|
||
let last = 0; try { last = +sessionStorage.getItem("anybot.fresh") || 0; } catch (_) {}
|
||
if (!S.entered && S.view === "gate" && Date.now() - last > 60000) {
|
||
try { sessionStorage.setItem("anybot.fresh", String(Date.now())); } catch (_) {}
|
||
history.replaceState(null, "", location.pathname + LAUNCH);
|
||
location.reload();
|
||
}
|
||
return;
|
||
}
|
||
const d = e.data && e.data.open; if (!d) return;
|
||
if (d.host && d.host !== S.host && S.relay) { toHost(d.host); S.version = 0; }
|
||
if (d.answer && d.ask && d.bot) {
|
||
// (Not signed in yet: kept, and sent once the phone is — apply.)
|
||
if (S.token) api(base() + `api/bots/${d.bot}/answer`, {json: {answer: d.answer, call: d.ask, from: "notice"}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message));
|
||
else S.answer = {bot: +d.bot, answer: d.answer, call: d.ask};
|
||
}
|
||
if (d.bot && S.token) go("chat", {bot: +d.bot}); else if (d.bot) S.open = +d.bot;
|
||
});
|
||
// ── 頂天立地: what the phone really gives the page, measured (no one CSS value is right on every iOS) ──
|
||
// · Most phones and iOS versions: the whole screen, drawn under a clear status bar — nothing to do.
|
||
// · iOS 26.1, 26.5 and later, 27 (WebKit bug 301994): a home-screen app still starts under the
|
||
// status bar but is a status bar short at the bottom — the system draws that strip, the page
|
||
// can't — and a frosted system bar lies over the top (measured on an iPhone 15 Pro: down to
|
||
// about the status bar and a half). Then the header moves below the frost, the home-indicator
|
||
// room isn't added again (it is inside the system's strip), and what meets the strip is the
|
||
// page's colour.
|
||
// · The status bar taking its room at the top (the inset is 0 then): nothing to do.
|
||
// · The keyboard bug (after the first keyboard the page stays a status bar short until the app is
|
||
// closed): when a text box lets go the page is laid out again once (that undoes it), then measured.
|
||
// (window.FIT_TEST stands in for the phone in the scratch checks: {iphone, standalone, screenW,
|
||
// screenH, innerH, safeT, safeB}.)
|
||
const FIT = {mode: "", lost: 0, safeT: 0, safeB: 0, screenW: 0, screenH: 0, innerH: 0, tallest: {}, healed: 0};
|
||
function insets() {
|
||
const p = document.createElement("div");
|
||
p.style.cssText = "position:fixed;visibility:hidden;pointer-events:none;padding-top:env(safe-area-inset-top);padding-bottom:env(safe-area-inset-bottom)";
|
||
document.body.appendChild(p);
|
||
const cs = getComputedStyle(p), v = [parseFloat(cs.paddingTop) || 0, parseFloat(cs.paddingBottom) || 0];
|
||
p.remove();
|
||
return v;
|
||
}
|
||
function fit() {
|
||
if (!document.body) return;
|
||
const T = window.FIT_TEST || {};
|
||
const iphone = T.iphone ?? /iPhone/.test(navigator.userAgent);
|
||
const standalone = T.standalone ?? installed();
|
||
const [safeT, safeB] = T.safeT != null ? [T.safeT, T.safeB || 0] : insets();
|
||
const sw = T.screenW ?? screen.width, sh = T.screenH ?? screen.height;
|
||
const landscape = matchMedia("(orientation: landscape)").matches;
|
||
const screenH = landscape ? Math.min(sw, sh) : Math.max(sw, sh), innerH = T.innerH ?? innerHeight;
|
||
const key = landscape ? "l" : "p";
|
||
FIT.tallest[key] = Math.max(FIT.tallest[key] || 0, innerH);
|
||
// Only an iPhone's home-screen app, and only about a status bar's worth (an iPad in a window
|
||
// is much shorter than its screen, and that is not this).
|
||
const lost = iphone && standalone ? Math.round(screenH - innerH) : 0;
|
||
const mode = lost >= 20 && lost <= 90 ? (safeT >= 20 ? "short" : "topbar") : "";
|
||
const root = document.documentElement;
|
||
if (mode === "short") {
|
||
// The frost ends at the status bar + 20 (measured: 79 pt on a 59 pt bar); the header's words
|
||
// start a little below that.
|
||
root.style.setProperty("--safe-t", Math.round(safeT + FROST_PAST) + "px");
|
||
root.style.setProperty("--safe-b", Math.max(0, Math.round(safeB - lost)) + "px");
|
||
// 像原生 App: no bands. The frost lightens what lies under it and the system's strip at the
|
||
// bottom is the page colour (#faf9f6 here, the manifest's too): on the page colour neither shows
|
||
// (measured: ≤ 1 level). The Bot list's own darker colour showed both as blocks — it wears the
|
||
// page colour here.
|
||
root.style.setProperty("--side", "var(--pane)");
|
||
root.classList.add("fit-short");
|
||
} else {
|
||
root.style.removeProperty("--safe-t");
|
||
root.style.removeProperty("--safe-b");
|
||
root.style.removeProperty("--side");
|
||
root.classList.remove("fit-short");
|
||
}
|
||
Object.assign(FIT, {mode, lost, safeT, safeB, screenW: landscape ? Math.max(sw, sh) : Math.min(sw, sh), screenH, innerH});
|
||
stripColor();
|
||
}
|
||
// How far below the status bar the header's words start when the system frosts the top.
|
||
const FROST_PAST = 26;
|
||
// What meets the system's strip: the page's own background is the showing view's (the remote
|
||
// screen's black, the list's colour…), so if the strip takes the page's colour it matches.
|
||
function stripColor() {
|
||
const root = document.documentElement, body = document.body;
|
||
// (The ruler holds the accent while it shows.)
|
||
if ($("ruler") || !body) return;
|
||
if (!root.classList.contains("fit-short")) {
|
||
root.style.removeProperty("background-color");
|
||
body.style.removeProperty("background-color");
|
||
return;
|
||
}
|
||
const v = document.querySelector(".view.on");
|
||
const c = v ? getComputedStyle(v).backgroundColor : "";
|
||
if (!c || c === "rgba(0, 0, 0, 0)") return;
|
||
root.style.backgroundColor = c;
|
||
body.style.backgroundColor = c;
|
||
}
|
||
// A text box let go: the keyboard bug leaves the page short — laid out again once, scroll kept.
|
||
function heal() {
|
||
const app = document.querySelector(".app");
|
||
if (!app) return;
|
||
const keep = [...document.querySelectorAll(".scroll")].map((x) => [x, x.scrollTop]);
|
||
app.style.display = "none"; void app.offsetHeight; app.style.display = "";
|
||
keep.forEach(([x, y]) => { x.scrollTop = y; });
|
||
FIT.healed++;
|
||
}
|
||
document.addEventListener("focusout", (e) => {
|
||
if (!e.target || !e.target.matches || !e.target.matches("input,textarea,[contenteditable]")) return;
|
||
setTimeout(() => {
|
||
const key = matchMedia("(orientation: landscape)").matches ? "l" : "p";
|
||
if (installed() && innerHeight < (FIT.tallest[key] || 0) - 4) heal();
|
||
requestAnimationFrame(fit);
|
||
}, 140);
|
||
});
|
||
addEventListener("resize", fit);
|
||
addEventListener("orientationchange", () => setTimeout(fit, 300));
|
||
addEventListener("pageshow", fit);
|
||
document.addEventListener("visibilitychange", () => { if (!document.hidden) fit(); });
|
||
fit();
|
||
// 設定 › 更新 › 畫面: what was measured, in words.
|
||
function fitWords() {
|
||
const f = FIT, ios = (navigator.userAgent.match(/OS (\d+)_(\d+)/) || []).slice(1).join(".");
|
||
const what = f.mode === "short" ? `iOS 少給了下面 ${f.lost} pt(系統自己畫),上面讓開霧面` : f.mode === "topbar" ? `狀態列佔了上面 ${f.lost} pt` : "整個螢幕都是 AnyBot 的";
|
||
return `${f.screenW}×${f.screenH},看得到 ${f.innerH};上 ${f.safeT}/下 ${f.safeB};${what}${ios ? `;iOS ${ios}` : ""}${installed() ? ";主畫面 App" : ";瀏覽器"}`;
|
||
}
|
||
// The ruler: tick marks every 10 pt from the top and from the bottom, the numbers in the middle,
|
||
// and a red band just past the page's bottom (seen: the strip below can be drawn on). A tap closes it.
|
||
function ruler() {
|
||
const old = $("ruler");
|
||
if (old) { old.remove(); return; }
|
||
fit();
|
||
const r = document.createElement("div");
|
||
r.id = "ruler";
|
||
let h = "";
|
||
// (Every mark in its own inline style: nothing else on the page may size it.)
|
||
const tick = (side, y) => `<i style="position:absolute;${side}:${y}px;${side === "top" ? "left" : "right"}:0;width:${y % 50 ? 12 : 26}px;height:1px;min-height:0;padding:0;background:var(--text)"></i>` +
|
||
(y % 20 ? "" : `<i style="position:absolute;${side}:${y - 7}px;${side === "top" ? "left" : "right"}:30px;font:600 var(--fs-caption)/1.2 var(--font);font-style:normal;background:var(--pane);padding:0 3px">${y}</i>`);
|
||
for (let y = 0; y <= 140; y += 10) h += tick("top", y) + tick("bottom", y);
|
||
h += `<div class="info">${esc(fitWords().split(";").join("\n"))}\n\n上面糊到哪一格、下面最後看得到哪一格?最下面那條有沒有變成強調色?截圖給我們。點一下關掉。</div>`;
|
||
h += `<div class="past">看到這條紅色=最下面還能畫</div>`;
|
||
r.innerHTML = h;
|
||
// (Does the system's strip at the bottom take the page's colour? While the ruler shows, the
|
||
// page wears the accent: a strip that turns with it does.)
|
||
const root = document.documentElement, accent = getComputedStyle(root).getPropertyValue("--accent").trim() || "orange";
|
||
root.style.backgroundColor = accent;
|
||
document.body.style.backgroundColor = accent;
|
||
r.onclick = () => { r.remove(); root.style.removeProperty("background-color"); document.body.style.removeProperty("background-color"); stripColor(); };
|
||
document.body.appendChild(r);
|
||
}
|
||
// iOS: the keyboard floats over the page instead of shrinking it; measure it and lift the composer.
|
||
if (window.visualViewport) {
|
||
const kb = () => {
|
||
// (Zoomed in with two fingers the visible part is smaller too: that isn't a keyboard.)
|
||
const k = visualViewport.scale > 1.01 ? 0 : Math.max(0, Math.round(innerHeight - visualViewport.height - visualViewport.offsetTop));
|
||
document.documentElement.style.setProperty("--kb", k + "px");
|
||
};
|
||
visualViewport.addEventListener("resize", kb);
|
||
visualViewport.addEventListener("scroll", kb);
|
||
}
|
||
document.addEventListener("visibilitychange", () => { if (document.hidden) { outOfView(); keepNow(); swapWhenAway(); return; } setTimeout(() => { picking = false; }, 1000); backInView(); kick(); if (S.view === "screen") startFrames(); });
|
||
addEventListener("online", kick);
|
||
addEventListener("offline", () => { if (S.token) netDown(true); });
|
||
addEventListener("pageshow", (e) => { if (e.persisted) kick(); });
|
||
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>
|