okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221host: ending a child that never started no longer signals the caller's own process group on macOScb73b620a

main
11.2 KiB182 linesraw
1import test from 'node:test';
2import assert from 'node:assert/strict';
3import { spawn, execFileSync } from 'node:child_process';
4import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
5import { tmpdir } from 'node:os';
6import { join, resolve, isAbsolute } from 'node:path';
7import { fileURLToPath } from 'node:url';
8import { chooseFolder, cleanChosenPath, typedFolder, windowsFolderScript } from '../server/folder-dialog.mjs';
9
10const HOST_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
11const failure = (code) => Object.assign(new Error(`exit ${code}`), { code });
12const recorder = () => {
13  const seen = [];
14  return { seen, run: (outcome) => async (command, args) => { seen.push({ command, args }); if (outcome instanceof Error) throw outcome; return { stdout: outcome }; } };
15};
16
17test('macOS keeps the osascript chooser and treats any dismissal as a cancel', async () => {
18  const c = recorder();
19  assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run('/Users/me/skills/\n') }), { path: '/Users/me/skills' });
20  assert.equal(c.seen[0].command, 'osascript');
21  assert.equal(c.seen[0].args[1], 'POSIX path of (choose folder with prompt "Pick")');
22  assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run(failure(1)) }), { cancelled: true });
23});
24
25test('Windows uses a PowerShell FolderBrowserDialog passed as an encoded command', async () => {
26  const c = recorder();
27  const result = await chooseFolder("Don't panic", { platform: 'win32', run: c.run('C:\\Users\\me\\Skills\r\n') });
28  assert.deepEqual(result, { path: 'C:\\Users\\me\\Skills' });
29  assert.match(c.seen[0].command, /powershell\.exe$/i);
30  assert.ok(c.seen[0].args.includes('-STA'));
31  const script = Buffer.from(c.seen[0].args.at(-1), 'base64').toString('utf16le');
32  assert.equal(script, windowsFolderScript("Don't panic"));
33  assert.match(script, /FolderBrowserDialog/);
34  assert.match(script, /Description = 'Don''t panic'/);
35  assert.deepEqual(await chooseFolder('Pick', { platform: 'win32', run: c.run('') }), { cancelled: true });
36  const missing = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure('ENOENT')) });
37  assert.equal(missing.unavailable, true);
38  // A window that fails after it was started no longer ends in an error with no way on (AGENT-LOST, item 11): the app asks for the path.
39  const failed = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure(2)) });
40  assert.equal(failed.unavailable, true); assert.match(failed.reason, /Type the folder path/);
41  const nodialog = await chooseFolder('Pick', { platform: 'win32', run: c.run('NODIALOG' + String.fromCharCode(13, 10)) });
42  assert.equal(nodialog.unavailable, true); assert.match(nodialog.reason, /Type the folder path/);
43});
44
45test('the generated PowerShell parses without errors', { skip: process.platform !== 'win32' && 'needs Windows PowerShell to parse the script (Windows only)' }, () => {
46  const shell = join(process.env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
47  const out = execFileSync(shell,
48    ['-NoProfile', '-NonInteractive', '-Command', '$e=$null; [void][System.Management.Automation.Language.Parser]::ParseInput($env:SCRIPT,[ref]$null,[ref]$e); $e.Count'],
49    { encoding: 'utf8', env: { ...process.env, SCRIPT: windowsFolderScript('Choose a folder for Strata') }, windowsHide: true }).trim();
50  assert.equal(out, '0');
51});
52
53test('Linux tries zenity, falls back to kdialog, then reports that none exists', async () => {
54  const order = [];
55  const run = async (command) => { order.push(command); if (command === 'zenity') throw failure('ENOENT'); return { stdout: '/home/me/skills/\n' }; };
56  assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', portal: async () => null, run }), { path: '/home/me/skills' });
57  assert.deepEqual(order, ['zenity', 'kdialog']);
58  const none = await chooseFolder('Pick', { platform: 'linux', portal: async () => null, run: async () => { throw failure('ENOENT'); } });   // no real gdbus monitor
59  assert.equal(none.unavailable, true);
60  assert.match(none.reason, /zenity or kdialog/);
61  assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', portal: async () => null, run: async () => { throw failure(1); } }), { cancelled: true });
62  assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', portal: async () => null, run: async () => ({ stdout: '' }) }), { cancelled: true });
63});
64
65test('chosen paths lose trailing separators but roots survive', () => {
66  assert.equal(cleanChosenPath('/a/b/\n'), '/a/b');
67  assert.equal(cleanChosenPath('/'), '/');
68  assert.equal(cleanChosenPath('C:\\Users\\me\\'), 'C:\\Users\\me');
69  assert.equal(cleanChosenPath('C:\\'), 'C:\\');
70});
71
72test('a typed path must be an absolute existing directory', async () => {
73  const dir = await mkdtemp(join(tmpdir(), 'strata-typed-'));
74  try {
75    await writeFile(join(dir, 'file.txt'), 'x');
76    assert.equal(await typedFolder(dir, { isAbsolute }), dir);
77    assert.equal(await typedFolder(undefined, { isAbsolute }), null);
78    await assert.rejects(typedFolder('relative/dir', { isAbsolute }), /full path/);
79    await assert.rejects(typedFolder(join(dir, 'missing'), { isAbsolute }), /does not exist/);
80    await assert.rejects(typedFolder(join(dir, 'file.txt'), { isAbsolute }), /not a file/);
81  } finally { await rm(dir, { recursive: true, force: true }); }
82});
83
84test('the model page takes a folder or one .gguf file, with or without quotes around the path', async () => {
85  const dir = await mkdtemp(join(tmpdir(), 'strata-gguf-typed-'));
86  try {
87    await writeFile(join(dir, 'model-00001-of-00002.gguf'), 'x');
88    await writeFile(join(dir, 'notes.txt'), 'x');
89    const only = { isAbsolute, fileType: /\.gguf$/i };
90    assert.equal(await typedFolder(dir, only), dir);
91    assert.equal(await typedFolder(join(dir, 'model-00001-of-00002.gguf'), only), join(dir, 'model-00001-of-00002.gguf'));
92    assert.equal(await typedFolder(`"${join(dir, 'model-00001-of-00002.gguf')}"`, only), join(dir, 'model-00001-of-00002.gguf'));
93    assert.equal(await typedFolder(`  "${dir}"  `, only), dir);
94    await assert.rejects(typedFolder(join(dir, 'notes.txt'), only), /folder, or a \.gguf file/);
95    await assert.rejects(typedFolder(join(dir, 'missing.gguf'), only), /does not exist/);
96    // the other pickers still refuse a file
97    await assert.rejects(typedFolder(join(dir, 'model-00001-of-00002.gguf'), { isAbsolute }), /not a file/);
98  } finally { await rm(dir, { recursive: true, force: true }); }
99});
100
101async function startHost() {
102  const home = await mkdtemp(join(tmpdir(), 'strata-folder-home-'));
103  const net = await import('node:net');
104  const probe = net.createServer();
105  await new Promise(r => probe.listen(0, '127.0.0.1', r));
106  const { port } = probe.address();
107  await new Promise(r => probe.close(r));
108  const child = spawn(process.execPath, [join(HOST_ROOT, 'server', 'index.mjs'), '--dist', join(HOST_ROOT, 'dist')], {
109    cwd: HOST_ROOT, env: { ...process.env, STRATA_HOME: home, STRATA_WORKSPACE: home, STRATA_PORT: String(port), STRATA_REAL_ENGINE: '0' }, stdio: 'ignore',
110  });
111  const base = `http://127.0.0.1:${port}`;
112  for (let i = 0; i < 150; i++) {
113    try { if ((await fetch(`${base}/api/health`)).ok) return { child, base, home }; } catch { /* not up yet */ }
114    await new Promise(r => setTimeout(r, 100));
115  }
116  child.kill();
117  throw new Error('the host did not become healthy');
118}
119
120test('the host accepts a typed folder path for the picker and for adding a skill, on every OS', { timeout: 60000 }, async () => {
121  const { child, base, home } = await startHost();
122  const skill = await mkdtemp(join(tmpdir(), 'strata-skill-'));
123  try {
124    const post = (path, body) => fetch(`${base}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
125    let r = await post('/api/workspaces/pick', { path: skill });
126    assert.deepEqual(await r.json(), { path: skill });
127    r = await post('/api/workspaces/pick', { path: join(skill, 'nope') });
128    assert.equal(r.status, 400);
129    assert.match((await r.json()).error, /does not exist/);
130    r = await post('/api/skills/add', { path: skill });
131    assert.equal(r.status, 400);
132    assert.match((await r.json()).error, /no SKILL\.md/);
133    await writeFile(join(skill, 'SKILL.md'), '---\nname: Typed\n---\nbody\n');
134    r = await post('/api/skills/add', { path: skill });
135    assert.equal(r.status, 200);
136    assert.ok((await r.json()).added);
137  } finally {
138    child.kill();
139    await rm(skill, { recursive: true, force: true });
140    await rm(home, { recursive: true, force: true }).catch(() => {});
141  }
142});
143
144// QA report F06: a Windows folder window that never opens must not leave the button disabled forever.
145import { EventEmitter } from 'node:events';
146import { watchedWindowsDialog } from '../server/folder-dialog.mjs';
147function fakeShell() {
148  const child = new EventEmitter(); child.stdout = new EventEmitter(); child.killed = false; child.kill = () => { child.killed = true; };
149  return { child, spawnProcess: () => child };
150}
151test('Windows: no READY from the dialog script means the host gives up and the app asks for the path', async () => {
152  const f = fakeShell();
153  const result = await watchedWindowsDialog('powershell.exe', [], { readyMs: 30, spawnProcess: f.spawnProcess });
154  assert.deepEqual(result, { noDialog: true }); assert.equal(f.child.killed, true, 'the stuck PowerShell is ended');
155  const answer = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => ({ noDialog: true }) });
156  assert.equal(answer.unavailable, true); assert.match(answer.reason, /Type the folder path/);
157});
158test('Windows: once READY has come the person may take their time, and the answer is read without the READY line', async () => {
159  const f = fakeShell();
160  const pending = watchedWindowsDialog('powershell.exe', [], { readyMs: 30, spawnProcess: f.spawnProcess });
161  f.child.stdout.emit('data', 'READY\r\n');
162  await new Promise(r => setTimeout(r, 80));   // longer than readyMs: still waiting, not given up
163  assert.equal(f.child.killed, false);
164  f.child.stdout.emit('data', 'C:\Users\me\Skills'); f.child.emit('close', 0);
165  const done = await pending;
166  const answer = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => done });
167  assert.deepEqual(answer, { path: 'C:\Users\me\Skills' });
168  const cancelled = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => ({ stdout: 'READY\r\n' }) });
169  assert.deepEqual(cancelled, { cancelled: true });
170});
171test('Windows: a PowerShell that is missing or fails is reported as before', async () => {
172  const f = fakeShell();
173  const missing = watchedWindowsDialog('powershell.exe', [], { spawnProcess: f.spawnProcess });
174  f.child.emit('error', Object.assign(new Error('x'), { code: 'ENOENT' }));
175  await assert.rejects(missing, e => e.code === 'ENOENT');
176  const g = fakeShell(); const failed = watchedWindowsDialog('powershell.exe', [], { spawnProcess: g.spawnProcess });
177  g.child.emit('close', 1);
178  // Ended by security software before any window opened (#3831): the app asks for the path instead of an error.
179  assert.deepEqual(await failed, { noDialog: true });
180  const h = fakeShell(); const late = watchedWindowsDialog('powershell.exe', [], { spawnProcess: h.spawnProcess });
181  h.child.stdout.emit('data', 'READY\n'); h.child.emit('close', 1); await assert.rejects(late, e => e.code === 1);
182});