okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
30.8 KiB453 linesraw
1import './helpers/isolate-profile.mjs';   // a test run never writes the owner's real Strata profile
2import test from 'node:test';
3import assert from 'node:assert/strict';
4import { EventEmitter } from 'node:events';
5import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync, existsSync } from 'node:fs';
6import { join, basename } from 'node:path';
7import { tmpdir } from 'node:os';
8import { bundledPython, controlEnvironment, createControl, findControl, runCli, updatedControlDirectory } from '../server/control-runtime.mjs';
9import { checkComponentUpdates, engineFirstRun } from '../server/updates.mjs';
10import { createAppUpdater } from '../server/app-updater.mjs';
11import { createNativeControl } from '../server/native-control.mjs';
12
13const isWin = process.platform === 'win32';
14
15function controlDir(parent, name, version) {
16  const dir = join(parent, name);
17  mkdirSync(join(dir, 'python', ...(isWin ? [] : ['bin'])), { recursive: true });
18  mkdirSync(join(dir, 'strata_control'), { recursive: true });
19  writeFileSync(bundledPython(dir), 'x');
20  writeFileSync(join(dir, 'strata.py'), '# cli');
21  if (version) writeFileSync(join(dir, 'BUNDLE.json'), JSON.stringify({ version }));
22  return dir;
23}
24
25test('only the update step may acquire: Control keeps STRATA_NO_ACQUIRE unless `acquire` is asked for', () => {
26  const control = { dir: '/c', python: '/c/python/python3', cli: '/c/strata.py' };
27  assert.equal(controlEnvironment(control, { env: {}, components: '/k' }).STRATA_NO_ACQUIRE, '1');
28  const env = controlEnvironment(control, { env: { STRATA_NO_ACQUIRE: '1' }, components: '/k', acquire: true });
29  assert.equal('STRATA_NO_ACQUIRE' in env, false);
30  assert.equal(env.STRATA_COMPONENTS_DIR, '/k');
31  assert.equal(env.PYTHONNOUSERSITE, '1');
32});
33
34test('an updated Control wins only when it is newer than the bundled one, and only when whole', () => {
35  const root = mkdtempSync(join(tmpdir(), 'strata-update-control-'));
36  try {
37    const install = join(root, 'install');
38    mkdirSync(join(install, 'host'), { recursive: true });
39    const bundled = controlDir(install, 'control', '0.1.45');
40    const components = join(root, 'components');
41    const updated = controlDir(join(components, 'control'), '0.1.46', '0.1.46');
42    writeFileSync(join(components, 'control', 'active.json'), JSON.stringify({ version: '0.1.46', folder: '0.1.46' }));
43    const find = (extra = {}) => findControl({ env: {}, hostDir: join(install, 'host'), components, ...extra });
44    assert.equal(find().dir, updated, 'the updated 0.1.46 beats the bundled 0.1.45');
45    writeFileSync(join(bundled, 'BUNDLE.json'), JSON.stringify({ version: '0.1.47' }));
46    assert.equal(find().dir, bundled, 'an app update that ships a newer Control is not held back by an older updated one');
47    writeFileSync(join(bundled, 'BUNDLE.json'), JSON.stringify({ version: '0.1.46' }));
48    assert.equal(find().dir, bundled, 'a tie keeps the bundled one');
49    rmSync(join(updated, 'strata.py'));
50    writeFileSync(join(bundled, 'BUNDLE.json'), JSON.stringify({ version: '0.1.45' }));
51    assert.equal(find().dir, bundled, 'a half-installed updated Control is not used');
52    writeFileSync(join(components, 'control', 'active.json'), JSON.stringify({ version: '0.1.46', folder: '../../etc' }));
53    assert.equal(updatedControlDirectory({ env: {}, components }), null, 'a pointer cannot leave the control folder');
54  } finally { rmSync(root, { recursive: true, force: true }); }
55});
56
57function fakeSpawn(lines, code = 0, seen = []) {
58  return (command, args, options) => {
59    seen.push({ command, args, options });
60    const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.kill = () => { child.killed = true; };
61    queueMicrotask(() => {
62      // split a line in two chunks: the reader must wait for the newline
63      const text = lines.map(l => JSON.stringify(l)).join('\n') + '\n';
64      child.stdout.emit('data', text.slice(0, 20)); child.stdout.emit('data', text.slice(20));
65      child.emit('close', code);
66    });
67    return child;
68  };
69}
70
71test('runCli streams JSON lines as events and returns the last record; `acquire` reaches the environment', async () => {
72  const seen = [];
73  const events = [];
74  const control = { dir: '/c', python: '/c/python/python3', cli: '/c/strata.py' };
75  const spawnProcess = fakeSpawn([{ event: 'phase', phase: 'feed', message: 'Reading' }, { event: 'progress', percent: 50, label: 'engine 0.1.46' }, { ok: true, results: [] }], 0, seen);
76  const result = await runCli(control, ['update', '--output', 'jsonl'], { spawnProcess, env: { STRATA_NO_ACQUIRE: '1' }, acquire: true, onLine: e => events.push(e) });
77  assert.equal(events.length, 3);
78  assert.equal(events[1].percent, 50);
79  assert.deepEqual(result.json, { ok: true, results: [] });
80  assert.equal('STRATA_NO_ACQUIRE' in seen[0].options.env, false);
81  await runCli(control, ['models', 'list'], { spawnProcess: fakeSpawn([{ ok: true }], 0, seen), env: {} });
82  assert.equal(seen[1].options.env.STRATA_NO_ACQUIRE, '1', 'everything else keeps the switch on');
83});
84
85test('createControl: the update calls ask the explicit commands; a failed step carries its message and exit code', async () => {
86  const seen = [];
87  const reply = { ok: true, results: [{ component: 'engine', status: 'updated' }] };
88  const control = createControl({
89    control: { dir: '/c', python: '/p', cli: '/c/strata.py' }, env: { STRATA_UPDATE_FEED: 'http://127.0.0.1:1/strata-feed.json', STRATA_APP_VERSION: '0.1.0' },
90    run: async (args, options) => { seen.push([args.join(' '), !!options.acquire]); return { code: 0, json: args.includes('--check') ? { ok: true, engine: {} } : args[0] === 'components' ? { ok: true, to: '0.1.45' } : reply, text: '', stderr: '' }; },
91  });
92  await control.updateCheck();
93  await control.update({ engine: true, control: false });
94  await control.rollbackEngine();
95  assert.deepEqual(seen, [
96    ['update --check --output json --feed http://127.0.0.1:1/strata-feed.json --app-version 0.1.0', true],
97    ['update --output jsonl --feed http://127.0.0.1:1/strata-feed.json --no-control --app-version 0.1.0', true],
98    ['components rollback --output json', false],
99  ], 'only the check and the update acquire; the rollback downloads nothing');
100  const failing = createControl({
101    control: { dir: '/c', python: '/p', cli: '/c/strata.py' }, env: {},
102    run: async () => ({ code: 7, json: { ok: false, results: [{ component: 'engine', status: 'failed', error: 'app-1 is serving.', exit_code: 7 }] }, text: '', stderr: '' }),
103  });
104  await assert.rejects(failing.update({}), err => err.code === 'engine_serving' && /serving/.test(err.message) && err.exitCode === 7);
105});
106
107test('the Settings check says so, in plain words, when the own update check of the app fails, and keeps the raw text for Details', async () => {
108  const feed = (control = { installed: '0.2.5', offered: '0.2.5', status: 'current' }) => ({ version: '0.2.5', async updateCheck() { return { ok: true, feed: { sequence: 3 }, engine: { installed: { version: '0.1.50' }, offered: { version: '0.1.50' }, status: 'current' }, control, app: { status: 'not-in-feed' } }; } });
109  const failing = { check: async () => { throw new Error('error decoding response body for url (http://127.0.0.1:19090/latest.json)'); } };
110  const nothing = await checkComponentUpdates({ control: feed(), appUpdater: failing, appVersion: '0.2.5' });
111  assert.equal(nothing.strata.status, 'error', 'it no longer says "up to date" when the app could not be checked');
112  assert.match(nothing.strata.message, /couldn't check for a new version of the app itself/);
113  assert.doesNotMatch(nothing.strata.message, /decoding|http|latest\.json/, 'no raw text in the main line');
114  assert.match(nothing.strata.details, /error decoding response body/);
115  const withControl = await checkComponentUpdates({ control: feed({ installed: '0.2.5', offered: '0.2.6', status: 'available' }), appUpdater: failing, appVersion: '0.2.5' });
116  assert.equal(withControl.strata.status, 'available');
117  assert.match(withControl.strata.message, /new version of Strata is available.*couldn't check for a new version of the app itself/s);
118  assert.match(withControl.strata.details, /decoding/);
119  const fine = await checkComponentUpdates({ control: feed(), appUpdater: { check: async () => ({ available: false }) }, appVersion: '0.2.5' });
120  assert.equal(fine.strata.status, 'current');
121  assert.equal(fine.strata.details, undefined);
122});
123
124test('the Settings update check maps the feed to the existing result shape', async () => {
125  const report = overrides => ({ ok: true, feed: { sequence: 3 }, engine: { installed: { version: '0.1.45' }, offered: { version: '0.1.46' }, status: 'available', download_bytes: 505_000_000 }, control: { installed: '0.1.45', offered: '0.1.45', status: 'current' }, app: { status: 'not-in-feed' }, ...overrides });
126  const make = value => ({ version: '0.1.45', async updateCheck() { if (value instanceof Error) throw value; return value; } });
127  let result = await checkComponentUpdates({ control: make(report()), appVersion: '0.1.0' });
128  assert.equal(result.engine.status, 'available');
129  assert.equal(result.engine.latestVersion, '0.1.46');
130  assert.match(result.engine.message, /new engine is available \(505 MB\)/);
131  assert.doesNotMatch(result.engine.message, /0\.1\.4|sha|exit/i);
132  assert.equal(result.engine.canInstall, true);
133  assert.equal(result.strata.status, 'current');
134  result = await checkComponentUpdates({ control: make(report({ engine: { installed: null, offered: { version: '0.1.46' }, status: 'install', download_bytes: 505_000_000 } })) });
135  assert.equal(result.engine.status, 'available');
136  assert.match(result.engine.message, /needs an engine to run models\. Press Update engine/);
137  result = await checkComponentUpdates({ control: make(report({ engine: { installed: { version: '0.1.46' }, offered: { version: '0.1.46' }, status: 'current' } })) });
138  assert.equal(result.engine.status, 'current');
139  result = await checkComponentUpdates({ control: make(report({ engine: { installed: null, offered: null, status: 'none-for-this-pc', reasons: ['0.1.46 is for linux-x86_64, this PC is windows-x86_64'] } })) });
140  assert.equal(result.engine.status, 'unavailable');
141  assert.doesNotMatch(result.engine.message, /windows-x86_64/);
142  assert.match(result.engine.details, /windows-x86_64/, 'the technical reason is kept for the Details disclosure');
143  result = await checkComponentUpdates({ control: make(report({ engine: { installed: { version: '0.1.46', backend: 'hip' }, offered: null, status: 'wrong-make', note: 'The engine installed here is for AMD cards, but this update would give your PC NVIDIA one. Nothing was changed.', reasons: ['x'] } })) });
144  assert.equal(result.engine.status, 'unavailable');
145  assert.equal(result.engine.canInstall, false);
146  assert.match(result.engine.message, /Nothing was changed/, 'the app says why in plain words, not that no engine exists for the card');
147  assert.doesNotMatch(result.engine.message, /isn't an engine for this PC/);
148  result = await checkComponentUpdates({ control: make(new Error('this build trusts no update key')) });
149  assert.equal(result.strata.status, 'error');
150  assert.equal(result.engine.status, 'error');
151  assert.doesNotMatch(result.engine.message, /update key/);
152  assert.match(result.engine.details, /no update key/);
153  assert.match(result.engine.message, /aren't available in this version/);
154  // the app's verdict comes from the shell's updater when the bridge exists
155  const appUpdater = { check: async () => ({ available: true, version: '0.2.0', notes: 'Faster starts.' }) };
156  result = await checkComponentUpdates({ control: make(report()), appUpdater, appVersion: '0.1.0' });
157  assert.equal(result.strata.status, 'available');
158  assert.equal(result.strata.latestVersion, '0.2.0');
159  assert.match(result.strata.message, /new version of Strata is available\. Faster starts/);
160});
161
162test('the shell bridge client exists only inside the desktop app, speaks to loopback with the token, and polls to the end', async () => {
163  assert.equal(createAppUpdater({ env: {} }), null);
164  assert.equal(createAppUpdater({ env: { STRATA_SHELL_BRIDGE: 'http://example.com:80', STRATA_SHELL_TOKEN: 'x' } }), null, 'not a loopback address');
165  const calls = [];
166  const states = [{ state: 'downloading', downloaded: 10, total: 100 }, { state: 'downloading', downloaded: 100, total: 100 }, { state: 'done' }];
167  const fetcher = async (url, init) => {
168    calls.push([init.method, url.replace(/:\d+/, ':P'), init.headers.authorization]);
169    if (url.endsWith('/app-update/status')) return Response.json(states.shift());
170    return Response.json(url.endsWith('/check') ? { available: true, version: '0.2.0' } : { state: 'downloading' });
171  };
172  const updater = createAppUpdater({ env: { STRATA_SHELL_BRIDGE: 'http://127.0.0.1:4000', STRATA_SHELL_TOKEN: 'tok' }, fetcher, sleep: async () => {} });
173  assert.equal((await updater.check()).version, '0.2.0');
174  const progress = [];
175  await updater.install({ onProgress: p => progress.push(p.downloaded ?? null) });
176  assert.deepEqual(progress, [10, 100, null]);
177  assert.ok(calls.every(c => c[2] === 'Bearer tok'));
178  assert.deepEqual(calls.map(c => c[0] + ' ' + c[1].split('/').pop()), ['GET check', 'POST install', 'GET status', 'GET status', 'GET status']);
179  const failing = createAppUpdater({ env: { STRATA_SHELL_BRIDGE: 'http://127.0.0.1:4000', STRATA_SHELL_TOKEN: 'tok' }, sleep: async () => {},
180    fetcher: async url => Response.json(url.endsWith('/status') ? { state: 'error', error: 'signature mismatch' } : {}) });
181  await assert.rejects(failing.install(), /signature mismatch/);
182});
183
184// ---------------------------------------------------------------------------------- the Settings buttons in the packaged app
185
186function fixture({ withApp = false, update, appInstall } = {}) {
187  const root = mkdtempSync(join(tmpdir(), 'strata-update-ops-'));
188  const install = join(root, 'install'), data = join(root, 'data');
189  mkdirSync(install, { recursive: true });
190  process.env.STRATA_INSTALL_DIR = install;      // the app's own install folder: the host always names it to Control
191  const config = join(install, 'strata-iq2_xs.json');
192  writeFileSync(config, JSON.stringify({ exe: 'component:strata-engine', tokenizer: join(install, 'tok'), args: ['--max-context', '32768'], model_name: 'Qwen', port: 8080 }));
193  const calls = [];
194  let previous = null;
195  const control = {
196    control: { dir: join(root, 'control') }, version: '0.1.45',
197    async installedModels() { return { install_dir: install, models: [{ id: 'iq2_xs', name: 'Qwen', source_config: config, component_status: 'present', context_tokens: 32768, backend: 'cuda' }] }; },
198    async engine() { return { usable: true, backend: 'cuda', components_dir: 'E:\\c', previous, engine: { version: '0.1.45', platform: 'windows-x86_64', backend: 'cuda', exe: 'e', root: 'r' } }; },
199    async saveProfile() { return {}; }, async start() { return { ok: true, state: 'ready' }; }, async stop() { return { ok: true }; },
200    async update(options) {
201      calls.push(['update', options.engine, options.control]);
202      options.onEvent?.({ event: 'phase', phase: 'download', message: 'Downloading engine 0.1.46 (505 MiB)' });
203      options.onEvent?.({ event: 'progress', phase: 'download', label: 'engine 0.1.46', percent: 42, done: 1, total: 2 });
204      await update?.(options);
205      previous = '0.1.45-windows-x86_64-cuda';
206      return { ok: true, results: [{ component: 'engine', status: 'updated', installed_after: { version: '0.1.46' } }] };
207    },
208    async installEngineFile(path, options) { calls.push(['install-file', path]); options.onEvent?.({ event: 'phase', phase: 'verify', message: 'Checking' }); return { ok: true, results: [{ component: 'engine', status: 'updated', installed_after: { version: '0.1.46' } }] }; },
209    async rollbackEngine() { calls.push(['rollback']); previous = null; return { ok: true, to: '0.1.45' }; },
210  };
211  const spawned = [];
212  const appUpdater = withApp ? {
213    check: async () => ({ available: true, version: '0.2.0' }),
214    install: appInstall ?? (async ({ onProgress }) => { calls.push(['app-install']); onProgress({ downloaded: 50, total: 100 }); return { state: 'done' }; }),
215  } : null;
216  const native = createNativeControl({ control, appUpdater, directory: data, spawnProcess: (...args) => { if (!args[1]?.some(a => String(a).endsWith('strata_mcp.py'))) spawned.push(args); throw new Error('no process but the installer tool (Control strata_mcp.py, absent in this fixture) may be started by the host in packaged mode'); }, fetcher: async () => Response.json({}), requests: () => [] });
217  return { native, calls, spawned, data, control, cleanup: () => rmSync(root, { recursive: true, force: true }) };
218}
219const finish = async (native, id) => { for (let i = 0; i < 400; i++) { const job = native.state().jobs.find(j => j.id === id); if (job.state !== 'running') return job; await new Promise(r => setTimeout(r, 10)); } throw new Error('job did not finish'); };
220
221test('packaged: "Update engine" runs the explicit component update, shows its progress, and then offers the rollback', async () => {
222  const f = fixture();
223  try {
224    await f.native.refresh(true);
225    assert.equal(f.native.state().capabilities.componentUpdates, true);
226    assert.equal(f.native.state().capabilities.rollback, false, 'nothing to roll back before the first update');
227    const started = f.native.operation('update-engine', {});
228    await new Promise(r => setTimeout(r, 5));
229    const job = await finish(f.native, started.id);
230    assert.equal(job.state, 'done', job.error);
231    assert.match(job.summary, /engine is updated and ready/);
232    assert.deepEqual(f.calls[0], ['update', true, false], 'the engine only: Control and the app are not touched by "Update engine"');
233    assert.equal(f.spawned.length, 0);
234    await f.native.refresh(true);
235    assert.equal(f.native.state().capabilities.rollback, true, 'the previous engine the update kept is offered for rollback');
236    const back = await finish(f.native, f.native.operation('rollback', {}).id);
237    assert.equal(back.state, 'done', back.error);
238    assert.match(back.summary, /previous engine is back/);
239  } finally { await f.native.close(); f.cleanup(); }
240});
241
242test('packaged: progress events become the existing job summary and download bar', async () => {
243  const seen = [];
244  const f = fixture({ update: async () => { await new Promise(r => setTimeout(r, 30)); } });
245  try {
246    await f.native.refresh(true);
247    const started = f.native.operation('update-engine', {});
248    for (let i = 0; i < 100; i++) {
249      const job = f.native.state().jobs.find(j => j.id === started.id);
250      if (job.result?.install?.download) { seen.push(job.result.install.download, job.summary); break; }
251      await new Promise(r => setTimeout(r, 5));
252    }
253    await finish(f.native, started.id);
254    assert.deepEqual(seen[0], { file: 'engine 0.1.46', percent: 42 });
255    assert.equal(seen[1], 'Downloading: 42%');
256  } finally { await f.native.close(); f.cleanup(); }
257});
258
259test('packaged: no update while a model is loaded; calibration is still refused', async () => {
260  const f = fixture();
261  try {
262    await f.native.refresh(true);
263    const load = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
264    assert.equal(load.state, 'done', load.error);
265    const job = await finish(f.native, f.native.operation('update-engine', {}).id);
266    assert.equal(job.state, 'error');
267    assert.match(job.error, /Unload native models/);
268    assert.equal(f.calls.filter(c => c[0] === 'update').length, 0);
269    const calibrate = await finish(f.native, f.native.operation('calibrate', { model: 'iq2_xs' }).id);
270    assert.match(calibrate.error, /Terminal|calibrates NVIDIA/);
271  } finally { await f.native.close(); f.cleanup(); }
272});
273
274test('packaged: "Update Strata" updates Control through the feed, then the app through the shell', async () => {
275  const f = fixture({ withApp: true });
276  try {
277    await f.native.refresh(true);
278    const job = await finish(f.native, f.native.operation('update-strata', {}).id);
279    assert.equal(job.state, 'done', job.error);
280    assert.deepEqual(f.calls.map(c => c[0]), ['update', 'app-install']);
281    assert.deepEqual(f.calls[0], ['update', false, true]);
282    assert.match(job.summary, /app update is installed\. Strata will restart/);
283  } finally { await f.native.close(); f.cleanup(); }
284});
285
286test('packaged: an app update that ends the app is recorded as finished by the new version, not as an interrupted operation', async () => {
287  const before = process.env.STRATA_APP_VERSION;
288  process.env.STRATA_APP_VERSION = '0.2.2';
289  const f = fixture({ withApp: true, appInstall: () => new Promise(() => {}) });      // the installer ends the app: install() never returns
290  try {
291    await f.native.refresh(true);
292    const started = f.native.operation('update-strata', {});
293    await new Promise(r => setTimeout(r, 60));
294    assert.equal(f.native.state().jobs.find(j => j.id === started.id).state, 'running');
295    const saved = JSON.parse(readFileSync(join(f.data, 'native-jobs.json'), 'utf8')).find(j => j.id === started.id);
296    assert.equal(saved.appUpdateFrom, '0.2.2', 'the job was saved with the version it started from before the app was ended');
297    // the app is gone; the installer starts the new one (0.2.3) on the same data
298    process.env.STRATA_APP_VERSION = '0.2.3';
299    const again = createNativeControl({ control: f.control, directory: f.data, spawnProcess: () => { throw new Error('no process'); }, fetcher: async () => Response.json({}), requests: () => [] });
300    const job = again.state().jobs.find(j => j.id === started.id);
301    assert.equal(job.state, 'done');
302    assert.equal(job.error, null);
303    assert.match(job.summary, /updated to 0\.2\.3/);
304    await again.close();
305    // the same record read by an app that did NOT change version stays an interruption
306    process.env.STRATA_APP_VERSION = '0.2.2';
307    const same = createNativeControl({ control: f.control, directory: f.data, spawnProcess: () => { throw new Error('no process'); }, fetcher: async () => Response.json({}), requests: () => [] });
308    const unfinished = same.state().jobs.find(j => j.id === started.id);
309    assert.equal(unfinished.state, 'error');
310    assert.match(unfinished.error, /update to 0\.2\.[0-9] did not finish.*releases/s, 'the app came back as the old version: the installer did not finish, and the alert says so');
311    await same.close();
312  } finally { if (before === undefined) delete process.env.STRATA_APP_VERSION; else process.env.STRATA_APP_VERSION = before; await f.native.close(); f.cleanup(); }
313});
314
315test('packaged: an update job an OLDER host left running is finished when the app program file is newer than the job', async () => {
316  // <install>/strata-desktop(.exe) as seen from <install>/host; native-control.mjs looks for the name of the platform it runs on
317  const exe = new URL(process.platform === 'win32' ? '../../strata-desktop.exe' : '../../strata-desktop', import.meta.url);
318  const f = fixture({ withApp: true });
319  try {
320    const { fileURLToPath } = await import('node:url');
321    const old = { id: 'old-1', kind: 'update-strata', state: 'running', startedAt: new Date(Date.now() - 60_000).toISOString(), summary: 'Starting…', result: null, error: null };
322    writeFileSync(join(f.data, 'native-jobs.json'), JSON.stringify([old]));
323    const mk = () => createNativeControl({ control: f.control, directory: f.data, spawnProcess: () => { throw new Error('no process'); }, fetcher: async () => Response.json({}), requests: () => [] });
324    const before = mk();
325    assert.equal(before.state().jobs[0].state, 'error', 'no new program file: still an interruption');
326    await before.close();
327    writeFileSync(join(f.data, 'native-jobs.json'), JSON.stringify([old]));
328    writeFileSync(fileURLToPath(exe), 'new program');
329    try {
330      const after = mk();
331      assert.equal(after.state().jobs[0].state, 'done');
332      assert.match(after.state().jobs[0].summary, /updated/i);
333      await after.close();
334    } finally { rmSync(fileURLToPath(exe), { force: true }); }
335  } finally { await f.native.close(); f.cleanup(); }
336});
337
338test('packaged: "Update engine" works in the first seconds, before the native snapshot has connected', async () => {
339  const f = fixture();
340  try {
341    assert.equal(f.native.state().available, false, 'nothing has been read yet');
342    const started = f.native.operation('update-engine', {});      // used to throw "Connect the native Strata installation first."
343    const job = await finish(f.native, started.id);
344    assert.equal(job.state, 'done', job.error);
345  } finally { await f.native.close(); f.cleanup(); }
346});
347
348test('packaged: a chosen engine file goes to Control; only a file in the own incoming folder is deleted afterwards', async () => {
349  const f = fixture();
350  try {
351    const incoming = join(f.data, 'incoming-engine');
352    mkdirSync(incoming, { recursive: true });
353    const mine = join(incoming, 'strata-engine-x.tar.gz'), theirs = join(f.data, 'keep-me.tar.gz');
354    writeFileSync(mine, 'x'); writeFileSync(theirs, 'y');
355    const job = await finish(f.native, f.native.operation('install-engine-file', { path: mine }).id);
356    assert.equal(job.state, 'done', job.error);
357    assert.deepEqual(f.calls.at(-1), ['install-file', mine]);
358    assert.equal(existsSync(mine), false, 'the copy the page uploaded is removed');
359    const other = await finish(f.native, f.native.operation('install-engine-file', { path: theirs }).id);
360    assert.equal(other.state, 'done', other.error);
361    assert.equal(existsSync(theirs), true, 'a file anywhere else is never deleted');
362    const none = await finish(f.native, f.native.operation('install-engine-file', {}).id);
363    assert.equal(none.state, 'error');
364    assert.equal(f.calls.filter(c => c[0] === 'install-file').length, 2, 'no file, no install');
365  } finally { await f.native.close(); f.cleanup(); }
366});
367
368test('first-run card data: an offer with its size, nothing-fits with reasons, offline, and an engine already there', async () => {
369  const gpus = [{ name: 'NVIDIA GeForce RTX 5070', vramGb: 12 }];
370  const report = engine => ({ ok: true, hardware: { nvidia_driver: '581.15', backend: 'cuda' }, engine });
371  const offer = await engineFirstRun({ control: { updateCheck: async () => report({ status: 'install', installed: null, offered: { version: '0.1.48', variant: 'cuda13', backend: 'cuda' }, download_bytes: 581299508 }) }, gpus });
372  assert.deepEqual([offer.status, offer.offer.bytes, offer.driver, offer.gpus[0].name], ['offer', 581299508, '581.15', 'NVIDIA GeForce RTX 5070']);
373  const none = await engineFirstRun({ control: { updateCheck: async () => report({ status: 'none-for-this-pc', installed: null, offered: null, reasons: ['needs NVIDIA driver 580.65 or newer, this PC has 560.1'] }) }, gpus });
374  assert.equal(none.status, 'none');
375  assert.match(none.reasons[0], /driver 580/);
376  const installed = await engineFirstRun({ control: { updateCheck: async () => report({ status: 'current', installed: { version: '0.1.48' }, offered: null }) }, gpus });
377  assert.equal(installed.status, 'installed');
378  const offline = await engineFirstRun({ control: { updateCheck: async () => { throw new Error('the update feed could not be read: could not read https://github.com/x (URLError: [WinError 10060] timed out)'); } }, gpus });
379  assert.equal(offline.status, 'offline');
380});
381
382test('without the shell bridge "Update Strata" still updates Control and says nothing false about the app', async () => {
383  const f = fixture();
384  try {
385    await f.native.refresh(true);
386    const job = await finish(f.native, f.native.operation('update-strata', {}).id);
387    assert.equal(job.state, 'done', job.error);
388    assert.doesNotMatch(job.summary, /app update is installed/);
389  } finally { await f.native.close(); f.cleanup(); }
390});
391
392test('packaged: opening the app, listing models and loading one never reach the update step', async () => {
393  const f = fixture();
394  try {
395    await f.native.refresh(true);
396    const load = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
397    assert.equal(load.state, 'done', load.error);
398    assert.deepEqual(f.calls, [], 'no update, check or rollback call: downloads happen only when the user presses Update');
399    assert.equal(f.spawned.length, 0);
400  } finally { await f.native.close(); f.cleanup(); }
401});
402
403test('plain words in the app: codes, hashes and exit codes stay in details, never in the main text', async () => {
404  const { plainUpdateError } = await import('../server/update-messages.mjs');
405  const raw = [
406    'the download of http://x/e.tar.gz was interrupted after 100 of 200 bytes (ConnectionResetError)',
407    'The new engine 0.1.46 did not pass its test start (it did not answer a one-token probe (server_exited))',
408    'http://x/e.tar.gz does not match the SHA-256 in the signed feed; the download was deleted',
409    'this build trusts no update key (update_keys.json is empty)',
410    'app-1 is serving.',
411    'something unexpected: exit 9',
412  ];
413  for (const text of raw) {
414    const plain = plainUpdateError(new Error(text));
415    assert.doesNotMatch(plain.message, /SHA|HTTP|http|exit|0\.1\.|server_exited|\.tar|key|bytes|probe/i, plain.message);
416    assert.equal(plain.details, text);
417    assert.ok(plain.next.length > 0);
418  }
419  assert.match(plainUpdateError(new Error(raw[0])).message, /internet connection/);
420  assert.match(plainUpdateError(new Error(raw[4])).message, /Unload the model/);
421});
422
423test('a failed update job shows plain words and keeps the technical reason as details', async () => {
424  const f = fixture({ update: async () => { throw new Error('the download of http://x/e.tar.gz was interrupted after 1 of 2 bytes (ConnectionResetError)'); } });
425  try {
426    await f.native.refresh(true);
427    const job = await finish(f.native, f.native.operation('update-engine', {}).id);
428    assert.equal(job.state, 'error');
429    assert.match(job.error, /Couldn't reach the update server\. Check your internet connection, then press Update engine in Settings\./);
430    assert.doesNotMatch(job.error, /http|bytes|Reset/);
431    assert.match(job.details, /ConnectionResetError/);
432  } finally { await f.native.close(); f.cleanup(); }
433});
434
435test('offline, the signed-feed check says there is no internet connection in plain words and keeps the reason in details', async () => {
436  for (const raw of ['fetch failed', '<urlopen error [Errno 11001] getaddrinfo failed>', 'getaddrinfo ENOTFOUND updates.example']) {
437    const control = { version: '0.1.45', async updateCheck() { throw new Error(raw); } };
438    const result = await checkComponentUpdates({ control, appVersion: '0.2.0' });
439    assert.equal(result.strata.status, 'error', raw);
440    assert.equal(result.strata.message, "No internet connection. Try again when you're online.", raw);
441    assert.equal(result.engine.message, "No internet connection. Try again when you're online.", raw);
442    assert.equal(result.strata.details, raw);
443  }
444});
445
446test('the app updater and the host never reach the network by themselves: only check() does', async () => {
447  const calls = [];
448  const updater = createAppUpdater({ env: { STRATA_SHELL_BRIDGE: 'http://127.0.0.1:4000', STRATA_SHELL_TOKEN: 'tok' }, fetcher: async url => { calls.push(url); return Response.json({ available: false }); } });
449  assert.ok(updater);
450  assert.equal(calls.length, 0, 'creating the updater makes no call');
451  await updater.check();
452  assert.equal(calls.length, 1);
453});