okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
31.4 KiB423 linesraw
1/**
2 * Load with "Read pictures" on and the picture files not on this computer (the owner's bug, 11-01): the Load fetches only those files and loads.
3 * It must not run the installer (no checking of the model files, no second pack, no second draft layer), must keep the model's pack, draft layer and data folder
4 * exactly where its run config has them, and must never rewrite data_dir in the settings. No internet: the model loads without pictures and says so in one line.
5 * Control is a fake that records what the host asked it to do; nothing here starts an engine or reaches a network.
6 */
7import './helpers/isolate-profile.mjs';   // a test run never writes the owner's real Strata profile
8import test from 'node:test';
9import assert from 'node:assert/strict';
10import { EventEmitter } from 'node:events';
11import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
12import { join } from 'node:path';
13import { tmpdir as osTmpdir } from 'node:os';
14// the canonical scratch root: on a Mac the temp folder is /var/folders/..., which resolves to /private/var/...; the paths the host reports are the resolved ones
15const tmpdir = () => realpathSync(osTmpdir());
16import { createNativeControl } from '../server/native-control.mjs';
17import { ControlError } from '../server/control-runtime.mjs';
18
19const finish = async (native, id) => { for (let i = 0; i < 600; 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'); };
20const until = async (test, what) => { for (let i = 0; i < 600; i++) { if (test()) return; await new Promise(r => setTimeout(r, 10)); } throw new Error(`never happened: ${what}`); };
21const listing = root => { const out = {}; const walk = dir => { for (const e of readdirSync(dir, { withFileTypes: true })) { const p = join(dir, e.name); if (e.isDirectory()) walk(p); else out[p.slice(root.length)] = statSync(p).size; } }; walk(root); return out; };
22
23/**
24 * layout 'own'      the model's files in their own folder, its pack and draft layer in a data folder that is not the app's models folder (the owner's case)
25 * layout 'normal'   everything under <data>/models/<tag>, <data>/packs, <data>/mtp (what the app's own download makes)
26 * layout 'local'    a model added with "Use a local GGUF": files in the person's folder, pack and draft layer in a Strata data folder of that day
27 */
28function fixture({ layout = 'own', vision = null, arch = undefined, onFetch = null, mmprojFile = false, engineRoot = null } = {}) {
29  const root = mkdtempSync(join(tmpdir(), 'strata-lp-test-'));
30  const install = join(root, 'install'), data = join(root, 'host-data'), home = join(root, 'home'), modelsDir = join(home, 'models');
31  for (const d of [install, data, modelsDir]) mkdirSync(d, { recursive: true });
32  const earlier = process.env.STRATA_INSTALL_DIR;
33  process.env.STRATA_INSTALL_DIR = install;
34  const dataFolder = layout === 'own' ? join(root, 'qwen-own') : layout === 'normal' ? join(root, 'Strata-data') : join(root, 'Strata-data');
35  const modelFolder = layout === 'normal' ? join(dataFolder, 'models', 'IQ3_S') : layout === 'local' ? join(root, 'my-files', 'IQ3_S') : join(dataFolder, 'IQ3_S');
36  const gguf = join(modelFolder, 'Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf');
37  mkdirSync(modelFolder, { recursive: true });
38  writeFileSync(gguf, 'GGUF'); writeFileSync(gguf.replace('00001', '00002'), 'GGUF');
39  const pack = join(dataFolder, 'packs', 'iq3_s'), mtp = join(dataFolder, 'mtp', 'rt');
40  mkdirSync(join(pack, 'tokenizer'), { recursive: true }); mkdirSync(mtp, { recursive: true });
41  writeFileSync(join(pack, 'native_experts.txt'), 'x'); writeFileSync(join(mtp, 'experts.bin'), 'e'); writeFileSync(join(dataFolder, 'mtp', 'mtp-q2_0.gguf'), 'm');
42  const mmproj = join(dataFolder, 'models', 'mmproj-Qwen3.8-Flash-Next-BF16.gguf');
43  if (mmprojFile) { mkdirSync(join(dataFolder, 'models'), { recursive: true }); writeFileSync(mmproj, 'mm'); }
44  const configPath = join(install, 'strata-iq3_s.json');
45  const args = ['--pack', pack, '--native', gguf, '--ple-gguf', gguf.replace('00001', '00002'), '--mtp', mtp, '--max-context', '8192', '--kv', 'int8'];
46  const config = { exe: 'component:strata-engine', tokenizer: join(pack, 'tokenizer'), args, model_name: 'qwen3.8-flash-next-iq3_s', port: 8080, ...(arch ? { arch } : {}),
47    ...(vision ? { vision: { exe: join(root, 'engine', 'strata-vision'), mmproj, model: gguf, gpu: false, max_tokens: 300 } } : {}) };
48  writeFileSync(configPath, JSON.stringify(config));
49  const settingsFile = process.env.STRATA_SETTINGS_FILE;
50  writeFileSync(settingsFile, JSON.stringify({ data_dir: join(root, 'host-owned', 'Strata-data'), data_dir_at: 1700000000 }));
51  const calls = [], saved = [], rpc = [];
52  const control = {
53    control: { dir: join(root, 'control'), python: join(root, 'control', 'python', 'python') }, version: '0.2.9',
54    async installedModels() {
55      const gone = vision && !existsSync(mmproj);
56      return { install_dir: install, models: [{ id: 'iq3_s', name: 'qwen3.8-flash-next-iq3_s', source_config: configPath, context_tokens: 8192, backend: 'cuda',
57        component_status: String(arch ?? '').startsWith('deepseek') ? 'retired' : gone ? 'missing_or_invalid' : 'present', ...(String(arch ?? '').startsWith('deepseek') ? { retired: 'deepseek', retired_line: 'DeepSeek - no longer supported.', refusal: 'DeepSeek-V4.1-Flash ISTA-DAS 2.00 bpw is a DeepSeek model. This version of Strata no longer runs DeepSeek models, so it was not started. Choose a Qwen model to run instead. If you no longer need the DeepSeek files, you can delete that folder to free the space.' } : {}), ...(gone ? { missing: [{ part: 'vision/mmproj', file: 'mmproj-Qwen3.8-Flash-Next-BF16.gguf', status: 'missing' }], issue_codes: ['COMPONENT_MISSING'] } : { missing: [], issue_codes: [] }) }] };
58    },
59    async engine() { return { usable: true, backend: 'cuda', components_dir: join(root, 'c'), engine: { version: '0.1.55', platform: 'linux-x86_64', backend: 'cuda', exe: join(root, 'engine', 'strata'), root: engineRoot ?? join(root, 'engine') } }; },
60    async saveProfile(name, path) { calls.push(['saveProfile', name]); saved.push(JSON.parse(readFileSync(path, 'utf8'))); return {}; },
61    async start() { calls.push(['start']); return { ok: true, state: 'ready' }; },
62    async stop() { return { ok: true }; },
63    async picturesFetch(options) {
64      calls.push(['picturesFetch', options]);
65      if (onFetch) return onFetch(options, { root, mmproj, gguf, calls });
66      options.onEvent?.({ event: 'progress', step: 'Downloading the picture files…', done: 9e8, total: 9e8 });
67      mkdirSync(join(options.dataDir, 'models'), { recursive: true });
68      writeFileSync(mmproj, 'mmproj');
69      return { ok: true, event: 'result', mmproj, vision: { exe: join(root, 'engine', 'strata-vision'), mmproj, model: gguf, gpu: false, max_tokens: 300, threads: 6 }, fetched: true, note: '', data_dir: options.dataFolder };
70    },
71  };
72  const catalog = { families: [{ family: 'qwen', title: 'Qwen3.8-Flash-Next', about: 'x', images: true, experimental: false, sizes: [
73    { id: 'iq3_s', model: 'IQ3_S', download_gb: 75.8, ram_needed_gb: 60, about: 'high quality', on_this_pc: 'fits', installed: true, images: true, experimental: false }] }],
74    contexts: [8192, 32768], recommendation: { family: 'qwen', model: 'IQ3_S', context: 32768 }, context_note: '' };
75  const hardware = { ram_gb: 63, cpu: { name: 'cpu', cores: 12 }, engine_vendor: 'nvidia', gpus: [{ index: 0, name: 'NVIDIA GeForce RTX 5070', vendor: 'nvidia', vram_gb: 11.9, arch: 120, usable: true }] };
76  const spawnProcess = (command, argv) => {
77    if (!String(argv[0]).endsWith('strata_mcp.py')) throw new Error('no process but the installer may be started in packaged mode: ' + command + ' ' + argv.join(' '));
78    const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.exitCode = null;
79    child.kill = () => { child.exitCode = 0; queueMicrotask(() => child.emit('exit', 0)); return true; };
80    child.stdin = { write(line) {
81      const message = JSON.parse(line); if (!message.id) return;
82      if (message.method === 'tools/call') rpc.push(message.params);
83      let result;
84      if (message.method === 'initialize') result = { protocolVersion: '2024-11-05' };
85      else if (message.method === 'tools/list') result = { tools: ['strata_models', 'strata_status', 'strata_install', 'strata_remove'].map(name => ({ name })) };
86      else if (message.params.name === 'strata_models') result = { structuredContent: catalog };
87      else if (message.params.name === 'strata_status') result = { structuredContent: { hardware, recommendation: catalog.recommendation, install: null, running: [], summary: 'x' } };
88      else if (Object.keys(message.params.arguments ?? {}).length === 0) result = { structuredContent: { summary: 'Install finished', install: { running: false, exit_code: 0 } } };
89      else if (message.params.arguments?.confirm) result = { structuredContent: { summary: 'Install started', plan: {}, install: { running: true, step: '1/7 checking your PC' } } };
90      else result = { structuredContent: { summary: 'Plan', plan: { title: 'Qwen3.8-Flash-Next IQ3_S', download_gb: 0, disk_short: null } } };
91      queueMicrotask(() => child.stdout.emit('data', Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + String.fromCharCode(10))));
92    } };
93    return child;
94  };
95  const native = createNativeControl({ control, directory: data, spawnProcess, fetcher: async () => Response.json({ status: 'ok' }), requests: () => [], modelsDirectory: () => modelsDir,
96    hardwareProbe: () => [{ index: 0, vram_gb: 11.9 }] });
97  const fetches = () => calls.filter(c => c[0] === 'picturesFetch').map(c => c[1]);
98  const installs = () => rpc.filter(p => p.name === 'strata_install');
99  return { native, calls, saved, rpc, fetches, installs, root, install, data, home, modelsDir, dataFolder, modelFolder, gguf, pack, mtp, mmproj, configPath, args, settingsFile,
100    config: () => JSON.parse(readFileSync(configPath, 'utf8')), settings: () => readFileSync(settingsFile, 'utf8'),
101    cleanup: () => { if (earlier === undefined) delete process.env.STRATA_INSTALL_DIR; else process.env.STRATA_INSTALL_DIR = earlier; rmSync(root, { recursive: true, force: true }); } };
102}
103const loadOp = (f, args) => f.native.operation('load', { model: 'iq3_s', ...args });
104
105test('own folder: the host knows the model\'s real data folder from its run config, not from the app\'s models folder', async () => {
106  const f = fixture();
107  try {
108    const state = await f.native.refresh(true);
109    const m = state.installed.models[0];
110    assert.equal(m.ready, true);
111    assert.equal(m.runDataFolder, f.dataFolder, 'the folder that holds packs/iq3_s and mtp/rt');
112    assert.notEqual(m.runDataFolder, f.modelsDir);
113    assert.equal(m.images, 'off');
114    assert.equal(m.visionPrepared, false, 'the page offers the picture files');
115    assert.equal(m.ownGgufDir, f.modelFolder);
116  } finally { await f.native.close(); f.cleanup(); }
117});
118
119test('own folder: Load with Read pictures on downloads only the picture files into that data folder, keeps pack, draft layer and data_dir, and loads', async () => {
120  const f = fixture();
121  try {
122    await f.native.refresh(true);
123    const settingsBefore = f.settings();
124    const treeBefore = listing(f.dataFolder);
125    const configBefore = f.config();
126    const job = await finish(f.native, loadOp(f, { vision: 'yes' }).id);
127    assert.equal(job.state, 'done', job.error);
128    assert.equal(job.kind, 'load');
129    assert.deepEqual(f.native.state().jobs.map(j => j.kind), ['load'], 'no install job');
130    assert.equal(f.installs().length, 0, 'the installer was not asked to do anything: no re-check, no second pack, no second draft layer');
131    const [asked] = f.fetches();
132    assert.equal(f.fetches().length, 1);
133    assert.equal(asked.dataDir, f.dataFolder, 'the data folder of the model, not <home>/Strata-data');
134    assert.equal(asked.configPath, f.configPath);
135    assert.equal(asked.vision, 'yes');
136    assert.equal(asked.family, 'qwen');
137    assert.equal(asked.engineDir, join(f.root, 'engine'));
138    assert.deepEqual(asked.hardware, { vram_gb: 11.9, make: 'nvidia', arch: 120 });
139    // what changed on disk: the picture file, and the picture section of the run config; nothing else of the model
140    const after = listing(f.dataFolder);
141    const added = Object.keys(after).filter(k => !(k in treeBefore));
142    assert.deepEqual(added.map(k => k.replaceAll('\\', '/')), ['/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf']);
143    for (const [k, size] of Object.entries(treeBefore)) assert.equal(after[k], size, `${k} untouched`);
144    assert.equal(existsSync(join(f.home, 'Strata-data')), false, 'no second data folder next to the app\'s models folder');
145    assert.equal(existsSync(join(f.root, 'host-data', 'mtp')), false);
146    const config = f.config();
147    assert.deepEqual(config.args, configBefore.args, 'the pack, the draft layer and the other arguments are exactly as they were');
148    assert.equal(config.vision.mmproj, f.mmproj);
149    assert.equal(config.vision.model, f.gguf);
150    assert.equal(f.settings(), settingsBefore, 'data_dir in the settings is not moved or rewritten');
151    // the engine was started with the pictures
152    assert.equal(f.saved.length, 1);
153    assert.equal(f.saved[0].vision.mmproj, f.mmproj);
154    assert.equal(f.native.state().instances[0].status, 'ready');
155    assert.equal(f.native.state().instances[0].picturesNote, undefined, 'nothing to apologise for');
156    assert.equal(f.native.state().installed.models[0].visionPrepared, true, 'the page stops offering the download');
157    assert.equal(f.native.state().installed.models[0].images, 'yes');
158  } finally { await f.native.close(); f.cleanup(); }
159});
160
161test('the progress is in plain words with a bar, and the Load goes on to "Loading the model…" after it', async () => {
162  let release;
163  const gate = new Promise(r => { release = r; });
164  const f = fixture({ onFetch: async (options, ctx) => {
165    options.onEvent({ event: 'progress', step: 'Downloading the picture files…', done: 3e8, total: 9e8 });
166    await gate;
167    writeFileSync(ctx.mmproj, 'x');
168    return { ok: true, vision: { exe: 'e', mmproj: ctx.mmproj, model: ctx.gguf, gpu: false, max_tokens: 300 }, fetched: true, note: '' };
169  } });
170  try {
171    await f.native.refresh(true);
172    const id = loadOp(f, { vision: 'yes' }).id;
173    await until(() => f.native.state().jobs.find(j => j.id === id)?.result?.install?.download, 'the first progress');
174    const running = f.native.state().jobs.find(j => j.id === id);
175    assert.equal(running.state, 'running');
176    assert.equal(running.summary, 'Downloading the picture files (0.9 GB, once)…');
177    const d = running.result.install.download;
178    assert.deepEqual([d.file, d.percent, +d.done_gb.toFixed(1), +d.total_gb.toFixed(1)], ['picture reader', 33, 0.3, 0.9]);
179    release();
180    const job = await finish(f.native, id);
181    assert.equal(job.state, 'done', job.error);
182    assert.equal(job.result?.install, undefined, 'the bar is gone');
183  } finally { release(); await f.native.close(); f.cleanup(); }
184});
185
186test('no internet: the model loads without pictures, says so in one short line, and nothing is saved about pictures', async () => {
187  const f = fixture({ onFetch: async () => { throw Object.assign(new ControlError("There is no internet connection, so the picture files can't be downloaded now."), { code: 'offline' }); } });
188  try {
189    await f.native.refresh(true);
190    const configBefore = readFileSync(f.configPath, 'utf8');
191    const started = Date.now();
192    const job = await finish(f.native, loadOp(f, { vision: 'yes' }).id);
193    assert.equal(job.state, 'done', job.error);
194    assert.ok(Date.now() - started < 5000, 'no hang');
195    const instance = f.native.state().instances[0];
196    assert.equal(instance.status, 'ready');
197    assert.equal(instance.picturesNote, 'No internet connection: the model is loaded without picture reading. Load it again when you are online.');
198    assert.equal(instance.vision, false);
199    assert.equal(f.saved[0].vision, undefined, 'started without the picture reader');
200    assert.equal(f.installs().length, 0);
201    assert.deepEqual(f.config(), JSON.parse(configBefore), 'the run config says what it said: Read pictures stays on for the next Load');
202    assert.deepEqual(f.native.state().jobs.map(j => j.kind), ['load']);
203  } finally { await f.native.close(); f.cleanup(); }
204});
205
206test('no room on the disk or a download that fails: the same, with the right line', async () => {
207  for (const [code, line] of [['disk', /not enough free disk space for the picture files/], ['failed', /could not be downloaded, so the model is loaded without picture reading\. Try again later\./], ['checksum', /could not be downloaded/]]) {
208    const f = fixture({ onFetch: async () => { throw Object.assign(new ControlError('x', { output: { error: { details: 'cause in words' } } }), { code }); } });
209    try {
210      await f.native.refresh(true);
211      const job = await finish(f.native, loadOp(f, { vision: 'yes' }).id);
212      assert.equal(job.state, 'done', job.error);
213      assert.match(f.native.state().instances[0].picturesNote, line, code);
214      assert.equal(f.native.state().instances[0].status, 'ready');
215    } finally { await f.native.close(); f.cleanup(); }
216  }
217});
218
219test('Stop during the download ends the Load; nothing is started', async () => {
220  let aborted = false;
221  const f = fixture({ onFetch: (options) => new Promise((_, reject) => { options.signal.addEventListener('abort', () => { aborted = true; reject(new ControlError('stopped')); }); options.onEvent({ event: 'progress', step: 'Downloading the picture files…', done: 1, total: 9 }); }) });
222  try {
223    await f.native.refresh(true);
224    const id = loadOp(f, { vision: 'yes' }).id;
225    await until(() => f.native.state().jobs.find(j => j.id === id)?.summary.startsWith('Downloading the picture files'), 'the download');
226    await f.native.cancel(id);
227    await until(() => aborted, 'the abort');
228    const job = f.native.state().jobs.find(j => j.id === id);
229    assert.equal(job.state, 'cancelled');
230    await new Promise(r => setTimeout(r, 50));
231    assert.equal(f.saved.length, 0, 'no engine was started');
232    assert.equal(f.native.state().instances.length, 0);
233  } finally { await f.native.close(); f.cleanup(); }
234});
235
236test('nothing is downloaded unless the Load asked for pictures, and never for a model whose files are all there', async () => {
237  // a restart or a tuning run passes no picture choice
238  let f = fixture();
239  try {
240    await f.native.refresh(true);
241    assert.equal((await finish(f.native, loadOp(f, {}).id)).state, 'done');
242    assert.equal(f.fetches().length, 0);
243    assert.equal(f.saved[0].vision, undefined);
244  } finally { await f.native.close(); f.cleanup(); }
245  // Read pictures off
246  f = fixture();
247  try { await f.native.refresh(true); assert.equal((await finish(f.native, loadOp(f, { vision: 'no' }).id)).state, 'done'); assert.equal(f.fetches().length, 0); } finally { await f.native.close(); f.cleanup(); }
248  // prepared, the file is there
249  f = fixture({ vision: true, mmprojFile: true });
250  try { await f.native.refresh(true); assert.equal((await finish(f.native, loadOp(f, { vision: 'yes' }).id)).state, 'done'); assert.equal(f.fetches().length, 0); assert.ok(f.saved[0].vision); } finally { await f.native.close(); f.cleanup(); }
251  // a DeepSeek model of an earlier Strata (Control: retired): the load stops with Control's own words, fetches nothing and writes nothing
252  f = fixture({ arch: 'deepseek41' });
253  try {
254    const m = (await f.native.refresh(true)).installed.models[0];
255    assert.deepEqual(m.retired, { line: 'DeepSeek - no longer supported.', refusal: 'DeepSeek-V4.1-Flash ISTA-DAS 2.00 bpw is a DeepSeek model. This version of Strata no longer runs DeepSeek models, so it was not started. Choose a Qwen model to run instead. If you no longer need the DeepSeek files, you can delete that folder to free the space.' });
256    assert.equal(m.ready, false);
257    const job = await finish(f.native, loadOp(f, { vision: 'yes' }).id);
258    assert.equal(job.state, 'error');
259    assert.match(String(job.error), /is a DeepSeek model\. This version of Strata no longer runs DeepSeek models, so it was not started\./);
260    assert.equal(f.fetches().length, 0);
261    assert.equal(f.saved.length, 0, 'no profile is saved');
262  } finally { await f.native.close(); f.cleanup(); }
263});
264
265test('the picture file was deleted after the model was prepared: the model is not "missing files"; Load fetches it again, a restart goes on without pictures', async () => {
266  let f = fixture({ vision: true });
267  try {
268    const m = (await f.native.refresh(true)).installed.models[0];
269    assert.equal(m.ready, true, 'only a picture file is gone');
270    assert.equal(m.picturesMissing, true);
271    assert.equal(m.visionPrepared, false);
272    assert.equal(m.images, 'off');
273    const job = await finish(f.native, loadOp(f, { vision: 'yes' }).id);
274    assert.equal(job.state, 'done', job.error);
275    assert.equal(f.fetches().length, 1);
276    assert.equal(f.native.state().installed.models[0].picturesMissing, false, 'the file is back');
277  } finally { await f.native.close(); f.cleanup(); }
278  f = fixture({ vision: true });
279  try {
280    await f.native.refresh(true);
281    const job = await finish(f.native, loadOp(f, {}).id);   // no choice passed: never downloads
282    assert.equal(job.state, 'done', job.error);
283    assert.equal(f.fetches().length, 0);
284    assert.equal(f.saved[0].vision, undefined, 'the reader is not started on a file that is not there');
285    assert.equal(f.native.state().instances[0].picturesNote, 'The picture files are missing, so the model is loaded without picture reading.');
286  } finally { await f.native.close(); f.cleanup(); }
287});
288
289test('"Download picture-reading files" fetches the files without loading the model', async () => {
290  const f = fixture();
291  try {
292    await f.native.refresh(true);
293    const job = await finish(f.native, f.native.operation('pictures', { model: 'iq3_s', vision: 'yes' }).id);
294    assert.equal(job.state, 'done', job.error);
295    assert.equal(job.summary, 'The picture files are ready.');
296    assert.equal(f.fetches().length, 1);
297    assert.equal(f.saved.length, 0, 'no engine');
298    assert.equal(f.installs().length, 0);
299    assert.ok(f.config().vision?.mmproj);
300    assert.equal(f.native.state().installed.models[0].visionPrepared, true);
301    // a second press has nothing to do
302    const again = await finish(f.native, f.native.operation('pictures', { model: 'iq3_s', vision: 'yes' }).id);
303    assert.equal(again.state, 'done');
304    assert.equal(f.fetches().length, 1);
305  } finally { await f.native.close(); f.cleanup(); }
306  // offline: the button says it, plainly
307  const g = fixture({ onFetch: async () => { throw Object.assign(new ControlError("There is no internet connection, so the picture files can't be downloaded now."), { code: 'offline' }); } });
308  try {
309    await g.native.refresh(true);
310    const job = await finish(g.native, g.native.operation('pictures', { model: 'iq3_s', vision: 'yes' }).id);
311    assert.equal(job.state, 'error');
312    assert.equal(job.error, "There is no internet connection, so the picture files can't be downloaded now.");
313    assert.equal(g.config().vision, undefined);
314  } finally { await g.native.close(); g.cleanup(); }
315});
316
317test('an installed model is prepared again in ITS data folder, never in the models folder, and the settings are not touched', async () => {
318  for (const layout of ['own', 'normal', 'local']) {
319    const f = fixture({ layout });
320    try {
321      await f.native.refresh(true);
322      const before = f.settings();
323      await f.native.plan({ family: 'qwen', model: 'IQ3_S', context: 32768, vision: 'yes', kv: 'int8' });
324      const [call] = f.installs();
325      assert.equal(call.arguments.data_dir, f.dataFolder, `${layout}: the folder with the pack and the draft layer`);
326      assert.notEqual(call.arguments.data_dir, f.modelsDir);
327      assert.equal(call.arguments.confirm, false, 'a plan only');
328      if (layout !== 'normal') assert.equal(call.arguments.gguf_dir, f.modelFolder, `${layout}: its own files folder`);
329      assert.equal(f.settings(), before, `${layout}: data_dir in the settings is not rewritten by looking at a plan`);
330      // and the real thing, with the model's own folder again
331      const job = await finish(f.native, f.native.operation('install', { family: 'qwen', model: 'IQ3_S', context: 32768, vision: 'yes', kv: 'int8' }).id);
332      assert.ok(['running', 'done', 'error', 'cancelled'].includes(job.state));
333      const real = f.installs().filter(p => p.arguments.confirm === true);
334      assert.equal(real[0].arguments.data_dir, f.dataFolder, layout);
335      assert.equal(f.settings(), before, `${layout}: the install did not move data_dir either`);
336    } finally { await f.native.close(); f.cleanup(); }
337  }
338});
339
340test('a model added with "Use a local GGUF" keeps its folder when the person later picks another downloads folder', async () => {
341  const f = fixture({ layout: 'local' });
342  try {
343    await f.native.refresh(true);
344    const elsewhere = join(f.root, 'elsewhere', 'Strata-data');
345    mkdirSync(elsewhere, { recursive: true });
346    f.native.setDownloadDirectory(elsewhere);
347    const chosen = f.settings();
348    assert.match(chosen, /elsewhere/, 'the person\'s choice is saved');
349    await f.native.plan({ family: 'qwen', model: 'IQ3_S', context: 32768, vision: 'yes', kv: 'int8' });
350    assert.equal(f.installs()[0].arguments.data_dir, f.dataFolder, 'the model\'s own pack and draft layer are not prepared again in the new folder');
351    assert.equal(f.settings(), chosen, 'and the choice is not changed by the model');
352    // a Load fetches the picture file next to the model\'s pack
353    const job = await finish(f.native, loadOp(f, { vision: 'yes' }).id);
354    assert.equal(job.state, 'done', job.error);
355    assert.equal(f.fetches()[0].dataDir, f.dataFolder);
356    assert.equal(existsSync(join(elsewhere, 'packs')), false);
357  } finally { await f.native.close(); f.cleanup(); }
358});
359
360test('a model that is not installed yet still goes to the person\'s chosen folder, and that choice is remembered as before', async () => {
361  const f = fixture();
362  try {
363    await f.native.refresh(true);
364    await f.native.plan({ family: 'qwen', model: 'Q2_0', context: 32768, vision: 'yes', kv: 'int8' });   // not in the catalog fixture: no installed model matches
365    const call = f.installs()[0];
366    assert.equal(call.arguments.data_dir, f.modelsDir, 'the app\'s models folder is the data folder of a new download');
367    assert.match(f.settings(), /models/, 'the chosen folder is written for the installer, as before');
368  } finally { await f.native.close(); f.cleanup(); }
369});
370
371// ---------------------------------------------------------------------------------------------- the Models page
372
373const read = rel => readFileSync(new URL(rel, import.meta.url), 'utf8');
374
375test('the Models page sends a plain Load, not the installer, when the only gap is the picture files', async () => {
376  const { build } = await import('esbuild');
377  const built = await build({ stdin: { contents: "export * from './src/lib/native-catalog';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } });
378  const { fetchesPictures, PICTURE_FETCH_FAMILIES } = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`);
379  for (const family of ['qwen', 'coder', 'unsloth', 'gyro', 'swift']) assert.equal(fetchesPictures({ sourceFamily: family }, true), true, family);
380  for (const family of ['nvfp4', 'qwen36', undefined]) assert.equal(fetchesPictures({ sourceFamily: family }, true), false, `${family} keeps the installer`);
381  assert.equal(fetchesPictures({ sourceFamily: 'qwen' }, false), false, 'a source checkout has no Control to fetch them');
382  assert.equal(fetchesPictures({ sourceFamily: 'qwen' }, undefined), false);
383  assert.equal(fetchesPictures(undefined, true), false);
384  assert.deepEqual(PICTURE_FETCH_FAMILIES.slice().sort(), ['coder', 'gyro', 'qwen', 'swift', 'unsloth']);
385  const screen = read('../src/components/NativeModels.tsx');
386  assert.match(screen, /const picturesByLoad = fetchesPictures\(selectedSize, native\?\.packaged\)/);
387  assert.match(screen, /\(!selectedSize\?\.images \|\| vision === 'no' \|\| picturesByLoad \|\| installed\.images && installed\.images !== 'off'\)/, 'the shortcut to a plain Load no longer needs the pictures to be prepared');
388  assert.match(screen, /loadedSelected\?\.picturesNote \? <p className="small muted native-vision-note" role="status">/, 'a failed picture download keeps one clear line under the checkbox');
389  assert.doesNotMatch(screen, /Download picture-reading files|Picture reading needs a few more files/, 'GUI-FB2 item 1: no button and no offer sentence: Load model does it');
390  assert.doesNotMatch(screen, /kind: 'pictures'/, 'the page no longer posts the picture-only step');
391  assert.match(screen, /job\.kind === 'pictures'\) \{[\s\S]*Load the model again to read pictures\./, 'a model that is loaded without pictures is told to load again');
392  // the host side of the same promise: the install path no longer takes its data folder from the app's models folder for an installed model
393  const host = read('../server/native-control.mjs');
394  assert.match(host, /const own=args\.data_dir===undefined\?existing\?\.runDataFolder:undefined;const data=own\?\?nativeDataDirectory\(/);
395  assert.match(host, /if\(data&&packaged&&!args\.data_dir&&!own\)rememberDataFolder\(/, 'a model\'s own folder is never written to the settings');
396});
397
398test('every sentence the Load of the picture files can say is in the catalog in all nine languages', async () => {
399  const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr'];
400  const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(read(`../src/locales/pic-${l}.json`))]));
401  const english = Object.values(catalogs.en);
402  const host = read('../server/native-control.mjs');
403  const words = host.slice(host.indexOf('const PICTURES_WORDS={'), host.indexOf('const PLAIN_PICTURE_CODES'));
404  const hostSentences = [...words.matchAll(/:'([^']+)'/g)].map(m => m[1]);
405  assert.equal(hostSentences.length, 7, 'download, check, loading, offline, disk, failed, gone');
406  // the sentences Control's pictures module gives the page's button (strata_control/pictures.py WORDS, with the "Try again" the module adds)
407  const python = ["There is no internet connection, so the picture files can't be downloaded now.", 'There is not enough free disk space for the picture files (about 1 GB).',
408    'The picture files could not be downloaded. Try again; it continues where it stopped.', 'The downloaded picture files did not pass the safety check, so they were deleted. Try again.',
409    'The picture files could not be downloaded. Try again.'];
410  for (const sentence of [...hostSentences, ...python, 'Downloading the picture files', 'The picture files are ready.', 'Picture files ready', 'Load the model again to read pictures.', 'Picture reading is ready.', 'Loading the model…']) {
411    if (sentence === 'Loading the model…') continue;   // already in the Drafting catalog
412    assert.ok(english.includes(sentence), `in the catalog: ${sentence}`);
413  }
414  const source = read('../../../strata_control/pictures.py');
415  for (const sentence of python.slice(0, 2)) assert.ok(source.includes(sentence.replace(' Try again; it continues where it stopped.', '')), `the module says: ${sentence}`);
416  const slots = t => (t.match(/\{\d+\}/g) ?? []).sort().join();
417  for (const [id, text] of Object.entries(catalogs.en)) for (const l of langs) {
418    const t = catalogs[l][id];
419    assert.ok(typeof t === 'string' && t.trim(), `${id} in ${l}`);
420    assert.equal(slots(t), slots(text), `${id} slots in ${l}`);
421    if (l !== 'en' && text.length > 25) assert.notEqual(t, text, `${id} is translated in ${l}`);
422  }
423});