okami.mom/strata

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

Niko1221Merge f-029-urgent (bc694233b)99866a47a

main
15.8 KiB225 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 { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
6import { join } from 'node:path';
7import { tmpdir } from 'node:os';
8import { createNativeControl } from '../server/native-control.mjs';
9import { createControl } from '../server/control-runtime.mjs';
10
11/** The host in the packaged app with a stand-in for Strata Control: the move itself is Control's (tests/terminal/test_models_move.py). */
12function fixture(t, { plan = {}, move = null, unfinished = null } = {}) {
13  const root = realpathSync(mkdtempSync(join(tmpdir(), 'strata-mfolder-')));
14  const install = join(root, 'install'), data = join(root, 'host'), oldFolder = join(root, 'old'), newFolder = join(root, 'new');
15  for (const d of [install, data, oldFolder, newFolder]) mkdirSync(d, { recursive: true });
16  const earlier = { install: process.env.STRATA_INSTALL_DIR, terminal: process.env.STRATA_TERMINAL_SETTINGS_FILE, settings: process.env.STRATA_SETTINGS_FILE, comp: process.env.STRATA_COMPONENTS_DIR };
17  process.env.STRATA_INSTALL_DIR = install;
18  process.env.STRATA_TERMINAL_SETTINGS_FILE = join(root, 'terminal-settings.json');
19  process.env.STRATA_COMPONENTS_DIR = join(root, 'components');
20  delete process.env.STRATA_SETTINGS_FILE;
21  const calls = [];
22  const control = {
23    control: { dir: join(root, 'control'), python: join(root, 'control', 'python.exe'), cli: join(root, 'control', 'strata.py') }, version: '0.2.2',
24    async installedModels() { return { install_dir: install, models: [] }; },
25    async engine() { return { usable: true, engine: { version: '0.2.2', root: root } }; },
26    async importPlan() { return {}; },
27    async planModelsMove(from, to) {
28      calls.push(['plan', from, to]);
29      return { ok: true, issue: null, old: from, new: to, same_drive: false, free_bytes: 900e9, models_bytes: 74e9, needed_bytes: 77.7e9, models: [{ group: 'gyro-s', name: 'gyro-s', bytes: 58e9 }, { group: 'coder', name: 'coder', bytes: 16e9 }],
30        choices: { move: { possible: true, reason: '' }, keep: { possible: true, reason: '' }, empty: { possible: true, reason: '' } }, ...plan };
31    },
32    async moveModels(from, to, options) {
33      calls.push(['move', from, to, options.installDir]);
34      if (move) return move(from, to, options);
35      options.onEvent({ event: 'progress', done: 5e9, total: 74e9, file: 'models/gyro-s/a.gguf', group: 'gyro-s', index: 1, count: 3, seconds_left: 300, same_drive: false });
36      return { ok: true, event: 'result', done: true, stopped: false, moved: ['gyro-s', 'coder'], remaining: [], bytes_moved: 74e9, total_bytes: 74e9, files_moved: 3, same_drive: false };
37    },
38    async interruptedModelsMove(from) { calls.push(['status', from]); return unfinished; },
39    async resumeModelsMove(from, options) {
40      calls.push(['resume', from, options.installDir]);
41      options.onEvent({ event: 'progress', done: 20e9, total: 74e9, file: 'models/coder/c.gguf', group: 'coder', index: 2, count: 3, seconds_left: 120, same_drive: false });
42      return { ok: true, event: 'result', done: true, stopped: false, moved: ['coder'], remaining: [], bytes_moved: 74e9, total_bytes: 74e9, files_moved: 2, same_drive: false };
43    },
44    async leaveModelsMove(from, options) { calls.push(['leave', from, options.installDir]); return { ok: true, removed: 1, restored: 1, bytes_removed: 5 }; },
45    async stop() { return { ok: true }; },
46  };
47  const spawnProcess = () => { throw new Error('the host starts no process here'); };
48  const native = createNativeControl({ control, directory: data, spawnProcess, fetcher: async () => Response.json({}), requests: () => [] });
49  t.after(() => {
50    for (const [key, name] of [['install', 'STRATA_INSTALL_DIR'], ['terminal', 'STRATA_TERMINAL_SETTINGS_FILE'], ['settings', 'STRATA_SETTINGS_FILE'], ['comp', 'STRATA_COMPONENTS_DIR']]) {
51      if (earlier[key] === undefined) delete process.env[name]; else process.env[name] = earlier[key];
52    }
53    rmSync(root, { recursive: true, force: true });
54  });
55  native.setDownloadDirectory(oldFolder);
56  return { native, control, calls, root, install, oldFolder, newFolder, terminalFile: process.env.STRATA_TERMINAL_SETTINGS_FILE };
57}
58const 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'); };
59
60test('the plan says what the picked folder means and keeps the person\'s spelling of it', async t => {
61  const f = fixture(t);
62  const plan = await f.native.planModelsFolder(f.newFolder);
63  assert.equal(plan.current, f.oldFolder);
64  assert.equal(plan.folder, f.newFolder);
65  assert.equal(plan.wholeDrive, false);
66  assert.equal(plan.shown, f.newFolder);
67  assert.equal(plan.models.length, 2);
68  assert.deepEqual(f.calls[0], ['plan', f.oldFolder, f.newFolder]);
69});
70
71test('a whole drive is planned as <drive>\\Strata, shown as <drive>\\Strata\\Models', async t => {
72  const f = fixture(t);
73  const root = f.root.slice(0, f.root.indexOf(process.platform === 'win32' ? '\\' : '/') + 1) || '/';
74  const before = existsSync(join(root, 'Strata'));
75  const plan = await f.native.planModelsFolder(root);
76  assert.equal(existsSync(join(root, 'Strata')), before, 'planning must not create or remove anything');
77  assert.equal(plan.wholeDrive, true);
78  assert.equal(plan.folder, join(root, 'Strata'));
79  assert.equal(plan.shown, join(root, 'Strata', 'Models'));
80  // Planning must not touch the disk. This test never creates <drive>\Strata, so it never deletes it either (#4689).
81});
82
83test('the card is blocked while a model runs or a job runs: a running model must be stopped on purpose', async t => {
84  const f = fixture(t);
85  await assert.rejects(f.native.startModelsFolder({ folder: f.newFolder, choice: 'bogus' }), /Choose what to do/);
86  const refused = fixture(t, { plan: { choices: { move: { possible: false, reason: 'Your models need 77 GB, this drive has 38 GB free.' }, keep: { possible: true, reason: '' }, empty: { possible: true, reason: '' } } } });
87  await assert.rejects(refused.native.startModelsFolder({ folder: refused.newFolder, choice: 'move' }), /need 77 GB/);
88  assert.equal(refused.calls.some(c => c[0] === 'move'), false);
89});
90
91test('Keep: the new folder is used for new downloads, nothing is moved, both settings files follow', async t => {
92  const f = fixture(t);
93  writeFileSync(f.terminalFile, JSON.stringify({ data_dir: f.oldFolder, data_dir_at: 1 }));   // the Terminal had chosen the old folder
94  const result = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'keep' });
95  assert.equal(result.done, true);
96  assert.equal(f.native.state().downloadDirectory, f.newFolder);
97  assert.equal(f.calls.some(c => c[0] === 'move'), false);
98  assert.equal(JSON.parse(readFileSync(f.terminalFile, 'utf8')).data_dir, f.newFolder);
99});
100
101test('Start empty: the old models are no longer listed (their run configs are set aside, not deleted), the model files stay', async t => {
102  const f = fixture(t);
103  const oldFile = join(f.oldFolder, 'models', 'gyro-s', 'a.gguf');
104  mkdirSync(join(f.oldFolder, 'models', 'gyro-s'), { recursive: true });
105  writeFileSync(oldFile, 'x');
106  writeFileSync(join(f.install, 'strata-gyro-s.json'), JSON.stringify({ args: ['--native', oldFile] }));
107  writeFileSync(join(f.install, 'strata-other.json'), JSON.stringify({ args: ['--native', join(f.root, 'elsewhere', 'b.gguf')] }));
108  const result = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'empty' });
109  assert.deepEqual(result.setAside, ['strata-gyro-s.json']);
110  assert.equal(existsSync(join(f.install, 'strata-gyro-s.json')), false);
111  assert.equal(existsSync(join(f.install, 'old-models', 'strata-gyro-s.json')), true);
112  assert.equal(existsSync(join(f.install, 'strata-other.json')), true, 'a model elsewhere is not touched');
113  assert.equal(existsSync(oldFile), true);
114  assert.equal(f.native.state().downloadDirectory, f.newFolder);
115});
116
117test('Move: a job with progress; the folder changes only when everything moved', async t => {
118  const f = fixture(t);
119  const job = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'move' });
120  assert.equal(job.kind, 'models-move');
121  const done = await finish(f.native, job.id);
122  assert.equal(done.state, 'done');
123  assert.equal(done.result.done, true);
124  assert.equal(done.result.sameDrive, false);
125  assert.equal(f.native.state().downloadDirectory, f.newFolder);
126  assert.deepEqual(f.calls.find(c => c[0] === 'move').slice(1), [f.oldFolder, f.newFolder, f.install]);
127});
128
129test('Move stopped: the folder stays, what moved is reported', async t => {
130  const f = fixture(t, { move: async () => ({ ok: true, event: 'result', done: false, stopped: true, moved: ['coder'], remaining: ['gyro-s'], bytes_moved: 16e9, total_bytes: 74e9, files_moved: 1, same_drive: false }) });
131  const job = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'move' });
132  const done = await finish(f.native, job.id);
133  assert.equal(done.result.stopped, true);
134  assert.deepEqual(done.result.moved, ['coder']);
135  assert.equal(f.native.state().downloadDirectory, f.oldFolder, 'a partial move never points the app at an incomplete folder');
136});
137
138test('Move failed (disk full): the folder stays and the job says what happened', async t => {
139  const f = fixture(t, { move: async () => { throw Object.assign(new Error('The drive ran out of space.'), { code: 'disk_full', details: 'ENOSPC: no space left on device', output: { moved: ['coder'], remaining: ['gyro-s'], bytes_moved: 52e9, total_bytes: 74e9 } }); } });
140  const job = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'move' });
141  const done = await finish(f.native, job.id);
142  assert.equal(done.state, 'error');
143  assert.equal(done.result.code, 'disk_full');
144  assert.equal(done.result.bytes, 52e9);
145  assert.match(done.details, /ENOSPC/);
146  assert.equal(f.native.state().downloadDirectory, f.oldFolder);
147});
148
149test('Move: Stop writes the cancel file and the run ends by itself', async t => {
150  let release;
151  const f = fixture(t, { move: (from, to, options) => new Promise(resolve => { release = () => resolve({ ok: true, event: 'result', done: false, stopped: existsSync(options.cancelFile), moved: [], remaining: ['gyro-s', 'coder'], bytes_moved: 0, total_bytes: 74e9, files_moved: 0, same_drive: false }); }) });
152  const job = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'move' });
153  await f.native.cancel(job.id);
154  assert.equal(f.native.state().jobs.find(j => j.id === job.id).state, 'running', 'it ends when Control has cleaned up, not before');
155  release();
156  const done = await finish(f.native, job.id);
157  assert.equal(done.result.stopped, true);
158  assert.equal(f.native.state().downloadDirectory, f.oldFolder);
159});
160
161test('a move needs the app: the Control command line is built from the plan and the cancel file', async () => {
162  const seen = [];
163  const control = createControl({ control: { dir: '/c', python: '/c/py', cli: '/c/strata.py' }, run: async (args, options) => { seen.push([args, options]); return args.includes('--plan') ? { code: 0, json: { ok: true, plan: { ok: true } }, text: '', stderr: '' } : { code: 0, json: { ok: true, event: 'result', done: true }, text: '', stderr: '' }; } });
164  assert.deepEqual(await control.planModelsMove('/old', '/new'), { ok: true });
165  assert.deepEqual(seen[0][0], ['models', 'move', '/new', '--from', '/old', '--plan', '--output', 'json']);
166  const result = await control.moveModels('/old', '/new', { installDir: '/i', cancelFile: '/c.cancel' });
167  assert.equal(result.done, true);
168  assert.deepEqual(seen[1][0], ['models', 'move', '/new', '--from', '/old', '--install-dir', '/i', '--cancel-file', '/c.cancel', '--output', 'jsonl']);
169  const failing = createControl({ control: { dir: '/c', python: '/c/py', cli: '/c/strata.py' }, run: async () => ({ code: 5, json: { ok: false, error: { code: 'disk_full', message: 'The drive ran out of space.', details: 'ENOSPC' }, moved: [] }, text: '', stderr: '' }) });
170  await assert.rejects(failing.moveModels('/o', '/n'), e => e.code === 'disk_full' && e.details === 'ENOSPC' && /ran out of space/.test(e.message));
171});
172
173test('an unfinished move is found at the next start, and Finish resumes it as a job that changes the folder only when done', async t => {
174  const f = fixture(t);
175  f.control.interruptedModelsMove = async from => { f.calls.push(['status', from]); return { state: 'failed', from: f.oldFolder, to: f.newFolder, bytes: 74e9 }; };
176  assert.equal((await f.native.interruptedMove()).to, f.newFolder);
177  assert.deepEqual(f.calls[0], ['status', f.oldFolder]);
178  const job = await f.native.finishInterruptedMove({ stopRunning: true });
179  const done = await finish(f.native, job.id);
180  assert.equal(done.state, 'done');
181  assert.equal(f.calls.find(c => c[0] === 'resume')[1], f.oldFolder);
182  assert.equal(f.native.state().downloadDirectory, f.newFolder);
183});
184
185test('Leave it keeps the old folder and asks Control to remove the partial copies; nothing interrupted means nothing to do', async t => {
186  const f = fixture(t);
187  assert.equal(await f.native.interruptedMove(), null);
188  await assert.rejects(f.native.leaveInterruptedMove(), /No move was interrupted/);
189  f.control.interruptedModelsMove = async () => ({ state: 'running', from: f.oldFolder, to: f.newFolder, bytes: 1 });
190  const result = await f.native.leaveInterruptedMove();
191  assert.equal(result.folder, f.oldFolder);
192  assert.deepEqual(f.calls.find(c => c[0] === 'leave').slice(0, 2), ['leave', f.oldFolder]);
193  assert.equal(f.native.state().downloadDirectory, f.oldFolder);
194});
195
196test('the Control command lines for status, resume and leave', async () => {
197  const seen = [];
198  const control = createControl({ control: { dir: '/c', python: '/c/py', cli: '/c/strata.py' }, run: async args => { seen.push(args); return args.includes('--status') ? { code: 0, json: { ok: true, interrupted: { from: '/o', to: '/n' } }, text: '', stderr: '' } : args.includes('--leave') ? { code: 0, json: { ok: true, removed: 0 }, text: '', stderr: '' } : { code: 0, json: { ok: true, event: 'result', done: true }, text: '', stderr: '' }; } });
199  assert.equal((await control.interruptedModelsMove('/o')).to, '/n');
200  await control.resumeModelsMove('/o', { installDir: '/i', cancelFile: '/c.cancel' });
201  await control.leaveModelsMove('/o', { installDir: '/i' });
202  assert.deepEqual(seen[0], ['models', 'move', '--status', '--from', '/o', '--output', 'json']);
203  assert.deepEqual(seen[1], ['models', 'move', '--resume', '--from', '/o', '--install-dir', '/i', '--cancel-file', '/c.cancel', '--output', 'jsonl']);
204  assert.deepEqual(seen[2], ['models', 'move', '--leave', '--from', '/o', '--install-dir', '/i', '--output', 'json']);
205});
206
207test('the models folder strings exist in all 9 languages with the same placeholders', () => {
208  const read = lang => JSON.parse(readFileSync(new URL(`../src/locales/${lang}.json`, import.meta.url), 'utf8'));
209  const en = read('en');
210  const ours = Object.keys(en).filter(k => Number(k.slice(1)) >= 8339 && Number(k.slice(1)) <= 8422);
211  assert.equal(ours.length, 84);
212  for (const lang of ['de', 'es', 'fr', 'ja', 'ko', 'pt', 'ru', 'zh']) {
213    const text = read(lang);
214    for (const key of ours) {
215      assert.ok(text[key], `${lang} ${key}`);
216      assert.deepEqual((text[key].match(/\{\d\}/g) ?? []).sort(), (en[key].match(/\{\d\}/g) ?? []).sort(), `${lang} ${key} placeholders`);
217    }
218  }
219  // every string the dialog shows through tr() is in the catalogue
220  const source = readFileSync(new URL('../src/components/ModelsFolderDialog.tsx', import.meta.url), 'utf8');
221  const values = new Set(Object.values(en));
222  for (const text of ['Models folder', 'Change folder', 'Move my models', 'Use both folders', 'Start empty', 'Stop moving', 'Your models are moved', 'Moving stopped']) {
223    assert.ok(source.includes(text) && values.has(text), text);
224  }
225});