A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Add the start window's page and its generated whale
AdamPlatin1234adf78032888
diff --git a/app/scripts/start-assets.mjs b/app/scripts/start-assets.mjsnew file mode 100644index 00000000..91514e79--- /dev/null+++ b/app/scripts/start-assets.mjs@@ -0,0 +1,147 @@+// Writes the generated blocks of the start page in src/start from the plugin's client modules+// in ../ds-bot (read only, as scripts/icon.mjs does):+// - start.html, between <!-- whale --> markers: the Main Bot's whale from characterMarkup('whale',+// 'deepseek'), cut at the tail stock into two copies so the tail can move on its own. The mask+// is st-eyes, the clips st-tail-cut and st-torso-cut; the fill stays var(--bt-ink-deepseek).+// - start.css, between /* tokens */ markers: the DeepSeek theme's light and dark colors.+// - start.css, between /* springs */ markers: motion.js's springs as linear() curves.+// Usage: node scripts/start-assets.mjs [--check] (--check exits 1 when a block is stale and+// writes nothing)+import { readFileSync, writeFileSync } from 'node:fs'+import { CHARACTERS, characterMarkup, MASK_ID } from '../../ds-bot/src/client/characters.js'+import { INKS } from '../../ds-bot/src/client/inks.js'+import { allThemes, themeCss } from '../../ds-bot/src/client/themes.js'++const client = new URL('../../ds-bot/src/client/', import.meta.url)+const page = new URL('../src/start/', import.meta.url)++const THEME_TOKENS = ['--bt-main', '--bt-card', '--bt-ink', '--bt-ink-2', '--bt-line', '--bt-line-2', '--bt-hover', '--bt-accent', '--bt-accent-ink']+// The status colors are the same in both modes; the plugin's base sheet defines them.+const BASE_TOKENS = ['--bt-green', '--bt-danger']+const SPRINGS = ['shape', 'tap', 'pop', 'stretch', 'list']++// Wraps the one self-closing element that starts with `start` in <g id>.+function wrap(markup, id, start) {+ const at = markup.indexOf(start)+ if (at < 0 || markup.indexOf(start, at + 1) >= 0) throw new Error(`${id}: expected exactly one match`)+ const stop = markup.indexOf('/>', at) + 2+ return `${markup.slice(0, at)}<g id="${id}">${markup.slice(at, stop)}</g>${markup.slice(stop)}`+}+function group(markup, start) {+ const at = markup.indexOf(start)+ const tags = /<g[\s>]|<\/g>/gu+ tags.lastIndex = at+ let depth = 0+ for (let match = tags.exec(markup); match !== null; match = tags.exec(markup)) {+ depth += match[0] === '</g>' ? -1 : 1+ if (depth === 0) return markup.slice(at, match.index + 4)+ }+ throw new Error('unclosed group')+}++function rig() {+ const whale = CHARACTERS.whale+ const raw = characterMarkup('whale', 'deepseek').replaceAll(MASK_ID, 'st-eyes')+ if (!raw.includes('fill="var(--bt-ink-deepseek)"')) throw new Error('the whale no longer fills with var(--bt-ink-deepseek)')+ const mask = raw.slice(raw.indexOf('<mask'), raw.indexOf('</mask>') + 7)+ .replace('<g class="bt-gaze">', '<g id="gaze" class="bt-gaze">')+ .replace('<g class="bt-eyes" fill="#000">', '<g id="eye-pair" class="bt-eyes" fill="#000">')+ let layers = group(raw, '<g fill-rule="evenodd">')+ layers = wrap(layers, 'w-body', `<path d="${whale.body}"`)+ layers = wrap(layers, 'w-belly', `<path d="${whale.paints[0][0]}"`)+ layers = wrap(layers, 'w-shade', `<path d="${whale.shade}"`)+ layers = wrap(layers, 'w-light', `<path d="${whale.light}"`)+ layers = layers.replace('<g fill-rule="evenodd">', '<g id="whale-layers" fill-rule="evenodd">')+ // The cut runs from the notch behind the upper fluke down through the bottom contour at the+ // pivot (27.9, 61.1), where the tail turns. The tail copy reaches 4 units past the cut under+ // the torso, so tipping the flukes opens no gap; at rest the two copies draw the plain whale.+ const top = [32.45, 52.05]+ const bottom = [23.35, 70.15]+ const pivot = [27.9, 61.1]+ const length = Math.hypot(bottom[0] - top[0], bottom[1] - top[1])+ const normal = [-(bottom[1] - top[1]) / length, (bottom[0] - top[0]) / length]+ const notch = [top[0] - normal[0] * 4, top[1] - normal[1] * 4].map(n => n.toFixed(2))+ const tailCut = `M-100 -100H${top[0]}V${top[1]}L${notch[0]} ${notch[1]}L${pivot[0]} ${pivot[1]}L${bottom[0]} ${bottom[1]}L${bottom[0]} 200H-100Z`+ const torsoCut = `M${top[0]} -100H200V200H-100V${bottom[1]}H${bottom[0]}L${top[0]} ${top[1]}Z`+ return `<svg class="whale-svg" viewBox="0 0 100 100" aria-hidden="true" focusable="false"><defs>${mask}`+ + `<clipPath id="st-tail-cut" clipPathUnits="userSpaceOnUse"><path d="${tailCut}"/></clipPath>`+ + `<clipPath id="st-torso-cut" clipPathUnits="userSpaceOnUse"><path d="${torsoCut}"/></clipPath>${layers}</defs>`+ + '<g class="bt-b"><g mask="url(#st-eyes)"><g id="tail"><use href="#whale-layers" clip-path="url(#st-tail-cut)"/></g>'+ + '<g id="torso"><use href="#whale-layers" clip-path="url(#st-torso-cut)"/></g></g></g></svg>'+}++const rules = css => [...css.matchAll(/\{([^}]*)\}/gu)].map(([, body]) => new Map(body.split(';').filter(Boolean).map(item => item.split(/:(.*)/su).slice(0, 2))))+function pick(vars, names, from) {+ return names.map((name) => {+ if (!vars.has(name)) throw new Error(`${from} no longer sets ${name}`)+ return `${name}:${vars.get(name)}`+ }).join(';')+}++function tokens() {+ const [light, dark] = rules(themeCss(allThemes().deepseek))+ const base = readFileSync(new URL('styles.js', client), 'utf8').match(/^body\{(--bt-[^}]*)\}$/mu)+ if (!base) throw new Error('styles.js: the base body rule was not found')+ const [ink, inkDark] = INKS.deepseek+ return [+ '/* Generated from the DeepSeek theme in ds-bot/src/client/themes.js, inks.js and styles.js by scripts/start-assets.mjs; do not edit. */',+ `:root{color-scheme:light dark;${pick(light, THEME_TOKENS, 'themeCss')};--bt-ink-deepseek:${ink};${pick(rules(`{${base[1]}}`)[0], BASE_TOKENS, 'styles.js')}}`,+ `@media (prefers-color-scheme:dark){:root{${pick(dark, THEME_TOKENS, 'themeCss')};--bt-ink-deepseek:${inkDark}}}`,+ ]+}++// motion.js imports React for its hooks; its springs are plain arithmetic, so the module runs+// here with the React names stubbed out.+async function motion() {+ const source = readFileSync(new URL('motion.js', client), 'utf8')+ const imports = source.match(/^import .*$/gmu) ?? []+ const react = imports.length === 1 ? imports[0].match(/^import \{([^}]*)\} from 'react'\r?$/u) : null+ if (!react) throw new Error('motion.js: expected its only import to be from react')+ const stub = `const {${react[1].replaceAll(' as ', ': ')}} = {}`+ return import(`data:text/javascript,${encodeURIComponent(source.replace(imports[0], stub))}`)+}++async function springs() {+ const curves = await motion()+ return [+ '/* Generated from ds-bot/src/client/motion.js by scripts/start-assets.mjs; do not edit. */',+ ':root {',+ ...SPRINGS.flatMap((name) => {+ const curve = curves[`SPRING_${name.toUpperCase()}`]+ if (!curve) throw new Error(`motion.js no longer exports SPRING_${name.toUpperCase()}`)+ return [` --spring-${name}: ${curve.easing};`, ` --spring-${name}-ms: ${curve.duration}ms;`]+ }),+ '}',+ ]+}++// Replaces what lies between the two markers; a block of lines takes the file's own line ends,+// which git may have turned into CRLF on checkout.+function between(text, open, close, block) {+ const eol = text.includes('\r\n') ? '\r\n' : '\n'+ const body = Array.isArray(block) ? `${eol}${block.join(eol)}${eol}` : block+ const a = text.indexOf(open)+ const b = text.indexOf(close, a + open.length)+ if (a < 0 || b < 0) throw new Error(`markers ${open} ${close} not found`)+ return `${text.slice(0, a + open.length)}${body}${text.slice(b)}`+}++const files = {+ 'start.html': html => between(html, '<!-- whale -->', '<!-- /whale -->', rig()),+ 'start.css': async css => between(between(css, '/* tokens */', '/* /tokens */', tokens()), '/* springs */', '/* /springs */', await springs()),+}+const check = process.argv.includes('--check')+const stale = []+for (const [name, generate] of Object.entries(files)) {+ const file = new URL(name, page)+ const text = readFileSync(file, 'utf8')+ const next = await generate(text)+ if (next === text) continue+ stale.push(name)+ if (!check) writeFileSync(file, next)+}+if (check && stale.length) {+ console.error(`start page: stale generated blocks in ${stale.join(', ')}; run node scripts/start-assets.mjs`)+ process.exit(1)+}+console.log(check ? 'start page: generated blocks are current' : stale.length ? `start page: wrote ${stale.join(', ')}` : 'start page: nothing to write')diff --git a/app/src/start/start.css b/app/src/start/start.cssnew file mode 100644index 00000000..159f6dc6--- /dev/null+++ b/app/src/start/start.css@@ -0,0 +1,246 @@+/* DeepSeek Bot start window. Geometry in DIP of the 720 x 540 window content (40 px band on top). */+/* tokens */+/* Generated from the DeepSeek theme in ds-bot/src/client/themes.js, inks.js and styles.js by scripts/start-assets.mjs; do not edit. */+:root{color-scheme:light dark;--bt-main:#fcfcfc;--bt-card:#ffffff;--bt-ink:#141414;--bt-ink-2:rgba(20,20,20,0.6);--bt-line:rgba(20,20,20,0.08);--bt-line-2:rgba(20,20,20,0.15);--bt-hover:rgba(119,119,119,.09);--bt-accent:#4d6bfe;--bt-accent-ink:#ffffff;--bt-ink-deepseek:#4D6BFE;--bt-green:#00c972;--bt-danger:#e02135}+@media (prefers-color-scheme:dark){:root{--bt-main:#141414;--bt-card:#1f1f1f;--bt-ink:#f2f2f2;--bt-ink-2:rgba(242,242,242,0.6);--bt-line:rgba(242,242,242,0.08);--bt-line-2:rgba(242,242,242,0.15);--bt-hover:rgba(160,160,160,.12);--bt-accent:#5b7bff;--bt-accent-ink:#141414;--bt-ink-deepseek:#6A84FF}}+/* /tokens */+:root{--font:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei UI",system-ui,sans-serif;--mono:ui-monospace,Consolas,monospace;--u:.88px}+/* springs */+/* Generated from ds-bot/src/client/motion.js by scripts/start-assets.mjs; do not edit. */+:root {+ --spring-shape: linear(0.0000,0.0510,0.1692,0.3153,0.4639,0.6001,0.7163,0.8102,0.8823,0.9350,0.9717,0.9955,1.0098,1.0171,1.0198,1.0195,1.0175,1.0147,1.0117,1.0089,1.0064,1.0044,1.0028,1.0016,1.0000);+ --spring-shape-ms: 420ms;+ --spring-tap: linear(0.0000,0.0541,0.1776,0.3279,0.4784,0.6141,0.7281,0.8187,0.8874,0.9369,0.9709,0.9928,1.0057,1.0124,1.0150,1.0149,1.0134,1.0112,1.0089,1.0067,1.0048,1.0033,1.0021,1.0013,1.0000);+ --spring-tap-ms: 290ms;+ --spring-pop: linear(0.0000,0.0698,0.2385,0.4520,0.6677,0.8566,1.0027,1.1009,1.1539,1.1695,1.1578,1.1293,1.0931,1.0566,1.0245,0.9997,0.9830,0.9740,0.9713,0.9732,0.9781,0.9842,0.9904,0.9958,1.0000);+ --spring-pop-ms: 430ms;+ --spring-stretch: linear(0.0000,0.0740,0.2474,0.4594,0.6666,0.8422,0.9740,1.0602,1.1060,1.1202,1.1126,1.0924,1.0670,1.0419,1.0204,1.0042,0.9934,0.9875,0.9856,0.9863,0.9887,0.9917,0.9947,0.9974,1.0000);+ --spring-stretch-ms: 560ms;+ --spring-list: linear(0.0000,0.0138,0.0503,0.1030,0.1666,0.2367,0.3099,0.3836,0.4556,0.5244,0.5891,0.6489,0.7034,0.7525,0.7962,0.8347,0.8681,0.8969,0.9215,0.9421,0.9592,0.9733,0.9846,0.9936,1.0000);+ --spring-list-ms: 190ms;+}+/* /springs */++[hidden]{display:none!important}+html,body{margin:0;height:100%;background:transparent}+/* The stage hangs 80 px below the window until a card needs the sheet; body clips it rather+ than scrolls, so no focus, scroll anchoring or restored scroll position can shift the page. */+html{overflow:hidden}+html[data-frame=system]{background:var(--bt-main)}+body{position:relative;overflow:clip;font:14px/22px var(--font);color:var(--bt-ink);-webkit-user-select:none;user-select:none;cursor:default}+html:not([data-start]) body>:not(.band){visibility:hidden}+p,h1,h2,ol,ul{margin:0;padding:0}+code{font-family:var(--mono);font-size:inherit}+.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}+.band{position:fixed;inset:0 0 auto;height:40px;-webkit-app-region:drag;app-region:drag}+html[data-frame=system] .band{display:none}++/* stage: everything that moves with the later-start shift */+.stage{position:absolute;left:calc(50% - 360px);top:0;width:720px;height:100%}+html[data-frame=system] .stage{top:-24px}+html:is([data-start=later],[data-start=moving]){--u:.64px}+/* Until a card needs the sheet, the whale, its line and the hint sit 80 px lower, at the+ window's visual centre (an integer translation, so the text stays on whole pixels). */+html:not([data-up]) .stage{translate:0 80px}+/* The whale's line: one centred line under the waterline, the only voice on the page. Every+ line of text sits on whole pixels in an untransformed box and never wraps (the copy is+ written to fit; the ellipsis is a last resort). */+.voice{position:absolute;left:48px;top:194px;width:624px;height:20px;text-align:center;font-size:15px;line-height:20px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;opacity:0;transition:opacity .16s ease-in}+.voice[data-on]{opacity:1;transition:opacity .16s ease-out}+/* The clock: top right, where the title row ended, outside the stage so it never moves with+ the group; in --bt-ink-2, the lightest text the design allows on Mica (note §10). */+.elapsed{position:absolute;right:calc(50% - 312px);top:54px;width:6.5em;height:18px;text-align:right;white-space:nowrap;font-size:13px;line-height:18px;color:var(--bt-ink-2);font-variant-numeric:tabular-nums;opacity:0;transition:opacity .16s}+html[data-elapsed] .elapsed{opacity:1;transition:opacity .22s ease-out}+html[data-frame=system] .elapsed{top:30px}+html:is([data-start=later],[data-start=moving]) :is(.elapsed,.water,.trace){display:none}++/* lane: the clipped water above the line at y 180 */+.lane{position:absolute;left:48px;top:76px;width:624px;height:104px;overflow:clip;pointer-events:none}+.whale-x{position:absolute;left:76px;top:28px;width:88px;height:88px}+html:is([data-start=later],[data-start=moving]) .whale-x{left:280px;top:47px;width:64px;height:64px}+.whale-gaze,.whale,.whale-move,.whale-loop{width:100%;height:100%}+/* .whale-gaze scales only for the breath at rest (whale.js), around the same pivot. */+.whale-gaze,.whale,.whale-move,.whale-loop{transform-origin:49.95% 79%}+.whale-gaze{translate:calc(var(--gx,0) * 4.6 * var(--u)) calc(var(--gy,0) * 2.3 * var(--u));transition:translate .18s ease-out}+.whale-svg{display:block;width:100%;height:100%;overflow:visible;forced-color-adjust:none}+#tail{transform-box:view-box;transform-origin:27.9px 61.1px}+.bt-eye,#eye-pair,#gaze{transform-box:fill-box;transform-origin:center}+#gaze{transform:translate(calc(var(--gx,0) * 12%),calc(var(--gy,0) * 11%));transition:transform .18s ease-out}+.whale-hit{position:absolute;left:calc(var(--hx,168px) - 58px);top:105px;width:116px;height:86px;border-radius:50%}+html:is([data-start=later],[data-start=moving]) .whale-hit{left:318px;top:124px;width:84px;height:63px}+.fx{position:absolute;inset:0;pointer-events:none}+.ripple{position:absolute;left:calc(var(--rx,168px) - 28px);top:174px;width:56px;height:12px;box-sizing:border-box;border:1.5px solid var(--bt-line-2);border-radius:50%;opacity:0}++/* Progress is where the whale is. The waterline is only the surface it rests on (faint, soft at+ both ends, nothing drawn on it); a stop the whale has left keeps a resting ring, which never+ moves again until the hand-off fades it. */+.water{position:absolute;left:48px;top:180px;width:624px;height:1px;background:linear-gradient(90deg,transparent,var(--bt-line) 12% 88%,transparent)}+.trace{position:absolute;top:174px;width:56px;height:12px;box-sizing:border-box;border:1px solid var(--bt-line-2);border-radius:50%;opacity:0}+.trace:nth-child(1){left:152px}+.trace:nth-child(2){left:344px}+.trace[data-on]{opacity:.5}+.track{list-style:none}+/* step marks of the copying card */+.mark{position:relative;flex:none;width:16px;height:16px;border-radius:50%;box-sizing:border-box;border:1.5px solid var(--bt-line-2);transition:border-color .12s}+.mark .dot{position:absolute;left:50%;top:50%;width:6px;height:6px;margin:-3px;border-radius:50%;background:var(--bt-ink);opacity:0;transition:opacity .12s}+.mark svg{position:absolute;left:-1.5px;top:-1.5px;width:16px;height:16px;opacity:0;overflow:visible}+.mark circle{stroke:none}+.mark path{fill:none;stroke:#fff;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}+.check circle{fill:var(--bt-green)}+[data-state=active]>.mark{border-color:var(--bt-ink)}+[data-state=active]>.mark .dot{opacity:1}+[data-state=done]>.mark{border-color:transparent}+[data-state=done]>.mark .check{opacity:1}+html[data-shimmer] .voice[data-on]>span{color:transparent;background:linear-gradient(90deg,var(--bt-ink) 0 40%,var(--bt-ink-2) 50%,var(--bt-ink) 60% 100%) 0 0/300% 100%;-webkit-background-clip:text;background-clip:text;animation:bt-shimmer 2.2s steps(60) infinite}+@keyframes bt-shimmer{from{background-position:100% 0}to{background-position:0 0}}++/* The hint row: one grey line that prepares the user for what comes next, or the log button. */+.caption{position:absolute;left:48px;top:220px;width:624px;height:28px;display:flex;align-items:center;justify-content:center;gap:8px;font-size:13px;line-height:18px;color:var(--bt-ink-2)}+.caption-text{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.caption>*{opacity:0;filter:blur(6px);transition:opacity .16s,filter .16s}+.caption>[data-on]{opacity:1;filter:none;transition:opacity .22s ease-out,filter .22s ease-out}+.caption>.btn[data-on]{transition:opacity .22s ease-out .09s,filter .22s ease-out .09s,scale var(--spring-tap-ms) var(--spring-tap) .09s}+@starting-style{.caption>.btn[data-on]{scale:.96}}++/* sheet: one surface that every card morphs in and out of */+.sheet{position:absolute;left:48px;top:260px;width:624px;height:calc(100% - 304px)}+.sheet-edge,.sheet-fill{position:absolute;inset:0;opacity:0;clip-path:inset(0 0 100% 0 round 12px)}+.sheet-edge{background:var(--bt-line)}+.sheet-fill{background:var(--bt-card)}+.sheet-body{position:absolute;inset:0}+.lead{font-size:14px;line-height:22px}+.small{font-size:13px;line-height:18px;color:var(--bt-ink-2)}+.dim{color:var(--bt-ink-2)}+.ink{color:var(--bt-ink)}+.danger{color:var(--bt-danger)}+.card{position:absolute;inset:0 0 auto;max-height:100%;box-sizing:border-box;padding:14px 16px;display:flex;flex-direction:column;transition:opacity .22s ease-out .07s,filter .22s ease-out .07s}+@starting-style{.card{opacity:0;filter:blur(6px)}}+.card-scroll,.log{scrollbar-width:thin;scrollbar-color:var(--bt-line-2) transparent}+.card-scroll{position:relative;min-height:0;flex:0 1 auto;overflow:auto}+.card-scroll>*+*{margin-top:6px}+.card-scroll>.card-actions{margin-top:12px}+.card-title{font-size:15px;line-height:20px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.card-actions{flex:none;display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-top:12px}+.card>.card-actions:first-child{margin-top:0}+.card-actions .foot,.card-actions .eta{margin-left:auto}+.foot{font-size:13px;line-height:18px;color:var(--bt-ink-2)}+.card>.foot,.miss{margin-top:8px}+.miss{font-size:13px;line-height:18px;color:var(--bt-danger)}+:is(.miss,.banner,.log,.confirm,.models,.more,[data-u]):not([hidden]){transition:opacity .22s ease-out,filter .22s ease-out}+@starting-style{:is(.miss,.banner,.log,.confirm,.models,.more,[data-u]):not([hidden]){opacity:0;filter:blur(6px)}}+/* Opened, the import card's body fits the sheet at 540 px with these gaps; a model list+ opened under it scrolls inside the card. */+.more{margin-top:4px;padding-top:5px;border-top:1px solid var(--bt-line)}+.more>*+*{margin-top:4px}+.card[data-kind=import] .card-scroll>*+*{margin-top:4px}+.extra-row{display:flex;gap:10px;align-items:baseline;flex-wrap:wrap}+.model-row{display:flex;gap:8px;align-items:baseline}+.models{list-style:none}+.models .btn{width:100%;justify-content:flex-start;border-radius:8px;background:none;height:30px;font-size:13px}+.models .btn:hover{background:var(--bt-hover)}+.opts{display:flex;gap:20px;font-size:13px;line-height:18px}+.opts label{display:inline-flex;align-items:center;gap:6px;cursor:pointer}+.opts input{margin:0;width:14px;height:14px;accent-color:var(--bt-accent)}+.steps{position:relative;list-style:none}+.steps li{display:flex;align-items:center;gap:10px;height:28px;align-items:flex-start;padding-top:2px;box-sizing:border-box;font-size:13px;line-height:18px;color:var(--bt-ink-2);font-variant-numeric:tabular-nums}+.steps li .mark{margin-top:1px}+.steps li[data-state=active]{color:var(--bt-ink)}+.card[data-confirm] .steps li:not([data-state=active]){display:none}+.card[data-confirm] .stop,.card:not([data-confirm]) [data-confirm]{display:none}+.copy-steps{position:relative}+.copy-steps .bar{position:absolute;left:26px;right:0;top:calc(var(--step,0) * 28px + 22px)}+.card[data-confirm] .copy-steps .bar{top:22px}+.bar{height:4px;border-radius:2px;background:var(--bt-hover);overflow:hidden}+.bar-fill{display:block;height:100%;background:var(--bt-accent);transform-origin:0 50%;scale:0 1}+.banner{border-radius:12px;background:var(--bt-hover);padding:12px 14px}+.card-scroll>.banner{margin-top:10px}+.banner+.card-actions{margin-top:10px}+.banner-row{display:flex;align-items:center;gap:12px}+.banner-row .lead{flex:1 1 auto}+.banner-down,.banner>.small,.banner-fail{margin-top:8px}+.banner-line{display:flex;gap:12px;justify-content:space-between;font-variant-numeric:tabular-nums}+.banner-down .bar{margin-top:6px}+.banner-fail{display:flex;align-items:center;gap:8px}+.banner-fail .danger{margin-right:auto}+.log{margin-top:12px;border-radius:8px;background:var(--bt-hover);height:168px;overflow:auto;-webkit-user-select:text;user-select:text}+.log pre{margin:0;padding:10px 12px;font:13px/18px var(--mono);color:var(--bt-ink-2);white-space:pre-wrap;word-break:break-all}++/* buttons: .bt-send (primary), .bt-soft, .bt-soft-sm and a text link, ui-standard 10.1 */+.btn{display:inline-flex;align-items:center;justify-content:center;gap:4px;flex:none;height:36px;padding:0 16px;border:0;border-radius:999px;background:var(--bt-hover);color:var(--bt-ink);font:inherit;font-size:14px;line-height:20px;white-space:nowrap;cursor:pointer;transition:background-color .12s,color .12s,scale var(--spring-tap-ms) var(--spring-tap)}+.btn:hover{background:color-mix(in srgb,var(--bt-hover),var(--bt-ink) 6%)}+.btn:active{scale:.96}+.btn[data-look=primary]{height:40px;background:var(--bt-accent);color:var(--bt-accent-ink)}+.btn[data-look=primary]:hover{background:color-mix(in srgb,var(--bt-accent),var(--bt-ink) 10%)}+.btn[data-look=small]{height:28px;padding:0 12px;font-size:13px;line-height:18px}+.btn[data-look=link]{height:auto;padding:0 2px;border-radius:4px;background:none;color:var(--bt-ink);font-size:13px;line-height:18px;text-decoration:underline;text-decoration-color:var(--bt-line-2);text-underline-offset:3px}+.btn[data-look=link]:hover{background:var(--bt-hover)}+.btn.danger{color:var(--bt-danger)}+.btn:focus-visible{outline:2px solid var(--bt-accent);outline-offset:2px}+.btn:focus:not(:focus-visible){outline:none}+.disclose{text-decoration:none!important;color:var(--bt-ink-2)!important}+.disclose svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round;transition:rotate var(--spring-tap-ms) var(--spring-tap)}+.disclose[aria-expanded=true] svg{rotate:180deg}++.note{position:absolute;left:calc(50% - 312px);top:calc(100% - 36px);font-size:13px;line-height:18px;color:var(--bt-ink-2)}+html:is([data-start=later],[data-start=moving]) .note{display:none}+/* A work area under 588 px gets a 500 px window: the stage rises 8 px and the sheet still ends+ above the footer. */+@media (max-height:520px){.stage{top:-8px}html[data-frame=system] .stage{top:-32px}.sheet{height:calc(100% - 296px)}.elapsed{top:46px}html[data-frame=system] .elapsed{top:22px}}++/* entrance, keyed on data-start (no JS timing) */+@keyframes bt-veil{from{opacity:0;filter:blur(6px)}}+@keyframes bt-enter-first{from{transform:translateY(64px) rotate(-12deg)}}+@keyframes bt-enter-later{from{transform:translateY(48px)}}+@keyframes bt-wake{0%{transform:scaleY(.05)}60%{transform:scaleY(1.06)}}+@keyframes bt-flick-in{0%,100%{transform:none}35%{transform:rotate(-10deg)}70%{transform:rotate(8deg)}}+@keyframes bt-ripple-scale{from{scale:.5}to{scale:1.6}}+@keyframes bt-ripple-fade{from{opacity:.9}to{opacity:0}}+html[data-start=first]:not([data-resume],[data-entered]) .whale-move{animation:bt-enter-first var(--spring-stretch-ms) var(--spring-stretch) backwards}+html[data-start=first]:not([data-resume],[data-entered]) .bt-eye{animation:bt-wake .16s ease-out .36s backwards}+html[data-start=first]:not([data-resume],[data-entered],[data-tier=quiet]) #tail{animation:bt-flick-in .4s ease-in-out .3s}+html[data-start=first]:not([data-resume],[data-settled],[data-tier=quiet]) .ripple{animation:bt-ripple-scale var(--spring-shape-ms) var(--spring-shape) .12s backwards,bt-ripple-fade .56s linear .12s}+html[data-start=first]:not([data-resume],[data-settled]) .voice{animation:bt-veil .22s ease-out .16s backwards}+html[data-start=first]:not([data-resume],[data-settled]) .water{animation:bt-veil .22s ease-out .22s backwards}+html[data-start=first]:not([data-resume],[data-settled]) .note{animation:bt-veil .22s ease-out .42s backwards}+html:is([data-start=later],[data-start=moving]):not([data-resume],[data-entered]) .whale-move{animation:bt-enter-later var(--spring-tap-ms) var(--spring-tap) backwards}+html:is([data-start=later],[data-start=moving]):not([data-resume],[data-settled]) .voice{animation:bt-veil .22s ease-out .06s backwards}++/* state loops, keyed on data-whale and data-tail; plugin keyframes (styles.js:84-105) in px via --u */+html[data-whale=searching] .whale-loop{animation:bt-seek 1s ease-in-out infinite}+html[data-whale=searching] #eye-pair{animation:bt-scan 1.6s ease-in-out infinite}+html[data-whale=working] .whale-loop{animation:bt-bob 1.6s ease-in-out infinite}+html[data-whale=working] .bt-eye{animation:bt-blink 2.4s ease-in-out infinite}+html[data-whale=pondering] .whale-loop{animation:bt-ponder 2.2s ease-in-out infinite}+html[data-whale=pondering] .bt-eye{animation:bt-squint 2.2s ease-in-out infinite}+html[data-whale=sending] .whale-loop{animation:bt-dash 1.1s cubic-bezier(.4,0,.2,1) infinite}+html[data-tail=beat]:not([data-tier=quiet]) #tail{animation:bt-tail-beat 1.1s ease-in-out -.55s infinite alternate}+html[data-tail=dash]:not([data-tier=quiet]) #tail{animation:bt-tail-dash .55s ease-in-out -.275s infinite alternate}+@keyframes bt-seek{0%,100%{transform:rotate(-4deg)}50%{transform:translateY(calc(-2.9 * var(--u))) rotate(-1deg)}}+@keyframes bt-scan{0%,100%{transform:translateX(-12%)}50%{transform:translateX(12%)}}+@keyframes bt-bob{0%,100%{transform:none}30%{transform:translateY(calc(-2.3 * var(--u))) rotate(-5deg)}65%{transform:rotate(4deg)}}+@keyframes bt-blink{0%,42%,50%,100%{transform:none}46%{transform:scaleY(.03)}48%{transform:scaleY(1.06)}}+@keyframes bt-ponder{0%,100%{transform:rotate(4deg)}50%{transform:translateY(calc(-1.7 * var(--u))) rotate(7deg)}}+@keyframes bt-squint{0%,100%{transform:translate(0,-4%) scaleY(.7)}50%{transform:translate(5%,-5%) scaleY(.78)}}+@keyframes bt-dash{0%,100%{transform:none}35%{transform:translateX(calc(8.3 * var(--u))) rotate(7deg)}55%{transform:translateX(calc(-1.8 * var(--u))) rotate(-3deg)}}+@keyframes bt-tail-beat{from{transform:rotate(-5deg)}to{transform:rotate(5deg)}}+@keyframes bt-tail-dash{from{transform:rotate(-8deg)}to{transform:rotate(8deg)}}++/* hand-off: window-level content fades */+html[data-exit~=caption] :is(.elapsed,.caption),html[data-exit~=all] :is(.voice,.water,.fx .trace,.sheet,.note){opacity:0;transition:opacity .16s}+html[data-hidden] *{animation-play-state:paused!important}++/* reduced motion (ui-standard 9.6, styles.js:106): static whale, fades only */+:root[data-eyes=squint] .bt-eye{transform:translate(0,-4%) scaleY(.7)}+:root[data-eyes=heavy] .bt-eye{transform:translateY(1.5px) scaleY(.55)}+:root[data-eyes=happy] .bt-eye{transform:scaleY(0)}+:root[data-eyes=happy] .bt-eye-happy{opacity:1}+@media (prefers-reduced-motion:reduce){+:root :is(.whale-x,.whale-gaze,.whale,.whale-move,.whale-loop,#tail,#gaze,#eye-pair,.bt-eye,.bt-eye-happy,.ripple,.trace,.stage){animation:none!important;transition:none!important}+:root :is(.voice,.water,.note){animation:none!important}+:root .voice>span{animation:none!important;background:none!important;color:var(--bt-ink)!important}+:root :is(.voice,.caption>*,.elapsed,.card,.miss,.banner,.log,.confirm,.models,[data-u]){filter:none!important;scale:none!important;transition-property:opacity!important;transition-duration:.12s!important;transition-delay:0s!important}+:root .btn:active{scale:none}+:root[data-exit~=lane] .lane{opacity:0;transition:opacity .12s}+}++@media (forced-colors:active){.sheet-edge{background:CanvasText}.sheet-fill{background:Canvas}.btn{border:1px solid ButtonText}.bar-fill{background:Highlight}.water{background:CanvasText}.trace{border-color:CanvasText}}diff --git a/app/src/start/start.html b/app/src/start/start.htmlnew file mode 100644index 00000000..7cb241fd--- /dev/null+++ b/app/src/start/start.html@@ -0,0 +1,52 @@+<!doctype html>+<html lang="zh-CN">+<head>+<meta charset="utf-8">+<meta http-equiv="Content-Security-Policy" content="default-src 'self'; base-uri 'none'; object-src 'none'">+<meta name="color-scheme" content="light dark">+<meta name="viewport" content="width=device-width">+<title>DeepSeek Bot</title>+<link rel="stylesheet" href="start.css">+<script type="module" src="start.js"></script>+</head>+<body>+<div class="band" aria-hidden="true"></div>+<span class="elapsed" aria-hidden="true"></span>+<main class="stage">+<div class="water" aria-hidden="true"></div>+<div class="lane"><div class="whale-x"><div class="whale-gaze"><div class="whale"><div class="whale-move"><div class="whale-loop">+<!-- whale --><svg class="whale-svg" viewBox="0 0 100 100" aria-hidden="true" focusable="false"><defs><mask id="st-eyes" maskUnits="userSpaceOnUse" x="-100" y="-100" width="300" height="300"><rect x="-100" y="-100" width="300" height="300" fill="#fff"/><g id="gaze" class="bt-gaze"><g id="eye-pair" class="bt-eyes" fill="#000"><g transform="translate(72.5 48.4) rotate(-15.8)"><rect class="bt-eye" x="-4.65" y="-11.5" width="9.3" height="23" rx="4.65"/></g><g transform="translate(85.6 43.4) rotate(-21.2)"><rect class="bt-eye" x="-3.5" y="-11.45" width="7" height="22.9" rx="3.5"/></g><g transform="translate(72.5 48.4) rotate(-15.8)"><path class="bt-eye-happy" opacity="0" d="M-5.766 3.22Q0 -9.66 5.766 3.22" fill="none" stroke="#000" stroke-width="4.65" stroke-linecap="round"/></g><g transform="translate(85.6 43.4) rotate(-21.2)"><path class="bt-eye-happy" opacity="0" d="M-4.34 3.206Q0 -9.617999999999999 4.34 3.206" fill="none" stroke="#000" stroke-width="3.5" stroke-linecap="round"/></g></g></g></mask><clipPath id="st-tail-cut" clipPathUnits="userSpaceOnUse"><path d="M-100 -100H32.45V52.05L36.02 53.85L27.9 61.1L23.35 70.15L23.35 200H-100Z"/></clipPath><clipPath id="st-torso-cut" clipPathUnits="userSpaceOnUse"><path d="M32.45 -100H200V200H-100V70.15H23.35L32.45 52.05Z"/></clipPath><g id="whale-layers" fill-rule="evenodd"><g id="w-body"><path d="M65.3 20.9l5.1 .1 4.8 .9 4.8 1.7 4.3 2.3 3.8 3.1 3 3.4 2.3 3.8 1.6 4.3 .9 4.3 0 4.8-.8 4.8-1.4 4.3-2.3 4.3-3.2 4.3-3.4 3.3-4.3 3.1-7.2 3.5-7.6 1.7-7.2 .1-9.6-1.6-3.3-1-2.9-1.7-8.8-8.9-6-4.7-3.3-.5-7.7 1.1-4.8-.1-4.7-1.2-1.9-1.2-1-1-.5-1.5 .4-1.4 1.1-1.3 1.9-1.3 4.7-1.5 7.7-.6 1.1-.5 .7-1 0-1.4-2.8-7.2-1.2-5.3-.1-4.3 .4-1.4 .9-1.2 1.9-.2 2 1 2.2 2.3 2.2 3.4 3.2 7.6 1.9 9.7 .5-.1 1.1-7.2 1.8-4.8 3.2-5.2 3.9-4.3 4.9-3.9 5.6-2.9 5.8-1.9z" fill="var(--bt-ink-deepseek)"/></g><g id="w-belly"><path d="M93.3 55.8l1-.3 .1 1.2-2.4 5.3-3.4 4.8-3.8 3.8-4.8 3.4-5.7 2.8-4.8 1.5-4.8 .4 20.1-17.4 5.2-3.7z" fill="#fff" fill-opacity="1"/></g><g id="w-shade"><path d="M88.6 29.5l2.4 2.9 1.9 2.8 2.4 6.3 .5 3.3 .1 5.3-1.5 6.6-1.9 4.3-2 3.3-4.8 5.4-5.7 4.3-7.2 3.3-6.2 1.5-6.7 .1-3.3-.2-9.6-1.8-3.3-1.5-2.4-1.9-8.6-8.9-5.3-3.9-3.3-.1-2.9 .2-3.3 .8-5.8 0-4.3-1-2.9-1.9 .6-.6 3.8-1.3 10.5-2.5 4.3 .9 1.4-.1 2.2-1.7 .5-1.4-.3-1.5-1.2-1.4-2.2-1.4-1.2-1.9-.6-12 .4-3.3 .5-.5 2.9 3.8 2.4 4.8 1.9 5.7 .7 5.8 .7 2.8 2.1 2.4 2.7 5.5 3.8 4.3 2.9 2.2 3.3 1 3.4-.4 6.2-3 7.1-4.5 7.3-5.6 6.6-5.9 5.9-6.5 3.7-5.3 1.7-4.2 .1-2.9z" fill="#000" fill-opacity=".14"/></g><g id="w-light"><path d="M55.6 22.8l1.9-.3 1.5 .3 .6 1 .1 .9-2 4.3-3.8 5.3-5.8 6.2-5.4 4.4-4.8 2.3-1.4 0-1.2-.5-.8-1.9 .5-3.3 2.5-4.8 3.3-4.3 2.4-2.4 5.3-3.9zM19.3 28.1l-1.4 2 .3-1.1zM21.7 49.1l.6 .5-.3 .5-.8 0zM35.8 52l1.2-.4 .9 .7 .7 1.6-.4 .9-1.2 .1-2.6-.5zM7.2 52.9l-2.9 2.9 1.2-1.6z" fill="#fff" fill-opacity=".16"/></g></g></defs><g class="bt-b"><g mask="url(#st-eyes)"><g id="tail"><use href="#whale-layers" clip-path="url(#st-tail-cut)"/></g><g id="torso"><use href="#whale-layers" clip-path="url(#st-torso-cut)"/></g></g></g></svg><!-- /whale -->+</div></div></div></div></div></div>+<div class="whale-hit" aria-hidden="true"></div>+<div class="fx" aria-hidden="true"><span class="trace"></span><span class="trace"></span><span class="ripple"></span></div>+<ol class="track sr" data-t-label="track.label">+<li class="station" data-phase="data" data-state="pending"><span data-t="phase.data"></span> <span class="sr"></span></li>+<li class="station" data-phase="engine" data-state="pending"><span data-t="phase.engine"></span> <span class="sr"></span></li>+<li class="station" data-phase="team" data-state="pending"><span data-t="phase.team"></span> <span class="sr"></span></li>+</ol>+<p class="voice"><span></span></p>+<p class="caption"><span class="caption-text"></span><button class="btn" data-look="small" data-act="openLogs" data-t="openLogs" hidden></button></p>+<section class="sheet">+<div class="sheet-edge"></div><div class="sheet-fill"></div>+<div class="sheet-body">+<section class="card" data-kind="recommend" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.{reason}"></h2><p class="lead"><span data-t="card.reason.{reason}"></span> <span class="ask" data-t="card.recommend.ask"></span></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="rec" data-rec data-t="card.recommend.use"></button><button class="btn" data-look="soft" data-act="answer" data-detail="keep" data-keep data-t="card.recommend.keep"></button><button class="btn" data-look="link" data-act="pick" data-rec data-t="card.recommend.other"></button><button class="btn" data-look="primary" data-act="pick" data-norec data-t="pickOther"></button><p class="foot" data-t="card.footnote"></p></div></section>+<section class="card" data-kind="rejected" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.rejected"></h2><p class="lead" data-t="card.rejected.{reason}"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="pick" data-t="card.picked.repick"></button><button class="btn" data-look="soft" data-act="answer" data-detail="rec" data-rec data-t="card.recommend.use"></button><button class="btn" data-look="soft" data-act="answer" data-detail="keep" data-keep data-t="card.recommend.keep"></button><p class="foot" data-t="card.footnote"></p></div></section>+<section class="card" data-kind="missing" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.missing"></h2><p class="lead" data-t="card.missing"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="retry" data-t="retry"></button><button class="btn" data-look="soft" data-act="pick" data-t="card.missing.relocate"></button><button class="btn" data-look="soft" data-act="freshStart" data-t="freshStart"></button></div><p class="miss" data-t="card.missing.retryMissed" hidden></p><p class="foot" data-t="card.footnote"></p></section>+<section class="card" data-kind="picked" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.picked"></h2><p class="lead" data-t="card.picked"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="use" data-t="card.picked.use"></button><button class="btn" data-look="soft" data-act="pick" data-t="card.picked.repick"></button><p class="foot" data-t="card.footnote"></p></div></section>+<section class="card" data-kind="import" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.import"></h2><p class="lead" data-t="import.lead"></p><p class="small extra-row"><span data-t="import.extra"></span><button class="btn disclose" data-look="link" data-act="toggleMore" aria-expanded="false"><span data-t="import.more"></span><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4.5 6.2 8 9.7l3.5-3.5"/></svg></button></p><div class="more" hidden><p class="small ink" data-t="import.found"></p><p class="small" data-t="import.scope"></p><p class="small ink model-row"><span data-t="import.model"></span><button class="btn" data-look="link" data-act="toggleModels" aria-expanded="false" data-t="import.change"></button></p><ul class="models" hidden></ul><div class="opts"><label><input type="checkbox" data-opt="regen"><span data-t="import.opt.regen"></span></label><label><input type="checkbox" data-opt="skipWork"><span data-t="import.opt.skipWork"></span></label></div></div></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="copy" data-t="import.copy"></button><button class="btn" data-look="soft" data-act="answer" data-detail="skip" data-t="import.skip"></button><p class="foot" data-t="import.footnote"></p></div></section>+<section class="card" data-kind="importSpace" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.importSpace"></h2><p class="lead" data-t="import.space"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="pick" data-t="pickOther"></button><button class="btn" data-look="soft" data-act="answer" data-detail="skip" data-t="import.skip"></button></div></section>+<section class="card" data-kind="copying" hidden><div class="card-scroll"><h2 class="card-title" data-t="copying.title"></h2><div class="copy-steps"><ol class="steps"><li data-step="1"><span class="mark" aria-hidden="true"><span class="dot"></span><svg class="check" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8"/><path d="M4.6 8.3 7 10.6l4.4-4.9"/></svg></span><span data-t="copying.step1"></span></li><li data-step="2"><span class="mark" aria-hidden="true"><span class="dot"></span><svg class="check" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8"/><path d="M4.6 8.3 7 10.6l4.4-4.9"/></svg></span><span data-t="copying.step2"></span></li><li data-step="3"><span class="mark" aria-hidden="true"><span class="dot"></span><svg class="check" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8"/><path d="M4.6 8.3 7 10.6l4.4-4.9"/></svg></span><span data-t="copying.step3"></span></li></ol><div class="bar" aria-hidden="true"><span class="bar-fill"></span></div></div><div class="confirm" hidden><p class="lead" data-t="stop.confirm"></p></div></div><div class="card-actions"><span class="eta small"></span><button class="btn stop" data-look="soft" data-act="stopCopy" data-t="stop"></button><button class="btn" data-look="primary" data-act="keepCopying" data-confirm data-t="keepCopying"></button><button class="btn danger" data-look="soft" data-act="stopCopy" data-detail="confirm" data-confirm data-t="stop"></button></div></section>+<section class="card" data-kind="inUse" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.inUse"></h2><p class="lead" data-t="inUse"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="skip" data-t="import.skip"></button></div></section>+<section class="card" data-kind="newerUpdating" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.newer"></h2><p class="lead" data-t="newer.updating"></p><p class="small"><span data-t="update.slow"></span> <button class="btn" data-look="link" data-act="manualDownload" data-t="manualDownload"></button></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="skip" data-t="import.skip"></button></div></section>+<section class="card" data-kind="newer" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.newer"></h2><p class="lead" data-t="newer.unreadable"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="startWithout" data-t="startWithout"></button><p class="foot" data-t="newer.footnote"></p></div></section>+<section class="card" data-kind="importFailed" hidden><div class="card-scroll"><p class="lead" data-t="importFailed"></p><div class="card-actions"><button class="btn" data-look="primary" data-act="retry" data-t="retry"></button><button class="btn" data-look="soft" data-act="answer" data-detail="startWithout" data-t="startWithout"></button><button class="btn" data-look="soft" data-act="copyDetails" data-t="copyDetails"></button><button class="btn disclose" data-look="link" data-act="toggleDetails" aria-expanded="false"><span data-t="details"></span><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4.5 6.2 8 9.7l3.5-3.5"/></svg></button></div><div class="log" hidden><pre></pre></div></div></section>+<section class="card" data-kind="watchdog" hidden><div class="card-actions"><button class="btn" data-look="primary" data-act="wait" data-t="wait"></button><button class="btn" data-look="soft" data-act="retry" data-t="retry"></button><button class="btn" data-look="soft" data-act="openLogs" data-t="openLogs"></button></div></section>+<section class="card" data-kind="failed" hidden><div class="card-scroll"><p class="lead" data-t="failed.reason.{reason}"></p><div class="banner" hidden><div class="banner-row"><p class="lead" data-t="update.available"></p><button class="btn" data-look="primary" data-act="installUpdate" data-u="available" data-t="update.install"></button></div><div class="banner-down" data-u="downloading"><p class="small banner-line"><span data-t="update.downloading"></span><span class="slow"><span data-t="update.slow"></span><button class="btn" data-look="link" data-act="manualDownload" data-t="manualDownload"></button></span></p><div class="bar"><span class="bar-fill"></span></div></div><p class="small" data-u="installing" data-t="update.installing"></p><div class="banner-fail" data-u="failed"><p class="small danger" data-t="update.failed"></p><button class="btn" data-look="small" data-act="installUpdate" data-t="retry"></button><button class="btn" data-look="small" data-act="manualDownload" data-t="manualDownload"></button></div></div><div class="card-actions"><button class="btn" data-look="primary" data-act="retry" data-main data-t="retry"></button><button class="btn" data-look="soft" data-act="pick" data-detail="changePlace" data-places data-t="changePlace" hidden></button><button class="btn" data-look="soft" data-act="freshStart" data-places data-t="freshStart" hidden></button><button class="btn" data-look="soft" data-act="openLogs" data-t="openLogs"></button><button class="btn" data-look="soft" data-act="copyDetails" data-t="copyDetails"></button><button class="btn disclose" data-look="link" data-act="toggleDetails" aria-expanded="false"><span data-t="details"></span><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4.5 6.2 8 9.7l3.5-3.5"/></svg></button></div><div class="log" hidden><pre></pre></div></div></section>+<section class="card" data-kind="viewFailed" hidden><div class="card-actions"><button class="btn" data-look="primary" data-act="reloadView" data-t="reload"></button><button class="btn" data-look="soft" data-act="openLogs" data-t="openLogs"></button><button class="btn" data-look="soft" data-act="copyDetails" data-t="copyDetails"></button></div></section>+</div>+</section>+</main>+<footer class="note" data-t="footer"></footer>+<p class="sr live" aria-live="polite"></p>+</body>+</html>diff --git a/app/src/start/start.js b/app/src/start/start.jsnew file mode 100644index 00000000..a2d08c7b--- /dev/null+++ b/app/src/start/start.js@@ -0,0 +1,511 @@+// The start page: binds window.dsBotStart and applies each full snapshot to the page (the+// whale's line, the hint row and the clock, the sheet and its cards, focus and the live+// region). The whale, its rings and the hidden stage list belong to the director in whale.js;+// the whale's line follows where the director has the whale, not the snapshot alone. Text is+// set only through textContent (and text nodes), never as markup.+import { t } from './text.mjs'+import { createDirector, reduced, play, spring, sleep, clamped } from './whale.js'++const root = document.documentElement+const asked = new URLSearchParams(location.search).get('start')+const START = ['first', 'later', 'moving'].includes(asked) ? asked : 'first'+const resume = performance.getEntriesByType('navigation')[0]?.type === 'reload'+const bridge = window.dsBotStart+if (resume) root.dataset.resume = ''+// The page shows nothing but the empty band (html:not([data-start])) without the preload's bridge.+if (bridge) root.dataset.start = START+const first = START === 'first'+root.dataset.sheet = 'none'++const $ = selector => document.querySelector(selector)+const sheet = $('.sheet'), edge = $('.sheet-edge'), fill = $('.sheet-fill'), stage = $('.stage'), live = $('.live')+const voiceEl = $('.voice'), voiceText = $('.voice>span')+const captionText = $('.caption-text'), logs = $('.caption .btn'), elapsed = $('.elapsed')+const CODE = new Set(['path', 'dataDir', 'workspace'])+let lang = 'zh'+let s = null+const say = (key, vars) => t(lang, key, vars)++// ---- text ----+const sigs = new WeakMap()+function render(el, vars = {}) {+ const key = el.dataset.t.replace(/\{(\w+)\}/gu, (all, name) => vars[name] ?? '')+ const parts = say(key).split(/\{(\w+)\}/u)+ const sig = parts.map((part, i) => (i % 2 ? `\u0001${vars[part] ?? ''}` : part)).join('')+ if (sigs.get(el) === sig) return+ sigs.set(el, sig)+ el.replaceChildren(...parts.map((part, i) => {+ if (i % 2 === 0) return part+ const value = String(vars[part] ?? '')+ return CODE.has(part) ? Object.assign(document.createElement('code'), { textContent: value }) : value+ }))+}+function renderStatic() {+ root.lang = lang === 'zh' ? 'zh-CN' : 'en'+ for (const el of document.querySelectorAll('.track [data-t], .note[data-t], .caption [data-t]')) render(el)+ $('.track').setAttribute('aria-label', say('track.label'))+ for (const st of document.querySelectorAll('.station')) st.querySelector('.sr').textContent = say(`state.${st.dataset.state}`)+ if (s) { fillBlock(shown); timeUI() }+}+function varsOf(snap) {+ const card = snap.card ?? {}+ const update = snap.update ?? {}+ const vars = { ...snap.explain, ...card }+ if (snap.view === 'failed' || snap.view === 'viewFailed') vars.reason = snap.failure?.reason ?? 'other'+ if (card.kind === 'importFailed') vars.reason = say(`importFailed.${card.reason}`)+ if (card.kind === 'newerUpdating') vars.p = card.percent ?? 0+ if (update.version) Object.assign(vars, { version: update.version, p: update.percent ?? 0, a: update.received ?? 0, b: update.total ?? 0 })+ return vars+}+function announce(text) { if (text) live.textContent = text }++// ---- the whale's line ----+// One short line at a time, under the waterline. It follows the whale: the stop it is at, the+// stage shown active there, the leg it is swimming. A card speaks with its own first line, so+// the whale's line is empty while a card is up (the 180 s question is the exception: its card+// holds only the buttons). Each line stays long enough to read before the next replaces it;+// lines skipped meanwhile are never shown late; the line is empty while the whale sinks to start+// over in a new folder. A failure and the 180 s question come at once;+// 「进去吧」 lets the line before it be read for READ_MS first, and the director starts the+// celebration READY_MS (whale.js) after 「进去吧」 is up.+const HOLDS = { 'voice.hello': 1500, 'voice.found': 700 }+const HOLD_MS = 900+const READ_MS = 400+const FADE_MS = 160+// Lines put up while a reloaded page catches up are not held.+const catchUp = resume ? performance.now() + 1000 : 0+// key/text: the line chosen (on screen, or coming in once the old one has faded out); shown/at:+// the line on screen and when it went up; last: the last line that really went up.+const v = { key: '', text: '', shown: '', at: 0, timer: 0, swap: 0, last: '', cards: false, readyAt: 0, waiters: [] }+const readyLine = () => (v.readyAt ? Promise.resolve(v.readyAt) : new Promise(resolve => v.waiters.push(resolve)))+function voiceWant() {+ const view = s.view+ if (view === 'failed' || view === 'viewFailed') return [`title.${view}`, true]+ if (view === 'watchdog') return ['voice.watchdog', true]+ if (view === 'card') return ['', false]+ if (!first) return [`title.${START}`, true]+ if (view === 'handoff') return ['voice.ready', false]+ const st = director.stage()+ if (st.sinking) return ['', false]+ if (st.ready) return ['voice.ready', false]+ if (st.at >= 2 || (st.at === 1 && st.legging)) return ['voice.team', false]+ const ms = bootMs()+ const engineDone = (s.done ?? []).includes('engine')+ if (view === 'boot' && !engineDone && ms >= 45000) return ['voice.slow45', false]+ if (view === 'boot' && !engineDone && ms >= 10000) return ['voice.slow10', false]+ if (st.active === 0) return ['voice.data', false]+ if (st.active === 1) return ['voice.engine', false]+ // Between stages: 「找到了」 answers 「先找个地方放东西」 only if that was said; the greeting+ // stays until there is news, unless a card has already spoken.+ if (['voice.data', 'voice.found'].includes(v.last) && (st.at === 1 || st.legging)) return ['voice.found', false]+ if (!v.cards && (!v.last || v.last === 'voice.hello')) return ['voice.hello', false]+ return [st.at === 0 ? 'voice.data' : 'voice.engine', false]+}+// The greeting names the Main Bot the user is about to meet: the team's own on a reinstall, the+// default name for a new team. A team to import has no name yet (the answer decides which Main+// Bot it is), and neither has a reinstall whose name could not be read. It stays one line+// (voice.hello) whichever words it takes: the main process may learn the team after the window+// opens, and the greeting on screen then changes in place.+function greeting() {+ const e = s.explain ?? {}+ if (e.mode === 'import' || (e.mode === 'reinstall' && !e.name)) return say('voice.helloBack')+ return e.name ? say('voice.helloName', { name: e.name }) : say('voice.hello')+}+function speak() {+ clearTimeout(v.timer)+ if (!s) return+ if (v.key === 'voice.hello' && v.shown === 'voice.hello' && !v.swap && greeting() !== v.text) {+ v.text = greeting()+ voiceText.textContent = v.text+ }+ const [key, urgent] = voiceWant()+ const text = key === 'voice.hello' ? greeting() : key ? say(key) : ''+ if (key === v.key) { if (text !== v.text) { v.text = text; if (!v.swap) voiceText.textContent = text } return }+ // The old line is already fading out: the new choice simply takes its place.+ if (v.swap) { v.key = key; v.text = text; return }+ const hold = urgent ? 0 : key === 'voice.ready' ? READ_MS : HOLDS[v.shown] ?? HOLD_MS+ const left = v.shown ? v.at + hold - performance.now() : 0+ if (left > 0) { v.timer = setTimeout(speak, left); return }+ v.key = key+ v.text = text+ if (!v.shown || !voiceEl.hasAttribute('data-on')) { put(); return }+ delete voiceEl.dataset.on+ v.swap = setTimeout(put, reduced() ? 120 : FADE_MS)+}+function put() {+ v.swap = 0+ v.shown = v.key+ voiceText.textContent = v.text+ voiceEl.toggleAttribute('data-on', Boolean(v.text))+ v.at = performance.now() < catchUp ? -Infinity : performance.now()+ if (!v.shown) return+ v.last = v.shown+ if (v.shown === 'title.failed' || v.shown === 'title.viewFailed') announce(v.text)+ if (v.shown === 'voice.ready' && !v.readyAt) { v.readyAt = performance.now(); for (const resolve of v.waiters.splice(0)) resolve(v.readyAt) }+}++// ---- the hint row and the clock ----+// The hint prepares the user for what comes next and is empty otherwise: the model to connect+// at the second stop (the team carried over on a reinstall), DSH's preview notice on the way to+// the last one; a short drive's one-line note for the first 10 s (as before). From 45 s the row+// holds only 〔打开日志文件夹〕, since the whale's line says why. Later starts keep their decided+// lines. Nothing shows while a card, the 180 s question or a failure is up.+function hintWant() {+ const view = s.view+ const ms = bootMs()+ const sec = Math.floor(ms / 1000)+ if (!first) {+ if (view !== 'boot' && view !== 'moving') return ['', {}, false]+ if (ms >= 45000) return ['slow.45.later', {}, true]+ if (ms >= 10000) return ['elapsed', { n: sec }, false]+ return [s.hint ? 'hint.space' : '', { ...s.hint }, false]+ }+ if (view !== 'boot' && view !== 'handoff') return ['', {}, false]+ const engineDone = (s.done ?? []).includes('engine')+ if (view === 'boot' && !engineDone && ms >= 45000) return ['', {}, true]+ const st = director.stage()+ if (st.sinking) return ['', {}, false]+ const e = s.explain ?? {}+ const toTeam = view === 'handoff' || st.ready || st.at >= 2 || (st.at === 1 && st.legging)+ if (toTeam && e.previewNotice) return ['hint.preview', {}, false]+ if (s.hint && ms < 10000) return ['hint.space', { ...s.hint }, false]+ if (st.at >= 1 && e.mode === 'reinstall') return ['hint.reinstall', e, false]+ if (st.at >= 1 && e.nextStep !== false) return ['hint.model', {}, false]+ return ['', {}, false]+}+let shimmerReady = false+if (!first) setTimeout(() => { shimmerReady = true; if (s) shimmer() }, resume ? 0 : 1000)+const shimmer = () => root.toggleAttribute('data-shimmer', shimmerReady && (s.view === 'boot' || s.view === 'moving'))+// The main process's boot clock: ms at the wall time `at`, paused while a card waits on the user.+const bootMs = () => { const c = s?.clock; if (!c) return 0; return c.running ? c.ms + Math.max(0, Date.now() - c.at) : c.ms }+let tick = 0+function timeUI() {+ clearTimeout(tick)+ if (!s) return+ const ms = bootMs()+ const sec = Math.floor(ms / 1000)+ const booting = s.view === 'boot' || s.view === 'moving'+ const engineDone = (s.done ?? []).includes('engine')+ if (first) {+ // The clock stays through 「进去吧」 and fades with the hint row when the celebration starts.+ const shown = (booting || s.view === 'handoff') && ms >= 5000+ root.toggleAttribute('data-elapsed', shown)+ if (shown) elapsed.textContent = say('elapsed', { n: sec })+ }+ hint()+ speak()+ if (booting) director.slow(first && engineDone ? 0 : ms >= 45000 ? 2 : ms >= 10000 ? 1 : 0)+ if (booting && s.clock?.running) tick = setTimeout(timeUI, (sec + 1) * 1000 - ms + 4)+}+const hint = () => { const [key, vars, withLogs] = hintWant(); caption(key, vars, withLogs) }+let captionKey = ''+let captionTimer = 0+function caption(key, vars, withLogs) {+ const text = key ? say(key, vars) : ''+ if (key !== captionKey) {+ const had = captionKey+ captionKey = key+ clearTimeout(captionTimer)+ const show = () => { captionText.textContent = text; captionText.toggleAttribute('data-on', Boolean(key)) }+ if (had) { delete captionText.dataset.on; captionTimer = setTimeout(show, 160) } else show()+ } else if (key && captionText.textContent !== text) captionText.textContent = text+ if (withLogs && logs.hidden) { logs.hidden = false; logs.dataset.on = '' }+ if (!withLogs && !logs.hidden) { delete logs.dataset.on; setTimeout(() => { if (!logs.dataset.on) logs.hidden = true }, 160) }+}++// ---- the sheet: one surface that every card morphs in and out of ----+const blockEl = name => (name ? $(`.card[data-kind="${name}"]`) : null)+let shown = ''+let edgeH = 0+let sheetRun = 0+function blockFor(snap) {+ if (snap.view === 'handoff') return shown+ if (snap.view === 'failed' || snap.view === 'viewFailed' || snap.view === 'watchdog') return snap.view+ if (snap.view === 'card') return snap.card?.kind === 'stopCopy' ? 'copying' : snap.card?.kind ?? ''+ return ''+}+// The edge and fill layers are pre-sized to the sheet; only their clip-path moves, so a card+// morph never lays anything out per frame.+function morph(target, jump) {+ const h = Math.max(0, Math.min(Math.round(target), sheet.clientHeight))+ if (h === edgeH) return+ const appear = edgeH === 0+ const vanish = h === 0+ edgeH = h+ const bottom = sheet.clientHeight - h+ const clips = [`inset(0px 0px ${bottom}px 0px round 12px)`, `inset(1px 1px ${bottom + 1}px 1px round 11px)`]+ ;[edge, fill].forEach((layer, k) => {+ const from = getComputedStyle(layer)+ const fromClip = from.clipPath+ const fromOpacity = Number(from.opacity)+ for (const a of layer.getAnimations()) a.cancel()+ layer.style.clipPath = clips[k]+ layer.style.opacity = vanish ? '0' : '1'+ if (jump) return+ if (reduced()) { if (appear || vanish) play(layer, [{ opacity: fromOpacity }, { opacity: vanish ? 0 : 1 }], { duration: vanish ? 160 : 120, fill: 'none' }); return }+ const shape = spring('shape')+ // A collapse is clamped at zero height: overshooting past it would only empty the clip.+ play(layer, [{ clipPath: fromClip }, { clipPath: clips[k] }], { duration: shape.duration, easing: vanish ? clamped(shape.easing) : shape.easing, fill: 'none' })+ if (appear) play(layer, [{ opacity: fromOpacity }, { opacity: 1 }], { duration: 220, easing: 'ease-out', fill: 'none' })+ // The fade-out ends before the clip area reaches zero (about half-way along the spring).+ else if (vanish) play(layer, [{ opacity: fromOpacity }, { opacity: 0 }], { duration: 160, easing: 'ease-in', fill: 'none' })+ })+}+function resize() {+ const el = blockEl(shown)+ if (el && !el.hidden) morph(el.offsetHeight)+}+const exits = new WeakMap()+function leave(el, jump) {+ if (!el || el.hidden) return+ if (jump) { el.hidden = true; return }+ const frames = reduced() ? [{ opacity: 1 }, { opacity: 0 }] : [{ opacity: 1, translate: '0 0', scale: '1', filter: 'none' }, { opacity: 0, translate: '0 6px', scale: '.975', filter: 'blur(3px)' }]+ const a = play(el, frames, { duration: 160, easing: 'ease-in' })+ exits.set(el, a)+ el.inert = true+ // The faded card stays in layout until the edges have collapsed (100 + 420 ms after the+ // exit starts): unhiding or hiding a block mid-morph would knock the edge layers off the+ // compositor.+ a.done.then(() => sleep(380)).then(() => { if (exits.get(el) !== a) return; exits.delete(el); if (blockEl(shown) !== el) el.hidden = true; el.inert = false; a.cancel() })+}+function enter(el) {+ const a = exits.get(el)+ if (a) { exits.delete(el); a.cancel() }+ el.inert = false+ el.hidden = false+}+function shift(up, jump) {+ const from = getComputedStyle(stage).translate+ for (const a of stage.getAnimations()) a.cancel()+ root.toggleAttribute('data-up', up)+ if (jump || reduced()) return+ play(stage, [{ translate: from }, { translate: up ? '0px 0px' : '0px 80px' }], { ...spring('shape'), fill: 'none' })+}+async function showBlock(name, jump) {+ if (name === shown) return+ const mine = (sheetRun += 1)+ const oldEl = blockEl(shown)+ const wasCard = Boolean(shown)+ shown = name+ if (wasCard) leave(oldEl, jump)+ const el = blockEl(name)+ if (name && el) {+ root.dataset.sheet = 'card'+ v.cards = true+ if (!root.hasAttribute('data-up')) {+ shift(true, jump)+ if (!jump) { await sleep(70); if (mine !== sheetRun) return }+ }+ enter(el)+ fillBlock(name)+ morph(el.offsetHeight, jump)+ ;[...el.querySelectorAll('.btn[data-look=primary]')].find(b => b.checkVisibility())?.focus({ preventScroll: true })+ announce(cardWords(el, name))+ return+ }+ if (!jump) await sleep(100)+ if (mine !== sheetRun) return+ morph(0, jump)+ if (!jump) await sleep(70)+ if (mine !== sheetRun) return+ root.dataset.sheet = name || 'none'+ if (document.activeElement?.closest?.('.sheet')) document.activeElement.blur()+ if (root.hasAttribute('data-up')) {+ if (!jump) await sleep(360)+ if (mine === sheetRun) shift(false, jump)+ }+}++// What a new card says to a screen reader: its first line and its first visible sentence (the+// 180 s card has only buttons; the whale's line asks its question).+function cardWords(el, name) {+ if (name === 'watchdog') return say('voice.watchdog')+ const title = el.querySelector('.card-title')+ const lead = [...el.querySelectorAll('.lead')].find(p => p.checkVisibility())+ return [title?.textContent, lead?.textContent].filter(Boolean).join(' ')+}++// ---- card contents ----+function fillBlock(name) {+ const el = blockEl(name)+ if (!el || !s) return+ const vars = varsOf(s)+ for (const node of el.querySelectorAll('[data-t]')) if (!node.closest('.steps, .copied')) render(node, vars)+ if (name === 'missing') missing(el)+ if (name === 'recommend' || name === 'rejected') recommend(el)+ if (name === 'import') importCard(el)+ if (name === 'copying') copying(el)+ if (name === 'failed') failed(el)+}+let missSeen = 0+let missTimer = 0+function missing(el) {+ const count = Number(s.card?.missedRetry ?? 0)+ if (!count || count === missSeen) return+ missSeen = count+ const line = el.querySelector('.miss')+ line.hidden = false+ delete line.dataset.gone+ clearTimeout(missTimer)+ missTimer = setTimeout(() => {+ const a = play(line, [{ opacity: 1 }, { opacity: 0 }], { duration: 160 })+ a.done.then(() => { line.hidden = true; a.cancel(); resize() })+ }, 4000)+}+// The recommended-drive card: the question and 〔放到 D 盘〕 only with a drive to recommend,+// 〔仍然放在 C 盘〕 only when the default place works but its drive is short on space. A+// rejected pick keeps the buttons of the card it came from (card.keep says whether it had+// 〔仍然放在 C 盘〕).+function recommend(el) {+ const card = s.card+ const rec = Boolean(card.rec)+ const keep = card.kind === 'rejected' ? Boolean(card.keep) : card.reason === 'space'+ const ask = el.querySelector('.ask')+ if (ask) ask.hidden = !rec+ for (const node of el.querySelectorAll('[data-rec]')) node.hidden = !rec+ for (const node of el.querySelectorAll('[data-norec]')) node.hidden = rec+ for (const node of el.querySelectorAll('[data-keep]')) node.hidden = !keep+}+function toggleMore(button, open = button.getAttribute('aria-expanded') !== 'true') {+ button.setAttribute('aria-expanded', String(open))+ button.closest('.card').querySelector('.more').hidden = !open+ resize()+}+let modelsSig = ''+function importCard(el) {+ const card = s.card+ for (const box of el.querySelectorAll('input[data-opt]')) box.checked = Boolean(card.options?.[box.dataset.opt])+ const sig = JSON.stringify(card.models ?? [])+ if (sig === modelsSig) return+ modelsSig = sig+ el.querySelector('.models').replaceChildren(...(card.models ?? []).map((model) => {+ const button = Object.assign(document.createElement('button'), { className: 'btn', type: 'button', textContent: model.label })+ Object.assign(button.dataset, { look: 'soft', act: 'importModel', detail: model.id })+ const item = document.createElement('li')+ item.append(button)+ return item+ }))+}+function toggleModels(button, open = button.getAttribute('aria-expanded') !== 'true') {+ button.setAttribute('aria-expanded', String(open))+ button.closest('.card').querySelector('.models').hidden = !open+ resize()+}+const bars = new WeakMap()+function bar(el, fraction, keep) {+ let f = Math.max(0, Math.min(1, fraction || 0))+ const was = bars.get(el) ?? 0+ if (keep && f < was) f = was+ if (f === was && el.style.scale) return+ bars.set(el, f)+ const from = getComputedStyle(el).scale+ for (const a of el.getAnimations()) a.cancel()+ el.style.scale = `${f} 1`+ if (!reduced()) play(el, [{ scale: from }, { scale: `${f} 1` }], { ...spring('list'), fill: 'none' })+}+let copyStep = 0+function copying(el) {+ const card = s.card+ el.toggleAttribute('data-confirm', card.kind === 'stopCopy')+ el.querySelector('.confirm').hidden = card.kind !== 'stopCopy'+ el.style.setProperty('--step', String(Math.max(0, card.step - 1)))+ ;[...el.querySelectorAll('.steps li')].forEach((li, k) => {+ const n = k + 1+ const state = n < card.step ? 'done' : n === card.step ? 'active' : 'pending'+ const was = li.dataset.state+ li.dataset.state = state+ if (state === 'done' && was && was !== 'done') {+ const check = li.querySelector('.check')+ if (reduced()) play(check, [{ opacity: 0 }, { opacity: 1 }], { duration: 120, fill: 'none' })+ else { play(check, [{ transform: 'scale(.4)' }, { transform: 'none' }], { ...spring('pop'), fill: 'none' }); play(check, [{ opacity: 0 }, { opacity: 1 }], { duration: 120, fill: 'none' }) }+ director.nod()+ }+ render(li.querySelector('[data-t]'), card.steps?.[k] ?? {})+ })+ const fillEl = el.querySelector('.copy-steps .bar-fill')+ if (card.step !== copyStep) { copyStep = card.step; bars.set(fillEl, 0); fillEl.style.scale = '0 1' }+ bar(fillEl, card.fraction, true)+ el.querySelector('.eta').textContent = card.eta === null || card.eta === undefined ? '' : card.eta < 1 ? say('eta.lt1') : say('eta.minutes', { n: card.eta })+}+// The recovery card. 〔换个位置…〕 and 〔用新的空白团队开始…〕 show only when the main process can+// carry them out (failure.places).+function failed(el) {+ for (const node of el.querySelectorAll('[data-places]')) node.hidden = !s.failure?.places+ const update = s.update+ const banner = el.querySelector('.banner')+ banner.hidden = !update+ if (update) for (const part of banner.querySelectorAll('[data-u]')) part.hidden = part.dataset.u !== update.state+ el.querySelector('[data-main]').dataset.look = update && update.state !== 'failed' ? 'soft' : 'primary'+ if (update?.state === 'downloading') bar(banner.querySelector('.bar-fill'), (update.percent ?? 0) / 100, true)+}+function toggleDetails(button) {+ const card = button.closest('.card')+ const log = card.querySelector('.log')+ const open = button.getAttribute('aria-expanded') !== 'true'+ button.setAttribute('aria-expanded', String(open))+ const pre = log.querySelector('pre')+ pre.textContent = ''+ log.hidden = !open+ resize()+ if (!open) return+ // The redacted log fills in after the morph, so the surface never reflows while it moves.+ setTimeout(() => {+ pre.textContent = (s.failure?.log ?? s.card?.log ?? []).slice(-200).join('\n')+ pre.parentElement.scrollTop = 1e6+ card.querySelector('.card-scroll').scrollTop = button.offsetTop - 14+ }, reduced() ? 0 : spring('shape').duration)+}+function copiedLabel(button) {+ button.classList.add('copied')+ button.textContent = say('copied')+ setTimeout(() => { button.classList.remove('copied'); sigs.delete(button); render(button) }, 1600)+}++// ---- input ----+document.addEventListener('click', (event) => {+ const button = event.target.closest?.('button[data-act]')+ if (!button) return+ const name = button.dataset.act+ const value = button.dataset.detail+ if (name === 'toggleDetails') return toggleDetails(button)+ if (name === 'toggleMore') return toggleMore(button)+ if (name === 'toggleModels') return toggleModels(button)+ if (name === 'copyDetails') copiedLabel(button)+ if (name === 'importModel') toggleModels(button.closest('.card').querySelector('[data-act=toggleModels]'), false)+ if (name === 'answer' || name === 'wait' || name === 'keepCopying') director.nod()+ bridge?.act(name, value === undefined ? undefined : { value })+})+document.addEventListener('change', (event) => {+ const box = event.target.closest?.('input[data-opt]')+ if (box) bridge?.act('importOption', { option: box.dataset.opt, value: box.checked })+})+document.addEventListener('visibilitychange', () => root.toggleAttribute('data-hidden', document.hidden))+matchMedia('(prefers-reduced-motion: reduce)').addEventListener('change', () => director.refresh())+new MutationObserver(() => director.refresh()).observe(root, { attributes: true, attributeFilter: ['data-motion'] })++// ---- snapshots ----+// The director reports every change of where the whale is (a stage shown active, a leg begun+// or ended, a reset, 「进去吧」); the line and the hint follow.+const onStage = () => { if (s) { hint(); speak() } }+const director = createDirector({ start: START, resume, act: (name, detail) => bridge?.act(name, detail), label: say, announce, onStage, readyLine })+let applied = false+function apply(next) {+ const jump = !applied && resume+ s = next+ if ((next.lang ?? 'zh') !== lang || !applied) { lang = next.lang ?? 'zh'; renderStatic() }+ const motion = next.motion ?? 'normal'+ if (root.dataset.motion !== motion) root.dataset.motion = motion+ // macOS and Linux draw a system title bar, so the page has no band of its own.+ if (next.frame === 'system') root.dataset.frame = 'system'+ else delete root.dataset.frame+ root.dataset.view = next.view+ shimmer()+ const name = blockFor(next)+ if (name !== shown) showBlock(name, jump)+ else { fillBlock(name); resize() }+ timeUI()+ director.update(next)+ applied = true+}+renderStatic()+bridge?.onState(apply)diff --git a/app/src/start/text.mjs b/app/src/start/text.mjsnew file mode 100644index 00000000..730eb6e7--- /dev/null+++ b/app/src/start/text.mjs@@ -0,0 +1,236 @@+// Start page strings, for the page and the main process. zh is the copy decided in+// docs/plans/2026-10-26-windows-onboarding.md §3 and docs/plans/2026-10-26-start-window.md;+// en mirrors it. The whale's lines are voice.*, a card's first line say.*, the hint row hint.*:+// one short line at a time, in the Main Bot's own words, none longer than one line.+// Placeholders are {name}; paths, sizes and names are filled from the snapshot, never from here.+export const TEXT = {+ zh: {+ 'title.later': '正在打开你的团队…',+ 'title.failed': 'DeepSeek Bot 没能启动',+ 'title.viewFailed': '团队界面没有加载出来。',+ 'title.moving': '正在搬 DeepSeek Bot 的数据…',+ 'phase.data': '准备数据文件夹',+ 'phase.engine': '启动本机引擎',+ 'phase.team': '打开团队',+ 'track.label': '启动进度',+ 'state.pending': '未开始',+ 'state.active': '进行中',+ 'state.done': '已完成',+ 'state.failed': '没有完成',+ 'sr.active': '{phase}:进行中',+ 'sr.done': '{phase}:已完成',+ elapsed: '已用 {n} 秒',+ footer: '社区开源项目,不是 DeepSeek 官方产品',+ 'voice.hello': '嗨,我是总管',+ 'voice.helloName': '嗨,我是{name}',+ 'voice.helloBack': '嗨,我来了',+ 'voice.data': '先找个地方放东西',+ 'voice.found': '找到了',+ 'voice.engine': '热身中,等我一下',+ 'voice.slow10': '第一次会慢一点',+ 'voice.slow45': '有点久,可能是杀毒软件在查新文件',+ 'voice.team': '开门去了',+ 'voice.ready': '进去吧',+ 'voice.watchdog': '等太久了,要不要重试?',+ 'hint.model': '待会儿要接一个模型:DeepSeek 账号或 API Key',+ 'hint.preview': '里面先有一页说明,点「继续」就行',+ 'hint.reinstall': '上次的 {bots} 个 Bot 和 {groups} 个群聊都在',+ 'slow.45.later': '比平时慢,请再等一会儿。',+ 'hint.space': '{drive} 盘只剩 {free}',+ openLogs: '打开日志文件夹',+ wait: '继续等待',+ retry: '重试',+ freshStart: '用新的空白团队开始…',+ 'say.space': '{drive} 盘有点挤',+ 'say.permission': '这里不让我放东西',+ 'say.rejected': '这里放不了',+ 'say.picked': '我多加了一层文件夹',+ 'say.missing': '数据不在原来的地方了',+ 'say.import': '找到你以前的团队了',+ 'say.importSpace': '地方不够放',+ 'say.inUse': 'DeepSeek Harness 还在用这个团队',+ 'say.newer': '这些对话比我新',+ 'card.reason.space': '{drive} 盘只剩 {free}。',+ 'card.reason.permission': 'DeepSeek Bot 没有权限在 {path} 里写文件。',+ 'card.recommend.ask': '放到 {rec} 盘(剩 {recFree})?',+ 'card.recommend.use': '放到 {rec} 盘',+ 'card.recommend.keep': '仍然放在 {drive} 盘',+ 'card.recommend.other': '其他位置…',+ pickOther: '选择其他位置…',+ 'card.rejected.permission': 'DeepSeek Bot 没有权限在 {path} 里写文件。',+ 'card.rejected.onedrive': '{path} 在 OneDrive 里,同步会打断正在写入的聊天记录。',+ 'card.rejected.foreign': '{path} 里已经有别的文件。',+ 'card.missing': '找不到数据文件夹 {path}。可能是移动硬盘没插上,或者文件夹被移走、删除了。旧数据不会被改动。',+ 'card.missing.relocate': '重新找到它…',+ 'card.missing.retryMissed': '还是找不到这个文件夹。',+ 'card.picked': '会放在 {path}',+ 'card.picked.use': '继续',+ 'card.picked.repick': '重新选',+ 'card.footnote': '以后可以在 设置 → 通用 → 位置 里改。',+ 'import.lead': 'DeepSeek Harness 里有 {bots} 个 Bot 和 {groups} 个群聊(对话 {chats},工作文件 {work})。复制过来?',+ 'import.extra': '复制后会多占 {total},DeepSeek Harness 里的原件不动。',+ 'import.more': '详细',+ 'import.found': '在 {path} 里找到 {bots} 个 Bot({names}等)和 {groups} 个群聊,{sessions} 段对话。',+ 'import.scope': '会复制:Bot、群聊、记忆、对话、附件、模型设置和 API Key。不会复制:MCP、技能和 DSH Agent。DeepSeek Harness 里的内容不会改动,复制以后两边各用各的。',+ 'import.model': '模型设置:{model}',+ 'import.change': '更换',+ 'import.opt.regen': '不复制可以重新生成的文件夹',+ 'import.opt.skipWork': '先不复制工作文件',+ 'import.copy': '复制过来',+ 'import.skip': '先不复制',+ 'import.footnote': '也可以在 设置 → 通用 → 位置 里复制。',+ 'import.space': '空间不够:复制要约 {need},{drive} 盘只剩 {free},还差 {short}。',+ 'copying.title': '正在搬过来',+ 'copying.step1': '检查对话 {a}/{b}',+ 'copying.step2': '复制 Bot 和对话 {a} / {b}',+ 'copying.step3': '启动团队',+ 'eta.minutes': '还要大约 {n} 分钟',+ 'eta.lt1': '不到 1 分钟',+ stop: '停止复制',+ 'stop.confirm': '停下后不会留下复制了一半的团队,DeepSeek Harness 里的团队不受影响。',+ keepCopying: '继续复制',+ inUse: '请完全退出 DSH Desktop(任务栏右下角的托盘图标也要退出),并关掉 DSH Web,这里会自动继续。',+ 'newer.updating': 'DeepSeek Bot {version} 能读它们,正在下载({p}%)。装好后会重新打开,再复制团队。',+ 'newer.unreadable': '这些对话是更新版本的 DeepSeek Harness 写的,DeepSeek Bot 现在读不了。',+ startWithout: '先不带团队开始',+ 'newer.footnote': '可以在 设置 → 通用 → 位置 里再复制。',+ importFailed: '团队没有复制完:{reason}。DeepSeek Harness 里的团队没有变化。',+ 'importFailed.inUse': '文件被别的程序占用',+ 'importFailed.permission': '没有权限读取',+ 'importFailed.full': '磁盘满了',+ 'failed.reason.permission': '没有写入权限。',+ 'failed.reason.space': '磁盘空间不够。',+ 'failed.reason.files': '程序文件不完整,可能被杀毒软件拦掉了一部分。',+ 'failed.reason.engine': '本机引擎启动到一半停下了。',+ 'failed.reason.other': '出了点意外。',+ changePlace: '换个位置…',+ copyDetails: '复制详细信息',+ copied: '已复制',+ details: '详细信息',+ 'update.available': 'DeepSeek Bot {version} 已经发布,可能修好了这个问题。',+ 'update.install': '下载并安装',+ 'update.downloading': '正在下载 {version}({p}%,{a}/{b} MB)',+ 'update.slow': '下载太慢?',+ 'update.installing': '正在安装,装好后会重新打开。',+ 'update.failed': '下载失败。',+ manualDownload: '手动下载',+ reload: '重新载入',+ },+ en: {+ 'title.later': 'Opening your team…',+ 'title.failed': 'DeepSeek Bot couldn’t start',+ 'title.viewFailed': 'The team view didn’t load.',+ 'title.moving': 'Moving DeepSeek Bot’s data…',+ 'phase.data': 'Prepare the data folder',+ 'phase.engine': 'Start the local engine',+ 'phase.team': 'Open the team',+ 'track.label': 'Start progress',+ 'state.pending': 'Not started',+ 'state.active': 'In progress',+ 'state.done': 'Done',+ 'state.failed': 'Not finished',+ 'sr.active': '{phase}: in progress',+ 'sr.done': '{phase}: done',+ elapsed: '{n} s so far',+ footer: 'A community open-source project, not an official DeepSeek product',+ 'voice.hello': 'Hi, I’m Chief',+ 'voice.helloName': 'Hi, I’m {name}',+ 'voice.helloBack': 'Hi, I’m here',+ 'voice.data': 'First, a place for my things',+ 'voice.found': 'Found one',+ 'voice.engine': 'Warming up, one moment',+ 'voice.slow10': 'The first time takes a bit longer',+ 'voice.slow45': 'Taking a while: antivirus may be checking new files',+ 'voice.team': 'Off to open the door',+ 'voice.ready': 'Come on in',+ 'voice.watchdog': 'This is taking too long. Try again?',+ 'hint.model': 'Next you’ll connect a model: a DeepSeek account or an API Key',+ 'hint.preview': 'A notice page comes first; just click “Continue”',+ 'hint.reinstall': 'Your {bots} Bots and {groups} group chats are still here',+ 'slow.45.later': 'Slower than usual. Please wait a little longer.',+ 'hint.space': 'Only {free} left on drive {drive}',+ openLogs: 'Open log folder',+ wait: 'Keep waiting',+ retry: 'Try again',+ freshStart: 'Start with a new blank team…',+ 'say.space': 'Drive {drive} is a bit full',+ 'say.permission': 'I’m not allowed to put things here',+ 'say.rejected': 'That place won’t work',+ 'say.picked': 'I added one more folder',+ 'say.missing': 'Your data isn’t where it was',+ 'say.import': 'Found your old team',+ 'say.importSpace': 'Not enough room',+ 'say.inUse': 'DeepSeek Harness is still using this team',+ 'say.newer': 'These chats are newer than me',+ 'card.reason.space': 'Only {free} left on drive {drive}.',+ 'card.reason.permission': 'DeepSeek Bot can’t write files in {path}.',+ 'card.recommend.ask': 'Put it on drive {rec} ({recFree} free)?',+ 'card.recommend.use': 'Put it on drive {rec}',+ 'card.recommend.keep': 'Keep it on drive {drive}',+ 'card.recommend.other': 'Another location…',+ pickOther: 'Choose another location…',+ 'card.rejected.permission': 'DeepSeek Bot can’t write files in {path}.',+ 'card.rejected.onedrive': '{path} is in OneDrive; syncing interrupts chats while they are being written.',+ 'card.rejected.foreign': '{path} already has other files in it.',+ 'card.missing': 'Can’t find the data folder {path}. The external drive may be unplugged, or the folder was moved or deleted. The old data won’t be changed.',+ 'card.missing.relocate': 'Find it again…',+ 'card.missing.retryMissed': 'Still can’t find this folder.',+ 'card.picked': 'It will go in {path}',+ 'card.picked.use': 'Continue',+ 'card.picked.repick': 'Choose again',+ 'card.footnote': 'You can change this later in Settings → General → Locations.',+ 'import.lead': 'DeepSeek Harness has {bots} Bots and {groups} group chats (chats {chats}, work files {work}). Copy them over?',+ 'import.extra': 'The copy takes another {total}; the originals in DeepSeek Harness stay untouched.',+ 'import.more': 'Details',+ 'import.found': 'Found {bots} Bots ({names} and others), {groups} group chats and {sessions} conversations in {path}.',+ 'import.scope': 'Copied: Bots, group chats, memory, conversations, attachments, model settings and API Keys. Not copied: MCP, skills and DSH Agent. Nothing in DeepSeek Harness changes; after the copy each side goes its own way.',+ 'import.model': 'Model settings: {model}',+ 'import.change': 'Change',+ 'import.opt.regen': 'Skip folders that can be regenerated',+ 'import.opt.skipWork': 'Don’t copy work files yet',+ 'import.copy': 'Copy them',+ 'import.skip': 'Not now',+ 'import.footnote': 'You can also copy them in Settings → General → Locations.',+ 'import.space': 'Not enough space: the copy needs about {need}, drive {drive} has {free} left, {short} short.',+ 'copying.title': 'Moving your team in',+ 'copying.step1': 'Checking conversations {a}/{b}',+ 'copying.step2': 'Copying Bots and conversations {a} / {b}',+ 'copying.step3': 'Starting the team',+ 'eta.minutes': 'About {n} minutes left',+ 'eta.lt1': 'Less than a minute left',+ stop: 'Stop copying',+ 'stop.confirm': 'Stopping leaves no half-copied team, and the team in DeepSeek Harness is not affected.',+ keepCopying: 'Keep copying',+ inUse: 'Quit DSH Desktop completely (its tray icon at the bottom right of the taskbar too) and close DSH Web; this continues by itself.',+ 'newer.updating': 'DeepSeek Bot {version} can read them and is downloading ({p}%). After installing it reopens and copies the team.',+ 'newer.unreadable': 'These conversations were written by a newer DeepSeek Harness, which DeepSeek Bot can’t read yet.',+ startWithout: 'Start without the team',+ 'newer.footnote': 'You can copy them again in Settings → General → Locations.',+ importFailed: 'The team wasn’t fully copied: {reason}. The team in DeepSeek Harness is unchanged.',+ 'importFailed.inUse': 'a file is in use by another program',+ 'importFailed.permission': 'no permission to read',+ 'importFailed.full': 'the disk is full',+ 'failed.reason.permission': 'No permission to write.',+ 'failed.reason.space': 'Not enough disk space.',+ 'failed.reason.files': 'Program files are incomplete; antivirus software may have blocked some of them.',+ 'failed.reason.engine': 'The local engine stopped halfway through starting.',+ 'failed.reason.other': 'Something unexpected happened.',+ changePlace: 'Change the location…',+ copyDetails: 'Copy details',+ copied: 'Copied',+ details: 'Details',+ 'update.available': 'DeepSeek Bot {version} is out and may fix this.',+ 'update.install': 'Download and install',+ 'update.downloading': 'Downloading {version} ({p}%, {a}/{b} MB)',+ 'update.slow': 'Download too slow?',+ 'update.installing': 'Installing; it reopens when done.',+ 'update.failed': 'The download failed.',+ manualDownload: 'Download manually',+ reload: 'Reload',+ },+}++export function t(lang, key, vars) {+ const text = TEXT[lang]?.[key] ?? TEXT.zh[key] ?? key+ return vars ? text.replace(/\{(\w+)\}/gu, (all, name) => (name in vars ? String(vars[name]) : all)) : text+}diff --git a/app/src/start/whale.js b/app/src/start/whale.jsnew file mode 100644index 00000000..e0975aff--- /dev/null+++ b/app/src/start/whale.js@@ -0,0 +1,901 @@+// The whale director: turns start snapshots into whale motion. The whale's place is the+// progress: it swims from stop to stop, leaves a resting ring at each stop it leaves, and keeps+// the hidden stage list (.station data-state, aria-current) for the live region and screen+// readers. start.js reads stage() to choose the whale's line.+// Layers (start.html): .whale-x legs > .whale-gaze pointer > .whale scale > .whale-move+// one-shots > .whale-loop CSS state loops > svg (#tail, #eye-pair, #gaze, .bt-eye).+// One-shots run on WAAPI and end with commitStyles() + cancel(); loops are CSS keyed on+// html[data-whale] and html[data-tail]. Every await is raced against a timer, because a+// hidden document stops ticking animations.+const root = document.documentElement+const rm = matchMedia('(prefers-reduced-motion: reduce)')+const tierNow = () => root.dataset.motion || 'normal'+// html[data-tier] is the tier the CSS reads; it follows data-motion (the snapshot's tier).+const syncTier = () => { if (root.dataset.tier !== tierNow()) root.dataset.tier = tierNow() }+syncTier()+new MutationObserver(syncTier).observe(root, { attributes: true, attributeFilter: ['data-motion'] })+export const reduced = () => rm.matches+export const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))+const cs = el => getComputedStyle(el)+const clamp = v => Math.max(-1, Math.min(1, v))+const IDENTITY = /^(none|1|0px|0px 0px|matrix\(1, 0, 0, 1, 0, 0\))$/u+const CLEAR = ['transform', 'scale', 'translate']+const OUT = 'cubic-bezier(.4,0,.2,1)'+const HOP = 'cubic-bezier(.3,.7,.4,1)'+const PHASES = ['data', 'engine', 'team']+// An active station and a state loop each hold at least 400 ms; the margin covers the frame+// on which the change is painted.+const HOLD = 420+// 「进去吧」 is on screen at least this long before the celebration starts; the page says when it+// went up (readyLine), and the director waits for that at most READY_CAP.+const READY_MS = 300+const READY_CAP = 600+// Hops land at .55 of their 1.3 s cycle; the lively tier spaces further hops out, never closer.+const HOP_MS = 1300+const LANDED = 0.55 * HOP_MS+const MORE_HOPS = [2600, 5200]+const HOP_EVERY = 9000+// Acts that only open, fold or copy something on the card; every other card button answers it.+const LOCAL = new Set(['toggleDetails', 'toggleMore', 'toggleModels', 'copyDetails'])+// Waits get calmer on the card's own clock: rates and blink gaps after 30 s and after 90 s.+const calmer = ms => (ms >= 90000 ? [0.6, 2] : ms >= 30000 ? [0.8, 1.4] : [1, 1])++const springs = {}+export function spring(name) {+ if (!springs[name]) {+ const style = cs(root)+ springs[name] = { duration: parseFloat(style.getPropertyValue(`--spring-${name}-ms`)) || 420, easing: style.getPropertyValue(`--spring-${name}`).trim() || 'ease-out' }+ }+ return springs[name]+}++let instant = false+// Plays keyframes; with `instant` (a resumed page) it writes the last frame and returns at once.+export function play(el, frames, opts) {+ if (instant) {+ for (const [key, value] of Object.entries(frames.at(-1))) if (key !== 'offset' && key !== 'easing') el.style[key] = CLEAR.includes(key) && IDENTITY.test(String(value)) ? '' : value+ return { done: Promise.resolve(), cancel() {}, finish() {}, commitStyles() {} }+ }+ const anim = el.animate(frames, { fill: 'forwards', ...opts })+ const count = opts.iterations ?? 1+ anim.done = count === Infinity ? new Promise(() => {}) : Promise.race([anim.finished.catch(() => {}), sleep((opts.delay ?? 0) + (opts.duration ?? 0) * count + 150)])+ return anim+}+// Ends a one-shot at its end state: finish, commit through CSSOM (CSP allows it), cancel.+export function settle(anim, el, commit = true) {+ if (!anim?.effect || anim.playState === 'idle') return+ try { if (anim.playState !== 'finished' && anim.effect.getComputedTiming().iterations !== Infinity) anim.finish() } catch { /* infinite */ }+ if (commit) try { anim.commitStyles() } catch { /* not rendered */ }+ anim.cancel()+ for (const key of CLEAR) if (IDENTITY.test(el.style[key])) el.style.removeProperty(key)+}+const scripted = el => el.getAnimations().filter(a => !(a instanceof CSSAnimation) && !(a instanceof CSSTransition))+// Replaces earlier one-shots on el, keeping the pose they have reached this frame (never+// their end state: finishing one mid-flight would teleport the whale).+function drop(el) {+ for (const a of scripted(el)) {+ try { a.commitStyles() } catch { /* not rendered */ }+ a.cancel()+ }+ for (const key of CLEAR) if (IDENTITY.test(el.style[key])) el.style.removeProperty(key)+}+function to(el, props, opts) {+ const from = {}+ for (const key of Object.keys(props)) from[key] = cs(el)[key]+ drop(el)+ const anim = play(el, [from, props], opts)+ anim.done.then(() => settle(anim, el))+ return anim+}+const kf = (frames, easing) => frames.map(frame => ({ easing, ...frame }))+export const clamped = easing => easing.replace(/\d+\.\d+/gu, value => String(Math.min(1, Number(value))))++export function createDirector({ start, resume, act, label, announce, onCheck, onActive, onStage, readyLine }) {+ const $ = selector => document.querySelector(selector)+ const x = $('.whale-x'), gazeLayer = $('.whale-gaze'), body = $('.whale'), move = $('.whale-move'), loop = $('.whale-loop')+ const tail = $('#tail'), pair = $('#eye-pair'), lane = $('.lane'), ripple = $('.ripple'), hit = $('.whale-hit')+ const eyes = [...document.querySelectorAll('.bt-eye')], happy = [...document.querySelectorAll('.bt-eye-happy')]+ const stations = [...document.querySelectorAll('.station')]+ const traces = [...document.querySelectorAll('.trace')]+ const first = start === 'first'+ const u = (first ? 88 : 64) / 100+ const t0 = performance.now()+ const entranceMs = resume ? 0 : first ? 560 : 290+ const D = { at: 0, checks: 0, pose: 'enter', loop: '', card: '', slow: 0, bx: 0, by: 0, since: [t0], activeAt: [], loopAt: 0, hop: null, pet: null, poking: false, handed: false, workReady: first, missed: false, sinking: false,+ // Rest on a card: its clock, the lean, the breath, the lively hops; the last glance and press.+ clockKind: '', cardAt: 0, ready: false, readyAt: 0, lean: false, leanDue: false, leanOff: false, leanMine: -1, restMine: -1, breath: null, hopsStopped: false, legging: false, glanceAt: -Infinity, press: null, nodAt: 0 }+ const rnd = Math.random+ let want = { station: 0, view: 'boot', phase: 'data', done: [], card: '', missed: false, celebrate: first, update: '' }+ let token = 0+ let wake = () => {}+ let bumped = new Promise(resolve => { wake = resolve })+ // Timers of the rest on a card belong to one token; a new state drops them all.+ const timers = new Set()+ function later(mine, ms, fn) {+ const id = setTimeout(() => { timers.delete(id); if (mine === token) fn() }, Math.max(0, ms))+ timers.add(id)+ }+ const bump = () => {+ token += 1+ for (const id of timers) clearTimeout(id)+ timers.clear()+ stopBreath()+ unpress()+ wake()+ bumped = new Promise(resolve => { wake = resolve })+ }+ const until = promise => Promise.race([promise, bumped])+ const wait = ms => (instant ? Promise.resolve() : sleep(ms))+ const tier = tierNow+ const playful = () => tier() !== 'quiet' && !reduced()+ const failure = () => want.view === 'failed' || want.view === 'viewFailed' || want.card === 'importFailed'+ const entered = sleep(entranceMs).then(() => { root.dataset.entered = '' })+ // Finished entrance veils are dropped, so later fades of the same blocks stay composited.+ sleep(resume ? 0 : 700).then(() => { root.dataset.settled = '' })+ if (resume) instant = true+ if (!first) setTimeout(() => { D.workReady = true; if (D.started) kick() }, resume ? 0 : 1000)++ // ---- stages: the hidden list, and the rings the whale leaves behind ----+ const changed = () => onStage?.()+ function setStation(i, state) {+ const st = stations[i]+ if (!st || st.dataset.state === state) return+ st.dataset.state = state+ st.querySelector('.sr').textContent = label(`state.${state}`)+ if (state === 'active') st.setAttribute('aria-current', 'step')+ else st.removeAttribute('aria-current')+ }+ // A stop the whale leaves keeps a faint ring on the water: it opens like a ripple and settles+ // at the resting opacity of .trace[data-on], then never animates again. The quiet tier and+ // reduced motion only fade it in.+ function leaveTrace(i) {+ const ring = traces[i]+ if (!ring || ring.hasAttribute('data-on')) return+ ring.dataset.on = ''+ if (instant) return+ const rest = Number(cs(ring).opacity)+ const anims = reduced() || !playful()+ ? [play(ring, [{ opacity: 0 }, { opacity: rest }], { duration: reduced() ? 120 : 160, fill: 'none' })]+ : [play(ring, [{ scale: '.5' }, { scale: '1' }], { ...spring('shape'), fill: 'none' }), play(ring, [{ opacity: 0.9 }, { opacity: rest }], { duration: 420, easing: 'ease-out', fill: 'none' })]+ // Dropped once done, so the hand-off's opacity fade of the ring finds no other animation on+ // it and stays on the compositor.+ for (const a of anims) a.done.then(() => a.cancel())+ }+ function popCheck(i) {+ if (D.checks > i) return+ D.checks = i + 1+ setStation(i, 'done')+ // The last stop gets no ring: the whale dives there.+ if (i < 2) leaveTrace(i)+ announce(label('sr.done', { phase: label(`phase.${PHASES[i]}`) }))+ onCheck?.(i)+ }+ let activeTimer = 0+ function armActive() {+ clearTimeout(activeTimer)+ const i = D.at+ if (!first || D.handed || failure() || i > 2 || D.checks > i || stations[i].dataset.state !== 'pending') return+ if (i < 2 && want.done.includes(PHASES[i])) return+ const now = performance.now()+ const delay = Math.max(0, (D.since[i] ?? now) + 250 - now, t0 + entranceMs - now)+ activeTimer = setTimeout(() => {+ if (D.at !== i || stations[i].dataset.state !== 'pending' || failure() || (i < 2 && want.done.includes(PHASES[i]))) return+ setStation(i, 'active')+ D.activeAt[i] = performance.now()+ announce(label('sr.active', { phase: label(`phase.${PHASES[i]}`) }))+ onActive?.(i)+ changed()+ }, instant ? 0 : delay)+ }+ function place() {+ hit.style.setProperty('--hx', `${168 + D.at * 192}px`)+ ripple.style.setProperty('--rx', `${180 + D.at * 192}px`)+ }++ // ---- loops ----+ const capture = () => ({ loop: cs(loop).transform, tail: cs(tail).transform, pair: cs(pair).transform, eyes: eyes.map(eye => cs(eye).transform) })+ // Every pose change starts here and then slides .whale-loop from where it is, lean included.+ const stopLoop = () => { delete root.dataset.whale; delete root.dataset.tail; D.loop = ''; D.lean = false }+ function slide(el, from, target, opts) {+ drop(el)+ if (from === 'none' && target === 'none') return null+ const anim = play(el, [{ transform: from }, { transform: target }], opts)+ anim.done.then(() => settle(anim, el))+ return anim+ }+ function release(pose, opts) {+ slide(loop, pose.loop, 'none', opts)+ slide(tail, pose.tail, 'none', opts)+ slide(pair, pose.pair, 'none', opts)+ eyes.forEach((eye, k) => slide(eye, pose.eyes[k], 'none', opts))+ }+ const START = { searching: { loop: 'rotate(-4deg)', pair: 'translateX(-12%)' }, pondering: { loop: 'rotate(4deg)', eye: 'translate(0,-4%) scaleY(.7)' } }+ async function startLoop(name) {+ const tailName = first && tier() !== 'quiet' ? ({ working: 'beat', sending: 'dash' }[name] ?? '') : ''+ if (D.loop === name) return+ const mine = token+ const pose = capture()+ stopLoop()+ if (!reduced()) {+ const shape = spring('shape')+ const begin = START[name] ?? {}+ slide(loop, pose.loop, begin.loop ?? 'none', shape)+ slide(pair, pose.pair, begin.pair ?? 'none', { duration: 240, easing: 'ease-out' })+ slide(tail, pose.tail, 'none', { duration: 240, easing: 'ease-out' })+ eyes.forEach((eye, k) => slide(eye, pose.eyes[k], begin.eye ?? 'none', { duration: 240, easing: 'ease-out' }))+ await until(wait(shape.duration))+ if (mine !== token) return+ }+ // The slides end on the loop's first frame, so dropping them in the same task as the+ // switch shows no jump.+ for (const el of [loop, pair, tail, ...eyes]) { for (const a of scripted(el)) a.cancel(); el.style.removeProperty('transform') }+ root.dataset.whale = name+ if (tailName) root.dataset.tail = tailName+ D.loop = name+ D.loopAt = performance.now()+ if (D.slow === 1) calm()+ }+ // Calmer, never faster (S6): every running whale animation at .85, no phase jump.+ function calm() {+ for (const el of [loop, tail, pair, move, ...eyes]) for (const a of el.getAnimations()) if (a.playbackRate === 1) a.updatePlaybackRate(0.85)+ }+ // The 10 s glance and the return glance share one budget: at most one every 20 s.+ async function glance(poses = ['loop']) {+ const now = performance.now()+ if (!playful() || !poses.includes(D.pose) || D.gazeHold || now - D.glanceAt < 20000) return+ D.glanceAt = now+ D.gazeHold = true+ setGaze(0, -0.3)+ for (const eye of eyes) play(eye, kf([{ transform: 'none' }, { transform: 'scaleY(.03)', offset: 1 / 3 }, { transform: 'scaleY(.03)', offset: 5 / 9 }, { transform: 'none' }], 'ease-in-out'), { duration: 360, fill: 'none' })+ await sleep(600)+ D.gazeHold = false+ applyGaze()+ }++ // ---- one-shots ----+ function nod() {+ if (!playful() || instant || ['down', 'lift', 'dive'].includes(D.pose) || D.pet || D.poking || D.hop) return+ // One answer nods once, whichever listener asks first.+ if (performance.now() - D.nodAt < 150) return+ D.nodAt = performance.now()+ const a = play(move, [{ transform: 'none' }, { transform: 'translateY(2px) rotate(3deg)' }], { ...spring('tap'), fill: 'forwards' })+ setTimeout(() => {+ if (D.pet || D.hop || D.poking) return+ const from = cs(move).transform+ a.cancel()+ const b = play(move, [{ transform: from }, { transform: 'none' }], spring('shape'))+ b.done.then(() => settle(b, move))+ }, 160)+ const keep = [D.bx, D.by]+ setBase(keep[0], 0.6)+ setTimeout(() => { if (D.by === 0.6) setBase(keep[0], keep[1]) }, 300)+ }+ function hop(count) {+ const lift = `translateY(${(-8.1 * u).toFixed(2)}px) scale(.96,1.05)`+ const frames = kf([{ offset: 0, transform: 'none' }, { offset: 0.2, transform: lift }, { offset: 0.4, transform: 'translateY(0) scale(1.06,.94)' }, { offset: 0.55, transform: 'none' }, { offset: 1, transform: 'none' }], HOP)+ drop(move)+ return play(move, frames, { duration: HOP_MS, iterations: count, fill: 'none' })+ }+ function stopHop() {+ const a = D.hop+ if (!a) return+ D.hop = null+ const from = cs(move).transform+ a.cancel()+ if (from !== 'none') slide(move, from, 'none', spring('shape'))+ }+ function happyEyes(on, ms = 140) {+ eyes.forEach(eye => to(eye, { transform: on ? 'scaleY(0)' : 'none' }, { duration: ms, easing: on ? 'ease-in' : 'ease-out' }))+ happy.forEach(arc => to(arc, { opacity: on ? '1' : '0' }, { duration: 120, delay: on ? 100 : 0, easing: 'ease-out' }))+ }+ function petStart() {+ if (!playful() || !['alert', 'rest'].includes(D.pose) || D.pet || D.poking || D.handed) return+ stopHop()+ D.hopsStopped = true+ leanOut()+ const lean = `translate(${(4.6 * u).toFixed(2)}px, ${(-0.58 * u).toFixed(2)}px) rotate(8deg)`+ const nuzzle = `translate(${(7.4 * u).toFixed(2)}px, ${(-1.74 * u).toFixed(2)}px) rotate(14deg) scale(1.03, .97)`+ const a = to(move, { transform: lean }, spring('pop'))+ const b = play(move, [{ transform: lean }, { transform: nuzzle, offset: 0.5 }, { transform: lean }], { duration: 780, delay: 320, iterations: Infinity, easing: 'ease-in-out', fill: 'none' })+ happyEyes(true)+ D.pet = [a, b]+ }+ function petEnd() {+ if (!D.pet) return+ const from = cs(move).transform+ for (const a of D.pet) a.cancel()+ D.pet = null+ slide(move, from, 'none', spring('pop'))+ happyEyes(false)+ leanIn()+ }+ async function poke() {+ if (!first || !playful() || D.poking || D.pet || D.hop || D.handed || ['down', 'lift', 'dive', 'sunk', 'enter'].includes(D.pose)) return+ D.poking = true+ drop(move)+ move.style.transformOrigin = '50% 60%'+ const a = play(move, kf([{ transform: 'none' }, { transform: `translateY(${(-9.3 * u).toFixed(2)}px) rotate(360deg)`, offset: 0.55 }, { transform: 'translateY(0) scale(1.08,.92) rotate(360deg)', offset: 0.78 }, { transform: 'rotate(360deg)' }], HOP), { duration: 800, fill: 'none' })+ await a.done+ a.cancel()+ move.style.removeProperty('transform-origin')+ D.poking = false+ }+ function lookAround() {+ if (!playful()) return+ const side = v => `translateX(${v}%)`+ play(pair, kf([{ transform: 'none' }, { transform: side(-14), offset: 0.15 }, { transform: side(-14), offset: 0.4 }, { transform: side(14), offset: 0.55 }, { transform: side(14), offset: 0.85 }, { transform: 'none' }], 'ease-in-out'), { duration: 900, fill: 'none' })+ }+ function sendRipple() {+ if (!playful()) return+ play(ripple, [{ scale: '.5' }, { scale: '1.6' }], { ...spring('shape'), fill: 'none' })+ play(ripple, [{ opacity: 0.9 }, { opacity: 0 }], { duration: 160, easing: 'linear', fill: 'none' })+ }++ // ---- rest on a card: lean, breath, blinks, lively hops (none in quiet, reduced or failure) ----+ const stirs = () => playful() && !failure()+ const px = v => (v * u / 0.88).toFixed(2)+ // Nose 2.5° down toward the sheet, 1.5 px forward, 1 px up (at 88 px), on .whale-loop, which+ // no loop uses while a card waits, so hops, nods and petting compose on top of it.+ const LEAN = () => `translate(${px(1.5)}px, ${px(-1)}px) rotate(2.5deg)`+ function leanAt(mine, ms) {+ D.leanDue = false+ D.leanOff = false+ D.leanMine = mine+ if (!stirs()) return+ if (instant) { D.leanDue = true; leanIn(); return }+ later(mine, ms, () => { D.leanDue = true; leanIn() })+ }+ function leanIn() {+ if (D.lean || !D.leanDue || D.leanOff || D.leanMine !== token || D.pet || D.handed || !stirs() || !['alert', 'rest'].includes(D.pose)) return+ D.lean = true+ to(loop, { transform: LEAN() }, spring('shape'))+ }+ function leanOut() {+ if (!D.lean) return+ D.lean = false+ to(loop, { transform: 'none' }, spring('shape'))+ }+ function breathe(mine) {+ if (D.breath || instant || !stirs() || D.pose !== 'rest') return+ // Compositor-only: the scale property on an HTML wrapper that nothing else scales.+ const a = gazeLayer.animate(kf([{ scale: '1' }, { scale: '1.008 1.018', offset: 0.45 }, { scale: '1' }], 'ease-in-out'), { duration: 4200, iterations: Infinity })+ D.breath = a+ const age = performance.now() - D.cardAt+ a.updatePlaybackRate(calmer(age)[0])+ const slower = () => { const rate = calmer(performance.now() - D.cardAt)[0]; if (D.breath === a && rate < a.playbackRate) a.updatePlaybackRate(rate) }+ for (const at of [30000, 90000]) if (age < at) later(mine, at - age, slower)+ }+ function stopBreath() {+ const a = D.breath+ if (!a) return+ D.breath = null+ const from = cs(gazeLayer).scale+ a.cancel()+ if (!reduced() && from !== 'none' && from !== '1') play(gazeLayer, [{ scale: from }, { scale: '1' }], { duration: 240, easing: 'ease-out', fill: 'none' })+ }+ const canBlink = () => stirs() && D.pose === 'rest' && !D.pet && !D.hop && !D.poking && !D.gazeHold && !D.handed && !root.dataset.eyes && !document.hidden && eyes.every(eye => !eye.style.transform && scripted(eye).length === 0)+ function blink() {+ if (!canBlink()) return+ for (const eye of eyes) {+ const a = play(eye, kf([{ transform: 'none' }, { transform: 'scaleY(.03)', offset: 0.48 }, { transform: 'scaleY(1.06)', offset: 0.78 }, { transform: 'none' }], 'ease-in-out'), { duration: 270, fill: 'none' })+ a.done.then(() => a.cancel())+ }+ }+ function blinkLater(mine, firstOne) {+ const gap = firstOne ? 1400 + 800 * rnd() : (3200 + 3600 * rnd()) * calmer(performance.now() - D.cardAt)[1]+ const double = rnd() < 0.2+ later(mine, gap, () => {+ blink()+ if (double) later(mine, 340, blink)+ blinkLater(mine, false)+ })+ }+ function resting(mine) {+ D.restMine = mine+ if (!stirs()) return+ later(mine, 600, () => breathe(mine))+ blinkLater(mine, true)+ }+ // Lively: after the two hops (starts 0 and 1.3 s), more at +2.6 s, +5.2 s, then every 9 s.+ function moreHops(mine, began) {+ let at = began + HOP_MS+ let k = 0+ const next = () => {+ at += MORE_HOPS[k] ?? HOP_EVERY+ k += 1+ later(mine, at - performance.now(), () => {+ if (D.hopsStopped || D.pose !== 'rest' || !stirs()) return+ if (D.pet || D.poking || D.hop) { next(); return }+ const a = hop(1)+ D.hop = a+ a.done.then(() => { if (D.hop === a) { D.hop = null; a.cancel() } })+ next()+ })+ }+ next()+ }++ // ---- poses ----+ async function leg(i, queued, ms) {+ D.legging = true+ changed()+ try { await swim(i, queued, ms) } finally { D.legging = false; changed() }+ }+ async function swim(i, queued, ms) {+ clearTimeout(activeTimer)+ petEnd()+ stopHop()+ const x0 = i * 192+ const x1 = x0 + 192+ const shape = spring('shape')+ const glideMs = ms || shape.duration+ if (reduced() || instant) {+ // Reduced motion: the whale never travels; the lane cross-fades and the ring fades in.+ if (!instant) await play(lane, [{ opacity: 1 }, { opacity: 0 }], { duration: 120, fill: 'none' }).done+ x.style.translate = `${x1}px 0`+ popCheck(i)+ D.at = i + 1+ place()+ if (!instant) await play(lane, [{ opacity: 0 }, { opacity: 1 }], { duration: 120, fill: 'none' }).done+ return+ }+ const pose = capture()+ stopLoop()+ release(pose, { duration: queued ? 160 : 120, easing: 'ease-out' })+ if (!queued) {+ to(body, { scale: '1.04 .96' }, { duration: 120, easing: OUT })+ to(move, { transform: 'translateX(-3px)' }, { duration: 120, easing: OUT })+ await sleep(120)+ }+ const timing = { duration: glideMs, easing: shape.easing }+ drop(x)+ // The glide is SPRING_SHAPE clamped at the target: its 2 % overshoot would settle back+ // leftwards, and the whale never swims backwards. Tilt and scale keep the full spring.+ const glide = play(x, [{ translate: `${x0}px 0` }, { translate: `${x1}px 0` }], { duration: glideMs, easing: clamped(shape.easing) })+ to(body, { scale: '1' }, timing)+ drop(move)+ const tilt = play(move, [{ transform: `${queued ? '' : 'translateX(-3px) '}rotate(-4deg)` }, { transform: 'none' }], timing)+ if (playful()) {+ const strokes = play(tail, [{ transform: 'none' }, { transform: 'rotate(10deg)' }, { transform: 'rotate(-10deg)' }, { transform: 'none' }], { duration: 200, iterations: 2, easing: 'ease-in-out', fill: 'none' })+ strokes.done.then(() => strokes.cancel())+ const gz = $('#gaze')+ const base = cs(gz).transform+ const lag = play(gz, [{ transform: `translateX(-1.5px)${base === 'none' ? '' : ` ${base}`}` }, { transform: base }], { duration: shape.duration, delay: 80, easing: shape.easing, fill: 'backwards' })+ lag.done.then(() => lag.cancel())+ }+ setTimeout(() => popCheck(i), 90)+ await glide.done+ settle(glide, x)+ settle(tilt, move)+ D.at = i + 1+ place()+ }+ async function runLegs(flush) {+ let ran = 0+ while (D.at < want.station) {+ const i = D.at+ if (!ran && !flush) {+ const holdTo = Math.max(D.activeAt[i] ? D.activeAt[i] + HOLD : 0, D.loopAt ? D.loopAt + HOLD : 0)+ if (holdTo > performance.now()) await wait(holdTo - performance.now())+ }+ await leg(i, ran > 0 || flush, flush ? Math.min(420, Math.floor(600 / (want.station - i))) : 0)+ ran += 1+ }+ if (!ran) return+ D.loopAt = 0+ armActive()+ if (!flush && D.at <= 2 && !(D.at < 2 && want.done.includes(PHASES[D.at]))) nod()+ }+ // A failed stage is only marked in the hidden list: the whale's pose says it, nothing is drawn.+ function failStation() {+ if (!first) return+ const i = want.view === 'viewFailed' ? 2 : Math.min(D.at, Math.max(0, PHASES.indexOf(want.phase)))+ clearTimeout(activeTimer)+ if (D.checks > i) return+ D.failed = i+ setStation(i, 'failed')+ }+ async function goDown() {+ if (['down', 'lift'].includes(D.pose)) return+ stopHop()+ petEnd()+ D.pose = 'down'+ D.card = ''+ D.clockKind = ''+ // A failed import leaves the phases as they were; only a failed start crosses a station.+ if (want.view === 'failed' || want.view === 'viewFailed') failStation()+ const pose = capture()+ stopLoop()+ setBase(0.2, 0.6)+ if (reduced()) { root.dataset.eyes = 'heavy'; return }+ const shape = spring('shape')+ release(pose, shape)+ eyes.forEach((eye, k) => slide(eye, pose.eyes[k], 'translateY(1.5px) scaleY(.55)', shape))+ to(body, { scale: '1' }, shape)+ await until(to(move, { transform: 'translateY(4px) rotate(4deg)' }, shape).done)+ }+ async function lift() {+ if (D.pose !== 'down') return+ D.pose = 'lift'+ setBase(0.4, -0.4)+ if (reduced()) return+ const shape = spring('shape')+ eyes.forEach(eye => to(eye, { transform: 'translateY(1px) scaleY(.8)' }, shape))+ await until(to(move, { transform: 'translateY(2px)' }, shape).done)+ }+ async function shakeOff() {+ D.pose = 'loop'+ delete root.dataset.eyes+ setBase(0, 0)+ if (D.failed !== undefined) {+ const i = D.failed+ D.failed = undefined+ setStation(i, 'pending')+ armActive()+ changed()+ }+ if (reduced()) { for (const el of [move, ...eyes]) el.style.removeProperty('transform'); return }+ const shape = spring('shape')+ to(move, { transform: 'none' }, shape)+ eyes.forEach(eye => to(eye, { transform: 'none' }, shape))+ drop(body)+ const s = play(body, kf([{ scale: '1' }, { scale: '.94 1.08', offset: 0.4 }, { scale: '1.03 .97', offset: 0.75 }, { scale: '1' }], OUT), { duration: 800 })+ await s.done+ settle(s, body)+ }+ async function resetRun() {+ // A new folder or a blank team: sink, fade the rings, resurface at the first stop. The+ // whale's line and the hint go quiet while it is under (stage().sinking).+ D.sinking = true+ changed()+ petEnd()+ stopHop()+ const pose = capture()+ stopLoop()+ const fadeOut = el => play(el, [{ opacity: Number(cs(el).opacity) }, { opacity: 0 }], { duration: 160 })+ if (!reduced()) {+ release(pose, spring('shape'))+ to(move, { transform: 'translateY(64px)' }, spring('shape'))+ play(move, [{ opacity: 1 }, { opacity: 0 }], { duration: 160 })+ await wait(spring('shape').duration)+ } else await fadeOut(lane).done+ const rings = traces.filter(ring => ring.hasAttribute('data-on'))+ const outs = rings.map(fadeOut)+ await Promise.all(outs.map(a => a.done))+ for (let i = 0; i < 3; i += 1) setStation(i, 'pending')+ D.at = 0+ D.checks = 0+ D.failed = undefined+ D.since = [performance.now()]+ D.activeAt = []+ delete root.dataset.eyes+ for (const el of [x, move, body, lane, ...eyes]) { for (const a of scripted(el)) a.cancel(); el.style.removeProperty('transform'); el.style.removeProperty('translate'); el.style.removeProperty('opacity'); el.style.removeProperty('scale') }+ for (const ring of rings) { delete ring.dataset.on; for (const a of scripted(ring)) a.cancel(); ring.style.removeProperty('opacity'); ring.style.removeProperty('scale') }+ place()+ D.sinking = false+ changed()+ D.pose = 'loop'+ setBase(0, 0)+ if (!reduced()) {+ const up = play(move, [{ transform: 'translateY(64px) rotate(-12deg)' }, { transform: 'none' }], { ...spring('stretch'), fill: 'none' })+ await up.done+ }+ armActive()+ }+ // Another state on the same card (a leg, a retry that missed): the rest starts over.+ function restAgain(mine) {+ if (D.pose === 'alert' && !D.hop) D.pose = 'rest'+ if (D.pose !== 'rest' || D.restMine === mine) return+ leanAt(mine, 0)+ resting(mine)+ }+ async function cardPose() {+ const kind = want.view === 'watchdog' ? 'watchdog' : want.card+ const mine = token+ if (kind === D.card && !(want.missed && !D.missed)) { restAgain(mine); return }+ const previous = D.card+ D.card = kind+ if (kind !== D.clockKind) { D.clockKind = kind; D.cardAt = performance.now(); D.hopsStopped = false }+ if (kind === 'missing' && want.missed && !D.missed) {+ D.missed = true+ if (previous === 'missing') { lookAround(); restAgain(mine); return }+ }+ if (kind !== 'missing') D.missed = false+ if (kind === 'copying' || kind === 'newerUpdating') { stopHop(); D.pose = 'loop'; setBase(0, 0); await startLoop('working'); return }+ if (kind === 'importFailed') return goDown()+ stopHop()+ const pose = capture()+ stopLoop()+ if (!reduced()) release(pose, spring('shape'))+ setBase(0.2, 0.6)+ // Cards the user caused (picked, rejected, the stop confirmation) do not hop; they lean in+ // as the morph starts (the content veils in 70 ms later).+ const count = { recommend: 2, missing: 2, import: 2, newer: 2, watchdog: 2, importSpace: 1 }[kind] ?? 0+ if (!count || reduced()) { D.pose = 'rest'; leanAt(mine, 70); resting(mine); return }+ D.pose = 'alert'+ const began = performance.now()+ const a = hop(count)+ D.hop = a+ leanAt(mine, (count - 1) * HOP_MS + LANDED)+ await until(a.done)+ if (D.hop === a) stopHop()+ if (mine !== token) return+ D.pose = 'rest'+ resting(mine)+ if (tier() === 'lively' && count === 2) moreHops(mine, began)+ }+ async function phaseLoop() {+ stopHop()+ petEnd()+ D.card = ''+ D.clockKind = ''+ D.missed = false+ D.pose = 'loop'+ setBase(0, 0)+ if (reduced()) root.dataset.eyes = D.slow >= 2 ? 'squint' : ''+ const name = D.slow >= 2 ? 'pondering' : !first ? (D.workReady ? 'working' : '') : ({ data: 'searching', engine: 'working', team: 'sending' }[want.phase] ?? '')+ if (name) await startLoop(name)+ else if (D.loop || D.lean) { const pose = capture(); stopLoop(); release(pose, { duration: 240, easing: 'ease-out' }) }+ }+ async function handoff() {+ if (D.handed) return+ clearTimeout(activeTimer)+ stopHop()+ petEnd()+ if (first) {+ // The whale says 「进去吧」 (start.js reads stage().ready) as soon as the team is ready; a+ // leg still to swim and the last stop's hold run while it is on screen, and the+ // celebration waits until it has been there READY_MS.+ if (!D.ready) { D.ready = true; D.readyAt = performance.now(); changed() }+ await runLegs(true)+ // An active stage stays at least 400 ms before it is done (no flash of 'in progress').+ const shownAt = stations[2].dataset.state === 'active' ? D.activeAt[2] ?? 0 : 0+ if (shownAt && performance.now() < shownAt + HOLD) await wait(shownAt + HOLD - performance.now())+ if (!instant) {+ const said = await Promise.race([readyLine ? readyLine() : Promise.resolve(D.readyAt), sleep(READY_CAP).then(() => performance.now())])+ if (said + READY_MS > performance.now()) await sleep(said + READY_MS - performance.now())+ }+ }+ D.handed = true+ D.pose = 'dive'+ applyGaze()+ const celebrate = want.celebrate+ const begin = performance.now()+ const at = ms => sleep(Math.max(0, begin + ms - performance.now()))+ if (first) popCheck(2)+ const pose = capture()+ stopLoop()+ if (reduced()) {+ // Reduced: the content fades over .12 s; the celebration is only the ^ ^ eyes.+ if (celebrate && tier() !== 'quiet') root.dataset.eyes = 'happy'+ await at(first ? 300 : 0)+ root.dataset.exit = 'caption all lane'+ await at((first ? 300 : 0) + 120)+ act('handoffShow')+ await at((first ? 300 : 0) + 140)+ act('handoffDone')+ return+ }+ release(pose, { duration: 200, easing: 'ease-out' })+ if (first) {+ const diveAt = celebrate ? 460 : 300+ if (celebrate) {+ drop(body)+ play(body, kf([{ scale: '1' }, { scale: '1.12 .88', offset: 240 / 460 }, { scale: '.93 1.09' }], OUT), { duration: 460 })+ if (playful()) { happyEyes(true); play(tail, [{ transform: 'none' }, { transform: 'rotate(12deg)' }, { transform: 'none' }], { duration: 400, easing: 'ease-in-out', fill: 'none' }) }+ }+ await at(160)+ root.dataset.exit = 'caption'+ await at(diveAt)+ root.dataset.exit = 'caption all'+ dive(18, DEEP(), 24, spring('shape'))+ await at(diveAt + 100)+ sendRipple()+ await at(diveAt + 160)+ act('handoffShow')+ await at(diveAt + 420)+ act('handoffDone')+ return+ }+ let lead = 0+ if (celebrate) {+ lead = 920+ drop(body)+ play(body, kf([{ scale: '1' }, { scale: '1.12 .88', offset: 240 / 920 }, { scale: '.93 1.09', offset: 460 / 920 }, { scale: '1.04 .97', offset: 680 / 920 }, { scale: '1' }], OUT), { duration: 920 })+ if (playful()) happyEyes(true)+ root.dataset.exit = 'caption'+ await at(lead)+ }+ root.dataset.exit = 'caption all'+ dive(12, DEEP(), 18, spring('tap'))+ await at(lead + 120)+ act('handoffShow')+ await at(lead + 290)+ act('handoffDone')+ }+ // 1.25 x the whale's height: fully under the waterline within about 200 ms, so the window+ // can grow around an empty sheet.+ const DEEP = () => Math.round(125 * u)+ function dive(dx, dy, deg, curve) {+ to(body, { scale: '1' }, curve)+ to(move, { transform: `translate(${dx}px, ${dy}px) rotate(${deg}deg)` }, curve)+ if (playful() && first) play(tail, [{ transform: 'none' }, { transform: 'rotate(-12deg)', offset: 0.48 }, { transform: 'none' }], { duration: 420, easing: 'ease-out', fill: 'none' })+ }++ // ---- pointer and keyboard focus ----+ let pointer = null+ let focused = null+ let keyboard = false+ let frame = 0+ function setGaze(gx, gy) {+ x.style.setProperty('--gx', gx.toFixed(3))+ x.style.setProperty('--gy', gy.toFixed(3))+ }+ // The eyes look at the pointer, or at a control that keyboard focus reached, until the next+ // pointer move. The whale's hit box moves with the stations, so it is measured each time.+ function applyGaze() {+ frame = 0+ if (reduced()) return setGaze(0, 0)+ let gx = D.bx+ let gy = D.by+ const control = focused && focused === document.activeElement && focused.checkVisibility() ? focused.getBoundingClientRect() : null+ const target = control ? { x: control.left + control.width / 2, y: control.top + control.height / 2 } : pointer+ if (target && playful() && !D.gazeHold && !D.handed && !failure() && !['down', 'lift', 'dive'].includes(D.pose)) {+ const rect = hit.getBoundingClientRect()+ gx = clamp((target.x - (rect.left + rect.width / 2)) / 160)+ gy = clamp((target.y - (rect.top + rect.height / 2)) / 160)+ }+ setGaze(gx, gy)+ }+ function setBase(bx, by) { D.bx = bx; D.by = by; applyGaze() }+ window.addEventListener('pointermove', (event) => { pointer = { x: event.clientX, y: event.clientY }; focused = null; frame ||= requestAnimationFrame(applyGaze) }, { passive: true })+ root.addEventListener('pointerleave', () => { pointer = null; applyGaze() })+ hit.addEventListener('pointerenter', petStart)+ hit.addEventListener('pointerleave', petEnd)+ hit.addEventListener('click', poke)+ // Keyboard focus only: the card's own focus move after a pointer answer is not followed.+ window.addEventListener('keydown', () => { keyboard = true }, true)+ window.addEventListener('pointerdown', () => { keyboard = false }, true)+ document.addEventListener('focusin', (event) => {+ const el = event.target+ if (!keyboard || !el.matches?.('button, input[type=checkbox]') || !el.closest('.sheet, .caption') || !el.matches(':focus-visible')) return+ focused = el+ applyGaze()+ })++ // ---- answering a card: press anticipation, nod, lean released ----+ const answering = target => { const button = target?.closest?.('.card button[data-act]'); return button && !LOCAL.has(button.dataset.act) ? button : null }+ function unpress() {+ const button = D.press+ if (!button) return+ D.press = null+ button.removeEventListener('pointerleave', unpress)+ to(body, { scale: '1' }, spring('tap'))+ }+ document.addEventListener('pointerdown', (event) => {+ const button = answering(event.target)+ if (!button || event.button !== 0 || instant || !stirs() || D.handed || D.legging || ['down', 'lift', 'dive', 'sunk', 'enter'].includes(D.pose)) return+ unpress()+ D.press = button+ button.addEventListener('pointerleave', unpress)+ to(body, { scale: '1.03 .97' }, { duration: 120, easing: OUT })+ })+ document.addEventListener('pointercancel', unpress)+ // A press that ends without a click (the button went away under it) springs back too.+ document.addEventListener('pointerup', () => { if (D.press) setTimeout(unpress, 0) })+ // Capture phase: this runs before start.js sends the act, so a state that the act brings+ // drops the lean's return timer with the old token. The act itself is never delayed.+ document.addEventListener('click', (event) => {+ const button = answering(event.target)+ if (!button) return+ unpress()+ if (!stirs()) return+ const mine = token+ D.hopsStopped = true+ D.leanOff = true+ leanOut()+ // A card that stays (a model picked on the import card, logs opened) leans in again.+ later(mine, 1000, () => { D.leanOff = false; leanIn() })+ nod()+ }, true)++ // ---- coming back to the window: one glance at the user ----+ let blurAt = 0+ let hiddenAt = 0+ function returnGlance(since) {+ if (!since || performance.now() - since < 5000) return+ if (!stirs() || D.legging || D.handed || D.hop || D.pet || D.poking) return+ glance(['loop', 'rest'])+ }+ window.addEventListener('blur', () => { blurAt = performance.now() })+ window.addEventListener('focus', () => { returnGlance(blurAt); blurAt = 0 })+ document.addEventListener('visibilitychange', () => {+ if (document.hidden) { hiddenAt = performance.now(); return }+ returnGlance(hiddenAt)+ hiddenAt = 0+ })++ // ---- reconcile ----+ async function step() {+ await entered+ if (want.view === 'handoff') return handoff()+ if (D.pose === 'enter') { D.pose = 'loop'; place(); armActive() }+ if (want.station < D.checks) await resetRun()+ if (!failure() && ['down', 'lift', 'redo'].includes(D.pose)) await shakeOff()+ await runLegs(false)+ if (want.view === 'handoff') return handoff()+ if (failure()) {+ if (D.pose === 'redo') D.pose = 'loop'+ await goDown()+ if (['available', 'downloading', 'installing'].includes(want.update)) await lift()+ else if (want.update === 'failed' && D.pose === 'lift') { D.pose = 'loop'; await goDown() }+ return+ }+ if (want.view === 'card' || want.view === 'watchdog') return cardPose()+ return phaseLoop()+ }+ let pumping = false+ let again = false+ function kick() {+ again = true+ if (pumping) return+ pumping = true+ ;(async () => {+ try {+ while (again) { again = false; await step(); instant = false }+ } catch (error) { console.error(error) } finally { pumping = false; instant = false }+ })()+ }++ return {+ // Where the whale is, for its line: the stop it is at (0-2), the stage shown active there (or+ // -1), whether it is swimming to the next stop, and whether it has said 「进去吧」.+ stage: () => ({ at: D.at, active: stations.findIndex(st => st.dataset.state === 'active'), legging: D.legging, ready: D.ready, sinking: D.sinking }),+ update(s) {+ const done = s.done ?? []+ const now = performance.now()+ if (done.includes('data') && !want.done.includes('data')) D.since[1] = now+ if (done.includes('engine') && !want.done.includes('engine')) D.since[2] = now+ let station = 0+ if (first && done.includes('data')) station = done.includes('engine') ? 2 : 1+ const next = { station, view: s.view, phase: s.phase, done, card: s.card?.kind ?? '', missed: Boolean(s.card?.missedRetry), celebrate: Boolean(s.celebrate), update: s.update?.state ?? '' }+ const changed = !D.started || ['station', 'view', 'phase', 'card', 'missed', 'update'].some(key => next[key] !== want[key])+ want = next+ D.started = true+ if (changed) { bump(); kick() }+ },+ slow(level) {+ if (level === D.slow) return+ const previous = D.slow+ D.slow = level+ if (level === 0) {+ D.glanced = false+ for (const el of [loop, tail, pair, move, ...eyes]) for (const a of el.getAnimations()) if (a.playbackRate !== 1) a.updatePlaybackRate(1)+ }+ if (level === 1) { calm(); if (!D.glanced) { D.glanced = true; glance() } }+ if (level === 2 || previous === 2) { bump(); kick() }+ },+ nod,+ // Live switch of reduced motion or of the tier: running one-shots jump to their end.+ refresh() {+ stopBreath()+ D.press = null+ for (const el of [x, body, move, loop, tail, pair, lane, ripple, ...traces, ...eyes, ...happy]) for (const a of scripted(el)) settle(a, el)+ D.hop = null+ D.pet = null+ D.lean = false+ if (reduced()) {+ for (const el of [gazeLayer, body, move, loop, ...eyes, ...happy]) { for (const a of scripted(el)) a.cancel(); el.style.removeProperty('transform'); el.style.removeProperty('scale'); el.style.removeProperty('opacity') }+ root.dataset.eyes = ['down', 'lift'].includes(D.pose) ? 'heavy' : D.slow >= 2 ? 'squint' : ''+ applyGaze()+ return+ }+ delete root.dataset.eyes+ if (['down', 'lift'].includes(D.pose)) D.pose = 'redo'+ D.loop = ''+ D.card = ''+ bump()+ kick()+ },+ }+}diff --git a/app/test/start-page.test.mjs b/app/test/start-page.test.mjsnew file mode 100644index 00000000..bac93ba0--- /dev/null+++ b/app/test/start-page.test.mjs@@ -0,0 +1,120 @@+import assert from 'node:assert/strict'+import { spawnSync } from 'node:child_process'+import { existsSync, readFileSync } from 'node:fs'+import { test } from 'node:test'+import { fileURLToPath } from 'node:url'+import { TEXT, t } from '../src/start/text.mjs'++const dir = new URL('../src/start/', import.meta.url)+const read = name => readFileSync(new URL(name, dir), 'utf8')+const SCRIPTS = ['start.js', 'whale.js', 'text.mjs']+const html = read('start.html')+const code = Object.fromEntries(SCRIPTS.map(name => [name, read(name)]))+const uncommented = text => text.replace(/\/\/[^\n]*|\/\*[\s\S]*?\*\//gu, '')++test('the start page runs under its CSP: no inline style or script, no data: or network URLs', () => {+ assert.ok(html.includes(`<meta http-equiv="Content-Security-Policy" content="default-src 'self'; base-uri 'none'; object-src 'none'">`), 'the CSP meta is missing or changed')+ const rules = [+ [/<style[\s>]/iu, '<style> element'],+ [/\sstyle\s*=/iu, 'style= attribute'],+ [/\son[a-z]+\s*=/iu, 'on* handler attribute'],+ [/<script(?![^>]*\ssrc=)[^>]*>/iu, 'inline <script>'],+ [/data:/iu, 'data: URL'],+ [/https?:/iu, 'http(s): URL'],+ ]+ for (const [pattern, what] of rules) assert.doesNotMatch(html, pattern, `start.html: ${what}`)+ for (const name of ['start.css', ...SCRIPTS]) {+ const body = uncommented(read(name))+ assert.doesNotMatch(body, /url\(\s*['"]?(?:data:|https?:)|@import/iu, `${name}: external or data: resource`)+ assert.doesNotMatch(body, /innerHTML|outerHTML|insertAdjacentHTML|document\.write|eval\(|new Function/u, `${name}: markup or code from strings`)+ }+})++test('every file the page loads is relative and inside src/start', () => {+ const inside = (from, url) => {+ assert.doesNotMatch(url, /^(?:[a-z][\w+.-]*:|\/|\\)|\.\./iu, `${from} loads ${url}`)+ assert.ok(existsSync(new URL(url, dir)), `${from} loads ${url}, which is missing`)+ }+ const loads = [...html.matchAll(/\s(?:src|href)="([^"#][^"]*)"/gu)].map(match => match[1])+ assert.deepEqual(loads, ['start.css', 'start.js'])+ assert.match(html, /<script type="module" src="start.js"><\/script>/u)+ for (const url of loads) inside('start.html', url)+ for (const [name, text] of Object.entries(code)) {+ const body = uncommented(text)+ assert.doesNotMatch(body, /\bimport\s*\(/u, `${name}: a dynamic import`)+ for (const match of body.matchAll(/^\s*(?:import|export)\b[^'"\n]*?\bfrom\s*['"]([^'"]+)['"]|^\s*import\s*['"]([^'"]+)['"]/gmu)) inside(name, match[1] ?? match[2])+ }+ for (const [, url] of uncommented(read('start.css')).matchAll(/url\(\s*['"]?([^'")#][^'")]*)/gu)) inside('start.css', url)+})++test('the page binds window.dsBotStart through onState and act only', () => {+ const used = new Set([...code['start.js'].matchAll(/\bbridge\??\.(\w+)/gu)].map(match => match[1]))+ assert.deepEqual([...used].sort(), ['act', 'onState'])+ assert.match(code['start.js'], /const bridge = window\.dsBotStart\b/u)+})++// The acts the main process must accept from the start window (its allowlist).+test('the page sends only the acts of the start window', () => {+ const local = new Set(['toggleDetails', 'toggleMore', 'toggleModels'])+ const sent = new Set([+ ...[...html.matchAll(/data-act="(\w+)"/gu)].map(match => match[1]),+ ...[...code['start.js'].matchAll(/\bact: '(\w+)'|\bact\('(\w+)'/gu)].map(match => match[1] ?? match[2]),+ ...[...code['whale.js'].matchAll(/\bact\('(\w+)'\)/gu)].map(match => match[1]),+ ].filter(name => !local.has(name)))+ assert.deepEqual([...sent].sort(), ['answer', 'copyDetails', 'freshStart', 'handoffDone', 'handoffShow', 'importModel', 'importOption', 'installUpdate', 'keepCopying', 'manualDownload', 'openLogs', 'pick', 'reloadView', 'retry', 'stopCopy', 'wait'])+})++test('zh and en carry the same keys and the same placeholders', () => {+ const placeholders = text => (text.match(/\{\w+\}/gu) ?? []).sort().join()+ assert.deepEqual(Object.keys(TEXT.en).sort(), Object.keys(TEXT.zh).sort())+ for (const [key, zh] of Object.entries(TEXT.zh)) assert.equal(placeholders(TEXT.en[key]), placeholders(zh), `${key}: placeholders differ`)+})++// docs/plans/2026-10-26-windows-onboarding.md, 用词: proper names and units only.+test('the zh copy shows no English but the allowed names and units', () => {+ const NAMES = ['DS Bot', 'DSH Desktop', 'DSH Web']+ const WORDS = new Set(['DeepSeek', 'Bot', 'API', 'Key', 'Harness', 'DSH', 'Agent', 'MCP', 'Windows', 'PowerShell', 'GitHub', 'SmartScreen', 'OneDrive', 'HTTP', 'SOCKS', 'KB', 'MB', 'GB'])+ const english = []+ for (const [key, value] of Object.entries(TEXT.zh)) {+ let rest = value.replace(/\{\w+\}/gu, ' ')+ for (const name of NAMES) rest = rest.replaceAll(name, ' ')+ for (const word of rest.match(/[A-Za-z][A-Za-z0-9.-]*/gu) ?? []) if (!WORDS.has(word)) english.push(`${key}: ${word}`)+ // A promise the engine cannot keep.+ assert.doesNotMatch(value, /马上|稍后|下个版本/u, key)+ }+ assert.deepEqual(english, [])+})++test('every text key that the page uses exists', () => {+ const keys = Object.keys(TEXT.zh)+ const matching = pattern => keys.filter(key => new RegExp(`^${pattern.replaceAll('.', '\\.').replace(/\{\w+\}/gu, '\\w+')}$`, 'u').test(key))+ for (const [, key] of html.matchAll(/data-t(?:-label)?="([^"]+)"/gu)) assert.ok(matching(key).length > 0, `start.html: unknown text key ${key}`)+ const literal = /^(?:voice|hint|title|say|card|import|copying|eta|sr|state|phase|slow|update|failed|newer|importFailed|track)\.[\w.]+$/u+ for (const name of ['start.js', 'whale.js']) {+ const text = uncommented(code[name])+ const used = [+ ...[...text.matchAll(/'([\w.]+)'/gu)].map(match => match[1]).filter(key => literal.test(key)),+ ...[...text.matchAll(/\b(?:say|label)\('([\w.]+)'/gu)].map(match => match[1]),+ ]+ for (const key of used) assert.ok(key in TEXT.zh, `${name}: unknown text key ${key}`)+ for (const [, prefix] of text.matchAll(/`([\w.]+\.)\$\{/gu)) assert.ok(keys.some(key => key.startsWith(prefix)), `${name}: no text key starts with ${prefix}`)+ }+ // Keys the page builds from the snapshot's views, the stages and the failure reasons.+ for (const key of ['title.failed', 'title.viewFailed', 'title.later', 'title.moving', 'phase.data', 'phase.engine', 'phase.team', 'state.pending', 'state.active', 'state.done', 'state.failed']) assert.ok(key in TEXT.zh, key)+ assert.deepEqual(matching('failed.reason.{reason}').sort(), ['failed.reason.engine', 'failed.reason.files', 'failed.reason.other', 'failed.reason.permission', 'failed.reason.space'])+})++test('t fills placeholders and falls back to zh, then to the key', () => {+ assert.equal(t('zh', 'elapsed', { n: 12 }), '已用 12 秒')+ assert.equal(t('en', 'elapsed', { n: 12 }), '12 s so far')+ assert.equal(t('en', 'voice.helloName', { name: 'Ada' }), 'Hi, I’m Ada')+ assert.equal(t('fr', 'retry'), '重试')+ assert.equal(t('en', 'hint.space', { drive: 'C' }), 'Only {free} left on drive C')+ assert.equal(t('zh', 'no.such.key'), 'no.such.key')+})++test('the generated blocks of the start page are current', () => {+ const script = fileURLToPath(new URL('../scripts/start-assets.mjs', import.meta.url))+ const result = spawnSync(process.execPath, [script, '--check'], { encoding: 'utf8' })+ assert.equal(result.status, 0, result.stderr || result.stdout)+})