cortico-world-agent-speed 0.2.2 → 0.2.4

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.
@@ -534,7 +534,6 @@ function runPetHost({ url, parentPid = 0, tray: withTray = true }) {
534
534
  dress.on('closed', () => { dress = null; });
535
535
  dress.loadURL(target);
536
536
  };
537
-
538
537
  onPet('pet:interactive', (_e, on) => { if (!shape) mouse.ask(on); });
539
538
  onPet('pet:inputRects', (_e, rects) => { if (shape && Array.isArray(rects)) mouse.ask(rects); });
540
539
  onPet('pet:focus', () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-agent-speed",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "type": "module",
5
5
  "description": "The Coopanion desktop pet with local Agent Speed activity animation",
6
6
  "main": "./src/index.ts",
@@ -242,120 +242,3 @@ export class PackImporter {
242
242
  if (staged) await rm(staged.root, { recursive: true, force: true });
243
243
  }
244
244
  }
245
-
246
- const ZIP_CHUNK_BYTES = 48 * 1024;
247
- const ZIP_EXPANDED_MAX = 2 * IMPORT_LARGE;
248
- const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$/;
249
-
250
- type ZipUpload = {
251
- token: string;
252
- bytes: Buffer | null;
253
- received: number;
254
- importer?: PackImporter;
255
- stage?: StageResult;
256
- pending?: Promise<unknown>;
257
- cancelled?: boolean;
258
- };
259
-
260
- /** The settings invoke flow owns its staging slot; the standalone dress page cannot replace or cancel it. */
261
- export class DressZipImport {
262
- private session: ZipUpload | null = null;
263
-
264
- constructor(private readonly createImporter: (text: PetText) => PackImporter) {}
265
-
266
- async start(total: unknown, text: PetText): Promise<string> {
267
- if (typeof total !== 'number' || !Number.isSafeInteger(total) || total < 22 || total > IMPORT_LARGE) {
268
- throw new Error(`ZIP size must be between 22 and ${IMPORT_LARGE} bytes`);
269
- }
270
- if (this.session?.pending) throw new Error(text.importing.expired);
271
- await this.cancel();
272
- if (this.session) throw new Error(text.importing.expired);
273
- const token = randomUUID();
274
- this.session = { token, bytes: Buffer.allocUnsafe(total), received: 0 };
275
- return token;
276
- }
277
-
278
- chunk(token: unknown, base64: unknown, text: PetText): void {
279
- const s = this.upload(token, text);
280
- const { bytes } = s;
281
- if (typeof base64 !== 'string' || !base64.length || base64.length > ZIP_CHUNK_BYTES / 3 * 4
282
- || base64.length % 4 !== 0 || !BASE64.test(base64)) {
283
- throw new Error(text.importing.truncated);
284
- }
285
- const size = Buffer.byteLength(base64, 'base64');
286
- if (size > bytes.length - s.received) throw new Error(text.importing.truncated);
287
- s.received += bytes.write(base64, s.received, size, 'base64');
288
- }
289
-
290
- finish(token: unknown, text: PetText): Promise<{
291
- token: string;
292
- packs: Array<Pick<StagedPack, 'dir' | 'id' | 'name' | 'installed'>>;
293
- problems: StageResult['problems'];
294
- }> {
295
- const s = this.upload(token, text);
296
- if (s.received !== s.bytes.length) throw new Error(text.importing.truncated);
297
- const files = filesFromZip(s.bytes, text.importing, ZIP_EXPANDED_MAX);
298
- this.session = null;
299
- const session: ZipUpload = { token: s.token, bytes: null, received: 0 };
300
- if (typeof files === 'string') throw new Error(files);
301
- this.session = session;
302
- const importer = this.createImporter(text);
303
- session.importer = importer;
304
- const pending = (async () => {
305
- try {
306
- const stage = await importer.stage(files, false);
307
- if (session.cancelled) throw new Error(text.importing.expired);
308
- if ('error' in stage) throw new Error(stage.error);
309
- if (stage.token) session.stage = stage;
310
- const { token, packs, problems } = stage;
311
- return { token, packs: packs.map(({ dir, id, name, installed }) => ({ dir, id, name, installed })), problems };
312
- } finally {
313
- delete session.pending;
314
- if (!session.stage && !session.cancelled) this.session = null;
315
- }
316
- })();
317
- session.pending = pending;
318
- return pending;
319
- }
320
-
321
- async install(token: unknown, dirs: unknown, replace: unknown, text: PetText): Promise<{ installed: string[] } | { conflicts: string[] }> {
322
- const s = this.session;
323
- if (!s?.importer || !s.stage || s.cancelled || s.pending || token !== s.stage.token) throw new Error(text.importing.expired);
324
- const chosen = s.stage.packs.filter((p) => Array.isArray(dirs) && dirs.includes(p.dir));
325
- if (!Array.isArray(dirs) || !chosen.length || dirs.length !== chosen.length
326
- || !Array.isArray(replace) || !replace.every((id) => chosen.some((p) => p.id === id))) {
327
- throw new Error(text.importing.noneChosen);
328
- }
329
- const pending = s.importer.install(s.stage.token, dirs, replace);
330
- s.pending = pending;
331
- try {
332
- const result = await pending;
333
- if ('error' in result) throw new Error(result.error);
334
- if ('installed' in result && !s.cancelled) this.session = null;
335
- return result;
336
- } finally {
337
- delete s.pending;
338
- }
339
- }
340
-
341
- /** An omitted token is for World shutdown and resetting the panel slot, never a panel request. */
342
- async cancel(token?: string): Promise<void> {
343
- const s = this.session;
344
- if (!s || (token !== undefined && token !== s.token && token !== s.stage?.token)) return;
345
- s.cancelled = true;
346
- s.bytes = null;
347
- // Do not delete a staging directory while it is being built or copied into the install root.
348
- await s.pending?.catch(() => {});
349
- try {
350
- await s.importer?.cancel();
351
- } finally {
352
- if (this.session === s) this.session = null;
353
- }
354
- }
355
-
356
- private upload(token: unknown, text: PetText): ZipUpload & { bytes: Buffer } {
357
- const s = this.session;
358
- if (!s?.bytes || s.cancelled || token !== s.token) throw new Error(text.importing.expired);
359
- return s as ZipUpload & { bytes: Buffer };
360
- }
361
- }
@@ -11,13 +11,14 @@ import { petText } from '../i18n/index.ts';
11
11
  import { describeHostReason, type HostReason } from '../host-reason.ts';
12
12
  import { captureKey, PRESSES, splitTaps, withTaps } from './key-capture.ts';
13
13
  import { apiRows, type ApiState } from './api-rows.ts';
14
- import { mountDress } from './dress-panel.ts';
14
+ import { hostFrameDressDialogs } from './dress-dialog.ts';
15
15
  import './style.css';
16
16
 
17
17
  interface Artifact { phase: 'absent' | 'working' | 'ready' | 'error'; path: string; done: number; total: number | null; detail: string | null }
18
18
  interface PetState {
19
19
  inWindow: boolean;
20
20
  url: string | null;
21
+ dressUrl: string | null;
21
22
  window: { phase: string; pid: number | null; source: string | null; reason: HostReason | null } | null;
22
23
  electron: Artifact & { supported: boolean };
23
24
  screen: { w: number; h: number } | null;
@@ -111,9 +112,72 @@ const petPanel: WebUiPanel = {
111
112
  const btnInstall = ui.button(t.install, { size: 'sm', variant: 'primary' });
112
113
  rt.acts.append(btnInstall);
113
114
 
114
- const dress = ui.sheet({ title: t.dress, desc: ctx.language === 'zh' || ctx.language === 'zh-Hant' ? '保存后同步到桌宠窗口' : 'Save changes to update the pet window' });
115
+ const dress = ui.sheet({ title: t.dress, desc: t.dressHint });
115
116
  root.appendChild(dress.el);
116
- mountDress(ctx, dress.body);
117
+ const doc = root.ownerDocument;
118
+ const frame = ui.h('iframe', 'pet-dressframe');
119
+ frame.title = t.dress;
120
+ frame.hidden = true;
121
+ const dressStatus = ui.h('div', 'read-feedback');
122
+ dressStatus.setAttribute('role', 'status');
123
+ dress.body.append(dressStatus, frame);
124
+ hostFrameDressDialogs({ doc, host: doc.body, signal: ctx.signal }, frame);
125
+
126
+ const appearance = () => {
127
+ const mode = doc.documentElement.dataset.colorMode;
128
+ return mode === 'dark' || (!mode && matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light';
129
+ };
130
+ const syncAppearance = () => {
131
+ if (!frame.dataset.origin) return;
132
+ const accent = getComputedStyle(doc.documentElement).getPropertyValue('--accent').trim();
133
+ frame.contentWindow?.postMessage({ type: 'companion:appearance', mode: appearance(), accent }, frame.dataset.origin);
134
+ };
135
+ const observer = new MutationObserver(syncAppearance);
136
+ observer.observe(doc.documentElement, { attributes: true, attributeFilter: ['data-color-mode', 'data-theme-scheme'] });
137
+ ctx.own({ dispose: () => observer.disconnect() });
138
+ frame.addEventListener('load', syncAppearance, { signal: ctx.signal });
139
+ const zh = ctx.language === 'zh' || ctx.language === 'zh-Hant';
140
+ let pending: { dispose(): void } | undefined;
141
+ doc.defaultView?.addEventListener('message', (event) => {
142
+ if (event.source !== frame.contentWindow || event.origin !== frame.dataset.origin) return;
143
+ if (event.data?.type === 'companion:height') {
144
+ const height = event.data.height;
145
+ if (Number.isFinite(height) && height > 0) frame.style.height = `${height}px`;
146
+ } else if (event.data?.type === 'companion:painted') {
147
+ pending?.dispose();
148
+ dressStatus.hidden = true;
149
+ frame.hidden = false;
150
+ frame.classList.remove('pet-dressframe-pending');
151
+ }
152
+ }, { signal: ctx.signal });
153
+ const showDress = (url: string | null) => {
154
+ if ((frame.dataset.src ?? null) === url) return;
155
+ pending?.dispose();
156
+ dressStatus.hidden = false;
157
+ if (url === null) {
158
+ frame.hidden = true;
159
+ delete frame.dataset.src;
160
+ delete frame.dataset.origin;
161
+ frame.removeAttribute('src');
162
+ dressStatus.textContent = zh ? '装扮服务尚未就绪。' : 'Dressing is not ready yet.';
163
+ return;
164
+ }
165
+ const target = new URL(url);
166
+ frame.dataset.src = url;
167
+ frame.dataset.origin = target.origin;
168
+ target.searchParams.set('appearance', appearance());
169
+ target.searchParams.set('fit', '1');
170
+ frame.classList.add('pet-dressframe-pending');
171
+ frame.hidden = false;
172
+ dressStatus.textContent = zh ? '正在加载装扮…' : 'Loading dressing…';
173
+ pending = ctx.timeout(() => {
174
+ if (!frame.classList.contains('pet-dressframe-pending')) return;
175
+ frame.hidden = true;
176
+ dressStatus.textContent = zh ? '无法加载内嵌装扮。请确认 Coopanion 支持 Agent Speed 内嵌装扮。'
177
+ : 'Could not load inline dressing. Check that this version of Coopanion supports Agent Speed inline dressing.';
178
+ }, 8000);
179
+ frame.src = target.href;
180
+ };
117
181
 
118
182
  s.append(win.row, rt.row);
119
183
  dress.el.hidden = true;
@@ -137,6 +201,7 @@ const petPanel: WebUiPanel = {
137
201
  else rt.set(e.supported ? t.notInstalled : t.noBuild, 'off', e.supported ? t.electronSize : '');
138
202
  btnInstall.hidden = e.phase === 'ready' || !e.supported;
139
203
  btnInstall.disabled = e.phase === 'working';
204
+ showDress(next.dressUrl);
140
205
  };
141
206
  const refresh = async () => { try { render(await ctx.invoke<PetState>('state')); } catch (err) { if (!ctx.signal.aborted) msg.replaceChildren(listProblem(root.ownerDocument, errText(err))); } };
142
207
  const call = (method: string, anchor: HTMLElement) => async () => {
@@ -1,16 +1,6 @@
1
- .pet-dress-controls,.pet-dress-axes{display:grid; gap:0}
2
- .pet-dress-field{display:flex; align-items:center; justify-content:space-between; gap:16px; padding:12px 0; border-top:1px solid var(--line, #e2dfe8)}
3
- .pet-dress-caption{display:flex; flex-direction:column; gap:3px; font-weight:600; color:var(--ink, #1b1a1e)}
4
- .pet-dress-caption small{font-size:13px; font-weight:400; color:var(--ink-soft, #5c5c60)}
5
- .pet-dress-field select,.pet-dress-field input{max-width:60%; min-width:0; padding:7px 10px; border:1px solid var(--line-2, #d0d2d0); border-radius:6px; background:var(--sheet, #fff); color:var(--ink, #1b1a1e); font:inherit}
6
- .pet-dress-field select:focus-visible,.pet-dress-field input:focus-visible{outline:2px solid var(--accent, #00a870); outline-offset:2px}
7
- .pet-dress-size{display:flex; align-items:center; justify-content:flex-end; gap:6px}
8
- .pet-dress-size input{width:6em; max-width:100%}
9
- .pet-dress-feedback{font-size:13px; line-height:1.5; color:var(--ink-soft, #5c5c60)}
10
- .pet-dress-feedback:not(:empty){padding-bottom:12px}
11
- .pet-dress-feedback.bad{color:var(--danger, #b33b3b)}
12
- .pet-dress-actions{display:flex; flex-wrap:wrap; gap:8px; padding:12px 0}
13
- @media(max-width:480px){.pet-dress-field{align-items:flex-start; flex-direction:column; gap:8px}.pet-dress-field select{max-width:100%; width:100%}}
1
+ .pet-dressframe{display:block; width:100%; height:620px; border:0; border-radius:12px}
2
+ .pet-dressframe[hidden]{display:none}
3
+ .pet-dressframe-pending{position:absolute; visibility:hidden; pointer-events:none}
14
4
  /* the meter belongs to how it listens: no rule between them */
15
5
  .pet-voicebody .mountrow.pet-meterrow{border-top:0; padding:4px 0 6px}
16
6
  /* the name's characters sit 1px low in their line box; the bar follows them */
@@ -99,7 +99,6 @@ export class WindowHost {
99
99
  this.st = { phase: code === 0 ? 'stopped' : 'error', pid: null, source: cmd.source, reason: code === 0 ? { kind: 'closed' } : { kind: 'exited', code } };
100
100
  });
101
101
  }
102
-
103
102
  async stop(): Promise<void> {
104
103
  const child = this.child;
105
104
  this.child = null;
package/src/world.ts CHANGED
@@ -54,12 +54,12 @@ import { toSimplified } from './asr/simplify.ts';
54
54
  import { estimateSeconds, parseActions, parseScript, vocabChange, vocabTable, type VocabWord } from './script.ts';
55
55
  import { ActivityGroup, ChatSockets, SELF_TYPE, chatHistory, chatItem, chatRefs, type ChatFigure } from './chat.ts';
56
56
  import { ASK_OPTION_MAX, petToolDecls } from './tools.ts';
57
- import { COO, figurePacks, lookOf, lookPatch, modelName, nameIn, packFor, type FigurePack, type MoveTarget, type PackProblem, type PackScan } from './packs.ts';
57
+ import { COO, figurePacks, lookOf, modelName, nameIn, packFor, type FigurePack, type MoveTarget, type PackProblem, type PackScan } from './packs.ts';
58
58
  import { moveChange, moveTable, readMove } from './moves.ts';
59
59
  import { Cua } from './cua/cua.ts';
60
60
  import { CUA_OFF_TOOL_DECLS } from './cua/tools.ts';
61
61
  import type { Answer } from './cua/engine-ipc.ts';
62
- import { DressZipImport, PackImporter } from './pack-import.ts';
62
+ import { PackImporter } from './pack-import.ts';
63
63
  import { dressTable, planSettings, sayScale, type SettingChange } from './self.ts';
64
64
  import { FIREWORKS_WORD, MODEL_TEXT, type ModelLanguage, type ModelText, type NoPortrait } from './model-text.ts';
65
65
 
@@ -521,7 +521,6 @@ export class DesktopPetWorld implements World {
521
521
 
522
522
  /** Installs packs the dressing page sends, when the app named a directory for them. */
523
523
  private readonly importer: PackImporter | null;
524
- private readonly dressImport: DressZipImport | null;
525
524
 
526
525
  constructor(private readonly opts: DesktopPetWorldOptions) {
527
526
  this.cfg = opts.cfg;
@@ -540,8 +539,6 @@ export class DesktopPetWorld implements World {
540
539
  },
541
540
  });
542
541
  this.importer = opts.packDir ? new PackImporter({ packDir: opts.packDir, packs: () => this.packs(), text: () => this.ui }) : null;
543
- const packDir = opts.packDir;
544
- this.dressImport = packDir ? new DressZipImport((text) => new PackImporter({ packDir, packs: () => this.packs(), text: () => text })) : null;
545
542
  this.status = new StatusTracker((status) => this.server.sendPet({ t: 'status', status }), opts.describeTool, () => this.ui.busy);
546
543
  this.segmenter = new Segmenter(this.segmentConfig(), FRAME_MS);
547
544
  this.segmenter.setSink(this.sink);
@@ -825,7 +822,6 @@ export class DesktopPetWorld implements World {
825
822
  if (this.holidayTimer) clearInterval(this.holidayTimer);
826
823
  this.holidayTimer = null;
827
824
  this.savePosition();
828
- await this.dressImport?.cancel();
829
825
  await this.importer?.cancel();
830
826
  if (this.packTimer) clearTimeout(this.packTimer);
831
827
  this.packTimer = null;
@@ -2631,7 +2627,7 @@ export class DesktopPetWorld implements World {
2631
2627
  this.voiceSockets.add(socket);
2632
2628
  socket.onClose(() => this.voiceSockets.delete(socket));
2633
2629
  },
2634
- links: this.server.port ? [{ label: c.viewInBrowser, href: this.petUrl }, { label: c.dress, href: `${this.server.origin}/dress` }] : [],
2630
+ links: this.server.port ? [{ label: c.viewInBrowser, href: this.petUrl }] : [],
2635
2631
  config: desktopPetConfigGroups(language),
2636
2632
  promptDocs: [{
2637
2633
  key: `worlds.${DESKTOP_PET_ID}.envPrompt`,
@@ -2644,94 +2640,10 @@ export class DesktopPetWorld implements World {
2644
2640
  };
2645
2641
  }
2646
2642
 
2647
- /** A settings client needs option ids, even when the stored scheme names a preset. */
2648
- private dressState(language: Language, packs = this.packs()) {
2649
- const skin = this.cfg.skin;
2650
- const pack = packFor(packs, skin.figure);
2651
- const scheme = pack ? lookOf(pack, skin) : '';
2652
- const parts = scheme.split('-');
2653
- const preset = pack?.id === COO ? undefined : pack?.manifest.presets.find((p) => p.id === scheme);
2654
- return {
2655
- skin: pack ? {
2656
- figure: pack.id,
2657
- scheme: pack.manifest.axes.map((a, i) => {
2658
- const pick = preset ? preset.pick[a.id] : parts[i];
2659
- return a.options.find((o) => o.id === pick)?.id ?? a.options[0]!.id;
2660
- }).join('-'),
2661
- } : {},
2662
- scale: this.cfg.window.scale,
2663
- packs: packs.map(({ id, manifest }) => ({
2664
- id, name: nameIn(manifest.name, language),
2665
- axes: manifest.axes.map((a) => ({
2666
- id: a.id, label: nameIn(a.name, language),
2667
- options: a.options.map((o) => ({ id: o.id, label: nameIn(o.name, language) })),
2668
- })),
2669
- })),
2670
- importable: !!this.dressImport,
2671
- };
2672
- }
2673
-
2674
- private saveDress(raw: unknown, language: Language) {
2675
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)
2676
- || Object.keys(raw).some((key) => key !== 'figure' && key !== 'scheme' && key !== 'scale')) {
2677
- throw new Error('Invalid dress settings');
2678
- }
2679
- const patch = raw as Record<string, unknown>;
2680
- const t = petText(language);
2681
- const scale = scaleOf(patch.scale);
2682
- if (Object.hasOwn(patch, 'scale') && scale === null) throw new Error('Invalid dress scale');
2683
- const packs = this.packs();
2684
- const hasFigure = Object.hasOwn(patch, 'figure'), hasScheme = Object.hasOwn(patch, 'scheme');
2685
- if (hasFigure || hasScheme) {
2686
- const current = this.cfg.skin.figure ?? COO;
2687
- const figure = hasFigure ? patch.figure : current;
2688
- const pack = packs.find((p) => p.id === figure);
2689
- if (!pack) throw new Error(t.packs.badId(JSON.stringify(figure) ?? ''));
2690
- const { axes, presets } = pack.manifest;
2691
- let scheme: string | undefined;
2692
- if (hasScheme) {
2693
- const want = patch.scheme;
2694
- if (typeof want !== 'string') throw new Error(t.packs.badPreset(JSON.stringify(want) ?? ''));
2695
- const parts = want === '' ? [] : want.split('-');
2696
- const picksAxes = axes.length === parts.length && axes.every((a, i) => a.options.some((o) => o.id === parts[i]));
2697
- if (!picksAxes && !presets.some((p) => p.id === want)) throw new Error(t.packs.badPreset(JSON.stringify(want)));
2698
- // Preserve a matching preset's styling, rather than saving only its equivalent axis combination.
2699
- if (picksAxes && pack.id !== COO) {
2700
- for (const p of presets) {
2701
- if (!axes.every((a, i) => p.pick[a.id] === parts[i])) continue;
2702
- scheme ??= p.id;
2703
- if (figure === current && p.id === this.cfg.skin.scheme) { scheme = p.id; break; }
2704
- }
2705
- }
2706
- scheme ??= want;
2707
- } else if (pack.id !== current && pack.id !== COO) {
2708
- scheme = presets[0]?.id ?? axes.map((a) => a.options[0]!.id).join('-');
2709
- }
2710
- this.saveSkin({ ...this.cfg.skin, figure: pack.id, ...(scheme === undefined ? {} : lookPatch(pack, scheme)) }, scale);
2711
- } else if (scale !== null) {
2712
- this.savePrefs({ scale });
2713
- }
2714
- return this.dressState(language, packs);
2715
- }
2716
-
2717
- private requireDressImport(language: Language): DressZipImport {
2718
- if (!this.dressImport) throw new Error(petText(language).importing.expired);
2719
- return this.dressImport;
2720
- }
2721
-
2722
2643
  private async invoke(panel: string, method: string, args: unknown[], language: Language = this.appLanguage): Promise<unknown> {
2723
2644
  if (panel === 'pet') {
2724
2645
  switch (method) {
2725
2646
  case 'state': return this.petState();
2726
- case 'dressState': return this.dressState(language);
2727
- case 'dressSave': return this.saveDress(args[0], language);
2728
- case 'dressImportStart': return this.requireDressImport(language).start(args[0], petText(language));
2729
- case 'dressImportChunk': this.requireDressImport(language).chunk(args[0], args[1], petText(language)); return { ok: true };
2730
- case 'dressImportFinish': return this.requireDressImport(language).finish(args[0], petText(language));
2731
- case 'dressImportInstall': return this.requireDressImport(language).install(args[0], args[1], args[2], petText(language));
2732
- case 'dressImportCancel':
2733
- if (typeof args[0] === 'string') await this.dressImport?.cancel(args[0]);
2734
- return { ok: true };
2735
2647
  case 'openWindow': this.openWindow(); return this.petState();
2736
2648
  case 'closeWindow': await this.windowHost?.stop(); return this.petState();
2737
2649
  // hides the window as the pet's menu does; it stays connected and comes back with openWindow
@@ -1,160 +0,0 @@
1
- import type { WebUiPanelContext } from 'cortico/web/shared/client-panel.ts';
2
- import { showDressDialog, type DressDialogView } from './dress-dialog.ts';
3
-
4
- interface Pack { id: string; name: string; axes: Array<{ id: string; label: string; options: Array<{ id: string; label: string }> }> }
5
- interface DressState { skin: { figure?: string; scheme?: string }; scale: number; packs: Pack[]; importable: boolean }
6
- interface ImportPreview { token: string; packs: Array<{ dir: string; id: string; name: Record<string, string>; installed: string | null }>; problems: Array<{ dir: string; reason: string }> }
7
-
8
- /** Settings never execute figure code: the desktop pet renders the selected figure. */
9
- export function mountDress(ctx: WebUiPanelContext, body: HTMLElement): void {
10
- const { ui, signal } = ctx;
11
- const doc = body.ownerDocument;
12
- const zh = ctx.language === 'zh' || ctx.language === 'zh-Hant';
13
- const text = zh ? {
14
- figure: '形象', size: '大小', save: '保存打扮', saving: '正在保存…', saved: '打扮已保存。', loading: '正在加载打扮…',
15
- empty: '没有可用的形象。', import: '导入形象 ZIP', uploading: '正在上传', inspecting: '正在检查形象包…',
16
- preview: '选择要导入的形象', previewHint: '选中要安装的形象包。已有的形象需要确认后才会替换。',
17
- installed: '已安装', cancel: '取消', install: '安装所选', conflict: '替换已有形象?',
18
- conflictHint: '以下形象已存在。确认后将替换它们。', replace: '替换并安装', done: '已导入',
19
- unavailable: '当前无法导入形象。', error: '操作失败', retry: '重试', sizeHint: '调整桌面上的显示大小',
20
- } : {
21
- figure: 'Figure', size: 'Size', save: 'Save outfit', saving: 'Saving…', saved: 'Outfit saved.', loading: 'Loading outfits…',
22
- empty: 'No figures are available.', import: 'Import figure ZIP', uploading: 'Uploading', inspecting: 'Checking figure packs…',
23
- preview: 'Choose figures to import', previewHint: 'Select the figure packs to install. Existing figures require confirmation before replacement.',
24
- installed: 'Installed', cancel: 'Cancel', install: 'Install selected', conflict: 'Replace existing figures?',
25
- conflictHint: 'These figures already exist. Confirm to replace them.', replace: 'Replace and install', done: 'Imported',
26
- unavailable: 'Figure import is unavailable.', error: 'Could not complete the action', retry: 'Try again', sizeHint: 'Adjust the size on your desktop',
27
- };
28
- const feedback = ui.h('div', 'pet-dress-feedback', text.loading);
29
- feedback.setAttribute('role', 'status'); feedback.setAttribute('aria-live', 'polite');
30
- const controls = ui.h('div', 'pet-dress-controls');
31
- const actions = ui.h('div', 'pet-dress-actions');
32
- const save = ui.button(text.save, { size: 'sm', variant: 'primary' });
33
- const importButton = ui.button(text.import, { size: 'sm' });
34
- const retry = ui.button(text.retry, { size: 'sm' });
35
- const file = doc.createElement('input'); file.type = 'file'; file.accept = '.zip,application/zip'; file.hidden = true;
36
- actions.append(save, importButton, retry, file); body.append(feedback, controls, actions);
37
- let state: DressState | null = null;
38
- let busy = false;
39
- let uploadToken: string | null = null;
40
- let figure: HTMLSelectElement;
41
- let size: HTMLInputElement;
42
- let axes: HTMLSelectElement[] = [];
43
- const message = (value: string, error = false) => { feedback.textContent = value; feedback.classList.toggle('bad', error); };
44
- const setBusy = (value: boolean) => {
45
- busy = value;
46
- controls.querySelectorAll<HTMLInputElement | HTMLSelectElement>('input, select').forEach(el => { el.disabled = value; });
47
- save.disabled = value || !state || !state.packs.length;
48
- importButton.disabled = value || !state?.importable;
49
- importButton.title = state && !state.importable ? text.unavailable : '';
50
- retry.hidden = value || !!state;
51
- };
52
- const label = (name: string, input: HTMLElement, hint?: string) => {
53
- const row = ui.h('label', 'pet-dress-field');
54
- const caption = ui.h('span', 'pet-dress-caption', name);
55
- if (hint) caption.append(ui.h('small', '', hint));
56
- row.append(caption, input); return row;
57
- };
58
- const option = (select: HTMLSelectElement, value: string, name: string) => {
59
- const el = doc.createElement('option'); el.value = value; el.textContent = name; select.append(el);
60
- };
61
- const drawAxes = (pack: Pack | undefined, scheme = '') => {
62
- controls.querySelector('.pet-dress-axes')?.remove();
63
- const group = ui.h('div', 'pet-dress-axes'); axes = [];
64
- const picks = scheme.split('-');
65
- pack?.axes.forEach((axis, index) => {
66
- const select = doc.createElement('select');
67
- axis.options.forEach(item => option(select, item.id, item.label));
68
- if (axis.options.some(item => item.id === picks[index])) select.value = picks[index];
69
- axes.push(select); group.append(label(axis.label, select));
70
- });
71
- controls.append(group);
72
- };
73
- const render = (next: DressState) => {
74
- state = next; controls.replaceChildren();
75
- figure = doc.createElement('select');
76
- next.packs.forEach(pack => option(figure, pack.id, pack.name));
77
- if (next.skin.figure && next.packs.some(pack => pack.id === next.skin.figure)) figure.value = next.skin.figure;
78
- controls.append(label(text.figure, figure));
79
- size = doc.createElement('input'); size.type = 'number'; size.min = '50'; size.max = '1000'; size.step = '5'; size.value = String(Math.round(next.scale * 100));
80
- const sizeWrap = ui.h('span', 'pet-dress-size'); sizeWrap.append(size, ui.h('span', 'pet-unit', '%'));
81
- controls.append(label(text.size, sizeWrap, text.sizeHint));
82
- drawAxes(next.packs.find(pack => pack.id === figure.value), next.skin.scheme);
83
- figure.addEventListener('change', () => drawAxes(next.packs.find(pack => pack.id === figure.value)));
84
- setBusy(false);
85
- };
86
- const load = async () => {
87
- setBusy(true); message(text.loading);
88
- try { const next = await ctx.invoke<DressState>('dressState'); if (!signal.aborted) { render(next); message(next.packs.length ? '' : text.empty); } }
89
- catch (err) { if (!signal.aborted) { setBusy(false); message(`${text.error}: ${String(err)}`, true); } }
90
- };
91
- retry.addEventListener('click', () => void load());
92
- save.addEventListener('click', () => void (async () => {
93
- if (!state || busy || !size.reportValidity()) return;
94
- const patch: { figure: string; scheme?: string; scale: number } = { figure: figure.value, scale: Number(size.value) / 100 };
95
- if (axes.length) patch.scheme = axes.map(axis => axis.value).join('-');
96
- setBusy(true); message(text.saving);
97
- try { const next = await ctx.invoke<DressState>('dressSave', [patch]); if (!signal.aborted) { render(next); message(text.saved); } }
98
- catch (err) { if (!signal.aborted) { setBusy(false); message(`${text.error}: ${String(err)}`, true); } }
99
- })());
100
- const dialog = (view: DressDialogView) => {
101
- const { promise, resolve } = Promise.withResolvers<{ action: string; selected: string[] }>();
102
- if (signal.aborted) resolve({ action: 'cancel', selected: [] });
103
- else showDressDialog({ doc, host: doc.body, signal }, view, resolve);
104
- return promise;
105
- };
106
- const cancelUpload = async () => {
107
- const token = uploadToken; uploadToken = null;
108
- if (token) await ctx.invoke('dressImportCancel', [token]);
109
- };
110
- signal.addEventListener('abort', () => { void cancelUpload().catch(() => {}); }, { once: true });
111
- importButton.addEventListener('click', () => file.click());
112
- file.addEventListener('change', () => void (async () => {
113
- const chosen = file.files?.[0]; file.value = '';
114
- if (!chosen || busy) return;
115
- setBusy(true);
116
- let resultMessage = '';
117
- let failed = false;
118
- try {
119
- message(`${text.uploading} 0%`);
120
- const token = await ctx.invoke<string>('dressImportStart', [chosen.size]);
121
- uploadToken = token;
122
- if (signal.aborted) return;
123
- const chunkSize = 48 * 1024;
124
- for (let offset = 0; offset < chosen.size; offset += chunkSize) {
125
- const bytes = new Uint8Array(await chosen.slice(offset, offset + chunkSize).arrayBuffer());
126
- if (signal.aborted) return;
127
- let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte);
128
- await ctx.invoke('dressImportChunk', [token, btoa(binary)]);
129
- if (signal.aborted) return;
130
- message(`${text.uploading} ${Math.round(Math.min(offset + chunkSize, chosen.size) / chosen.size * 100)}%`);
131
- }
132
- message(text.inspecting);
133
- const preview = await ctx.invoke<ImportPreview>('dressImportFinish', [token]);
134
- uploadToken = preview.token;
135
- if (signal.aborted) return;
136
- const answer = await dialog({ title: text.preview, body: text.previewHint, selectable: true,
137
- items: preview.packs.map(pack => ({ key: pack.dir, label: pack.name[ctx.language ?? 'zh'] || pack.name[zh ? 'zh' : 'en'] || pack.name.en || pack.id, meta: [pack.id], ...(pack.installed ? { notice: `${text.installed}: ${pack.installed}` } : {}) })),
138
- warnings: preview.problems.map(problem => `${problem.dir}: ${problem.reason}`),
139
- actions: [{ key: 'cancel', label: text.cancel }, ...(preview.packs.length ? [{ key: 'install', label: text.install, kind: 'primary' as const, selection: true }] : [])] });
140
- if (answer.action !== 'install' || signal.aborted) return;
141
- let installed = await ctx.invoke<{ installed?: string[]; conflicts?: string[] }>('dressImportInstall', [preview.token, answer.selected, []]);
142
- if (signal.aborted) return;
143
- if (installed.conflicts?.length) {
144
- const confirm = await dialog({ title: text.conflict, body: text.conflictHint, items: installed.conflicts.map(id => ({ key: id, label: id, meta: [] })), actions: [{ key: 'cancel', label: text.cancel }, { key: 'replace', label: text.replace, kind: 'danger' }] });
145
- if (confirm.action !== 'replace' || signal.aborted) return;
146
- installed = await ctx.invoke<{ installed?: string[]; conflicts?: string[] }>('dressImportInstall', [preview.token, answer.selected, installed.conflicts]);
147
- if (signal.aborted) return;
148
- if (installed.conflicts?.length) throw new Error(`${text.conflict}: ${installed.conflicts.join(', ')}`);
149
- }
150
- resultMessage = `${text.done}: ${(installed.installed ?? []).join(', ')}`;
151
- const next = await ctx.invoke<DressState>('dressState');
152
- if (!signal.aborted) render(next);
153
- } catch (err) { failed = true; resultMessage = `${text.error}: ${String(err)}`; }
154
- finally {
155
- try { await cancelUpload(); } catch (err) { failed = true; resultMessage = `${text.error}: ${String(err)}`; }
156
- if (!signal.aborted) { setBusy(false); message(resultMessage, failed); }
157
- }
158
- })());
159
- void load();
160
- }