@takboo/dsh-coopanion 0.4.13 → 0.4.15

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.
Files changed (44) hide show
  1. package/README.md +4 -4
  2. package/desktop/display-controller.cjs +8 -4
  3. package/desktop/main.cjs +8 -2
  4. package/desktop/preload.cjs +2 -0
  5. package/dist/bridge.js +90 -8
  6. package/dist/bridge.js.map +4 -4
  7. package/dist/build-info.json +2 -2
  8. package/dist/client.js +1 -1
  9. package/dist/figure-server.cjs +1 -1
  10. package/dist/index.js +91 -9
  11. package/dist/index.js.map +4 -4
  12. package/docs/desktop-recovery-contract.md +4 -0
  13. package/docs/development.md +20 -0
  14. package/docs/multi-display-contract.md +6 -0
  15. package/docs/release-notes.md +25 -0
  16. package/docs/releasing.md +2 -2
  17. package/docs/session-chat-contract.md +1 -1
  18. package/docs/usage.md +22 -7
  19. package/npm-shrinkwrap.json +21 -21
  20. package/package.json +20 -20
  21. package/scripts/observe-companion.mjs +1 -1
  22. package/src/bridge.ts +19 -4
  23. package/src/client/index.ts +1 -1
  24. package/src/controls.ts +1 -1
  25. package/src/electron-runtime.ts +50 -0
  26. package/src/figure-server.ts +3 -1
  27. package/tests/companionship-ui.mjs +38 -4
  28. package/tests/display-geometry.test.js +37 -1
  29. package/tests/electron-startup.test.ts +93 -0
  30. package/tests/figures.test.ts +45 -2
  31. package/tests/fixtures/late-display-quit.cjs +8 -0
  32. package/tests/fixtures/lifecycle-shutdown-trace.cjs +37 -0
  33. package/tests/helpers/native-pointer.mjs +33 -7
  34. package/tests/helpers/windows-taskbar.ps1 +22 -0
  35. package/tests/inbox-ui.mjs +1 -0
  36. package/tests/install.mjs +15 -5
  37. package/tests/lifecycle-startup-native.mjs +44 -9
  38. package/tests/locale-client.mjs +23 -0
  39. package/tests/multi-display-ui.mjs +42 -0
  40. package/tests/preload-geometry.test.js +23 -0
  41. package/tests/session-replies-ui.mjs +22 -0
  42. package/tests/windows-geometry-native.mjs +78 -0
  43. package/tests/windows-pointer-native.mjs +43 -0
  44. package/web/pet.js +23 -5
@@ -51,10 +51,41 @@ async function fixture(t, mode = 'interactive', vocab, star = false, timing = nu
51
51
  }
52
52
  async function tickNext(page, extra = 0) { await advanceCompanion(page, await page.evaluate(() => window.companionState.active?.dueAt) + extra); }
53
53
  async function finishActivity(page) {
54
+ const body = page.frames().find(frame => frame.url().includes('figure-frame.html'));
55
+ assert.ok(body, 'live API 2 body frame exists');
56
+ // The real tick handler runs first; this observer only acknowledges processing.
57
+ await body.evaluate(() => addEventListener('message', event => {
58
+ if (event.source === parent && event.data?.t === 'tick' && Number.isSafeInteger(event.data.companionTestTick))
59
+ parent.postMessage({ t: 'companion-test-tick-ack', id: event.data.companionTestTick }, '*');
60
+ }));
61
+ await page.evaluate(() => { window.companionPhysicsTicks = 0; });
54
62
  for (let i = 0; i < 6 && await page.evaluate(() => !!window.companionState.active); i++) {
55
63
  const index = await page.evaluate(() => window.companionState.active.index);
56
64
  await tickNext(page);
57
- await page.waitForFunction(index => !window.companionState.active || window.companionState.active.index !== index, index);
65
+ // Actual body inputs and the original progress predicate share this ten-second wait.
66
+ await page.waitForFunction(async index => {
67
+ if (!window.companionState.active || window.companionState.active.index !== index) return true;
68
+ const frame = document.querySelector('#body-layer iframe');
69
+ if (!frame?.contentWindow) throw new Error('Live body frame required');
70
+ const tick = () => new Promise((resolve, reject) => {
71
+ const id = ++window.companionPhysicsTicks;
72
+ let layout;
73
+ const receive = event => {
74
+ if (event.source !== frame.contentWindow) return;
75
+ if (event.data?.t === 'frame') layout = event.data.layout;
76
+ if (event.data?.t !== 'companion-test-tick-ack' || event.data.id !== id) return;
77
+ removeEventListener('message', receive);
78
+ if (typeof layout?.moving !== 'boolean') reject(new Error('Invalid body motion report'));
79
+ else resolve(layout);
80
+ };
81
+ addEventListener('message', receive);
82
+ frame.contentWindow.postMessage({ t: 'tick', dt: .05, companionTestTick: id }, '*');
83
+ });
84
+ let layout;
85
+ while (window.companionPhysicsTicks < 400) { layout = await tick(); if (!layout.moving) break; }
86
+ if (layout?.moving) throw new Error('Body motion exceeded twenty seconds of controlled physics');
87
+ return !window.companionState.active || window.companionState.active.index !== index;
88
+ }, index);
58
89
  }
59
90
  }
60
91
  async function menu(page) { await page.locator('#pet').dispatchEvent('contextmenu', { button: 2 }); await page.locator('#menu').waitFor(); }
@@ -113,6 +144,7 @@ test('manual play grows only after completion, aborted play does not, archive su
113
144
  await menu(page); await page.locator('#companion-play').click(); await page.mouse.move(0, 0); assert.equal((await read()).relation.total, 0);
114
145
  await finishActivity(page); await page.waitForFunction(() => document.querySelector('#companion-status').textContent.includes('1'));
115
146
  assert.equal((await read()).relation.total, 1);
147
+ assert.ok(await f.body.evaluate(() => window.bodyOrders.some(order => order.t === 'do' && order.word === 'dance')), 'the default long recipe reaches its real body');
116
148
  f.setDay(16); await menu(page); await page.locator('#companion-play').click(); await page.mouse.move(0, 0);
117
149
  await f.receive({ type: 'snapshot', snapshot: snapshot({ mood: 'working', active: true, sessions: [{ ...session, mood: 'working', active: true }] }) });
118
150
  await advanceCompanion(page, await page.evaluate(() => window.companionNow + 20000)); assert.equal((await read()).relation.total, 1);
@@ -148,7 +180,8 @@ test('real strokes count once, forged sandbox touches do not, missing words rema
148
180
  await body.evaluate(() => parent.postMessage({ t: 'frame', layout: null, events: [{ kind: 'touch', detail: { kind: 'pet' } }] }, '*'));
149
181
  await page.waitForTimeout(100); assert.equal((await read()).relation.total, 0);
150
182
  const b = await page.locator('#pet').boundingBox();
151
- for (let i = 0; i < 18; i++) await page.mouse.move(b.x + b.width * (i % 2 ? .35 : .65), b.y + b.height * .45, { steps: 1 });
183
+ // Cross the real hit region broadly enough to remain a stroke under input jitter.
184
+ for (let i = 0; i < 18; i++) await page.mouse.move(b.x + b.width * (i % 2 ? .2 : .8), b.y + b.height * .45, { steps: 1 });
152
185
  await page.waitForFunction(() => document.querySelector('#companion-status').textContent.includes('1'));
153
186
  assert.equal((await read()).relation.total, 1);
154
187
  const missing = await fixture(t, 'quiet', ['neutral', 'stand']);
@@ -183,7 +216,7 @@ test('twenty real strokes keep visible feedback while hovering and share the gro
183
216
  await page.mouse.move(0, 0);
184
217
  if (trial) await page.waitForTimeout(2550);
185
218
  const b = await page.locator('#pet').boundingBox();
186
- for (let i = 0; i < 18; i++) await page.mouse.move(b.x + b.width * (i % 2 ? .35 : .65), b.y + b.height * .45, { steps: 1 });
219
+ for (let i = 0; i < 18; i++) await page.mouse.move(b.x + b.width * (i % 2 ? .2 : .8), b.y + b.height * .45, { steps: 1 });
187
220
  await page.waitForFunction(n => window.strokeLatencies.length > n, trial);
188
221
  await page.waitForTimeout(300);
189
222
  assert.equal(await page.locator('#companion-feedback').isVisible(), true);
@@ -292,7 +325,8 @@ test('native NPC waits for acknowledged workArea before establishing home', asyn
292
325
  });
293
326
 
294
327
  test('manual interaction survives a frame timestamp preceding the click event clock', async t => {
295
- const { page, read, configure } = await fixture(t, 'quiet', undefined, false, { frameLag: 100 });
328
+ // Isolate clock ordering from the longer dance physics at low frame rates.
329
+ const { page, read, configure } = await fixture(t, 'quiet', ['happy', 'nod', 'neutral'], false, { frameLag: 100 });
296
330
  await configure({ roam: false });
297
331
  await menu(page); await page.locator('#companion-play').click(); await page.mouse.move(0, 0);
298
332
  await page.waitForTimeout(200);
@@ -39,7 +39,7 @@ it('native controller replays switching, taskbars, unplugging and DPI/rotation c
39
39
  let layout = structuredClone(irregular), rectangle = {...layout[0].workArea}, cursor = {x:500,y:-500};
40
40
  const messages = [], moves = [];
41
41
  const screen = { getPrimaryDisplay: () => layout[0], getAllDisplays: () => layout, getCursorScreenPoint: () => cursor };
42
- const win = { getBounds: () => rectangle, getContentBounds: () => ({...rectangle}), setBounds(b) { rectangle = {...b}; moves.push(b); } };
42
+ const win = { isDestroyed: () => false, getBounds: () => rectangle, getContentBounds: () => ({...rectangle}), setBounds(b) { rectangle = {...b}; moves.push(b); } };
43
43
  const c = createDisplayController({screen, win, send: m => messages.push(m)});
44
44
  c.refresh(); expect(c.state.displayId).toBe(1);
45
45
  c.moveToCursor(); expect(c.state.displayId).toBe(3); expect(rectangle).toEqual(layout[2].workArea);
@@ -53,3 +53,39 @@ it('native controller replays switching, taskbars, unplugging and DPI/rotation c
53
53
  expect(messages.every(m => m.type === 'display-changed')).toBe(true);
54
54
  expect(moves.length).toBe(3);
55
55
  });
56
+
57
+ it('re-reads settled content bounds when replaying geometry after an asynchronous resize', () => {
58
+ const target = display(1, 0, 25, 1440, 1104, 1.25);
59
+ let bounds = { ...target.workArea, height: 1152 }, content = { ...bounds };
60
+ const messages = [];
61
+ const controller = createDisplayController({
62
+ screen: { getPrimaryDisplay: () => target, getAllDisplays: () => [target] },
63
+ win: { isDestroyed: () => false, getBounds: () => bounds, getContentBounds: () => ({ ...content }), setBounds: value => { bounds = { ...value }; } },
64
+ send: value => messages.push(value),
65
+ });
66
+ controller.refresh();
67
+ expect(controller.state.contentBounds.height).toBe(1152);
68
+ const revision = controller.state.revision;
69
+ content = { ...bounds }; // Native content bounds settle after setBounds returns.
70
+ controller.publish();
71
+ expect(messages.at(-1).contentBounds.height).toBe(1104);
72
+ expect(messages.at(-1).revision).toBeGreaterThan(revision);
73
+ controller.publish();
74
+ expect(messages.at(-1).revision).toBe(controller.state.revision);
75
+ });
76
+
77
+ it('ignores queued display work after its native window is destroyed', () => {
78
+ const target = irregular[0], messages = [];
79
+ let destroyed = false, calls = 0;
80
+ const alive = () => { if (destroyed) throw new TypeError('Object has been destroyed'); calls++; };
81
+ const controller = createDisplayController({
82
+ screen: { getPrimaryDisplay: () => target, getAllDisplays: () => { alive(); return [target]; }, getCursorScreenPoint: () => { alive(); return { x: 0, y: 0 }; } },
83
+ win: { isDestroyed: () => destroyed, getBounds: () => { alive(); return target.workArea; }, getContentBounds: () => { alive(); return target.workArea; } },
84
+ send: value => messages.push(value),
85
+ });
86
+ controller.refresh(); const before = { calls, messages: messages.length };
87
+ destroyed = true;
88
+ expect(() => { controller.refresh(); controller.publish(); controller.moveToCursor(); }).not.toThrow();
89
+ expect(controller.cursor()).toBeUndefined();
90
+ expect({ calls, messages: messages.length }).toEqual(before);
91
+ });
@@ -0,0 +1,93 @@
1
+ import { it, expect } from 'vitest';
2
+ import { build } from 'esbuild';
3
+ import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';
4
+ import { createRequire } from 'node:module';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ import type { ElectronBridge as Bridge } from '../src/bridge.ts';
9
+
10
+ // Keep Electron's real lazy-install entrypoint; replace only the download with
11
+ // a deterministic slow installer and a tiny IPC peer, without network access.
12
+ async function fixture(install = '') {
13
+ const directory = await mkdtemp(join(tmpdir(), 'dsh-first-electron-'));
14
+ const electron = join(directory, 'node_modules/electron');
15
+ const previous = process.env.ELECTRON_OVERRIDE_DIST_PATH;
16
+ const previousDisplay = process.env.WAYLAND_DISPLAY;
17
+ if (process.platform === 'linux') process.env.WAYLAND_DISPLAY = 'test-only';
18
+ delete process.env.ELECTRON_OVERRIDE_DIST_PATH;
19
+ let bridge: Bridge | undefined;
20
+ const close = async () => {
21
+ await bridge?.dispose();
22
+ if (previous !== undefined) process.env.ELECTRON_OVERRIDE_DIST_PATH = previous;
23
+ if (previousDisplay === undefined) delete process.env.WAYLAND_DISPLAY; else process.env.WAYLAND_DISPLAY = previousDisplay;
24
+ await rm(directory, { recursive: true, force: true });
25
+ };
26
+ try {
27
+ await mkdir(electron, { recursive: true });
28
+ await writeFile(join(directory, 'package.json'), '{"type":"module"}');
29
+ await writeFile(join(electron, 'package.json'), '{"main":"index.js"}');
30
+ await writeFile(join(electron, 'index.js'), await readFile(createRequire(import.meta.url).resolve('electron')));
31
+ await mkdir(join(directory, 'desktop'));
32
+ await writeFile(join(directory, 'desktop/main.cjs'), `process.on('message', m => { if(m.type === 'quit') process.exit(0); }); process.send({type:'ready'});`);
33
+ // A real executable plus a JS main works on Windows as well as POSIX;
34
+ // spawning a shebang-only fixture silently omitted the Windows regression.
35
+ const success = `setTimeout(()=>{fs.mkdirSync(path.join(__dirname,'dist'));const executable=path.join(__dirname,'dist/peer.exe');try{fs.linkSync(process.execPath,executable);}catch(error){if(error.code!=='EXDEV')throw error;fs.copyFileSync(process.execPath,executable);fs.chmodSync(executable,0o700);}fs.writeFileSync(path.join(__dirname,'path.txt'),'peer.exe');},800);`;
36
+ await writeFile(join(electron, 'install.js'), `const fs=require('node:fs'),path=require('node:path');fs.writeFileSync(path.join(__dirname,'installer-pid'),String(process.pid));${install || success}`);
37
+ await build({ entryPoints: ['src/bridge.ts'], outfile: join(directory, 'dist/bridge.mjs'), bundle: true, packages: 'external', platform: 'node', format: 'esm' });
38
+ const { ElectronBridge } = await import(pathToFileURL(join(directory, 'dist/bridge.mjs')).href);
39
+ bridge = new ElectronBridge();
40
+ return { bridge: bridge!, electron, close };
41
+ } catch (error) { await close(); throw error; }
42
+ }
43
+ const options = { size: 150, roam: false, notifications: false, bubbleDurationMs: 12000 };
44
+ it('keeps the Host event loop responsive during Electron first-run preparation', async () => {
45
+ const { bridge, close } = await fixture();
46
+ const ticks: number[] = [];
47
+ const timer = setInterval(() => ticks.push(performance.now()), 20);
48
+ try {
49
+ const began = performance.now();
50
+ ticks.push(began);
51
+ const starting = bridge.start(options);
52
+ const returnedAfter = performance.now() - began;
53
+ await starting;
54
+ ticks.push(performance.now());
55
+ expect(returnedAfter, 'start must yield while Electron installs').toBeLessThan(250);
56
+ expect(Math.max(...ticks.slice(1).map((time, i) => time - ticks[i])), 'Host timers must continue during installation').toBeLessThan(500);
57
+ } finally {
58
+ clearInterval(timer);
59
+ await close();
60
+ }
61
+ }, 15000);
62
+
63
+ it('reports installer failure without launching a native window', async () => {
64
+ const { bridge, close } = await fixture('process.exit(7);');
65
+ try { await expect(bridge.start(options)).rejects.toMatchObject({ recoverable: false, message: expect.stringContaining('(7)') }); }
66
+ finally { await close(); }
67
+ });
68
+
69
+ it('cancels runtime preparation, reaps its installer and rejects a concurrent start', async () => {
70
+ const { bridge, electron, close } = await fixture('setInterval(()=>{},1000);');
71
+ const controller = new AbortController();
72
+ const starting = bridge.start(options, { signal: controller.signal, generation: 1 });
73
+ const rejected = expect(starting).rejects.toThrow('启动已取消');
74
+ try {
75
+ await expect(bridge.start(options)).rejects.toThrow('already running or starting');
76
+ let pid = 0;
77
+ for (let i = 0; i < 100 && !pid; i++) {
78
+ try { pid = Number(await readFile(join(electron, 'installer-pid'), 'utf8')); }
79
+ catch { await new Promise(resolve => setTimeout(resolve, 20)); }
80
+ }
81
+ expect(pid).toBeGreaterThan(0);
82
+ controller.abort(); await bridge.dispose(); await rejected;
83
+ expect(() => process.kill(pid, 0)).toThrow();
84
+ } finally { await close(); }
85
+ });
86
+
87
+ it('direct disposal cancels preparation even without a caller lifetime', async () => {
88
+ const { bridge, close } = await fixture('setInterval(()=>{},1000);');
89
+ const starting = bridge.start(options);
90
+ const rejected = expect(starting).rejects.toThrow('启动已取消');
91
+ try { await bridge.dispose(); await rejected; }
92
+ finally { await close(); }
93
+ });
@@ -3,7 +3,8 @@ import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { once } from 'node:events';
6
- import { request } from 'node:http';
6
+ import { request, type IncomingMessage, type ServerResponse } from 'node:http';
7
+ import { createConnection } from 'node:net';
7
8
  import { zipSync, strToU8, unzipSync, strFromU8 } from 'fflate';
8
9
  import { CharacterStore, knownScheme, PACK_LIMIT } from '../src/character-store.ts';
9
10
  import { createPetServer } from '../src/figure-server.ts';
@@ -67,6 +68,48 @@ describe('upstream API 2 packs', () => {
67
68
  }));
68
69
  });
69
70
 
71
+ it('serves accepted pipelined requests after the listening socket closes', async () => withStore(async store => {
72
+ const listing = await store.list();
73
+ let release!: () => void, entered!: () => void, second!: () => void;
74
+ const blocked = new Promise<void>(resolve => { release = resolve; });
75
+ const firstRequest = new Promise<void>(resolve => { entered = resolve; });
76
+ const secondRequest = new Promise<void>(resolve => { second = resolve; });
77
+ store.list = async () => { entered(); await blocked; return listing; };
78
+ const server = createPetServer({ webRoot: resolve('web'), store });
79
+ const handler = server.listeners('request')[0] as (req: IncomingMessage, res: ServerResponse) => Promise<void>;
80
+ const escaped: unknown[] = [];
81
+ let requests = 0;
82
+ // Observe escaped async listener errors without letting the test runner's
83
+ // process-wide rejection handler replace the assertion about this request.
84
+ server.removeListener('request', handler);
85
+ server.on('request', (req, res) => {
86
+ if (++requests === 2) second();
87
+ void Promise.resolve(handler(req, res)).catch(error => {
88
+ escaped.push(error); res.writeHead(500).end();
89
+ });
90
+ });
91
+ server.listen(0, '127.0.0.1'); await once(server, 'listening');
92
+ const port = (server.address() as { port: number }).port;
93
+ const socket = createConnection({ host: '127.0.0.1', port });
94
+ let deadline: ReturnType<typeof setTimeout> | undefined;
95
+ try {
96
+ await once(socket, 'connect'); socket.setEncoding('utf8');
97
+ let response = ''; socket.on('data', part => { response += part; });
98
+ const ended = once(socket, 'close');
99
+ const send = (connection: string) => socket.write(`GET /api/characters/list HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: ${connection}\r\n\r\n`);
100
+ send('keep-alive'); await firstRequest;
101
+ const closed = new Promise<void>(resolve => { server.close(() => resolve()); });
102
+ expect(server.address()).toBeNull();
103
+ send('close');
104
+ await Promise.race([secondRequest, new Promise((_, reject) => { deadline = setTimeout(() => reject(new Error('Queued request did not arrive')), 2000); })]);
105
+ release(); await ended; await closed;
106
+ expect(escaped).toEqual([]);
107
+ expect(response.match(/HTTP\/1\.1 200/g)).toHaveLength(2);
108
+ } finally { clearTimeout(deadline); release(); socket.destroy(); server.close(); }
109
+ }));
110
+
111
+ // This checks the complete source archive's contents, including original assets.
112
+ // Disk and ZIP work can exceed Vitest's default 5 s on the Windows test VM.
70
113
  it('serves the frame with an opaque-origin CSP, rejects cross-origin mutations and offers matching source', async () => withStore(async store => {
71
114
  await store.import(archive());
72
115
  const server = createPetServer({ webRoot: resolve('web'), store, prefix: '/test-token/' });
@@ -92,7 +135,7 @@ it('serves the frame with an opaque-origin CSP, rejects cross-origin mutations a
92
135
  expect(source['scripts/build.mjs']).toBeDefined(); expect(source['npm-shrinkwrap.json']).toBeDefined();
93
136
  expect(Object.keys(source).some(p => /node_modules|figures-v2|\.aws/.test(p))).toBe(false);
94
137
  } finally { await new Promise<void>(resolve => server.close(() => resolve())); }
95
- }));
138
+ }), 30_000);
96
139
 
97
140
  it('bounds untrusted hit areas and only accepts touch events following real input', async () => {
98
141
  // @ts-expect-error The upstream browser module is JavaScript.
@@ -0,0 +1,8 @@
1
+ // Reproduce a queued OS display update after the native window is destroyed.
2
+ const { app, screen } = require('electron');
3
+ app.on('browser-window-created', (_event, win) => {
4
+ win.once('closed', () => {
5
+ if (process.connected) process.send({ type: 'late-display-injected' }, () => {});
6
+ screen.emit('display-metrics-changed', {}, screen.getPrimaryDisplay(), ['workArea']);
7
+ });
8
+ });
@@ -0,0 +1,37 @@
1
+ // Loaded only by the controlled native lifecycle probe. No paths, URLs or text.
2
+ const { app, BrowserWindow } = require('electron');
3
+ // Observe Electron's default exception path without handling or suppressing it.
4
+ // Keep only error classifications and source basenames in this empty probe.
5
+ process.on('uncaughtExceptionMonitor', (error, origin) => {
6
+ const frames = String(error?.stack ?? '').split('\n').slice(1, 13).flatMap(line => {
7
+ const match = line.match(/^\s*at\s+(?:(.*?)\s+\()?(.+?):(\d+):(\d+)\)?$/);
8
+ return match ? [{ function: match[1] ?? null, file: match[2].split(/[\\/]/).at(-1).replace(/[?#].*$/, ''), line: Number(match[3]), column: Number(match[4]) }] : [];
9
+ });
10
+ const kind = /object.*destroyed/i.test(error?.message ?? '') ? 'object-destroyed'
11
+ : /channel.*closed|closed.*channel/i.test(error?.message ?? '') ? 'closed-ipc' : 'unclassified';
12
+ const exception = { origin, name: error?.name, code: error?.code, kind, frames };
13
+ try { require('node:fs').writeSync(2, 'Lifecycle exception: ' + JSON.stringify(exception) + '\n'); } catch {}
14
+ });
15
+ function trace(phase) {
16
+ let windows = [], inspectionFailed = false;
17
+ const resources = {};
18
+ try {
19
+ windows = app.isReady() ? BrowserWindow.getAllWindows().map(win => ({
20
+ destroyed: win.isDestroyed(), visible: !win.isDestroyed() && win.isVisible(),
21
+ loading: !win.isDestroyed() && !win.webContents.isDestroyed() && win.webContents.isLoading(),
22
+ })) : [];
23
+ for (const name of process.getActiveResourcesInfo()) resources[name] = (resources[name] ?? 0) + 1;
24
+ } catch { inspectionFailed = true; }
25
+ try { if (process.connected) process.send({ type: 'lifecycle-shutdown-trace', phase, windows, resources, inspectionFailed }, () => {}); } catch {}
26
+ }
27
+ process.prependListener('message', message => {
28
+ if (message?.type !== 'quit') return;
29
+ trace('quit-received');
30
+ setImmediate(() => trace('quit-immediate'));
31
+ setTimeout(() => trace('quit-after-one-second'), 1000).unref();
32
+ });
33
+ app.on('browser-window-created', (_event, win) => {
34
+ win.on('close', () => trace('window-close'));
35
+ win.on('closed', () => trace('window-closed'));
36
+ });
37
+ for (const event of ['before-quit', 'will-quit', 'quit']) app.on(event, () => trace(event));
@@ -3,6 +3,33 @@ import assert from 'node:assert/strict';
3
3
  import { promisify } from 'node:util';
4
4
 
5
5
  const run = promisify(execFile);
6
+
7
+ // Electron supplies physical pixels for Windows input. PowerShell starts DPI
8
+ // unaware: both cursor movement and readback can otherwise be virtualized.
9
+ async function warpWindowsCursor({ x, y }) {
10
+ assert.ok(Number.isFinite(x) && Number.isFinite(y), 'Native cursor requires finite physical coordinates');
11
+ const point = { x: Math.round(x), y: Math.round(y) };
12
+ const script = `
13
+ Add-Type -TypeDefinition @'
14
+ using System;
15
+ using System.Runtime.InteropServices;
16
+ public class PetNativeCursor {
17
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int x; public int y; }
18
+ [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
19
+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
20
+ [DllImport("user32.dll")] public static extern bool GetPhysicalCursorPos(out POINT point);
21
+ }
22
+ '@
23
+ $previous = [PetNativeCursor]::SetThreadDpiAwarenessContext([IntPtr](-4))
24
+ if ($previous -eq [IntPtr]::Zero) { throw 'Cannot set native input DPI awareness' }
25
+ if (-not [PetNativeCursor]::SetCursorPos(${point.x}, ${point.y})) { throw 'Cannot move the native test cursor' }
26
+ $actual = New-Object PetNativeCursor+POINT
27
+ if (-not [PetNativeCursor]::GetPhysicalCursorPos([ref]$actual)) { throw 'Cannot read the physical cursor' }
28
+ if ($actual.x -ne ${point.x} -or $actual.y -ne ${point.y}) { throw 'Native cursor did not reach the requested physical point' }
29
+ `;
30
+ await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')]);
31
+ }
32
+
6
33
  const warpMacCursor = `
7
34
  import ctypes, sys
8
35
  class Point(ctypes.Structure):
@@ -77,9 +104,7 @@ export async function petClick(page, options = {}, twice = false) {
77
104
  }
78
105
  if (process.platform === 'win32') {
79
106
  const { point } = await nativeMeasurement(page, '#pet');
80
- await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
81
- `Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class PetCursor { [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y); }'; if (-not [PetCursor]::SetCursorPos(${point.x}, ${point.y})) { throw 'Cannot move the native test cursor' }`,
82
- ]);
107
+ await warpWindowsCursor(point);
83
108
  }
84
109
  await pet.hover();
85
110
  await page.waitForSelector('#pet[data-native-hit=true]');
@@ -120,8 +145,7 @@ export async function nativeClick(page, selector) {
120
145
  const measurement = await nativeMeasurement(page, selector), p = measurement.point;
121
146
  if (process.platform === 'darwin') await run('python3', ['-c', warpMacCursor, String(p.x), String(p.y)]);
122
147
  else if (process.platform === 'linux') await run('python3', ['-c', warpCursor, String(p.x), String(p.y)]);
123
- else await run('powershell.exe', ['-NoProfile','-NonInteractive','-Command',
124
- `Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class PetPanelCursor { [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y); }'; if (-not [PetPanelCursor]::SetCursorPos(${p.x}, ${p.y})) { throw 'Cannot move the native test cursor' }`]);
148
+ else await warpWindowsCursor(p);
125
149
  // A font/size update can reflow the panel while the OS helper starts. Keep
126
150
  // CDP and the physical cursor on the same measured point rather than mixing
127
151
  // two layout samples; locator trial above waits for actionability/stability.
@@ -140,7 +164,9 @@ export async function parkNativePointer(page) {
140
164
  const origin = await page.evaluate(() => ({ x: screenX + 2, y: screenY + 2 }));
141
165
  if (process.platform === 'darwin') await run('python3', ['-c', warpMacCursor, String(origin.x), String(origin.y)]);
142
166
  else if (process.platform === 'linux' && process.env.DISPLAY) await run('python3', ['-c', warpCursor, String(origin.x), String(origin.y)]);
143
- else if (process.platform === 'win32') await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
144
- `Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class PetParkCursor { [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y); }'; if (-not [PetParkCursor]::SetCursorPos(${Math.round(origin.x)}, ${Math.round(origin.y)})) { throw 'Cannot park native cursor' }`]);
167
+ else if (process.platform === 'win32') {
168
+ const point = await page.evaluate(() => window.dshPetBridge.testScreenPoint({ x: 2, y: 2, width: innerWidth, height: innerHeight }).then(value => value.point));
169
+ await warpWindowsCursor(point);
170
+ }
145
171
  await page.mouse.move(2, 2);
146
172
  }
@@ -0,0 +1,22 @@
1
+ # Run only inside the isolated Windows test user's interactive session.
2
+ # https://learn.microsoft.com/windows/win32/shell/abm-setstate
3
+ $ErrorActionPreference = 'Stop'
4
+ Add-Type -TypeDefinition @'
5
+ using System;
6
+ using System.Runtime.InteropServices;
7
+ public static class DshTaskbarGeometry {
8
+ [StructLayout(LayoutKind.Sequential)] public struct Rect { public int left, top, right, bottom; }
9
+ [StructLayout(LayoutKind.Sequential)] public struct Data {
10
+ public uint size; public IntPtr window; public uint callback, edge; public Rect rect; public IntPtr state;
11
+ }
12
+ [DllImport("shell32.dll")] static extern UIntPtr SHAppBarMessage(uint message, ref Data data);
13
+ public static uint Read() { var data = new Data { size = (uint)Marshal.SizeOf(typeof(Data)) }; return (uint)SHAppBarMessage(4, ref data).ToUInt64(); }
14
+ public static void Set(uint state) { var data = new Data { size = (uint)Marshal.SizeOf(typeof(Data)), state = new IntPtr(state) }; SHAppBarMessage(10, ref data); }
15
+ }
16
+ '@
17
+ $before = [DshTaskbarGeometry]::Read()
18
+ if ($null -ne $requestedState) {
19
+ if ($requestedState -lt 0 -or $requestedState -gt 3) { throw 'Invalid taskbar state' }
20
+ [DshTaskbarGeometry]::Set([uint32]$requestedState)
21
+ }
22
+ @{ before = $before; after = [DshTaskbarGeometry]::Read() } | ConvertTo-Json -Compress
@@ -60,6 +60,7 @@ try {
60
60
  assert.deepEqual(await actions(), [], 'opening a list neither reads replies nor selects a conversation');
61
61
  await page.locator(`[data-result-id="${second.id}"][data-action=open]`).click();
62
62
  assert.deepEqual(await actions(), [{ type: 'read', resultId: second.id }, { type: 'select', sessionId: a.id }], 'a reply row continues its exact source in the composer');
63
+ await receive({ type: 'snapshot', snapshot: { ...frame([waitingA, b, issue], [{ ...second, read: true }, third]), sessionId: a.id } });
63
64
 
64
65
  await page.locator('#chat-close').click();
65
66
  const fourth = reply('multi-c-full', a, 4, '另一份完整回复。');
package/tests/install.mjs CHANGED
@@ -20,7 +20,7 @@ import { crashNative, connectRecovered, waitRecovery } from './helpers/desktop-r
20
20
 
21
21
  const sourceCommit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
22
22
  const version = process.env.DSH_TEST_VERSION ?? '0.2.0-rc.2';
23
- assert.ok(['0.2.0-rc.2', '0.2.1-alpha.1', '0.2.1-rc.1', '0.2.1-rc.2'].includes(version), 'test only advertised DSH versions');
23
+ assert.ok(['0.2.0-rc.2', '0.2.1-alpha.1', '0.2.1-rc.1', '0.2.1-rc.2', '0.2.1-rc.3'].includes(version), 'test only advertised DSH versions');
24
24
  const project = fileURLToPath(new URL('../', import.meta.url));
25
25
  const manifest = JSON.parse(await readFile(join(project, 'package.json'), 'utf8'));
26
26
  const archive = resolve(process.env.DSH_TEST_PACKAGE ?? (process.env.DSH_TEST_PACKAGE_DIR
@@ -107,9 +107,10 @@ async function run(command, args, cwd = project, timeoutMs = 240000) {
107
107
  async function stop(child) {
108
108
  if (!child || child.exitCode !== null || child.signalCode !== null) return;
109
109
  const finished = once(child, 'exit');
110
- // Windows cannot deliver a catchable SIGTERM. The fixture uses the real
111
- // launcher's bounded appExit hook, preserving the clean-exit assertion.
112
- if (child === host && child.connected) child.send({ type: 'shutdown-host' });
110
+ // POSIX uses the launcher's signal shutdown, which exits after disposal.
111
+ // appExit instead waits for natural event-loop quiescence and old hosts can
112
+ // retain handles after disposing. Windows needs the catchable IPC exit hook.
113
+ if (process.platform === 'win32' && child === host && child.connected) child.send({ type: 'shutdown-host' });
113
114
  else child.kill('SIGTERM');
114
115
  const deadline = setTimeout(() => child.kill('SIGKILL'), 10000);
115
116
  try { await finished; } finally { clearTimeout(deadline); }
@@ -133,6 +134,15 @@ try {
133
134
  const bootFile = join(runtime, 'node_modules', '@deepseek-ai', 'dsh-app-boot', 'lib', 'index.js');
134
135
  const { evaluatePluginCompatibility } = await import(pathToFileURL(bootFile).href);
135
136
  assert.equal(evaluatePluginCompatibility(manifest, {}, version), undefined);
137
+ for (const supported of manifest.engines.dsh.split(' || ')) {
138
+ assert.equal(evaluatePluginCompatibility(manifest, {}, supported), undefined, `advertised host ${supported} is accepted`);
139
+ }
140
+ const previousHostRange = structuredClone(manifest);
141
+ previousHostRange.engines.dsh = previousHostRange.engines.dsh.replace(' || 0.2.1-rc.3', '');
142
+ for (const peer of Object.keys(previousHostRange.peerDependencies)) {
143
+ if (peer.startsWith('@deepseek-ai/dsh-')) previousHostRange.peerDependencies[peer] = previousHostRange.peerDependencies[peer].replace(' || 0.2.1-rc.3', '');
144
+ }
145
+ assert.ok(evaluatePluginCompatibility(previousHostRange, {}, '0.2.1-rc.3'), 'the previous host declarations reject rc.3');
136
146
  const previous = structuredClone(manifest);
137
147
  previous.version = '0.1.0';
138
148
  for (const peer of Object.keys(previous.peerDependencies)) {
@@ -140,7 +150,7 @@ try {
140
150
  }
141
151
  if (version === '0.2.0-rc.2') assert.equal(evaluatePluginCompatibility(previous, {}, version)?.exempted, false, 'reproduce the previous release rejection');
142
152
  assert.ok(evaluatePluginCompatibility(manifest, {}, '0.2.0-rc.1'), 'unverified versions remain incompatible');
143
- assert.ok(evaluatePluginCompatibility(manifest, {}, '0.2.1-rc.3'), 'later prereleases require explicit verification');
153
+ assert.ok(evaluatePluginCompatibility(manifest, {}, '0.2.1-rc.4'), 'later prereleases require explicit verification');
144
154
  if (version.startsWith('0.2.1-rc.')) {
145
155
  const restricted = structuredClone(manifest);
146
156
  restricted.engines.dsh = '0.2.0-rc.2';
@@ -1,5 +1,6 @@
1
1
  import assert from 'node:assert/strict';
2
- import { spawn } from 'node:child_process';
2
+ import { spawn, execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
3
4
  import { createRequire } from 'node:module';
4
5
  import { once } from 'node:events';
5
6
  import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises';
@@ -7,25 +8,39 @@ import { tmpdir } from 'node:os';
7
8
  import { join, resolve } from 'node:path';
8
9
  import { listDiagnostics, readDiagnostics } from '../scripts/diagnostics-client.mjs';
9
10
  const require = createRequire(import.meta.url), packageRoot = resolve(process.env.DSH_LIFECYCLE_PACKAGE_ROOT ?? '.');
11
+ const run = promisify(execFile);
10
12
  const real = process.env.DSH_LIFECYCLE_NATIVE_REAL === '1';
11
13
  const expectedRealState = process.env.DSH_LIFECYCLE_EXPECT_STATE ?? 'locked';
12
14
  assert.ok(['locked', 'unlocked'].includes(expectedRealState));
13
- const records = [];
15
+ const records = [], shutdowns = [];
16
+ const traceShutdown = !real && process.env.DSH_LIFECYCLE_TRACE === '1';
17
+ const lateDisplay = !real && process.env.DSH_LIFECYCLE_LATE_DISPLAY === '1';
18
+ const reportPath = real ? 'artifacts/lifecycle-startup-real.json' : lateDisplay ? 'artifacts/lifecycle-startup-late-display.json' : 'artifacts/lifecycle-startup-native.json';
14
19
  for (const initialState of real ? ['system'] : ['locked', 'unknown', 'restore-locked', 'system']) {
20
+ console.log(`Lifecycle startup case: ${initialState}`);
15
21
  const root = await mkdtemp(join(tmpdir(), 'dsh-initial-lock-'));
16
22
  const env = { ...process.env, DSH_PET_TEST_DATA_DIR: join(root, 'pet'), DSH_PET_TEST_DIAGNOSTICS_DIR: join(root, 'registry'), DSH_PET_SCREEN_LOCKED: initialState === 'restore-locked' ? '1' : '0', DSH_PET_SYSTEM_ASLEEP: '0' };
17
23
  delete env.ELECTRON_RUN_AS_NODE;
18
24
  if (real) { delete env.DSH_PET_TEST_NO_SANDBOX; delete env.DSH_PET_TEST_DEBUG_PORT; delete env.DSH_PET_TEST_INITIAL_LOCK_STATE; }
19
25
  else { env.DSH_PET_TEST_NO_SANDBOX = '1'; env.DSH_PET_TEST_DEBUG_PORT = '0'; env.DSH_PET_TEST_INITIAL_LOCK_STATE = initialState === 'restore-locked' ? 'unlocked' : initialState; }
20
- const child = spawn(require('electron'), [...(real ? [] : ['--no-sandbox']), join(packageRoot, 'desktop/main.cjs')], { env, stdio: ['ignore', 'ignore', 'pipe', 'ipc'] });
26
+ const child = spawn(require('electron'), [...(traceShutdown ? ['--require', resolve('tests/fixtures/lifecycle-shutdown-trace.cjs')] : []), ...(lateDisplay ? ['--require', resolve('tests/fixtures/late-display-quit.cjs')] : []), ...(real ? [] : ['--no-sandbox']), join(packageRoot, 'desktop/main.cjs')], { env, stdio: ['ignore', 'ignore', 'pipe', 'ipc'] });
21
27
  const exited = once(child, 'exit'); let stderr = '';
28
+ let nativeReady = false, lateDisplayEvents = 0, originalError, shutdownError;
29
+ const phases = [];
30
+ child.on('message', message => {
31
+ if (message?.type === 'ready') nativeReady = true;
32
+ if (message?.type === 'late-display-injected') lateDisplayEvents++;
33
+ if (message?.type === 'lifecycle-shutdown-trace' && phases.length < 64) phases.push(message);
34
+ });
22
35
  child.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-4000); });
23
36
  try {
24
37
  child.send({ type: 'init', baseline: true, options: { size: 150, companionship: 'quiet', roam: true, diagnostics: true, notifications: false }, snapshot: { mood: 'idle', active: false, sessionId: null, sessions: [], results: [] } });
25
38
  let snapshot;
26
39
  for (let attempt = 0; attempt < 80; attempt++) {
27
40
  const [endpoint] = await listDiagnostics(join(root, 'registry'));
28
- if (endpoint) { snapshot = await readDiagnostics(endpoint); break; }
41
+ // The diagnostic endpoint exists before loadURL finishes. Quitting on
42
+ // that signal alone cancels a slow first navigation and exits with error.
43
+ if (endpoint && nativeReady) { snapshot = await readDiagnostics(endpoint); break; }
29
44
  assert.equal(child.exitCode, null, stderr); await new Promise(r => setTimeout(r, 100));
30
45
  }
31
46
  assert.ok(snapshot, 'Initial diagnostic endpoint must become available');
@@ -51,20 +66,40 @@ for (const initialState of real ? ['system'] : ['locked', 'unknown', 'restore-lo
51
66
  if (!state.lockStateKnown || state.screenLocked) assert.equal(state.suspended, true);
52
67
  }
53
68
  records.push({ platform: process.platform, build: snapshot.build, controlledInitialState: real ? null : initialState, expectedRealState: real ? expectedRealState : null, normalSandbox: real, runtime: state, npc: snapshot.value.renderer?.npc });
54
- } finally {
55
- const deadline = setTimeout(() => child.kill('SIGKILL'), 10000);
69
+ } catch (error) { originalError = error; }
70
+ finally {
71
+ const began = performance.now(); let forced = false, exitedAt, sample, sampleFile, sampleError;
72
+ exited.then(() => { exitedAt = performance.now(); });
73
+ // Capture the owned process before the existing kill guard. A quit event
74
+ // alone cannot identify a native shutdown stall after JavaScript stops.
75
+ const sampling = traceShutdown && process.platform === 'darwin' ? setTimeout(() => {
76
+ sampleFile = `artifacts/lifecycle-shutdown-${initialState}.txt`;
77
+ sample = mkdir('artifacts', { recursive: true }).then(() => run('/usr/bin/sample', [String(child.pid), '1', '1', '-file', resolve(sampleFile)], { timeout: 3000 }))
78
+ .catch(error => { sampleError = String(error.message).slice(0, 600); });
79
+ }, 1500) : undefined;
80
+ const deadline = setTimeout(() => { forced = true; child.kill('SIGKILL'); }, 10000);
56
81
  try {
57
82
  // Windows SIGTERM forcibly terminates the main process before Chromium
58
83
  // releases its profile. Use the desktop's normal IPC quit path instead.
84
+ console.log(`Lifecycle shutdown case: ${initialState}, ready=${nativeReady}`);
59
85
  if (child.connected) child.send({ type: 'quit' }); else child.kill('SIGTERM');
60
86
  const [code, signal] = await exited;
61
87
  assert.equal(signal, null, stderr); assert.equal(code, 0, stderr);
88
+ assert.ok(!stderr.includes('Lifecycle exception: '), stderr);
89
+ if (lateDisplay) assert.ok(lateDisplayEvents > 0, 'The late native display event must actually fire');
90
+ } catch (error) { shutdownError = error;
62
91
  } finally {
63
- clearTimeout(deadline);
92
+ clearTimeout(deadline); clearTimeout(sampling); await sample;
93
+ shutdowns.push({ initialState, nativeReady, lateDisplayEvents, code: child.exitCode, signal: child.signalCode, forced, elapsedMs: Math.round((exitedAt ?? performance.now()) - began), phases,
94
+ ...(sampleFile ? { sampleFile, ...(sampleError ? { sampleError } : {}) } : {}),
95
+ originalError: originalError ? String(originalError) : null, shutdownError: shutdownError ? String(shutdownError) : null });
96
+ await mkdir('artifacts', { recursive: true });
97
+ await writeFile(reportPath, JSON.stringify({ records, shutdowns }, null, 2) + '\n');
64
98
  await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
65
99
  }
66
100
  }
101
+ if (originalError && shutdownError) throw new AggregateError([originalError, shutdownError], 'Native lifecycle assertion and cleanup failed; see ' + reportPath);
102
+ if (originalError) throw originalError;
103
+ if (shutdownError) throw shutdownError;
67
104
  }
68
- await mkdir('artifacts', { recursive: true });
69
- await writeFile(real ? 'artifacts/lifecycle-startup-real.json' : 'artifacts/lifecycle-startup-native.json', JSON.stringify({ records }, null, 2) + '\n');
70
105
  console.log('Native lifecycle startup passed: ' + (real ? 'ordinary sandbox, expected ' + expectedRealState : 'controlled locked/unknown and system adapter observation') + '.');
@@ -23,3 +23,26 @@ test('the real Client factory synchronizes resolved Harness locale without works
23
23
  const disposedCalls=calls.length; focusEvents.dispatchEvent(new Event('focus')); await new Promise(resolve=>setTimeout(resolve,20));
24
24
  assert.equal(calls.length,disposedCalls,'focus subscriptions are removed on disposal');
25
25
  });
26
+
27
+ test('the real Client accepts automatic recovery from status and control replies', async () => {
28
+ let factory, face; const cleanup=[];
29
+ const events=new EventTarget();
30
+ const document={createElement:()=>({dataset:{},remove(){}}),head:{append(){}},visibilityState:'visible',addEventListener:events.addEventListener.bind(events),removeEventListener:events.removeEventListener.bind(events)};
31
+ runInNewContext(readFileSync(new URL('../dist/client.js',import.meta.url),'utf8'),{window:{__ModuleLoader__:{load(value){factory=value.factory;}},addEventListener:events.addEventListener.bind(events),removeEventListener:events.removeEventListener.bind(events)},document,URL,TextEncoder,TextDecoder,AbortController,setTimeout,clearTimeout});
32
+ const client=factory(()=>({}));
33
+ let status={phase:'recovering',generation:2,visibilityRevision:1,visible:false,desiredVisible:true,suspended:false,recoveryAttempt:1,retryAt:Date.now()+1000};
34
+ const methods=[];
35
+ const ctx={effect(fn){const stop=fn();if(stop)cleanup.push(stop);},inject(){},locale:{register:()=>()=>{},resolveText:()=> 'en',subscribe:()=>()=>{}},configForms:{get:()=>({})},slots:{inject(_name,register){register();},register(spec){face=spec.inject();return()=>{};}},connection:{isLoopback:true,rpc:{async call(_path,method){if(method==='coopanion/locale')return{ok:true,value:{}};methods.push(method);return{ok:true,value:status};}}}};
36
+ try {
37
+ client.apply(ctx);
38
+ for(const command of [undefined,'restart']) {
39
+ const reply=await face.call(command);
40
+ assert.equal(reply.phase,'recovering'); assert.equal(reply.recoveryAttempt,1); assert.equal(reply.retryAt,status.retryAt);
41
+ }
42
+ assert.deepEqual(methods,['coopanion/status','coopanion/control']);
43
+ status={...status,phase:'unknown'};
44
+ await assert.rejects(()=>face.call(),/Invalid desktop pet status/);
45
+ status={...status,phase:'recovering',visible:undefined};
46
+ await assert.rejects(()=>face.call(),/Invalid desktop pet status/);
47
+ } finally { for(const stop of cleanup.reverse())stop(); }
48
+ });