okami.mom/strata

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

Niko1221Merge f-clean-7 (045843071): the app loads screens, languages, Prism and Time-skip on first use; main chunk 3,123,528 -> 755,418 B, start screen 248.5 -> 143.4 ms (p2006 Chrome, median of 10); nothing users see changes (cleanup step 7)1631a9fde

main
14.5 KiB222 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 { readFileSync as read, mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
5import { join } from 'node:path';
6import { tmpdir } from 'node:os';
7import { createControl } from '../server/control-runtime.mjs';
8import { createNativeControl } from '../server/native-control.mjs';
9
10const src = name => read(new URL(`../${name}`, import.meta.url), 'utf8');
11
12/** A packaged host with one installed model and a fake Control whose `update` plays the events of `strata update --stop-model --output jsonl`. */
13function fixture({ updateScript } = {}) {
14  const root = mkdtempSync(join(tmpdir(), 'strata-update-model-'));
15  const install = join(root, 'install'), data = join(root, 'data');
16  mkdirSync(install, { recursive: true });
17  process.env.STRATA_INSTALL_DIR = install;
18  const config = join(install, 'strata-iq2_xs.json');
19  writeFileSync(config, JSON.stringify({ exe: 'component:strata-engine', tokenizer: join(install, 'tok'), args: ['--max-context', '32768'], model_name: 'Qwen', port: 8080 }));
20  const calls = [];
21  const control = {
22    control: { dir: join(root, 'control') }, version: '0.1.45',
23    async installedModels() { return { install_dir: install, models: [{ id: 'iq2_xs', name: 'Qwen', source_config: config, component_status: 'present', context_tokens: 32768, backend: 'cuda' }] }; },
24    async engine() { return { usable: true, backend: 'cuda', components_dir: 'E:\\c', previous: null, engine: { version: '0.1.45', platform: 'windows-x86_64', backend: 'cuda', exe: 'e', root: 'r' } }; },
25    async saveProfile(profile) { calls.push(['saveProfile', profile]); return {}; },
26    async start(profile) { calls.push(['start', profile]); return { ok: true, state: 'ready' }; },
27    async stop(profile) { calls.push(['stop', profile]); return { ok: true }; },
28    async update(options) {
29      calls.push(['update', options.engine, options.stopModel === true]);
30      const ids = native.state().instances.map(i => i.id);
31      const profile = 'app-1';
32      options.onEvent?.({ event: 'models', phase: 'consent', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'ready' }], message: 'Qwen is running' });
33      if (updateScript) return updateScript(options, { profile, ids, native });
34      options.onEvent?.({ event: 'progress', phase: 'download', label: 'engine 0.1.46', percent: 40 });
35      options.onEvent?.({ event: 'models', phase: 'stopping', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'ready' }] });
36      options.onEvent?.({ event: 'models', phase: 'stopped', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'stopped' }] });
37      options.onEvent?.({ event: 'models', phase: 'left-stopped', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'stopped' }], start: 'strata launch' });
38      return { ok: true, results: [{ component: 'engine', status: 'updated', installed_after: { version: '0.1.46' } }] };
39    },
40    async rollbackEngine() { return { ok: true }; },
41  };
42  const native = createNativeControl({ control, directory: data, spawnProcess: () => { throw new Error('no process'); }, fetcher: async () => Response.json({}), requests: () => [] });
43  return { native, calls, control, cleanup: () => rmSync(root, { recursive: true, force: true }) };
44}
45const 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'); };
46async function loaded(f) {
47  await f.native.refresh(true);
48  const load = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
49  assert.equal(load.state, 'done', load.error);
50  assert.equal(f.native.state().instances.length, 1);
51}
52
53test('Control is called with --stop-model only when the app asks for it', async () => {
54  const seen = [];
55  const control = createControl({ control: { dir: '/c', python: '/c/python', cli: '/c/strata.py' }, env: {}, run: async args => { seen.push(args); return { code: 0, json: { ok: true, results: [] } }; } });
56  await control.update({ engine: true, control: false });
57  await control.update({ engine: true, control: false, stopModel: true });
58  assert.ok(!seen[0].includes('--stop-model'));
59  assert.ok(seen[1].includes('--stop-model'));
60  assert.deepEqual(seen[1].slice(0, 3), ['update', '--output', 'jsonl'], 'the host reads the events (jsonl)');
61  assert.ok(!seen[1].includes('--start-again'), 'starting again is the person\'s answer in the dialog, not an automatic flag');
62});
63
64test('a loaded model is stopped for the update only with the person\'s yes, and is then offered a start with the same settings', async () => {
65  const f = fixture();
66  try {
67    await loaded(f);
68    const refused = await finish(f.native, f.native.operation('update-engine', {}).id);
69    assert.equal(refused.state, 'error');
70    assert.match(refused.error, /Unload native models/, 'no yes, no stop');
71    assert.equal(f.calls.filter(c => c[0] === 'update').length, 0);
72
73    const job = await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id);
74    assert.equal(job.state, 'done', job.error);
75    assert.deepEqual(f.calls.find(c => c[0] === 'update'), ['update', true, true]);
76    const state = f.native.state();
77    assert.equal(state.instances.length, 0, 'the stopped model has left the list');
78    assert.equal(state.stoppedForUpdate.updated, true);
79    assert.deepEqual(state.stoppedForUpdate.models.map(m => m.label), [state.stoppedForUpdate.models[0].label]);
80    assert.equal(job.step, 'stopped');
81    assert.equal(f.calls.filter(c => c[0] === 'start').length, 1, 'only the first load started it; nothing started it again by itself');
82
83    const again = await finish(f.native, f.native.operation('restart-models', {}).id);
84    assert.equal(again.state, 'done', again.error);
85    assert.match(again.summary, /running again with the same settings/);
86    const starts = f.calls.filter(c => c[0] === 'start');
87    assert.equal(starts.length, 2);
88    assert.equal(starts[1][1], starts[0][1], 'the same profile (its saved run settings) is started again');
89    const after = f.native.state();
90    assert.equal(after.instances.length, 1);
91    assert.equal(after.instances[0].status, 'ready');
92    assert.equal(after.stoppedForUpdate, null);
93  } finally { await f.native.close(); f.cleanup(); }
94});
95
96test('a failed update leaves the old engine and still offers the model back, on the old engine', async () => {
97  const f = fixture({
98    updateScript: async (options, { profile }) => {
99      options.onEvent?.({ event: 'models', phase: 'stopping', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'ready' }] });
100      options.onEvent?.({ event: 'models', phase: 'stopped', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'stopped' }] });
101      throw Object.assign(new Error('The new engine did not pass its test start'), { exitCode: 6 });
102    },
103  });
104  try {
105    await loaded(f);
106    const job = await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id);
107    assert.equal(job.state, 'error');
108    assert.match(job.error, /didn't start correctly, so nothing was changed\. Your current version still works/, 'plain words, not the exit code');
109    const state = f.native.state();
110    assert.equal(state.instances.length, 0);
111    assert.equal(state.stoppedForUpdate.updated, false, 'the dialog says the update did not finish and offers the old engine');
112    const again = await finish(f.native, f.native.operation('restart-models', {}).id);
113    assert.equal(again.state, 'done', again.error);
114    assert.equal(f.native.state().instances[0].status, 'ready');
115  } finally { await f.native.close(); f.cleanup(); }
116});
117
118test('a failed update that never touched the model offers nothing', async () => {
119  const f = fixture({ updateScript: async () => { throw new Error('Could not reach the update server (timed out).'); } });
120  try {
121    await loaded(f);
122    const job = await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id);
123    assert.equal(job.state, 'error');
124    assert.equal(f.native.state().instances.length, 1, 'the model is still running');
125    assert.equal(f.native.state().stoppedForUpdate, null);
126  } finally { await f.native.close(); f.cleanup(); }
127});
128
129test('a model the app did not start is never stopped: the update ends at the first event, before any download', async () => {
130  const f = fixture({
131    updateScript: async (options, { profile }) => {
132      options.onEvent?.({ event: 'models', phase: 'consent', models: [{ profile: 'launch-qwen', name: 'Qwen (port 8081)', port: 8081, kind: 'launch', state: 'ready' }] });
133      if (options.signal.aborted) throw new Error('killed');   // as runCli does: an aborted signal ends the Control process
134      await new Promise((resolve, reject) => options.signal.addEventListener('abort', () => reject(new Error('killed')), { once: true }));
135    },
136  });
137  try {
138    await loaded(f);
139    const stopsBefore = f.calls.filter(c => c[0] === 'stop').length;
140    const job = await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id);
141    assert.equal(job.state, 'error');
142    assert.match(job.error, /not started from this app is running, so nothing was changed/);
143    assert.equal(f.native.state().instances.length, 1);
144    assert.equal(f.native.state().stoppedForUpdate, null);
145    assert.equal(f.calls.filter(c => c[0] === 'stop').length, stopsBefore, 'nothing was stopped by the update');
146  } finally { await f.native.close(); f.cleanup(); }
147});
148
149test('"Not now" forgets the offer; with nothing stopped there is nothing to start again', async () => {
150  const f = fixture();
151  try {
152    await loaded(f);
153    await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id);
154    assert.ok(f.native.state().stoppedForUpdate);
155    f.native.dismissRestart();
156    assert.equal(f.native.state().stoppedForUpdate, null);
157    const none = await finish(f.native, f.native.operation('restart-models', {}).id);
158    assert.equal(none.state, 'error');
159    assert.match(none.error, /no stopped model/);
160  } finally { await f.native.close(); f.cleanup(); }
161});
162
163test('with no model loaded the update behaves as before: no stop flag, no offer', async () => {
164  const f = fixture();
165  try {
166    await f.native.refresh(true);
167    const job = await finish(f.native, f.native.operation('update-engine', {}).id);
168    assert.equal(job.state, 'done', job.error);
169    assert.deepEqual(f.calls.find(c => c[0] === 'update'), ['update', true, false]);
170    assert.equal(f.native.state().stoppedForUpdate, null);
171    const withFlag = await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id);
172    assert.deepEqual(f.calls.filter(c => c[0] === 'update')[1], ['update', true, false], 'the flag is only sent when a model is loaded');
173    assert.equal(withFlag.state, 'done');
174  } finally { await f.native.close(); f.cleanup(); }
175});
176
177test('the dialog: warns naming the model, progress in plain words, the offer, the old-engine offer, and only Settings > About and the Models screen mount it', () => {
178  const dialog = src('src/components/EngineUpdateDialog.tsx');
179  assert.match(dialog, /args: \{ stopModel: true \}/);
180  assert.match(dialog, /kind: 'restart-models'/);
181  assert.match(dialog, /To update the engine, Strata has to stop the model that is loaded: \{0\}\./, 'the warning names the model');
182  for (const words of ['Getting the new engine ready. {0} keeps working until it is ready.', 'Stopping {0}. Answers in progress finish first.', '{0} is stopped. Updating the engine…',
183    'The engine is updated. Start {0} again with the same settings?', "The update didn't finish. Your old engine is unchanged and still works. Start {0} again on it?"])
184    assert.ok(dialog.includes(words), words);
185  assert.doesNotMatch(dialog, /fetch\(|api\.get|XMLHttpRequest/, 'no network from the dialog');
186  const code = dialog.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
187  assert.doesNotMatch(code, /exit code|--stop-model|jsonl/i, 'no flags or codes in the words');
188  assert.match(src('src/components/SettingsUpdates.tsx'), /<EngineUpdateDialog open=\{confirm === 'update-engine' && withModel\}/);
189  assert.match(src('src/components/SettingsUpdates.tsx'), /<Dialog open=\{!!confirm && !\(confirm === 'update-engine' && withModel\)\}/, 'with no model loaded the older dialog is the one shown');
190  assert.equal((src('src/components/NativeModels.tsx').match(/<EngineUpdateDialog /g) ?? []).length, 1);
191  assert.match(src('server/index.mjs'), /\/api\/native\/engine-restart\/dismiss/);
192});
193
194test('the notice for a newer engine stays an ordinary quiet card: no toast, no banner, no timer, no network', () => {
195  const card = src('src/components/EngineUpdateCard.tsx');
196  assert.doesNotMatch(card, /toast|setInterval|setTimeout|fetch\(|Notification/);
197  assert.doesNotMatch(src('src/components/EngineUpdateDialog.tsx'), /setInterval|setTimeout|Notification|toast/);
198});
199
200test('offline, the update says nothing by itself: the dialog opens only from a button and shows only what the host reports', () => {
201  const settings = src('src/components/SettingsUpdates.tsx');
202  assert.match(settings, /onClick=\{\(\) => setConfirm\(name === 'Strata' \? 'update-strata' : 'update-engine'\)\}/, 'the button opens the confirmation; nothing opens it on a timer or on a failed check');
203});
204
205test('all nine languages carry the dialog\'s words with the same slots', () => {
206  const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr'];
207  const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(src(`src/locales/upd-${l}.json`))]));
208  const keys = Object.keys(catalogs.en);
209  assert.equal(keys.length, 17);
210  for (const l of langs) {
211    assert.deepEqual(Object.keys(catalogs[l]), keys, l);
212    for (const k of keys) {
213      assert.ok(catalogs[l][k].trim(), `${l} ${k}`);
214      assert.deepEqual([...catalogs[l][k].matchAll(/\{\d+\}/g)].map(m => m[0]).sort(), [...catalogs.en[k].matchAll(/\{\d+\}/g)].map(m => m[0]).sort(), `${l} ${k} slots`);
215      if (l !== 'en') assert.notEqual(catalogs[l][k], catalogs.en[k], `${l} ${k} is translated`);
216    }
217  }
218  // English is in the main catalog (src/lib/i18n.ts); each other language is one file (src/lib/catalog-<lang>.ts) that the app fetches when the language is used.
219  const i18n = src('src/lib/i18n.ts');
220  assert.match(i18n, /\.\.\.upd_en\b/);
221  for (const l of langs.filter(x => x !== 'en')) assert.match(src(`src/lib/catalog-${l}.ts`), new RegExp(`from '\\.\\./locales/upd-${l}\\.json'`));
222});