cortico-world-agent-speed 0.2.7 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-agent-speed",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
4
4
  "type": "module",
5
5
  "description": "The Coopanion desktop pet with local Agent Speed activity animation",
6
6
  "main": "./src/index.ts",
@@ -3,12 +3,16 @@
3
3
  .own-dress-status{font-size:13px;color:var(--dress-muted);margin-bottom:12px}
4
4
  .own-dress-status[hidden]{display:none}
5
5
  .own-dress-retry{font:inherit;color:var(--dress-accent);border:0;background:none;text-decoration:underline;cursor:pointer}
6
- .own-dress-stage{position:relative;height:300px;overflow:hidden;border:1px solid #252c37;border-radius:12px;background:#10151c radial-gradient(#232b37 1.2px,transparent 1.3px) 0 0 / 22px 22px}
6
+ .own-dress-stage{position:relative;height:300px;overflow:hidden;touch-action:none;border:1px solid #252c37;border-radius:12px;background:#10151c radial-gradient(#232b37 1.2px,transparent 1.3px) 0 0 / 22px 22px}
7
7
  .own-dress-stage[data-theme=light]{border-color:#e2dfe8;background-color:#e8e6ee;background-image:radial-gradient(#cfcbd9 1.2px,transparent 1.3px)}
8
8
  .own-dress-floor{position:absolute;bottom:0;left:0;right:0;height:48px;border-top:1px solid #252c37;background:#151a22}
9
9
  .own-dress-stage[data-theme=light] .own-dress-floor{border-color:#e2dfe8;background:#fff}
10
- .own-dress-art{position:absolute;inset:25px 0 48px;display:flex;align-items:flex-end;justify-content:center;pointer-events:none}
11
- .own-dress-art svg,.own-dress-art img{width:190px;height:190px;object-fit:contain}
10
+ .own-dress-layer,.own-dress-layer .figure-clip{position:absolute;inset:0;pointer-events:none}
11
+ .own-dress-layer iframe{position:absolute;inset:0;width:100%;height:100%;border:0;background:transparent;color-scheme:normal;pointer-events:none}
12
+ .own-dress-preview-status{position:absolute;inset:0 16px 48px;display:flex;align-items:center;justify-content:center;flex-wrap:wrap;gap:4px;color:#e9edf2;font-size:13px;text-align:center;pointer-events:none}
13
+ .own-dress-preview-status[hidden]{display:none}
14
+ .own-dress-preview-status button{pointer-events:auto}
15
+ .own-dress-stage[data-theme=light] .own-dress-preview-status{color:#1b1626}
12
16
  .own-dress-corner{position:absolute;top:12px;right:12px;display:flex;gap:8px}
13
17
  .own-dress-round{display:grid;place-items:center;width:34px;height:34px;padding:0;border:1px solid #252c37;border-radius:50%;background:#151a22;color:#e9edf2;font:inherit;font-size:21px;cursor:pointer}
14
18
  .own-dress-stage[data-theme=light] .own-dress-round{background:#fff;border-color:#e2dfe8;color:#1b1626}
@@ -1,5 +1,6 @@
1
1
  import type { WebUiPanelContext } from 'cortico/web/shared/client-panel.ts';
2
2
  import { mini, normalizeSkin, skinVars, wear } from '../../web/coo/coo.js';
3
+ import { loadBody } from '../../web/body-host.js';
3
4
  import { localDressDialogs, type DressDialogView, type DressDialogAnswer } from './dress-dialog.ts';
4
5
  import './dress.css';
5
6
 
@@ -7,8 +8,16 @@ type Skin = Record<string, unknown>;
7
8
  type Pack = { id: string; name: string; thumb: string | null; axes: Array<{ id: string; label: string; options: Array<{ id: string; label: string; thumb?: string | null }> }>; picks: Record<string, string> };
8
9
  type State = { skin: Skin; scale: number; theme: 'dark' | 'light'; looks: Array<{ id: string; name: string; skin: Skin; scale?: number }>; packs: Pack[]; importable: boolean };
9
10
  type ImportResult = { token: string; packs: Array<{ dir: string; id: string; name: string; installed: string | null }>; problems: Array<{ dir: string; reason: string }> };
11
+ type PreviewBody = {
12
+ tick(dt: number): void;
13
+ set(state: Record<string, unknown>): void;
14
+ setScheme(scheme: unknown): Promise<void>;
15
+ pointer(type: string, point: Record<string, number>): void;
16
+ hit(point: { x: number; y: number }): boolean;
17
+ dispose(): void;
18
+ };
10
19
 
11
- /** The settings page renders only built-in Coo code and backend-validated raster images. */
20
+ /** The settings page renders validated figure packs in an isolated preview. */
12
21
  export function mountDress(ctx: WebUiPanelContext, host: HTMLElement): void {
13
22
  const doc = host.ownerDocument;
14
23
  const zh = ctx.language === 'zh' || ctx.language === 'zh-Hant';
@@ -24,8 +33,113 @@ export function mountDress(ctx: WebUiPanelContext, host: HTMLElement): void {
24
33
  let state: State | undefined;
25
34
  let activeLook: string | null = null;
26
35
  let queue: Promise<void> = Promise.resolve();
27
- let paint: (() => void) | undefined;
28
- let timer = 0;
36
+ const stage = el('div', 'own-dress-stage');
37
+ stage.setAttribute('aria-label', text('Preview', '预览'));
38
+ const floor = el('div', 'own-dress-floor');
39
+ const layer = el('div', 'own-dress-layer');
40
+ const previewStatus = el('div', 'own-dress-preview-status');
41
+ previewStatus.setAttribute('role', 'status');
42
+ const stageControls = el('div', 'own-dress-controls');
43
+ stage.append(floor, layer, previewStatus, stageControls);
44
+ content.append(stage);
45
+ let grid: HTMLElement | undefined;
46
+ let body: PreviewBody | undefined;
47
+ let loading: AbortController | undefined;
48
+ let wanted = '';
49
+ let shownScheme: unknown;
50
+ let visible = false;
51
+ let frame = 0;
52
+ let lastFrame = 0;
53
+ const bounds = () => {
54
+ const W = stage.clientWidth, H = stage.clientHeight, floorY = Math.max(0, H - 48);
55
+ return { W, H, floorY, S: Math.max(0.01, Math.min(.5, (floorY - 12) / 384, (W - 24) / 384)) };
56
+ };
57
+ const animate = (now: number) => {
58
+ frame = 0;
59
+ if (!visible || doc.hidden || ctx.signal.aborted || !body) { lastFrame = 0; return; }
60
+ if (lastFrame) body.tick(Math.min((now - lastFrame) / 1000, .05));
61
+ lastFrame = now;
62
+ frame = requestAnimationFrame(animate);
63
+ };
64
+ const updateAnimation = () => {
65
+ if (visible && !doc.hidden && body && !ctx.signal.aborted) {
66
+ if (!frame) frame = requestAnimationFrame(animate);
67
+ } else {
68
+ cancelAnimationFrame(frame); frame = 0; lastFrame = 0;
69
+ }
70
+ };
71
+ const previewError = (error: unknown) => {
72
+ previewStatus.replaceChildren(doc.createTextNode(text('Preview could not load: ', '预览加载失败:') + errorText(error) + ' '));
73
+ const retry = button(text('Retry', '重试'), 'own-dress-retry');
74
+ retry.addEventListener('click', () => { wanted = ''; showPreview(); });
75
+ previewStatus.append(retry);
76
+ previewStatus.hidden = false;
77
+ };
78
+ const showPreview = () => {
79
+ if (!state || ctx.signal.aborted) return;
80
+ const current = state;
81
+ const id = typeof current.skin.figure === 'string' ? current.skin.figure : 'coo';
82
+ stage.dataset.theme = current.theme;
83
+ if (wanted === id) {
84
+ body?.set({ skin: current.skin, theme: current.theme, bounds: bounds() });
85
+ if (body && id !== 'coo' && shownScheme !== current.skin.scheme) {
86
+ shownScheme = current.skin.scheme;
87
+ void body.setScheme(shownScheme);
88
+ }
89
+ return;
90
+ }
91
+ wanted = id;
92
+ loading?.abort();
93
+ body?.dispose(); body = undefined;
94
+ updateAnimation();
95
+ previewStatus.hidden = false;
96
+ previewStatus.textContent = text('Loading preview…', '正在加载预览…');
97
+ const controller = new AbortController(); loading = controller;
98
+ void (async () => {
99
+ try {
100
+ const result = await ctx.invoke<{ origin: string; pack: unknown }>('dressPreview', [id]);
101
+ if (controller.signal.aborted || ctx.signal.aborted) return;
102
+ const startBounds = bounds();
103
+ const next = await loadBody({
104
+ layer, pack: result.pack, previewOrigin: result.origin, languageCode: ctx.language,
105
+ start: { x: startBounds.W / 2, skin: current.skin, scheme: current.skin.scheme },
106
+ theme: current.theme, bounds: startBounds, signal: controller.signal,
107
+ onError: (error: unknown) => {
108
+ if (controller.signal.aborted || ctx.signal.aborted) return;
109
+ body?.dispose(); body = undefined; updateAnimation(); previewError(error);
110
+ },
111
+ }) as PreviewBody;
112
+ if (controller.signal.aborted || ctx.signal.aborted) { next.dispose(); return; }
113
+ body = next;
114
+ const latest = state!;
115
+ next.set({ skin: latest.skin, theme: latest.theme, bounds: bounds(), roam: 'calm' });
116
+ shownScheme = latest.skin.scheme;
117
+ if (id !== 'coo') void next.setScheme(shownScheme);
118
+ previewStatus.hidden = true;
119
+ updateAnimation();
120
+ } catch (error) {
121
+ if (!controller.signal.aborted && !ctx.signal.aborted) previewError(error);
122
+ }
123
+ })();
124
+ };
125
+ const resize = new ResizeObserver(() => body?.set({ bounds: bounds() }));
126
+ resize.observe(stage);
127
+ const intersection = new IntersectionObserver(entries => { visible = entries[0]?.isIntersecting ?? false; updateAnimation(); });
128
+ intersection.observe(stage);
129
+ doc.addEventListener('visibilitychange', updateAnimation, { signal: ctx.signal });
130
+ const local = (event: PointerEvent) => {
131
+ const rect = stage.getBoundingClientRect();
132
+ return { x: event.clientX - rect.left, y: event.clientY - rect.top, t: event.timeStamp };
133
+ };
134
+ stage.addEventListener('pointerdown', event => {
135
+ if ((event.target as Element).closest('button')) return;
136
+ const point = local(event); body?.pointer('down', point);
137
+ if (body?.hit(point)) stage.setPointerCapture(event.pointerId);
138
+ });
139
+ stage.addEventListener('pointermove', event => body?.pointer('move', local(event)));
140
+ stage.addEventListener('pointerup', event => body?.pointer('up', local(event)));
141
+ stage.addEventListener('pointercancel', event => body?.pointer('cancel', local(event)));
142
+ stage.addEventListener('pointerleave', () => body?.pointer('leave', {}));
29
143
  let scaleTimer = 0;
30
144
  const errorText = (error: unknown) => error instanceof Error ? error.message : String(error);
31
145
  const tell = (message: string, retry?: () => void) => {
@@ -96,28 +210,20 @@ export function mountDress(ctx: WebUiPanelContext, host: HTMLElement): void {
96
210
  installed = await ctx.invoke<{ installed?: string[]; conflicts?: string[] }>('dressInstall', [token, picked.selected, installed.conflicts]);
97
211
  }
98
212
  if (installed.conflicts?.length) throw new Error(text('Some figures could not be replaced.', '部分形象无法替换。'));
99
- token = undefined; await refresh();
213
+ token = undefined;
214
+ if (installed.installed?.includes(String(state?.skin.figure ?? 'coo'))) wanted = '';
215
+ await refresh();
100
216
  } catch (err) { if (!ctx.signal.aborted) tell(errorText(err), () => void chooseZip()); }
101
217
  finally { if (token) { try { await ctx.invoke('dressCancel', [token]); } catch { /* The import may already have expired. */ } } }
102
218
  };
103
219
  function render() {
104
220
  if (!state) return;
105
- const current = state; content.replaceChildren();
106
- const stage = el('div', 'own-dress-stage'); stage.dataset.theme = current.theme; stage.setAttribute('aria-label', text('Preview', '预览'));
107
- const floor = el('div', 'own-dress-floor'); stage.append(floor);
108
- const art = el('div', 'own-dress-art'); const pic = picture(current.skin, current.theme); if (pic) art.append(pic); stage.append(art);
109
- if (current.skin.figure === 'coo' || !current.skin.figure) {
110
- const svg = art.querySelector('svg'); const skin = normalizeSkin(current.skin);
111
- paint = () => {
112
- const t = performance.now() / 1000;
113
- const phase = t % 4;
114
- const blink = phase < .24 ? Math.sin(phase / .24 * Math.PI) : 0;
115
- if (svg?.isConnected) svg.innerHTML = mini('neutral', skin, t, { blink });
116
- };
117
- } else paint = undefined;
221
+ const current = state;
222
+ showPreview();
223
+ stageControls.replaceChildren();
118
224
  const theme = button(current.theme === 'dark' ? '☀' : '☾', 'own-dress-round own-dress-theme');
119
225
  theme.title = theme.ariaLabel = current.theme === 'dark' ? text('Light preview', '切换日间') : text('Dark preview', '切换夜间');
120
- theme.addEventListener('click', () => run('dressApply', [{ theme: current.theme === 'dark' ? 'light' : 'dark' }])); stage.append(theme);
226
+ theme.addEventListener('click', () => run('dressApply', [{ theme: current.theme === 'dark' ? 'light' : 'dark' }])); stageControls.append(theme);
121
227
  const corner = el('div', 'own-dress-corner');
122
228
  const active = current.looks.find(l => l.id === activeLook);
123
229
  if (active && (JSON.stringify(active.skin) !== JSON.stringify(current.skin) || (active.scale ?? current.scale) !== current.scale)) {
@@ -126,8 +232,10 @@ export function mountDress(ctx: WebUiPanelContext, host: HTMLElement): void {
126
232
  }
127
233
  const save = button('+', 'own-dress-round'); save.title = save.ariaLabel = text('Save look', '保存装扮');
128
234
  save.addEventListener('click', () => { const pack = current.packs.find(p => p.id === current.skin.figure); const name = pack?.name ?? 'Coo'; run('dressLook', [{ kind: 'save', name }], next => { activeLook = next.looks.find(l => !current.looks.some(old => old.id === l.id))?.id ?? null; }); });
129
- corner.append(save); stage.append(corner); content.append(stage);
130
- const grid = el('div', 'own-dress-grid'); content.append(grid);
235
+ corner.append(save); stageControls.append(corner);
236
+ const nextGrid = el('div', 'own-dress-grid');
237
+ if (grid) grid.replaceWith(nextGrid); else content.append(nextGrid);
238
+ grid = nextGrid;
131
239
  grid.append(el('h3', 'own-dress-heading first', text('Saved looks', '已保存的装扮')));
132
240
  const looks = el('div', 'own-dress-looks'); grid.append(looks);
133
241
  if (!current.looks.length) looks.append(el('p', 'own-dress-empty', text('Save a look to find it here.', '保存装扮后会显示在这里。')));
@@ -178,7 +286,10 @@ export function mountDress(ctx: WebUiPanelContext, host: HTMLElement): void {
178
286
  }
179
287
  }
180
288
  }
181
- if (!doc.defaultView?.matchMedia('(prefers-reduced-motion: reduce)').matches) timer = window.setInterval(() => paint?.(), 120);
182
- ctx.own({ dispose: () => { window.clearInterval(timer); window.clearTimeout(scaleTimer); dialogs.close(); } });
289
+ ctx.own({ dispose: () => {
290
+ loading?.abort(); body?.dispose(); body = undefined;
291
+ cancelAnimationFrame(frame); resize.disconnect(); intersection.disconnect();
292
+ window.clearTimeout(scaleTimer); dialogs.close();
293
+ } });
183
294
  void refresh();
184
295
  }
package/src/world.ts CHANGED
@@ -2716,6 +2716,20 @@ export class DesktopPetWorld implements World {
2716
2716
  switch (method) {
2717
2717
  case 'state': return this.petState();
2718
2718
  case 'dressState': return this.dressState(language);
2719
+ case 'dressPreview': {
2720
+ const { id, base, manifest } = dressPack(this.packs(), args[0]);
2721
+ const origin = this.server.origin;
2722
+ if (!origin) throw new Error('Figure preview server is not running');
2723
+ return {
2724
+ origin,
2725
+ pack: {
2726
+ id, base, entry: manifest.entry, export: manifest.export, model: manifest.model ?? null,
2727
+ axes: manifest.axes.map(({ options }) => ({ options: options.map(({ id }) => ({ id })) })),
2728
+ presets: manifest.presets.map(({ id }) => ({ id })),
2729
+ vocab: manifest.vocab.map(({ id }) => ({ id })),
2730
+ },
2731
+ };
2732
+ }
2719
2733
  case 'dressApply': this.applyDress(args[0]); return this.dressState(language);
2720
2734
  case 'dressLook': this.changeDressLook(args[0]); return this.dressState(language);
2721
2735
  case 'dressImport': {
@@ -13,6 +13,7 @@ const PEAK_ENTER = 180;
13
13
  const PEAK_REARM = 150;
14
14
  const ATTACK_SECONDS = .2;
15
15
  const RELEASE_SECONDS = .7;
16
+ export const MAX_TAIL_TEMPO = 3.4;
16
17
  const STATIONARY_MOTION = /^(?:(?:small|little|gentle|quick)[_-])?(point|nod|wave|hop|flap|spin|dance|bow)(?:[_-](?:once|twice))?$/i;
17
18
 
18
19
  const isFresh = (sample, now) =>
@@ -21,10 +22,10 @@ const outputRate = (sample) =>
21
22
  Number.isFinite(sample?.outputPerSecond) && sample.outputPerSecond > 0 ? sample.outputPerSecond : 0;
22
23
 
23
24
  function targetTempo(rate) {
24
- // (t/s, multiplier): (0, 1), (20, 1.2), (80, 1.65), (180+, 2.3).
25
- if (rate <= 20) return 1 + .2 * (rate / 20);
26
- if (rate <= 80) return 1.2 + .45 * ((rate - 20) / 60);
27
- return 1.65 + .65 * (Math.min(rate - 80, 100) / 100);
25
+ // (t/s, multiplier): (0, 1), (20, 1.5), (80, 2.35), (180+, 3.4).
26
+ if (rate <= 20) return 1 + .5 * (rate / 20);
27
+ if (rate <= 80) return 1.5 + (2.35 - 1.5) * ((rate - 20) / 60);
28
+ return 2.35 + (MAX_TAIL_TEMPO - 2.35) * (Math.min(rate - 80, 100) / 100);
28
29
  }
29
30
 
30
31
  function findMotion(words, reported, kind) {
@@ -44,7 +45,8 @@ export function createActivityMotion() {
44
45
  let peakArmed = true, nextCueAt = -Infinity, nextSustainedAt = null, spinsSinceDance = 0;
45
46
  let nextSmall = 'point', nextPeak = 'hop';
46
47
  let tempoFrom = 1, tempoTo = 1, tempoElapsed = 0;
47
- const activity = { engaged: false, cue: null, tailTempo: 1 };
48
+ let workStartedAt = null, faceUntil = 0, nextExcitedAt = 0;
49
+ const activity = { active: false, engaged: false, cue: null, face: null, tailTempo: 1 };
48
50
 
49
51
  function clearCueHistory() {
50
52
  previous = null;
@@ -70,8 +72,23 @@ export function createActivityMotion() {
70
72
  step(now, dt, eligible, canCue, words, reported = null, gentleOnly = false) {
71
73
  const fresh = isFresh(sample, now) ? sample : null;
72
74
  const rate = outputRate(fresh);
73
- activity.engaged = eligible && (rate > 0 || !!(fresh?.generating || fresh?.tools));
75
+ const wasActive = activity.active;
76
+ activity.active = rate > 0 || !!(fresh?.generating || fresh?.tools);
77
+ activity.engaged = eligible && activity.active;
74
78
  activity.cue = null;
79
+ if (!activity.active) {
80
+ workStartedAt = null;
81
+ nextExcitedAt = 0;
82
+ } else if (!wasActive) workStartedAt = now;
83
+ if (!activity.engaged || now >= faceUntil) activity.face = null;
84
+ if (workStartedAt !== null && now - workStartedAt > CUE_MAX_AGE_MS) workStartedAt = null;
85
+ if (workStartedAt !== null && canCue && activity.engaged) {
86
+ workStartedAt = null;
87
+ if (reported?.includes('happy')) {
88
+ activity.face = 'happy';
89
+ faceUntil = now + 1200;
90
+ }
91
+ }
75
92
 
76
93
  // Tail response needs only a fresh observed rate, not a complete aggregate or an idle pose.
77
94
  const target = targetTempo(eligible ? rate : 0);
@@ -107,6 +124,11 @@ export function createActivityMotion() {
107
124
  if (changed && rate >= PEAK_ENTER) peakArmed = false;
108
125
  const marked = changed && prior > 0 && rate >= MARKED_ENTER && rate - prior >= MARKED_RISE;
109
126
  const small = changed && prior > 0 && prior < SMALL_PREVIOUS_LIMIT && rate >= SMALL_ENTER && rate < MARKED_ENTER;
127
+ if (marked && fresh.complete === true && eligible && canCue && now >= nextExcitedAt && reported?.includes('excited')) {
128
+ activity.face = 'excited';
129
+ faceUntil = now + 1600;
130
+ nextExcitedAt = now + CUE_COOLDOWN_MS;
131
+ }
110
132
 
111
133
  const sustained = nextSustainedAt !== null && rate >= HIGH_EXIT && now >= nextSustainedAt;
112
134
  if (!eligible || !canCue || now < nextCueAt || (!changed && !sustained)) return activity;
package/web/body-host.js CHANGED
@@ -118,16 +118,38 @@ export function knownScheme(pack, scheme) {
118
118
  /**
119
119
  * `pack`: the entry of `/api/figures`; `start`: { x, facing, enter, skin }; `bounds`: { W, H, floorY, S };
120
120
  * `theme`: 'dark' | 'light'. Resolves to the body once it is ready.
121
+ * `previewOrigin` loads the same sandbox controller as a subresource of an opaque srcdoc frame
122
+ * for settings hosts that restrict subframe navigation. `signal` owns the pending and running frame.
121
123
  */
122
- export function loadBody({ layer, pack, start, theme, bounds, onEvent, onSound, onError }) {
124
+ export function loadBody({ layer, pack, start, theme, bounds, onEvent, onSound, onError, previewOrigin, languageCode, signal }) {
123
125
  return new Promise((resolve, reject) => {
126
+ if (signal?.aborted) { reject(signal.reason); return; }
124
127
  const frame = document.createElement('iframe');
125
128
  frame.setAttribute('sandbox', 'allow-scripts');
126
129
  frame.setAttribute('aria-hidden', 'true');
127
130
  frame.tabIndex = -1;
128
131
  frame.className = 'figure-frame';
129
- // the server lets the frame fetch the files of the pack it names (an installed one)
130
- frame.src = `/figure-frame?pack=${encodeURIComponent(pack.id)}`;
132
+ let previewKey, previewPort;
133
+ if (previewOrigin) {
134
+ const installed = pack.id !== 'coo' && pack.base === `/packs/${pack.id}/`;
135
+ const builtIn = (pack.id === 'coo' || pack.id === 'whale') && pack.base === `/web/${pack.id}/`;
136
+ if (!/^http:\/\/127\.0\.0\.1:[1-9]\d{0,4}$/.test(previewOrigin) ||
137
+ !/^[a-z0-9][a-z0-9-]{0,31}$/.test(pack.id) ||
138
+ !(installed || builtIn)) {
139
+ reject(new Error('Invalid figure preview source'));
140
+ return;
141
+ }
142
+ // An opaque sandbox keeps the pack out of the settings origin. Only its
143
+ // own asset folder can be fetched; the renderer is a loopback subresource.
144
+ const web = `${previewOrigin}/web/`, assets = `${previewOrigin}${pack.base}`;
145
+ const csp = `default-src 'none'; script-src ${web} ${assets}; connect-src ${pack.id === 'coo' ? "'none'" : assets}; img-src ${web} ${assets} data: blob:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`;
146
+ frame.referrerPolicy = 'no-referrer';
147
+ previewKey = crypto.randomUUID();
148
+ frame.srcdoc = `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${csp}"><style>html,body{margin:0;height:100%;overflow:hidden;background:transparent}#root{position:absolute;inset:0}</style><div id="root" aria-hidden="true" data-preview-key="${previewKey}"></div><script type="module" src="${web}figure-frame.js"></script>`;
149
+ } else {
150
+ // The server lets the frame fetch the files of the pack it names (an installed one).
151
+ frame.src = `/figure-frame?pack=${encodeURIComponent(pack.id)}`;
152
+ }
131
153
  // the frame's window onto the stage: all of it, or with the halo on, the halo's rect around the body (haloRect)
132
154
  const clip = document.createElement('div');
133
155
  clip.className = 'figure-clip';
@@ -137,14 +159,20 @@ export function loadBody({ layer, pack, start, theme, bounds, onEvent, onSound,
137
159
  let layout = null, z = null, words = null;
138
160
  const touches = touchGate();
139
161
  const waits = new Map();
140
- const post = (m) => { if (!gone) frame.contentWindow?.postMessage(m, '*'); };
162
+ const post = (m) => {
163
+ if (gone) return;
164
+ if (previewPort) previewPort.postMessage(m);
165
+ else if (!previewKey) frame.contentWindow?.postMessage(m, '*');
166
+ };
141
167
  const timer = setTimeout(() => fail(new Error(t('figure.notReady', { seconds: READY_MS / 1000 }))), READY_MS);
142
168
 
143
169
  function close() {
144
170
  if (gone) return;
145
171
  gone = true;
146
172
  clearTimeout(timer);
147
- removeEventListener('message', onMessage);
173
+ removeEventListener('message', receive);
174
+ previewPort?.close();
175
+ signal?.removeEventListener('abort', abort);
148
176
  clip.remove();
149
177
  for (const done of waits.values()) done();
150
178
  waits.clear();
@@ -155,6 +183,11 @@ export function loadBody({ layer, pack, start, theme, bounds, onEvent, onSound,
155
183
  if (ready) onError?.(err); else reject(err);
156
184
  }
157
185
 
186
+ function abort() {
187
+ close();
188
+ if (!ready) reject(signal.reason);
189
+ }
190
+
158
191
  const body = {
159
192
  pack: pack.id,
160
193
  get layout() { return layout; },
@@ -166,8 +199,8 @@ export function loadBody({ layer, pack, start, theme, bounds, onEvent, onSound,
166
199
  /** Whether stage point `p` is on the body. */
167
200
  hit: (p) => onBody(layout, p),
168
201
  /** Advances the body `dt` seconds; with `draw` false (the pet window is hidden) it need not draw. */
169
- tick(dt, draw = true, engaged = false, tailTempo = 1) {
170
- if (ready) post({ t: 'tick', dt, draw, engaged, tailTempo });
202
+ tick(dt, draw = true, engaged = false, tailTempo = 1, activityFace = null) {
203
+ if (ready) post({ t: 'tick', dt, draw, engaged, tailTempo, activityFace });
171
204
  },
172
205
  do: (word) => post({ t: 'do', word }),
173
206
  walk: (x, run, id) => post({ t: 'walk', x, run, id }),
@@ -213,16 +246,31 @@ export function loadBody({ layer, pack, start, theme, bounds, onEvent, onSound,
213
246
  dispose: close,
214
247
  };
215
248
 
249
+ function receive(e) {
250
+ if (!previewKey) {
251
+ if (e.source === frame.contentWindow) void onMessage(e);
252
+ } else if (e.origin === 'null' && e.data?.t === 'loaded' && e.data.key === previewKey && e.ports.length === 1) {
253
+ // The opaque srcdoc can have a different WindowProxy from iframe.contentWindow.
254
+ // Authenticate this one handshake, then use its private port.
255
+ previewPort = e.ports[0];
256
+ previewPort.onmessage = onMessage;
257
+ removeEventListener('message', receive);
258
+ void onMessage(e);
259
+ }
260
+ }
261
+
216
262
  async function onMessage(e) {
217
- if (e.source !== frame.contentWindow) return;
218
263
  const m = e.data || {};
219
264
  if (m.t === 'loaded' && !ready) {
220
265
  try {
221
- const model = pack.model ? await (await fetch(new URL(pack.base + pack.model, location.href))).json() : null;
266
+ const base = new URL(pack.base, previewOrigin || location.href);
267
+ const modelUrl = pack.model ? new URL(pack.model, base).href : null;
268
+ const model = modelUrl && !previewOrigin ? await (await fetch(modelUrl)).json() : null;
222
269
  post({
223
- t: 'init', entry: new URL(pack.base + pack.entry, location.href).href, export: pack.export,
224
- base: new URL(pack.base, location.href).href, model, scheme: knownScheme(pack, start.scheme), start: { x: start.x, facing: start.facing, enter: start.enter, skin: start.skin }, theme, bounds: size,
225
- language: language(),
270
+ t: 'init', entry: new URL(pack.entry, base).href, export: pack.export,
271
+ base: base.href, model, ...(previewOrigin && modelUrl ? { modelUrl } : {}),
272
+ scheme: knownScheme(pack, start.scheme), start: { x: start.x, facing: start.facing, enter: start.enter, skin: start.skin }, theme, bounds: size,
273
+ language: languageCode ?? language(),
226
274
  });
227
275
  } catch (err) { fail(err); }
228
276
  } else if (m.t === 'ready' && !ready) {
@@ -253,7 +301,8 @@ export function loadBody({ layer, pack, start, theme, bounds, onEvent, onSound,
253
301
  fail(new Error(m.message));
254
302
  }
255
303
  }
256
- addEventListener('message', onMessage);
304
+ addEventListener('message', receive);
305
+ signal?.addEventListener('abort', abort, { once: true });
257
306
  layer.appendChild(clip);
258
307
  });
259
308
  }
@@ -38,7 +38,7 @@
38
38
  * that ends on its own, `touch` ({ kind: poke | pet | grab | drop | throw | crash, ... }), `mode` ({ mode }).
39
39
  *
40
40
  * Messages in: `init { entry, export, base, model, scheme, start, theme, bounds, language }` (the app language,
41
- * for the frame's own error messages), then `tick { dt, draw, engaged, tailTempo }`
41
+ * for the frame's own error messages), then `tick { dt, draw, engaged, tailTempo, activityFace }`
42
42
  * once a frame, `windows { ledges, windows }` (null when there are none to read) and the calls above by name. Out: `loaded`, `ready { z, words }`, `frame { layout, events: [{ kind,
43
43
  * detail }], sounds: [{ name, kind, args }], z }` after each tick, `scheme { seq, z }`, and `error { message }`
44
44
  * once, after which it stops.
@@ -51,7 +51,10 @@ let body = null, dead = false, bounds = { W: 0, H: 0, floorY: 0, S: .42 }, desk
51
51
  /** The stage's size from the page, with the windows when there are any. */
52
52
  const setBounds = (b) => { bounds = desk ? { ...b, ...desk } : { ...b }; };
53
53
  let events = [], sounds = [];
54
- const post = (m) => parent.postMessage(m, '*');
54
+ const previewKey = root.dataset.previewKey;
55
+ delete root.dataset.previewKey;
56
+ const channel = previewKey ? new MessageChannel() : null;
57
+ const post = (m) => channel ? channel.port1.postMessage(m) : parent.postMessage(m, '*');
55
58
  function fail(err) {
56
59
  if (dead) return;
57
60
  dead = true;
@@ -77,8 +80,8 @@ const host = {
77
80
  sound: (name, kind, ...args) => sounds.push({ name, kind, args }),
78
81
  };
79
82
 
80
- addEventListener('message', async (e) => {
81
- if (e.source !== parent || dead) return;
83
+ async function receive(e) {
84
+ if (dead) return;
82
85
  const m = e.data || {};
83
86
  try {
84
87
  if (m.t === 'windows') {
@@ -93,13 +96,19 @@ addEventListener('message', async (e) => {
93
96
  const make = mod[m.export];
94
97
  if (typeof make !== 'function') throw new Error(t('figure.notFunction', { name: m.export }));
95
98
  const base = new URL(m.base);
96
- body = await make(base, { model: m.model ?? undefined, scheme: m.scheme, kit, loadImage, asset: (p) => new URL(p, base), host: { ...host, start: m.start } });
99
+ let model = m.model;
100
+ if (m.modelUrl) {
101
+ const response = await fetch(m.modelUrl, { credentials: 'omit' });
102
+ if (!response.ok) throw new Error(`Figure model unavailable (${response.status})`);
103
+ model = await response.json();
104
+ }
105
+ body = await make(base, { model: model ?? undefined, scheme: m.scheme, kit, loadImage, asset: (p) => new URL(p, base), host: { ...host, start: m.start } });
97
106
  for (const fn of ['step', 'layout', 'do']) if (typeof body?.[fn] !== 'function') throw new Error(t('figure.missingMethod', { name: fn }));
98
107
  post({ t: 'ready', z: body.z ?? null, words: Array.isArray(body.words) ? body.words.filter((w) => typeof w === 'string') : null });
99
108
  } else if (!body) {
100
109
  // calls that come before the body is ready have nothing to act on
101
110
  } else if (m.t === 'tick') {
102
- body.setActivityEngaged?.(m.engaged === true, m.tailTempo);
111
+ body.setActivityEngaged?.(m.engaged === true, m.tailTempo, m.activityFace);
103
112
  body.step(m.dt, m.draw);
104
113
  post({ t: 'frame', layout: body.layout(), events, sounds, z: body.z ?? null });
105
114
  events = []; sounds = [];
@@ -124,5 +133,11 @@ addEventListener('message', async (e) => {
124
133
  } catch (err) {
125
134
  fail(err);
126
135
  }
127
- });
128
- post({ t: 'loaded' });
136
+ }
137
+ if (channel) {
138
+ channel.port1.onmessage = receive;
139
+ parent.postMessage({ t: 'loaded', key: previewKey }, '*', [channel.port2]);
140
+ } else {
141
+ addEventListener('message', e => { if (e.source === parent) void receive(e); });
142
+ post({ t: 'loaded' });
143
+ }
package/web/i18n/en.js CHANGED
@@ -34,6 +34,7 @@ export default {
34
34
  // the status bubble: added when the same kind of thing was done several times
35
35
  'status.more': ' and {others} more',
36
36
  'status.thinking': 'Thinking',
37
+ 'status.working': 'Working',
37
38
  'status.seconds': '{seconds} s',
38
39
 
39
40
  // the menu and the hover buttons
package/web/i18n/zh.js CHANGED
@@ -32,6 +32,7 @@ export default {
32
32
  // 状态气泡:同一类事做了好几次时接在后面
33
33
  'status.more': ' 和另外 {others} 个',
34
34
  'status.thinking': '思考中',
35
+ 'status.working': '工作中',
35
36
  'status.seconds': '{seconds} 秒',
36
37
 
37
38
  // 菜单与悬停按钮的说明
package/web/kit/body.js CHANGED
@@ -12,6 +12,8 @@
12
12
  * Nothing here plays sound or talks to the World: sounds are asked for through `opts.sfx` and what
13
13
  * happens to the body is told through `opts.onEvent`; the page around the frame does the rest.
14
14
  */
15
+ import { MAX_TAIL_TEMPO } from '../activity-motion.js';
16
+
15
17
  export { createRig } from './rig.js';
16
18
 
17
19
  export const f = n => Math.round(n * 10) / 10;
@@ -160,6 +162,7 @@ export function createPet(els, opts) {
160
162
  };
161
163
  let activityEngaged = false;
162
164
  let tailTempo = 1;
165
+ let activityFace = null;
163
166
  const pointer = { x: -1e4, y: -1e4, inside: false, vx: 0, samples: [] };
164
167
  let press = null, strokeAcc = 0, petCool = 0;
165
168
  /** Whether the last frame found the horizontal speed not finite: a run of such frames is logged once. */
@@ -372,8 +375,11 @@ export function createPet(els, opts) {
372
375
  if (m === 'wake') return pet.startle ? 'surprised' : 'waking';
373
376
  if (pet.listening && m !== 'sleep') return 'listening';
374
377
  if (m === 'sleep') return 'sleep';
378
+ // The wave supplies its own smile; a speed accent can make it look excited instead.
379
+ if (activityFace === 'excited' && pet.pulse?.kind === 'wave' && !press && !pet.thinking) return activityFace;
375
380
  if (pet.expr && T < pet.exprUntil) return pet.expr;
376
381
  if (pet.thinking) return 'thinking';
382
+ if (activityFace && m === 'idle' && !press && !pet.talkK) return activityFace;
377
383
  if (m === 'sit') return 'content';
378
384
  if (m === 'run') return 'run';
379
385
  return 'neutral';
@@ -936,9 +942,10 @@ export function createPet(els, opts) {
936
942
  custom?.setSkin?.(skin);
937
943
  return {
938
944
  pet, step, render, resize, act, setExpr, doWord, walkTo, stopWalk, toStage, hitPet, busy, layout,
939
- setActivityEngaged(engaged, tempo) {
945
+ setActivityEngaged(engaged, tempo, face) {
940
946
  activityEngaged = engaged;
941
- tailTempo = Number.isFinite(tempo) ? clamp(tempo, 1, 2.3) : 1;
947
+ tailTempo = Number.isFinite(tempo) ? clamp(tempo, 1, MAX_TAIL_TEMPO) : 1;
948
+ activityFace = engaged && (face === 'happy' || face === 'excited') ? face : null;
942
949
  },
943
950
  pointerDown, pointerMove, pointerUp, pointerLeave, dropAt, shiftDrag,
944
951
  get pressing() { return !!press; },
package/web/pet-app.js CHANGED
@@ -1565,6 +1565,7 @@ function stepLines() {
1565
1565
 
1566
1566
  /* ---------- activity: the same bubble, with conversation always taking priority ---------- */
1567
1567
  const status = { wanted: null, since: 0, shown: null, shownAt: 0, fadeAt: null };
1568
+ let speedStatus = null;
1568
1569
  function setStatus(next) {
1569
1570
  setBody({ thinking: next?.kind === 'think', status: next?.kind ?? null });
1570
1571
  const prev = status.wanted;
@@ -1602,7 +1603,7 @@ function statusParts(s) {
1602
1603
  };
1603
1604
  }
1604
1605
  const statusLabel = (s) => Object.values(statusParts(s)).join('');
1605
- function stepStatus() {
1606
+ function stepStatus(speedActive) {
1606
1607
  // Never replace dialogue with activity, including while a queued line waits for the body or for the place over the head.
1607
1608
  if (!prefs.statusBubble || listen.phase || item || queue.length || headShown()) {
1608
1609
  if (bubble.classList.contains('status')) bubble.hidden = true;
@@ -1613,7 +1614,13 @@ function stepStatus() {
1613
1614
  bubble.hidden = true;
1614
1615
  status.shown = null; status.fadeAt = null;
1615
1616
  }
1616
- const next = status.wanted, shown = status.shown;
1617
+ let next = status.wanted;
1618
+ if (!next && speedActive) {
1619
+ const text = t('status.working');
1620
+ if (speedStatus?.text !== text) speedStatus = { kind: 'work', text };
1621
+ next = speedStatus;
1622
+ }
1623
+ const shown = status.shown;
1617
1624
  if (next?.kind === 'think' && T - status.since < .6) return;
1618
1625
  if (shown && next && shown.kind === next.kind && shown.text === next.text) {
1619
1626
  if (shown !== next || status.fadeAt !== null || (next.endsAt !== undefined && bubble.querySelector('.status-text')?.textContent !== statusLabel(next))) drawStatus(next, false);
@@ -2950,10 +2957,11 @@ function frame(steps, now, last) {
2950
2957
  stepTalkRead(dt);
2951
2958
  stepTalkMotion();
2952
2959
  stepLines();
2953
- stepStatus();
2954
2960
  setBody({ dialogOpen: !!item || !!listen.phase, still: !menu.hidden });
2955
2961
  let engaged = false;
2962
+ let speedActive = false;
2956
2963
  let tailTempo = 1;
2964
+ let activityFace = null;
2957
2965
  if (host) {
2958
2966
  const figure = at();
2959
2967
  const eligible = drawn && !!body && !pressing && !figure?.pressing &&
@@ -2963,10 +2971,13 @@ function frame(steps, now, last) {
2963
2971
  const activity = agentSpeedMotion.step(Date.now(), dt, eligible, canCue, words, body?.words ?? null, lowMotion());
2964
2972
  if (activity.cue) body.do(activity.cue);
2965
2973
  engaged = activity.engaged;
2974
+ speedActive = !!body && activity.active;
2966
2975
  tailTempo = activity.tailTempo;
2976
+ activityFace = activity.face;
2967
2977
  }
2978
+ stepStatus(speedActive);
2968
2979
  if (drawnScale.step(dt)) body?.set({ bounds: bounds() });
2969
- body?.tick(dt, drawn && i === steps.length - 1, engaged, tailTempo);
2980
+ body?.tick(dt, drawn && i === steps.length - 1, engaged, tailTempo, activityFace);
2970
2981
  });
2971
2982
  if (drawn) {
2972
2983
  const dt = steps.reduce((a, b) => a + b, 0);