okami.mom/strata

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

Niko1221app install: with no engine on the PC yet, the engine comes before setup, so pictures stay on (0.2.15 release test)2a3e33b8e

main
53.2 KiB775 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 } from 'node:fs';
6import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync, realpathSync } from 'node:fs';
7import { join, basename } from 'node:path';
8import { tmpdir as osTmpdir } from 'node:os';
9// 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
10const tmpdir = () => realpathSync(osTmpdir());
11import { bundledPython, componentsDirectory, controlEnvironment, createControl, findControl, runCli } from '../server/control-runtime.mjs';
12import { resolvePython } from '../server/python-resolver.mjs';
13import { createNativeControl } from '../server/native-control.mjs';
14
15const isWin = process.platform === 'win32';
16
17function fakeControlDir() {
18  const dir = mkdtempSync(join(tmpdir(), 'strata-control-dir-'));
19  mkdirSync(join(dir, 'python', ...(isWin ? [] : ['bin'])), { recursive: true });
20  mkdirSync(join(dir, 'strata_control'), { recursive: true });
21  mkdirSync(join(dir, 'serve'), { recursive: true });
22  writeFileSync(bundledPython(dir), 'x');
23  writeFileSync(join(dir, 'strata.py'), '# cli');
24  writeFileSync(join(dir, 'serve', 'server.py'), 'port\nparallel\n/v1/responses');
25  writeFileSync(join(dir, 'BUNDLE.json'), JSON.stringify({ version: '0.1.45', python: '3.12.15' }));
26  return dir;
27}
28
29test('the Control component is found by STRATA_CONTROL_DIR or beside the host, and only if it is whole', () => {
30  const dir = fakeControlDir();
31  // The explicit env has no STRATA_COMPONENTS_DIR, so findControl would look in the real per-user components folder and find an updated Control installed on this PC.
32  const none = join(dir, 'no-components');
33  try {
34    const found = findControl({ env: { STRATA_CONTROL_DIR: dir }, hostDir: join(dir, 'nowhere'), components: none });
35    assert.equal(found.dir, dir);
36    assert.equal(found.python, bundledPython(dir));
37    assert.equal(found.bundle.python, '3.12.15');
38    // beside the host: <install>/host + <install>/control
39    const install = mkdtempSync(join(tmpdir(), 'strata-install-'));
40    try {
41      mkdirSync(join(install, 'host', 'server'), { recursive: true });
42      assert.equal(findControl({ env: {}, hostDir: join(install, 'host'), components: none }), null, 'nothing beside the host yet');
43      mkdirSync(join(install, 'control', 'python', ...(isWin ? [] : ['bin'])), { recursive: true });
44      mkdirSync(join(install, 'control', 'strata_control'));
45      writeFileSync(bundledPython(join(install, 'control')), 'x');
46      writeFileSync(join(install, 'control', 'strata.py'), '#');
47      assert.equal(findControl({ env: {}, hostDir: join(install, 'host'), components: none }).dir, join(install, 'control'));
48    } finally { rmSync(install, { recursive: true, force: true }); }
49    rmSync(join(dir, 'strata.py'));
50    assert.equal(findControl({ env: { STRATA_CONTROL_DIR: dir }, hostDir: join(dir, 'x'), components: none }), null, 'a half component is not used');
51  } finally { rmSync(dir, { recursive: true, force: true }); }
52});
53
54test("Control runs on its own interpreter with nothing from the user's Python and acquiring forbidden", () => {
55  const control = { dir: '/c', python: '/c/python/python3', cli: '/c/strata.py' };
56  const env = controlEnvironment(control, { env: { PYTHONHOME: 'x', PYTHONPATH: 'y', VIRTUAL_ENV: 'z', STRATA_PYTHON: 'q', PATH: 'p', STRATA_API_KEY: 'secret' }, components: '/components' });
57  assert.equal(env.PYTHONHOME, undefined);
58  assert.equal(env.PYTHONPATH, undefined);
59  assert.equal(env.VIRTUAL_ENV, undefined);
60  assert.equal(env.STRATA_PYTHON, undefined);
61  assert.equal(env.PYTHONNOUSERSITE, '1');
62  assert.equal(env.STRATA_NO_ACQUIRE, '1');
63  assert.equal(env.STRATA_COMPONENTS_DIR, '/components');
64  assert.equal(env.STRATA_API_KEY, undefined, 'an inherited inference key never reaches the engine (the run config carries its own)');
65  assert.equal(env.PATH, 'p');
66  // the resolver prefers the bundled interpreter over py -3 / PATH / a venv
67  const python = resolvePython({ repo: '/repo', control, env: {}, exists: () => true, starts: () => { throw new Error('must not probe'); }, useCache: false });
68  assert.deepEqual([python.command, python.source], ['/c/python/python3', 'bundled']);
69  assert.equal(resolvePython({ control, env: { STRATA_PYTHON: '/mine' }, useCache: false }).command, '/mine', 'an explicit choice still wins');
70  assert.equal(componentsDirectory({ env: { STRATA_COMPONENTS_DIR: '/x' } }), '/x');
71  assert.match(componentsDirectory({ env: { LOCALAPPDATA: 'C:\\L' }, platform: 'win32', home: 'C:\\H' }), /Strata[\\/]components$/);
72});
73
74test('runCli passes the arguments untouched (no shell) and reads JSON', async () => {
75  const seen = [];
76  const spawnProcess = (command, args, options) => {
77    seen.push({ command, args, options });
78    const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.kill = () => {};
79    queueMicrotask(() => { child.stdout.emit('data', '{"ok": true, "n": 1}\n'); child.emit('close', 0); });
80    return child;
81  };
82  const control = { dir: '/c', python: '/c/python/python3', cli: '/c/strata.py' };
83  const result = await runCli(control, ['models', 'list', '--installed', '--output', 'json'], { spawnProcess, env: {} });
84  assert.deepEqual(result.json, { ok: true, n: 1 });
85  assert.deepEqual(seen[0].args, ['/c/strata.py', 'models', 'list', '--installed', '--output', 'json']);
86  assert.equal(seen[0].options.shell, undefined);
87  assert.equal(seen[0].options.windowsHide, true);
88  assert.equal(seen[0].options.env.STRATA_NO_ACQUIRE, '1');
89});
90
91// ---------------------------------------------------------------------------------- native-control in packaged mode
92
93function packagedFixture({ engineUsable = true, updater = null, repair = false, ids = ['iq2_xs', 'iq3_s'], controlVersion = '0.1.45', extraSizes = [], cliStartWait = 'old', installPoll = null } = {}) {
94  const root = mkdtempSync(join(tmpdir(), 'strata-packaged-test-'));
95  const install = join(root, 'install'), data = join(root, 'data');
96  mkdirSync(install, { recursive: true });
97  /* The Control this app found, as it is on disk. The app reads the start-wait ceiling out of these files instead of trusting
98     the version, because a start wait is checked three times before the engine is reached and a released Control has those
99     three ceilings disagreeing:
100       'old'        no runtime ceiling at all, both gates 600 (Control before #3949)
101       'split'      the runtime takes 1800, the CLI and the record still stop at 600 (every Control 0.1.50 to 0.1.52)
102       'cli-only'   the CLI follows the runtime, the record still stops at 600 (`direct runtime intent has an invalid timeout`)
103       'runtime'    all three hand the wait to the runtime's own ceiling */
104  const controlSource = join(root, 'control', 'strata_control');
105  mkdirSync(controlSource, { recursive: true });
106  writeFileSync(join(controlSource, 'runtime.py'), cliStartWait === 'old' ? '' : 'MAX_START_WAIT = 1800\n');
107  writeFileSync(join(controlSource, 'management.py'), ['cli-only', 'runtime'].includes(cliStartWait)
108    ? '        wait = _seconds(wait, 0, runtime.MAX_START_WAIT, "start wait")\n'
109    : '        wait = _seconds(wait, 0, 600, "start wait")\n');
110  writeFileSync(join(controlSource, 'journal.py'), cliStartWait === 'runtime'
111    ? '        ranges = {"wait_s": (0, start_wait_max) if kind == "runtime.start" else\n'
112    : '        ranges = {"wait_s": (0, 600) if kind == "runtime.start" else\n');
113  const earlierInstallEnv = process.env.STRATA_INSTALL_DIR;
114  process.env.STRATA_INSTALL_DIR = install;      // the app's own install folder (the host always tells Control which one; it never falls back to an older CLI folder)
115  const configs = ids.map(id => {
116    const path = join(install, `strata-${id}.json`);
117    writeFileSync(path, JSON.stringify({ exe: 'component:strata-engine', tokenizer: join(install, 'tok'), args: ['--max-context', '32768'], model_name: `Qwen ${id}`, port: 8080 }));
118    return { id, path };
119  });
120  const calls = [];
121  const saved = [];
122  const spawned = [];
123  const rpc = [];
124  let startFailure = null, startFailureLeft = Infinity;
125  let statusAnswer = { state: 'ready' }, metricsDown = false, healthDown = false;
126  const control = {
127    control: { dir: join(root, 'control'), python: join(root, 'control', 'python', 'python.exe') }, version: controlVersion,
128    async installedModels(options) { calls.push(['installedModels', options?.installDir ?? null]); return { install_dir: install, models: configs.map(c => ({ id: c.id, name: `Qwen ${c.id}`, source_config: c.path, component_status: 'present', context_tokens: 32768, backend: 'cuda', ...(/^deepseek/.test(c.id) ? { component_status: 'retired', retired: 'deepseek', name: 'DeepSeek-V4.1-Flash ISTA-DAS 2.00 bpw', 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.' } : {}) })) }; },
129    async engine() {
130      calls.push(['engine']);
131      return engineUsable
132        ? { usable: true, backend: 'cuda', components_dir: 'E:\\c', engine: { version: '0.1.45', platform: 'windows-x86_64', backend: 'cuda', exe: 'E:\\engine\\strata.exe', root: 'E:\\engine' } }
133        : { usable: false, notice: 'No engine for this PC was found in E:\\c: the component folder holds no engine package. The app never downloads an engine while it starts or serves.', backend: 'cuda', engine: null, components_dir: 'E:\\c' };
134    },
135    async importPlan(path) { calls.push(['importPlan', path]); return { file_set_status: 'plausible', candidate_selection: { family: 'qwen', model: 'IQ3_S' }, file_count: 2, total_bytes: 1e9, issues: [] }; },
136    async saveProfile(name, path) { calls.push(['saveProfile', name, basename(path)]); saved.push(JSON.parse(readFileSync(path, 'utf8'))); return {}; },
137    async start(name, options) { calls.push(['start', name, options?.waitSeconds]); if (startFailure && startFailureLeft-- > 0) { const e = new Error(startFailure.message); e.output = startFailure.output; throw e; } return { ok: true, state: 'ready' }; },
138    async stop(name) { calls.push(['stop', name]); return { ok: true, state: 'stopped' }; },
139    async status(name) { calls.push(['status', name]); return typeof statusAnswer === 'function' ? statusAnswer(name) : statusAnswer; },
140    ...(repair ? { async repairAccess() { calls.push(['repairAccess']); return { ok: true }; } } : {}),
141    ...(updater ? { async updateCheck() { calls.push(['updateCheck']); return updater.report; }, async update(options) { calls.push(['update', options.engine, options.control]); return updater.update(options); } } : {}),
142  };
143  const requests = [];
144  const fetcher = async url => {
145    calls.push(['fetch', url.replace(/:\d+/, ':PORT')]);
146    if (metricsDown && /\/(metrics|mcp)/.test(url)) throw new Error('the engine does not answer');
147    if (healthDown && /\/health/.test(url)) throw new Error('the engine does not answer');
148    return Response.json({ status: 'ok' });
149  };
150  // The only process the host may start is Control's installer (its bundled tools/strata_mcp.py on Control's Python); the fake
151  // answers like it: the catalog, the hardware with the GPUs, and an install plan or job.
152  const catalog = { families: [{ family: 'qwen', title: 'Qwen3.8-Flash-Next', about: 'x', images: true, experimental: false, sizes: [
153    { id: 'q2_0', model: 'Q2_0', download_gb: 66.4, ram_needed_gb: 48, about: 'fast', on_this_pc: 'fits', installed: false, images: true, experimental: false },
154    { id: 'iq3_xxs', model: 'IQ3_XXS', download_gb: 75.8, ram_needed_gb: 60, about: 'balanced', on_this_pc: 'fits', installed: false, images: true, experimental: false }, ...extraSizes] }],
155    contexts: [8192, 32768], recommendation: { family: 'qwen', model: 'IQ3_XXS', context: 32768 }, context_note: '' };
156  const hardware = { ram_gb: 63, cpu: { name: 'cpu', cores: 12 }, gpus: [{ index: 0, name: 'NVIDIA GeForce RTX 5070', vram_gb: 11.9, usable: true }] };
157  let installJob = null;
158  const spawnProcess = (command, args, options) => {
159    spawned.push({ command, args, options });
160    if (!String(args[0]).endsWith('strata_mcp.py')) throw new Error('no process but the installer may be started by the host in packaged mode: ' + command + ' ' + args.join(' '));
161    const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.exitCode = null;
162    child.kill = () => { child.exitCode = 0; queueMicrotask(() => child.emit('exit', 0)); return true; };
163    child.stdin = { write(line) {
164      const message = JSON.parse(line); if (!message.id) return;
165      if (message.method === 'tools/call') rpc.push(message.params);
166      let result;
167      if (message.method === 'initialize') result = { protocolVersion: '2024-11-05' };
168      else if (message.method === 'tools/list') result = { tools: ['strata_models', 'strata_status', 'strata_install', 'strata_remove'].map(name => ({ name })) };
169      else if (message.params.name === 'strata_models') result = { structuredContent: catalog };
170      else if (message.params.name === 'strata_remove') result = { structuredContent: { summary: 'Deleted', plan: { gb: 1.2 }, failed: [] } };
171      else if (message.params.name === 'strata_status') result = { structuredContent: { hardware, recommendation: catalog.recommendation, install: installJob, running: [], summary: 'x' } };
172      else if (message.params.arguments?.confirm) { installJob = { running: false, exit_code: 0 }; result = { structuredContent: { summary: 'Install started', plan: { download_gb: 66.4 }, install: { running: true, step: 'downloading' } } }; }
173      else if (message.params.arguments?.cancel === undefined && message.params.arguments?.confirm === undefined) result = { structuredContent: installPoll ?? { summary: 'Install finished', install: { running: false, exit_code: 0 } } };
174      else result = { structuredContent: { summary: 'Plan', plan: { title: 'Qwen3.8-Flash-Next Q2_0', download_gb: 66.4, disk_short: null } } };
175      queueMicrotask(() => child.stdout.emit('data', Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + String.fromCharCode(10))));
176    } };
177    return child;
178  };
179  const native = createNativeControl({ control, directory: data, spawnProcess, fetcher, requests: () => requests });
180  const others = () => spawned.filter(s => !String(s.args[0]).endsWith('strata_mcp.py'));
181  return { native, calls, saved, spawned, others, rpc, setStatus: v => { statusAnswer = v; }, setMetricsDown: v => { metricsDown = v; }, setHealthDown: v => { healthDown = v; }, failStart: (v, times = Infinity) => { startFailure = v; startFailureLeft = times; }, catalog, hardware, install, root, cleanup: () => { if (earlierInstallEnv === undefined) delete process.env.STRATA_INSTALL_DIR; else process.env.STRATA_INSTALL_DIR = earlierInstallEnv; rmSync(root, { recursive: true, force: true }); } };
182}
183const 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'); };
184
185test('packaged: models come from Control, no python, git or engine process is started by the host', async () => {
186  const f = packagedFixture();
187  try {
188    const state = await f.native.refresh(true);
189    assert.equal(state.available, true, state.error);
190    assert.deepEqual(state.installed.models.map(m => m.model), ['iq2_xs', 'iq3_s']);
191    assert.equal(state.installed.models[0].ready, true);
192    assert.equal(state.packaged, true);
193    assert.match(state.summary, /engine 0\.1\.45/);
194    assert.equal(state.version, '0.1.45');
195    assert.equal(f.others().length, 0, 'nothing but the installer is started');
196    // the catalog, the GPUs and the recommendation come from the bundled installer, run on Control's own Python
197    assert.equal(state.catalog.families[0].sizes.length, 2);
198    assert.equal(state.catalog.recommendation.model, 'IQ3_XXS');
199    assert.equal(state.hardware.gpus[0].name, 'NVIDIA GeForce RTX 5070');
200    assert.equal(state.hardware.ram_gb, 63);
201    const installer = f.spawned[0];
202    assert.equal(installer.command, join(f.root, 'control', 'python', 'python.exe'));
203    assert.deepEqual(installer.args.slice(1), ['--root', f.install, '--src', join(f.root, 'control')]);
204    assert.equal(installer.options.env.STRATA_CONTROL_INSTALL, '1');
205    assert.equal(installer.options.env.STRATA_NO_ACQUIRE, '1', 'the installer process itself may not acquire; only its explicit install job does');
206    assert.equal(installer.options.env.STRATA_INSTALL_DIR, f.install);
207    assert.equal(installer.options.env.PYTHONNOUSERSITE, '1');
208  } finally { await f.native.close(); f.cleanup(); }
209});
210
211test('packaged: load = saved profile + runtime start under Control; unload = runtime stop; two models get two profiles', async () => {
212  const f = packagedFixture();
213  try {
214    await f.native.refresh(true);
215    const load = async args => { const job = await finish(f.native, f.native.operation('load', args).id); assert.equal(job.state, 'done', job.error); return job; };
216    await load({ model: 'iq2_xs' });
217    const first = f.native.state().instances[0];
218    assert.equal(first.status, 'ready');
219    const startCalls = f.calls.filter(c => ['saveProfile', 'start'].includes(c[0]));
220    assert.deepEqual(startCalls.map(c => c.slice(0, 2)), [['saveProfile', 'app-1'], ['start', 'app-1']]);
221    assert.equal(startCalls[1][2], 300);
222    await load({ model: 'iq3_s', multiple: true });
223    assert.deepEqual(f.calls.filter(c => c[0] === 'start').map(c => c[1]), ['app-1', 'app-2']);
224    assert.equal(f.native.state().instances.length, 2);
225    await f.native.unload(first.id);
226    assert.deepEqual(f.calls.filter(c => c[0] === 'stop').at(-1), ['stop', 'app-1']);
227    assert.equal(f.native.state().instances.length, 1);
228    assert.equal(f.others().length, 0, 'the host never spawned anything itself');
229  } finally { await f.native.close(); f.cleanup(); }
230});
231
232test('packaged: a DeepSeek model of an earlier Strata (an id with dots) is listed with its one line; its load is refused with Control\'s words and starts nothing', async () => {
233  const id = 'deepseek-v4.1-flash-ist-das-2.00bpw';
234  const f = packagedFixture({ ids: [id] });
235  try {
236    const path = join(f.install, `strata-${id}.json`);
237    writeFileSync(path, JSON.stringify({ exe: join(f.install, 'engine-dsv41', 'strata-dsv41'), arch: 'deepseek41', tokenizer: join(f.install, 'tok'), args: ['--pack', join(f.install, 'pack'), '--max-context', '8192', '--eos', '1'], model_name: 'deepseek-v4.1-flash', port: 8080, engine_ready_s: 3600 }));
238    const before = readFileSync(path, 'utf8');
239    const state = await f.native.refresh(true);
240    assert.deepEqual(state.installed.models.map(m => m.model), [id], 'listed');
241    assert.equal(state.installed.models[0].ready, false);
242    assert.equal(state.installed.models[0].retired.line, 'DeepSeek - no longer supported.');
243    const job = await finish(f.native, f.native.operation('load', { model: id }).id);
244    assert.equal(job.state, 'error');
245    assert.match(String(job.error), /^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\./);
246    assert.deepEqual(f.calls.filter(c => ['saveProfile', 'start'].includes(c[0])), [], 'nothing is saved or started');
247    assert.equal(readFileSync(path, 'utf8'), before, 'its settings file is not written');
248    for (const odd of ['a..b', '../x', 'x/y', '.hidden']) assert.equal((await finish(f.native, f.native.operation('load', { model: odd }).id)).state, 'error', odd);
249  } finally { await f.native.close(); f.cleanup(); }
250});
251
252test('packaged: no engine for this PC is the notice, and nothing is started', async () => {
253  const f = packagedFixture({ engineUsable: false });
254  try {
255    await f.native.refresh(true);
256    const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
257    assert.equal(job.state, 'error');
258    assert.match(job.error, /No engine for this PC/);
259    assert.match(job.error, /never downloads an engine/);
260    assert.equal(f.calls.some(c => ['saveProfile', 'start'].includes(c[0])), false);
261    assert.equal(f.others().length, 0);
262  } finally { await f.native.close(); f.cleanup(); }
263});
264
265test('packaged: the user can download and prepare a model: the plan and the install job go to the bundled installer, the engine is not touched', async () => {
266  const f = packagedFixture();
267  try {
268    await f.native.refresh(true);
269    const plan = await f.native.plan({ family: 'qwen', model: 'Q2_0' });
270    assert.equal(plan.plan.title, 'Qwen3.8-Flash-Next Q2_0');
271    const planned = f.rpc.at(-1);
272    assert.equal(planned.name, 'strata_install');
273    assert.equal(planned.arguments.confirm, false, 'a plan changes nothing');
274    const job = await finish(f.native, f.native.operation('install', { family: 'qwen', model: 'Q2_0' }).id);
275    assert.equal(job.state, 'done', job.error);
276    const started = f.rpc.filter(c => c.name === 'strata_install' && c.arguments.confirm);
277    assert.equal(started.length, 1);
278    assert.equal(started[0].arguments.family, 'qwen');
279    assert.equal(started[0].arguments.model, 'Q2_0');
280    assert.equal(f.others().length, 0, 'the host starts no pip, git, python of its own or engine');
281    assert.equal(f.calls.filter(c => ['saveProfile', 'start'].includes(c[0])).length, 0, 'installing does not start an engine');
282  } finally { await f.native.close(); f.cleanup(); }
283});
284
285test('packaged: the installer works in a folder the app can write, never in the read-only bundle', async () => {
286  const f = packagedFixture();
287  try {
288    await f.native.refresh(true);
289    assert.equal(existsSync(f.install), true);
290    assert.notEqual(f.native.state().installDir, join(f.root, 'control'));
291    assert.equal(f.spawned[0].args.at(-3), f.install);
292  } finally { await f.native.close(); f.cleanup(); }
293});
294
295test('packaged: update, rollback and calibration are refused with the Terminal notice and start nothing', async () => {
296  const f = packagedFixture();
297  try {
298    await f.native.refresh(true);
299    for (const [kind, args] of [['update-engine', {}], ['update-strata', {}], ['rollback', {}], ['calibrate', { model: 'iq3_s' }]]) {
300      const job = await finish(f.native, f.native.operation(kind, args).id);
301      assert.equal(job.state, 'error', kind);
302      assert.match(job.error, /Terminal|calibrates NVIDIA|No saved previous engine/, `${kind}: ${job.error}`);
303    }
304    assert.equal(f.others().length, 0);
305    assert.equal(f.calls.filter(c => ['saveProfile', 'start'].includes(c[0])).length, 0);
306  } finally { await f.native.close(); f.cleanup(); }
307});
308
309test('packaged: the install folder can be chosen, and it is what Control is asked about', async () => {
310  const f = packagedFixture();
311  try {
312    const other = join(f.root, 'other');
313    mkdirSync(other);
314    await f.native.configure({ repository: other });
315    const saved = JSON.parse(readFileSync(join(f.root, 'data', 'native-host.json'), 'utf8'));
316    assert.equal(saved.installDir.toLowerCase(), other.toLowerCase());
317    assert.equal(f.calls.filter(c => c[0] === 'installedModels').at(-1)[1].toLowerCase(), other.toLowerCase());
318  } finally { await f.native.close(); f.cleanup(); }
319});
320
321test('createControl asks the CLI for the engine, models and runtime and reads the notice of a missing engine', async () => {
322  const seen = [];
323  const control = createControl({
324    control: { dir: '/c', python: '/p', cli: '/c/strata.py', bundle: { version: '9' } },
325    run: async args => { seen.push(args.join(' ')); return args[0] === 'components' ? { code: 5, json: { ok: false, usable: false, notice: 'No engine for this PC' }, text: '', stderr: '' } : { code: 0, json: { ok: true, profiles: [] }, text: '', stderr: '' }; },
326  });
327  assert.equal((await control.engine()).notice, 'No engine for this PC');
328  await control.installedModels({ installDir: 'D:\\Strata' });
329  await control.saveProfile('app-1', 'C:\\x.json');
330  await control.start('app-1');
331  await control.stop('app-1');
332  assert.deepEqual(seen, [
333    'components engine --output json',
334    'models list --installed --install-dir D:\\Strata --output json',
335    'profile list --output json',
336    'profile create app-1 --from-config C:\\x.json --output json',
337    `runtime start --profile app-1 --wait 300 --shutdown-timeout 15 --die-with-pid ${process.pid} --output json`,
338    'runtime stop --profile app-1 --wait 120 --output json',
339  ]);
340  assert.equal(createControl({ control: null }), null);
341});
342
343test('packaged: the catalog offers no picture reading, an install asks for none by default and for it only when Read pictures was ticked', async () => {
344  const f = packagedFixture();
345  try {
346    const state = await f.native.refresh(true);
347    assert.ok(state.catalog.families[0].sizes.every(s => s.images === false));
348    assert.ok(state.catalog.families.every(fam => fam.images === false));
349    await f.native.plan({ family: 'qwen', model: 'Q2_0' });
350    assert.equal(f.rpc.at(-1).arguments.vision, 'no');
351    await f.native.plan({ family: 'qwen', model: 'Q2_0', vision: 'yes' });
352    assert.equal(f.rpc.at(-1).arguments.vision, 'yes');
353  } finally { await f.native.close(); f.cleanup(); }
354});
355
356test('packaged: an engine that stops while loading keeps the code and the last engine line for the Details disclosure', async () => {
357  const f = packagedFixture();
358  try {
359    await f.native.refresh(true);
360    f.failStart({ message: 'server_exited', output: { log_tail: 'memory guard: 5.1 GiB free is under the 6 GiB limit' } });
361    const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
362    assert.equal(job.state, 'error');
363    assert.match(job.error, /^server_exited: memory guard: 5\.1 GiB free/);
364  } finally { await f.native.close(); f.cleanup(); }
365});
366
367test('packaged: a start that died because Windows ran out of locked memory is tried once more with a smaller pin, said in plain words, and the saved settings stay as they were', async () => {
368  const f = packagedFixture();
369  try {
370    await f.native.refresh(true);
371    f.failStart({ message: 'server_exited', output: { log_tail: 'verify: mapped staging allocation failed [pinned-memory-exhausted] the OS gave no more page-locked memory; start again with STRATA_ARENA_PIN_GIB=26 (pin less of the expert arena)' } }, 1);
372    const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
373    assert.equal(job.state, 'done', job.error);
374    assert.equal(f.calls.filter(c => c[0] === 'start').length, 2, 'one try and exactly one more');
375    assert.match(job.result.summary, /ready, after a second try: Windows would not lock as much memory/);
376    assert.match(job.details[0], /pinned-memory-exhausted/);
377    assert.match(job.details[1], /STRATA_ARENA_PIN_GIB=26/);
378    const instance = f.native.state().instances[0];
379    assert.equal(instance.status, 'ready');
380    const saved = JSON.parse(readFileSync(join(f.install, 'strata-iq2_xs.json'), 'utf8'));
381    assert.equal(saved.env, undefined, 'the safer setting is for this start only; the model config is not changed');
382  } finally { await f.native.close(); f.cleanup(); }
383});
384
385test('packaged: the second try is the last one: a second failure is reported with both, and nothing loops', async () => {
386  const f = packagedFixture();
387  try {
388    await f.native.refresh(true);
389    f.failStart({ message: 'server_exited', output: { log_tail: 'mapped staging allocation failed [pinned-memory-exhausted]' } });
390    const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
391    assert.equal(job.state, 'error');
392    assert.equal(f.calls.filter(c => c[0] === 'start').length, 2);
393    assert.doesNotMatch(job.error, /first stop was/, 'the same stop twice is said once, not repeated');
394    assert.match(job.details.join(' '), /Second try/, 'the second try stays in the details');
395  } finally { await f.native.close(); f.cleanup(); }
396});
397
398test('packaged: retrySafer false keeps the single try', async () => {
399  const f = packagedFixture();
400  try {
401    await f.native.refresh(true);
402    f.failStart({ message: 'server_exited', output: { log_tail: 'mapped staging allocation failed [pinned-memory-exhausted]' } });
403    const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs', retrySafer: false }).id);
404    assert.equal(job.state, 'error');
405    assert.equal(f.calls.filter(c => c[0] === 'start').length, 1);
406  } finally { await f.native.close(); f.cleanup(); }
407});
408
409test('packaged: a Control whose wait ran out has not stopped the engine, so the load is kept and watched, not failed (#5177 #4293)', async () => {
410  /* `runtime start --wait N` answers "startup_wait_expired" (exit 8) while the engine is still loading, and "runtime operation wait expired" when the owner
411     was too busy to answer a status question in time; neither stops the engine. Control is asked: starting or ready means the app keeps the load. */
412  for (const message of ['The engine did not start.', 'runtime operation wait expired; inspect runtime status']) {
413    const f = packagedFixture();
414    try {
415      await f.native.refresh(true);
416      f.setStatus({ ok: true, state: 'starting', phase: 'loading' });
417      f.failStart({ message, output: { ok: false, state: 'starting', error: message.startsWith('runtime') ? undefined : 'startup_wait_expired', phase: 'loading', exit_code: 8 } }, 1);
418      const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
419      assert.equal(job.state, 'done', job.error);
420      assert.equal(f.calls.filter(c => c[0] === 'start').length, 1, 'a wait that ran out is not a failure: no second try');
421      assert.equal(f.calls.filter(c => c[0] === 'stop').length, 1, 'the one stop is startWith clearing the slot; the loading engine is never stopped by the app');
422      assert.equal(f.native.state().instances[0].status, 'ready', 'ready once /health answers');
423      assert.ok(f.calls.some(c => c[0] === 'status' && c[1] === 'app-1'), 'Control was asked before the load was kept');
424    } finally { await f.native.close(); f.cleanup(); }
425  }
426});
427
428test('packaged: an expired wait with an engine Control says is gone is a failure, and an adopted load whose engine dies ends as one', async () => {
429  const f = packagedFixture();
430  try {
431    await f.native.refresh(true);
432    f.setStatus({ ok: false, state: 'failed', error: 'server_exited', engine_exit_code: 1 });
433    f.failStart({ message: 'The engine did not start.', output: { ok: false, state: 'starting', error: 'startup_wait_expired', exit_code: 8 } }, 1);
434    const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs', retrySafer: false }).id);
435    assert.equal(job.state, 'error', 'Control says the engine is gone: nothing to adopt');
436  } finally { await f.native.close(); f.cleanup(); }
437  const g = packagedFixture();
438  try {
439    await g.native.refresh(true);
440    g.setHealthDown(true);                                           // never answers /health ...
441    let asked = 0;                                                    // the first look (is the wait's engine still loading?) says starting, every later one says it ended
442    g.setStatus(() => (++asked === 1 ? { ok: true, state: 'starting', phase: 'loading' } : { ok: false, state: 'failed', error: 'server_exited', engine_exit_code: 3 }));
443    g.failStart({ message: 'The engine did not start.', output: { ok: false, state: 'starting', error: 'startup_wait_expired', exit_code: 8 } }, 1);
444    const started = g.native.operation('load', { model: 'iq2_xs' });
445    const job = await finish(g.native, started.id);
446    assert.equal(job.state, 'error');
447    assert.match(String(job.error ?? ''), /server_exited/);
448  } finally { await g.native.close(); g.cleanup(); }
449});
450
451test('packaged: a ready instance whose engine stopped answering is marked stopped once Control says so, and stays ready while the engine is only busy (#4973)', async () => {
452  const f = packagedFixture();
453  try {
454    await f.native.refresh(true);
455    const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
456    assert.equal(job.state, 'done', job.error);
457    f.setMetricsDown(true);
458    f.setStatus({ ok: true, state: 'ready' });                       // busy, not gone
459    await new Promise(r => setTimeout(r, 5200));
460    assert.equal(f.native.state().instances[0].status, 'ready');
461    assert.equal(f.native.state().instances[0].phase, 'unavailable');
462    f.setStatus({ ok: true, state: 'stopped' });                     // the owner left with its engine
463    await new Promise(r => setTimeout(r, 2600));
464    const instance = f.native.state().instances[0];
465    assert.equal(instance.status, 'error');
466    assert.match(instance.error, /Engine stopped/);
467  } finally { await f.native.close(); f.cleanup(); }
468});
469
470test('packaged: a run config that points into an old Control folder is repaired to this Control (a reinstall or an update moved it)', async () => {
471  const f = packagedFixture();
472  try {
473    const here = join(f.root, 'control');
474    mkdirSync(join(here, 'data'), { recursive: true });
475    writeFileSync(join(here, 'data', 'expert-profile.bin'), 'profile');
476    const path = join(f.install, 'strata-iq2_xs.json');
477    const old = 'C:/Users/Alex/AppData/Local/Temp/strata-life-install/control';
478    writeFileSync(path, JSON.stringify({ exe: 'component:strata-engine', cwd: old, args: ['--pack', 'D:/Strata/packs/x', '--expert-profile', old + '/data/expert-profile.bin', '--max-context', '32768'], model_name: 'x', port: 8080 }));
479    await f.native.refresh(true);
480    const repaired = JSON.parse(readFileSync(path, 'utf8'));
481    assert.equal(repaired.cwd.toLowerCase(), here.toLowerCase());
482    assert.equal(repaired.args[repaired.args.indexOf('--expert-profile') + 1].toLowerCase(), join(here, 'data', 'expert-profile.bin').toLowerCase());
483    assert.equal(repaired.args[1], 'D:/Strata/packs/x', 'paths outside Control are left alone');
484    assert.ok(existsSync(path + '.bak'), 'the old config is kept');
485    // a config that is already right, or whose new target is not there, is not touched
486    const before = readFileSync(path, 'utf8');
487    await f.native.refresh(true);
488    assert.equal(readFileSync(path, 'utf8'), before);
489  } finally { await f.native.close(); f.cleanup(); }
490});
491
492test('packaged: deleting a downloaded model unloads it first, then the installer removes its files', async () => {
493  const f = packagedFixture();
494  try {
495    await f.native.refresh(true);
496    const load = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
497    assert.equal(load.state, 'done', load.error);
498    assert.equal(f.native.state().instances.length, 1);
499    const job = await finish(f.native, f.native.operation('remove', { model: 'iq2_xs' }).id);
500    assert.equal(job.state, 'done', job.error);
501    assert.equal(f.native.state().instances.length, 0, 'the loaded model was unloaded first');
502    assert.deepEqual(f.calls.filter(c => c[0] === 'stop').at(-1), ['stop', 'app-1']);
503    const removed = f.rpc.filter(c => c.name === 'strata_remove');
504    assert.equal(removed.length, 1);
505    assert.deepEqual(removed[0].arguments, { model: 'iq2_xs', confirm: true });
506    assert.equal(f.others().length, 0);
507    const bad = await finish(f.native, f.native.operation('remove', { model: '../x' }).id);
508    assert.equal(bad.state, 'error', 'an id that is not an installed model is refused');
509  } finally { await f.native.close(); f.cleanup(); }
510});
511
512test('packaged: a local GGUF folder is checked by Control, then installed from where it is (no download)', async () => {
513  const f = packagedFixture();
514  try {
515    await f.native.refresh(true);
516    const preview = await f.native.localPreview('D:/models/iq3s');
517    assert.equal(preview.candidate_selection.model, 'IQ3_S');
518    assert.deepEqual(f.calls.find(c => c[0] === 'importPlan'), ['importPlan', 'D:/models/iq3s']);
519    await assert.rejects(() => f.native.localPreview('  '), /Choose a folder/);
520    await f.native.plan({ family: 'qwen', model: 'IQ3_S', gguf_dir: 'D:/models/iq3s' });
521    assert.equal(f.rpc.at(-1).arguments.gguf_dir, 'D:/models/iq3s');
522  } finally { await f.native.close(); f.cleanup(); }
523});
524
525test('packaged: the install job also fetches the engine through Control (merge of the model progress and the engine step); a failed engine keeps the model and says so', async () => {
526  const report = { engine: { status: 'install', offered: { version: '0.1.46' }, download_bytes: 5e8 } };
527  const f = packagedFixture({ engineUsable: false, updater: { report, async update(options) {
528    options.onEvent({ event: 'progress', phase: 'download', percent: 50, done: 2.5e8, total: 5e8 });
529    return { ok: true, results: [{ component: 'engine', status: 'updated', installed_after: { version: '0.1.46' } }] };
530  } } });
531  try {
532    await f.native.refresh(true);
533    const job = await finish(f.native, f.native.operation('install', { family: 'qwen', model: 'Q2_0' }).id);
534    assert.equal(job.state, 'done', job.error);
535    assert.equal(job.result.install.engine.state, 'done');
536    assert.deepEqual(job.result.install.parts.map(p => p.kind), ['model', 'engine']);
537    assert.deepEqual(f.calls.filter(c => c[0] === 'update'), [['update', true, false]], 'the engine only, from this install job');
538    assert.equal(f.calls.filter(c => ['saveProfile', 'start'].includes(c[0])).length, 0);
539  } finally { await f.native.close(); f.cleanup(); }
540  const g = packagedFixture({ engineUsable: false, updater: { report, async update() { throw new Error('the download of http://x/e.tar.gz was interrupted after 100 of 200 bytes (ConnectionResetError)'); } } });
541  try {
542    await g.native.refresh(true);
543    const job = await finish(g.native, g.native.operation('install', { family: 'qwen', model: 'Q2_0' }).id);
544    assert.equal(job.state, 'done', job.error);
545    assert.match(job.summary, /Your model is ready\. The engine for this PC couldn't be downloaded/);
546    assert.equal(job.result.install.engine.state, 'failed');
547    assert.doesNotMatch(job.summary, /http|ConnectionReset|bytes/);
548  } finally { await g.native.close(); g.cleanup(); }
549});
550
551test('packaged: a model install that fails does not cancel the engine download it started (DL99: a retry would fail the same way again)', async () => {
552  const report = { engine: { status: 'install', offered: { version: '0.1.46' }, download_bytes: 5e8 } };
553  const seen = { finished: false, aborted: null };
554  const f = packagedFixture({ engineUsable: false,
555    installPoll: { summary: 'failed', install: { running: false, exit_code: 1, error: 'this engine (99.0.0) does not run Qwen3.6-35B-A3B yet - update Strata' } },
556    updater: { report, async update(options) {
557      options.onEvent({ event: 'progress', phase: 'download', percent: 40, done: 2e8, total: 5e8 });
558      await new Promise(r => setTimeout(r, 2500));          // longer than the install job's first poll (1.5 s), which reads the failure
559      seen.aborted = options.signal?.aborted === true; seen.finished = true;
560      return { ok: true, results: [{ component: 'engine', status: 'updated', installed_after: { version: '0.1.46' } }] };
561    } } });
562  try {
563    await f.native.refresh(true);
564    const job = await finish(f.native, f.native.operation('install', { family: 'qwen', model: 'Q2_0' }).id);
565    assert.equal(job.state, 'error');
566    assert.match(job.error, /does not run Qwen3\.6-35B-A3B yet/);
567    assert.equal(seen.finished, true, 'the engine download ran to its end before the job ended');
568    assert.equal(seen.aborted, false, 'the engine download was not cancelled');
569    assert.equal(job.result.install.engine.state, 'done');
570  } finally { await f.native.close(); f.cleanup(); }
571});
572
573test('packaged: with no engine on the PC yet, the engine is installed before setup starts (setup takes the picture reader from it; Qwen3.6 came up text-only)', async () => {
574  const report = { engine: { status: 'install', offered: { version: '0.1.60' }, download_bytes: 7e8 } };
575  const seen = { installsWhenEngineDone: null };
576  let f;
577  f = packagedFixture({ engineUsable: false, updater: { report, async update(options) {
578    options.onEvent({ event: 'progress', phase: 'download', percent: 50, done: 3.5e8, total: 7e8 });
579    await new Promise(r => setTimeout(r, 300));
580    seen.installsWhenEngineDone = f.rpc.filter(c => c.name === 'strata_install' && c.arguments.confirm).length;
581    return { ok: true, results: [{ component: 'engine', status: 'updated', installed_after: { version: '0.1.60' } }] };
582  } } });
583  try {
584    await f.native.refresh(true);
585    const job = await finish(f.native, f.native.operation('install', { family: 'qwen', model: 'Q2_0' }).id);
586    assert.equal(job.state, 'done', job.error);
587    assert.equal(seen.installsWhenEngineDone, 0, 'setup was not started before the engine was in');
588    assert.equal(f.rpc.filter(c => c.name === 'strata_install' && c.arguments.confirm).length, 1);
589    assert.deepEqual(f.calls.filter(c => c[0] === 'update'), [['update', true, false]], 'the engine is fetched once');
590    assert.equal(job.result.install.engine.state, 'done');
591  } finally { await f.native.close(); f.cleanup(); }
592  // an engine that is there already: setup starts at once and the engine step runs beside it, as before
593  const g = packagedFixture({ engineUsable: true, updater: { report: { engine: { status: 'current', installed: { version: '0.1.60' } } }, async update() { throw new Error('not called'); } } });
594  try {
595    await g.native.refresh(true);
596    const job = await finish(g.native, g.native.operation('install', { family: 'qwen', model: 'Q2_0' }).id);
597    assert.equal(job.state, 'done', job.error);
598    assert.equal(g.calls.filter(c => c[0] === 'update').length, 0, 'a current engine is not fetched');
599  } finally { await g.native.close(); g.cleanup(); }
600});
601
602test('packaged: Stop still cancels the engine download of an install', async () => {
603  const report = { engine: { status: 'install', offered: { version: '0.1.46' }, download_bytes: 5e8 } };
604  const seen = { aborted: null };
605  const f = packagedFixture({ engineUsable: false,
606    installPoll: { summary: 'running', install: { running: true, step: '5/7: downloading' } },
607    updater: { report, async update(options) {
608      await new Promise(resolve => { if (options.signal?.aborted) resolve(); else options.signal?.addEventListener('abort', resolve, { once: true }); });
609      seen.aborted = true;
610      throw new Error('stopped');
611    } } });
612  try {
613    await f.native.refresh(true);
614    const id = f.native.operation('install', { family: 'qwen', model: 'Q2_0' }).id;
615    await new Promise(r => setTimeout(r, 300));
616    await f.native.cancel(id);
617    const job = await finish(f.native, id);
618    assert.equal(job.state, 'cancelled');
619    for (let i = 0; i < 100 && seen.aborted === null; i++) await new Promise(r => setTimeout(r, 10));
620    assert.equal(seen.aborted, true);
621    await new Promise(r => setTimeout(r, 2000));             // the install loop's 1.5 s wait ends and it returns before the folder goes
622  } finally { await f.native.close(); f.cleanup(); }
623});
624
625test('packaged: the app default of several requests at once and the memory retry share ONE second try, never two', async () => {
626  const f = packagedFixture(); f.hardware.gpus[0].vram_gb = 48;
627  try {
628    await f.native.refresh(true);
629    f.failStart({ message: 'server_exited', output: { log_tail: 'something else went wrong' } }, 1);
630    const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
631    assert.equal(job.state, 'done', job.error);
632    assert.equal(f.calls.filter(c => c[0] === 'start').length, 2, 'the failed first start and one second try');
633    assert.match(job.result.summary, /after a second try/);
634    assert.equal(f.native.state().instances[0].parallel, 1, 'the second try runs one request at a time');
635  } finally { await f.native.close(); f.cleanup(); }
636  const g = packagedFixture(); g.hardware.gpus[0].vram_gb = 48;
637  try {
638    await g.native.refresh(true);
639    g.failStart({ message: 'server_exited', output: { log_tail: 'mapped staging allocation failed [pinned-memory-exhausted]' } });
640    const job = await finish(g.native, g.native.operation('load', { model: 'iq2_xs' }).id);
641    assert.equal(job.state, 'error');
642    assert.equal(g.calls.filter(c => c[0] === 'start').length, 2, 'memory change and parallel drop ride on the same single try');
643  } finally { await g.native.close(); g.cleanup(); }
644});
645
646test('packaged: a tune measures the engine a load starts: same start args, slots included, for the same model and profile', async () => {
647  for (const vram of [11.9, 48]) {
648    const f = packagedFixture(); f.hardware.gpus[0].vram_gb = vram;
649    try {
650      await f.native.refresh(true);
651      const args = { model: 'iq2_xs', resourceProfile: 'work', vision: 'no' };
652      await f.native.tuneStatus(args).catch(() => {});      // the fake host cannot run Control's tuner; the config it would measure is written first
653      const tuned = JSON.parse(readFileSync(join(f.root, 'data', 'native-tune', 'iq2_xs.json'), 'utf8'));
654      const job = await finish(f.native, f.native.operation('load', args).id);
655      assert.equal(job.state, 'done', job.error);
656      const loaded = { ...f.saved.at(-1) }; delete loaded.port; delete loaded.api_key;
657      assert.deepEqual(tuned.args, loaded.args, 'the engine arguments are identical');
658      for (const [key, value] of Object.entries(tuned)) assert.deepEqual(loaded[key], value, `${key} is the same in the tune and the load`);   // a load adds only its own identity (aliases, model name, key, port)
659      if (vram > 40) assert.ok(tuned.parallel > 1, 'a big card gets the app default of several slots in the tune too');
660    } finally { await f.native.close(); f.cleanup(); }
661  }
662});
663
664test('packaged: a profile an elevated run locked (PermissionError) is repaired once and the start is tried again; without repair it is a plain message, not a memory retry', async () => {
665  const f = packagedFixture({ repair: true });
666  try {
667    await f.native.refresh(true);
668    f.failStart({ message: 'cannot read profile (PermissionError)' }, 1);
669    const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
670    assert.equal(job.state, 'done', job.error);
671    assert.equal(f.calls.filter(c => c[0] === 'repairAccess').length, 1);
672    assert.equal(f.calls.filter(c => c[0] === 'start').length, 2);
673  } finally { await f.native.close(); f.cleanup(); }
674  const g = packagedFixture({ repair: true });
675  try {
676    await g.native.refresh(true);
677    g.failStart({ message: 'cannot read profile (PermissionError)' });
678    const job = await finish(g.native, g.native.operation('load', { model: 'iq2_xs' }).id);
679    assert.equal(job.state, 'error');
680    assert.equal(g.calls.filter(c => c[0] === 'start').length, 2, 'one repair try, no memory retry on top');
681    assert.match(job.error, /PermissionError/);
682  } finally { await g.native.close(); g.cleanup(); }
683});
684
685test('a GGUF folder Control refuses (exit 5, ok:false) still comes back as a checked plan with its reasons, so the page can say it in words', async () => {
686  const plan = { file_set_status: 'invalid_or_incomplete', candidate_selection: null, issues: ['x.gguf: GGUF tensor or metadata count exceeds the inspection limit', 'unrecognized_or_unsupported_model_variant'] };
687  const control = createControl({ control: { dir: '/c', python: '/p', cli: '/c/strata.py', bundle: { version: '9' } }, run: async () => ({ code: 5, json: { ok: false, plan }, text: '', stderr: '' }) });
688  assert.deepEqual(await control.importPlan('/some/folder'), plan);
689  const broken = createControl({ control: { dir: '/c', python: '/p', cli: '/c/strata.py', bundle: { version: '9' } }, run: async () => ({ code: 1, json: null, text: '', stderr: 'boom' }) });
690  await assert.rejects(() => broken.importPlan('/some/folder'), /boom/);
691});
692
693test("preparing an adopted GGUF folder again never takes the folder's parent for the data folder (it is the person's, not Strata's)", async () => {
694  const f = packagedFixture();
695  try {
696    // The model is already adopted: its run config points at a GGUF in someone's own ".../models/IQ3_S" folder.
697    const own = join(f.root, 'own');
698    const configPath = join(f.install, 'strata-iq3_s.json');
699    const config = JSON.parse(readFileSync(configPath, 'utf8'));
700    writeFileSync(configPath, JSON.stringify({ ...config, args: [...config.args, '--native', join(own, 'models', 'IQ3_S', 'a-00001-of-00002.gguf')] }));
701    f.catalog.families[0].sizes.push({ id: 'iq3_s', model: 'IQ3_S', download_gb: 83, ram_needed_gb: 62, about: 'x', on_this_pc: 'fits', installed: true, images: true, experimental: false });
702    await f.native.refresh(true);
703    await f.native.plan({ family: 'qwen', model: 'IQ3_S', gguf_dir: join(own, 'models', 'IQ3_S') });
704    const sent = f.rpc.at(-1).arguments;
705    assert.notEqual(sent.data_dir, own, "the person's own folder is not used for the packs");
706    assert.equal(sent.gguf_dir, join(own, 'models', 'IQ3_S'));
707  } finally { await f.native.close(); f.cleanup(); }
708});
709
710test('the app never adopts an older command-line install: Control is always told the app\'s own folder, and has its own settings file', async () => {
711  const f = packagedFixture();
712  try {
713    await f.native.refresh(true);
714    const asked = f.calls.filter(c => c[0] === 'installedModels').map(c => c[1]);
715    assert.ok(asked.length > 0 && asked.every(dir => dir === f.install || (dir && dir.toLowerCase() === f.install.toLowerCase())), `Control was asked about ${JSON.stringify(asked)}`);
716  } finally { f.cleanup(); }
717  const env = controlEnvironment({ dir: '/c' }, { env: { APPDATA: '/old/appdata' }, components: join(tmpdir(), 'Strata', 'components') });
718  assert.equal(env.STRATA_SETTINGS_FILE, join(tmpdir(), 'Strata', 'app-settings.json'));
719});
720
721test("onboarding 'use your own GGUF' (#3507, #3424): the models folder the person picked holds the GGUF files, so preparing them never takes it for the data folder", async () => {
722  const f = packagedFixture();
723  try {
724    const own = join(f.root, 'Strata-data', 'models', 'unsloth-UD-Q4_K_XL');
725    mkdirSync(own, { recursive: true });
726    await f.native.refresh(true);
727    f.native.setDownloadDirectory(own);                        // what the first-run folder chooser wrote
728    await f.native.plan({ family: 'qwen', model: 'IQ3_S', gguf_dir: own });
729    const sent = f.rpc.at(-1).arguments;
730    assert.equal(sent.gguf_dir, own);
731    assert.notEqual(sent.data_dir, own, 'the folder of GGUF files is not the data folder: the packs would be downloaded into it');
732    // a folder of GGUF files named like a data folder's models/<tag> hands its Strata folder to the installer
733    assert.ok(sent.data_dir === undefined || sent.data_dir === join(f.root, 'Strata-data'), `data_dir was ${sent.data_dir}`);
734  } finally { await f.native.close(); f.cleanup(); }
735});
736
737/* The start wait follows the model's size, as `strata launch` does since #3949, and never asks an older Control for more than it takes.
738   Reported on the app side by #3459 and #4191: a big model on a slow disk was stopped at 300 s while the engine went on reading. */
739test('packaged: a big model is waited for by its size, inside the ceiling of the Control this app has (#3459 #4191)', async () => {
740  const run = async (cliStartWait, downloadGb) => {
741    const f = packagedFixture({ ids: ['big'], cliStartWait, extraSizes: [{ id: 'big', model: 'BIG', download_gb: downloadGb, ram_needed_gb: 60, about: 'x', on_this_pc: 'fits', installed: false, images: false, experimental: false }] });
742    try {
743      await f.native.refresh(true);
744      const job = await finish(f.native, f.native.operation('load', { model: 'big' }).id);
745      assert.equal(job.state, 'done', job.error);
746      const start = f.calls.find(c => c[0] === 'start');
747      const saved = f.saved[0];
748      await f.native.close();
749      return { wait: start[2], ready: saved.engine_ready_s };
750    } finally { f.cleanup(); }
751  };
752  assert.equal((await run('old', 180)).wait, 600, 'a Control with no long-wait ceiling at all is asked for 600 s, as today');
753  assert.equal((await run('split', 180)).wait, 600, 'a Control whose runtime takes 1800 s but whose CLI still stops at 600 is asked for 600 s: the CLI would refuse the start outright (#3949)');
754  assert.equal((await run('cli-only', 180)).wait, 600, 'a Control whose CLI takes it but whose operation record still stops at 600 is asked for 600 s too: the record is written before the start runs');
755  const long = await run('runtime', 180);
756  assert.equal(long.wait, 1720, '600 s + 8 s per GB above 40 GB, as in strata launch, once the CLI really takes it');
757  assert.equal(long.ready, 1780, 'the server readies after the start gave up, never before it');
758  const small = await run('runtime', 20);
759  assert.equal(small.wait, 300, 'a model under 40 GB keeps the 300 s it always had');
760  assert.equal(small.ready, undefined, 'nothing is added to a small model’s run config');
761  const huge = await run('runtime', 400);
762  assert.equal(huge.wait, 1800, 'and never more than this Control accepts');
763});
764
765test('packaged: a run config that names a longer engine wait is honoured, and never shortened by the app', async () => {
766  const f = packagedFixture({ ids: ['qwen3.6-35b-a3b-ud-q4_k_xl'], cliStartWait: 'runtime' });
767  try {
768    writeFileSync(join(f.install, 'strata-qwen3.6-35b-a3b-ud-q4_k_xl.json'), JSON.stringify({ exe: 'component:strata-engine', tokenizer: join(f.install, 'tok'), args: ['--max-context', '32768'], model_name: 'Qwen qwen3.6-35b-a3b-ud-q4_k_xl', port: 8080, engine_ready_s: 3600 }));
769    await f.native.refresh(true);
770    const job = await finish(f.native, f.native.operation('load', { model: 'qwen3.6-35b-a3b-ud-q4_k_xl' }).id);
771    assert.equal(job.state, 'done', job.error);
772    assert.equal(f.calls.find(c => c[0] === 'start')[2], 1800, 'the wait of the newest Control, which is what the ceiling allows');
773    assert.equal(f.saved[0].engine_ready_s, 3600, 'setup’s own longer wait stays as it is');
774  } finally { await f.native.close(); f.cleanup(); }
775});