okami.mom/strata

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

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

main
12.1 KiB179 linesraw
1import test from 'node:test';
2import { readFileSync as readSource } from 'node:fs';
3import assert from 'node:assert/strict';
4import { build } from 'esbuild';
5import { createEngineStep } from '../server/engine-step.mjs';
6
7const compiled = await build({
8  stdin: {
9    contents: "export * from './src/lib/native'; export * from './src/lib/download-eta'; export * from './src/lib/native-fit'; export * from './src/lib/native-names'; export * from './src/lib/native-catalog'; export * from './src/lib/i18n';",
10    resolveDir: process.cwd(),
11  },
12  bundle: true, write: false, platform: 'node', format: 'esm',
13});
14const lib = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`);
15for (const l of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) await lib.loadCatalog(l);  // the non-English catalogs load on first use (src/lib/i18n.ts loadCatalog); load them before the first tr()
16
17const job = (progress, state = 'running') => ({ id: 'j1', kind: 'install', state, startedAt: '', summary: '', error: null, result: { install: progress } });
18const stateWith = (jobs, extra = {}) => ({ available: true, repo: '', summary: '', error: null, catalog: null, installed: null, hardware: null, instances: [], jobs, ...extra });
19const answer = body => ({ ok: true, status: 200, statusText: 'OK', text: async () => JSON.stringify(body) });
20
21test('a slow forced read never holds the light poll: a running download keeps moving', async () => {
22  const seen = [];
23  globalThis.fetch = async url => {
24    seen.push(url);
25    if (String(url).includes('refresh=1')) { await new Promise(r => setTimeout(r, 400)); return answer(stateWith([job({ download: { done_gb: 1, total_gb: 10 } })])); }
26    return answer(stateWith([job({ download: { done_gb: 5, total_gb: 10 } })]));
27  };
28  const slow = lib.refreshNative(true);
29  const t0 = Date.now();
30  await lib.refreshNative();
31  assert.ok(Date.now() - t0 < 200, 'the light read answered while the forced one was still running');
32  assert.equal(lib.nativeState().jobs[0].result.install.download.done_gb, 5);
33  await slow;
34  assert.ok(seen.some(u => String(u).includes('refresh=1')) && seen.some(u => !String(u).includes('refresh=1')));
35});
36
37test('a second forced read waits for the first and then reads again (it never joins a read that began before the action)', async () => {
38  let calls = 0;
39  globalThis.fetch = async () => { calls += 1; await new Promise(r => setTimeout(r, 50)); return answer(stateWith([], { summary: `read ${calls}` })); };
40  const a = lib.refreshNative(true), b = lib.refreshNative(true), c = lib.refreshNative(true);
41  await Promise.all([a, b, c]);
42  assert.equal(calls, 2, 'one read for the first, one more for everything asked meanwhile');
43  assert.equal(lib.nativeState().summary, 'read 2');
44});
45
46test('the host pushes its native state and the page takes it at once', () => {
47  lib.applyNativeEvent(stateWith([job({ download: { done_gb: 7, total_gb: 10 } })], { summary: 'pushed' }));
48  assert.equal(lib.nativeState().summary, 'pushed');
49  lib.applyNativeEvent({ nonsense: true });
50  lib.applyNativeEvent(null);
51  assert.equal(lib.nativeState().summary, 'pushed', 'a frame that is not a native state changes nothing');
52});
53
54test('the poll is quick while a job runs, normal otherwise, and stops while the window is hidden', () => {
55  assert.equal(lib.nativePollDelay(null), 2500);
56  assert.equal(lib.nativePollDelay(stateWith([job({})], {})), 1000);
57  assert.equal(lib.nativePollDelay(stateWith([job({}, 'done')])), 2500);
58  assert.equal(lib.nativePollDelay(stateWith([job({})]), true), null);
59});
60
61const parts = (model, vision, engine = { kind: 'engine', name: 'Engine', state: 'done', done_gb: 0.4, total_gb: 0.4 }) => [model, vision, engine];
62const modelPart = (state, done, total, files_done, files_total) => ({ kind: 'model', name: 'Model files', state, done_gb: done, total_gb: total, files_done, files_total });
63const visionPart = (state, done = 0) => ({ kind: 'vision', name: 'Picture reader', state, done_gb: done, total_gb: 0.9 });
64
65test('a model in parts says which part is under way, then the picture reader', () => {
66  lib.setTranslationLanguage('en');
67  const second = { parts: parts(modelPart('downloading', 20, 66, 1, 2), visionPart('waiting')) };
68  assert.deepEqual(lib.installStage(second), { kind: 'model', index: 2, count: 2 });
69  assert.equal(lib.stageText(lib.installStage(second)), 'Downloading model files · part 2 of 2');
70  const reader = { parts: parts(modelPart('done', 66, 66, 2, 2), visionPart('downloading', 0.3)) };
71  assert.deepEqual(lib.installStage(reader), { kind: 'vision' });
72  assert.equal(lib.stageText(lib.installStage(reader)), 'Downloading the picture reader…');
73  assert.equal(lib.stageText(lib.installStage(undefined)), 'Downloading model files…');
74  const single = { parts: [modelPart('downloading', 1, 20, 0, 1), visionPart('waiting')] };
75  assert.equal(lib.stageText(lib.installStage(single)), 'Downloading model files…', 'one file is not "part 1 of 1"');
76});
77
78test('the figure counts every part: the model whole but the picture reader not yet is not finished', () => {
79  const p = lib.installProgress({ parts: parts(modelPart('done', 10, 10, 2, 2), visionPart('downloading', 0.3)) });
80  assert.equal(p.percent, 94, 'the bar is not at its end while the picture reader is still coming');
81  assert.ok(Math.abs(p.total_gb - 11.3) < 0.01, `total ${p.total_gb}`);
82  assert.ok(p.remaining_gb > 0.5);
83  const half = lib.installProgress({ parts: parts(modelPart('downloading', 33, 66, 1, 2), visionPart('waiting')) });
84  assert.equal(half.percent, Math.floor(100 * (33 + 0.4) / (66 + 0.9 + 0.4)));
85});
86
87test('the engine step keeps the install job\'s own parts (model parts, picture reader) and adds the engine', () => {
88  const step = createEngineStep({ control: null });
89  const install = { running: true, step: '5/7: downloading', download: { file: 'picture reader', done_gb: 66.3, total_gb: 66.9, remaining_gb: 0.6, percent: 99 },
90    parts: [modelPart('done', 66, 66, 2, 2), visionPart('downloading', 0.3)] };
91  const merged = step.merge(install);
92  assert.deepEqual(merged.parts.map(p => p.kind), ['model', 'vision', 'engine']);
93  assert.equal(merged.parts[0].files_total, 2);
94  const bare = step.merge({ running: true, download: { file: 'model files', done_gb: 1, remaining_gb: 9 } });
95  assert.deepEqual(bare.parts.map(p => p.kind), ['model', 'engine'], 'an install without part information keeps the old two-part list');
96});
97
98test('the recommended four come first; the others are what the "More versions" list holds', () => {
99  const v = (sourceFamily, model) => ({ sourceFamily, model, id: `${sourceFamily}-${model}` });
100  const all = [v('qwen', 'Q2_0'), v('gyro', 'Gyro-S'), v('swift', 'IQ2_XS'), v('qwen', 'IQ3_S'), v('unsloth', 'UD-Q4_K_XL'), v('nvfp4', 'NVFP4')];
101  const rec = lib.recommendedVersions(all).map(x => x.v.model);
102  assert.deepEqual(rec, ['Gyro-S', 'IQ2_XS', 'IQ3_S', 'UD-Q4_K_XL']);
103  assert.deepEqual(all.filter(x => !rec.includes(x.model)).map(x => x.model), ['Q2_0', 'NVFP4']);
104  assert.deepEqual(lib.recommendedVersions([v('qwen36', 'UD-Q4_K_XL')]), [], 'Qwen3.6 has no recommended set: its versions are all shown');
105});
106
107test('the three NVFP4 versions have clear names and one line that tells them apart', () => {
108  lib.setTranslationLanguage('en');
109  const names = ['NVFP4', 'NVFP4-NVIDIA', 'NVFP4-QAD'].map(m => lib.nativeVersionLabel(m));
110  assert.deepEqual(names, ['NVFP4 (Strata’s version)', 'NVFP4 (NVIDIA’s version)', 'NVFP4 (NVIDIA, trained for FP4)']);
111  assert.equal(new Set(names).size, 3);
112  const lines = ['NVFP4', 'NVFP4-NVIDIA', 'NVFP4-QAD'].map(m => lib.versionNote(m));
113  assert.match(lines[0], /best quality/i);
114  assert.match(lines[1], /NVIDIA’s own NVFP4 checkpoint/);
115  assert.match(lines[2], /trained for FP4/);
116  assert.match(lines[2], /faster on short prompts/);
117  assert.equal(lib.versionNote('IQ3_S'), '');
118  assert.equal(lib.nativeShortName('nvfp4-nvfp4-nvidia'), 'NVFP4 (NVIDIA’s version)');
119  for (const language of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) {
120    lib.setTranslationLanguage(language);
121    const local = ['NVFP4', 'NVFP4-NVIDIA', 'NVFP4-QAD'].map(m => lib.nativeVersionLabel(m));
122    assert.equal(new Set(local).size, 3, `${language}: three different names`);
123    assert.ok(local.every((n, i) => n !== names[i]), `${language}: translated`);
124    assert.ok(['NVFP4', 'NVFP4-NVIDIA', 'NVFP4-QAD'].every((m, i) => lib.versionNote(m) !== lines[i]), `${language}: the line is translated`);
125  }
126  lib.setTranslationLanguage('en');
127});
128
129test('4d: picture reading is on unless the person turned it off (no saved choice is not "off")', async () => {
130  const { nativeFixture } = await import('./helpers/native-fixture.mjs');
131  const { readFileSync, writeFileSync } = await import('node:fs');
132  const { join } = await import('node:path');
133  const f = nativeFixture();
134  try {
135    await f.control.refresh(true);
136    const first = () => f.control.state().installed.models.find(m => m.model === 'iq2_xs');
137    assert.equal(first().visionEnabled, undefined, 'a model never loaded and never turned off');
138    const path = join(f.repo, 'strata-iq2_xs.json');
139    const cfg = JSON.parse(readFileSync(path, 'utf8'));
140    writeFileSync(path, JSON.stringify({ ...cfg, ui_vision_enabled: false }));
141    await f.control.refresh(true);
142    assert.equal(first().visionEnabled, false, 'turned off by the person: stays off');
143    writeFileSync(path, JSON.stringify({ ...cfg, ui_vision_enabled: true, ui_vision_device: 'cpu' }));
144    await f.control.refresh(true);
145    assert.equal(first().visionEnabled, true);
146  } finally { await f.cleanup(); }
147  const screen = readSource(new URL('../src/components/NativeModels.tsx', import.meta.url), 'utf8');
148  // the rule lives in lib/pictures-choice.ts (GUI-FB2 item 4); the page opens a version with it the first time it sees it installed
149  const choice = readSource(new URL('../src/lib/pictures-choice.ts', import.meta.url), 'utf8');
150  assert.match(choice, /installed\.visionEnabled === false && \(installed\.visionPrepared !== false \|\| installed\.visionChosen === true\)\) return 'no'/);
151  assert.match(screen, /shownVision\(known, installed\)/);
152  assert.match(screen, /shownVision\(visionPicks\.current\.get\(selectedSize\.id\), undefined\)/, 'a version that is not downloaded starts with Read pictures on');
153});
154
155test('no recognised engine: the app still downloads, warns in the card, and loading says it with the next step', async () => {
156  const { ENGINE_NOT_RECOGNISED } = await import('../server/native-control.mjs');
157  assert.match(ENGINE_NOT_RECOGNISED, /Settings → About/);
158  assert.match(ENGINE_NOT_RECOGNISED, /didn’t recognise an engine/);
159  const source = readSource(new URL('../server/native-control.mjs', import.meta.url), 'utf8');
160  assert.equal((source.match(/ENGINE_NOT_RECOGNISED\+/g) ?? []).length, 2, 'both load paths use it');
161  const models = readSource(new URL('../src/components/NativeModels.tsx', import.meta.url), 'utf8');
162  const guided = readSource(new URL('../src/components/GuidedSetup.tsx', import.meta.url), 'utf8');
163  assert.match(models, /<EngineWarning native=\{native\}\/>/);
164  assert.match(guided, /<EngineWarning native=\{native\}\/>/);
165  const warn = readSource(new URL('../src/components/EngineWarning.tsx', import.meta.url), 'utf8');
166  assert.match(warn, /The model will download, but it may not run until the right engine is installed \(Settings → About\)\./);
167  // the install is not refused for a missing engine (only the engine-minimum refusal for a version that is too old stays)
168  assert.doesNotMatch(source.slice(source.indexOf('async function install(job,args)'), source.indexOf('function terminate')), /engine\.usable/);
169});
170
171test('the draft layer download of setup step 6 is a stage of its own and counts in the one figure (#3257)', () => {
172  lib.setTranslationLanguage('en');
173  const draft = { parts: [{ kind: 'model', name: 'Model files', state: 'done', done_gb: 60, total_gb: 60 }, { kind: 'draft', name: 'Draft layer', state: 'downloading', done_gb: 2, total_gb: 5 }] };
174  assert.deepEqual(lib.installStage(draft), { kind: 'draft' });
175  assert.equal(lib.stageText(lib.installStage(draft)), 'Preparing your model…');
176  const p = lib.installProgress(draft);
177  assert.equal(p.total_gb, 65);
178  assert.equal(p.done_gb, 62);
179});