okami.mom/strata

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

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

main
10.1 KiB119 linesraw
1import { ROOMY_HOST } from './helpers/hardware.mjs';
2/** Host regressions use a disposable demo home. No browser automation or model downloads. */
3import assert from 'node:assert/strict';
4import { test } from 'node:test';
5import { spawn } from 'node:child_process';
6import { mkdtemp, rm } from 'node:fs/promises';
7import { tmpdir } from 'node:os';
8import { join, resolve } from 'node:path';
9import { createServer } from 'node:net';
10import { createRequire } from 'node:module';
11import { build } from 'esbuild';
12
13const root = resolve(import.meta.dirname, '..');
14
15test('Markdown renders every incomplete stream prefix without looping', { timeout: 15000 }, async () => {
16  const bundle = await build({
17    stdin: { contents: `import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import { Markdown } from './src/components/Markdown.tsx'; export {setTranslationLanguage as setLanguage, loadCatalog} from './src/lib/i18n.ts'; export const render = text => renderToStaticMarkup(React.createElement(Markdown, { text }));`, resolveDir: root },
18    bundle: true, write: false, platform: 'node', format: 'cjs', jsx: 'automatic', external: ['katex', 'katex/dist/katex.min.css'],   // math loads on demand in the browser
19    plugins: [{ name: 'copy-control-stub', setup(b) {
20      b.onResolve({ filter: /^\.\/ui$/ }, () => ({ path: 'ui', namespace: 'test-stub' }));
21      b.onLoad({ filter: /.*/, namespace: 'test-stub' }, () => ({ contents: 'export const IconBtn = () => null; export const Btn = () => null; export const Icon = () => null;' }));
22    } }],
23  });
24  // SSR is a parser regression, not a substitute for browser appearance checks.
25  const mod = { exports: {} };
26  new Function('require', 'module', 'exports', bundle.outputFiles[0].text)(createRequire(import.meta.url), mod, mod.exports);
27  const { render, setLanguage, loadCatalog } = mod.exports;
28  for (const l of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) await loadCatalog(l);  // the non-English catalogs load on first use (src/lib/i18n.ts loadCatalog); load them before the first tr()
29  for(const language of ['zh','ja','de','es','ru','pt','ko','fr']) { setLanguage(language); const markup=render('Ready\n\n**Settings**\n\n*Download*\n\n[Cancel](https://example.com)\n\n| Name | Value |\n| --- | --- |\n| Close | Language |'); for(const word of ['Ready','Settings','Download','Cancel','Name','Value','Close','Language'])assert(markup.includes(word),language+': user text changed: '+word); }
30  setLanguage('en');
31  for (const marker of ['- ', '* ', '+ ', '1. ', '2) ', '  - ', '  12. ']) assert.ok(render(marker).includes(marker));
32  const text = '# Answer\n\n- First item\n- Second item\n\n1. First step\n2. Second step\n\n```js\nconsole.log("hello");\n```\n\n| Name | Value |\n| --- | --- |\n| One | Two |';
33  for (let i = 0; i <= text.length; i++) assert.equal(typeof render(text.slice(0, i)), 'string');
34  assert.match(render(text), /<ul>/); assert.match(render(text), /<ol>/); assert.match(render(text), /<table/);
35  assert.ok(!render('<script>alert(1)</script>').includes('<script>'));
36  // #3268: math is found in a paragraph and as a block; until KaTeX is loaded it shows as source, and money is plain text
37  assert.match(render('Radius $r = 2$ here'), /md-math md-math--source/);
38  assert.match(render('$$\nx = 1\n$$'), /md-math-block/);
39  assert.ok(!render('costs $5 and $10').includes('md-math'));
40  for (let i = 0; i <= 40; i++) assert.equal(typeof render('A $$x^2 + y$$ and $q$ b'.slice(0, i)), 'string');
41});
42
43test('setup, config and lifecycle preserve truthful outcomes in the demo host', { timeout: 30000 }, async () => {
44  const home = await mkdtemp(join(tmpdir(), 'strata-reliability-'));
45  const socket = createServer(); await new Promise(r => socket.listen(0, '127.0.0.1', r));
46  const port = socket.address().port; await new Promise(r => socket.close(r));
47  const host = spawn(process.execPath, ['server/index.mjs'], { cwd: root, env: { ...process.env, STRATA_HOME:home,STRATA_MODELS_DIR:join(home,'models'), STRATA_PORT: String(port), STRATA_REAL_ENGINE: '0', STRATA_TEST_HARDWARE: ROOMY_HOST }, stdio: ['ignore', 'pipe', 'pipe'] });
48  let logs = ''; host.stdout.on('data', d => logs += d); host.stderr.on('data', d => logs += d);
49  const base = `http://127.0.0.1:${port}`;
50  async function call(path, method = 'GET', body) {
51    const response = await fetch(base + path, { method, headers: body ? { 'Content-Type': 'application/json' } : undefined, body: body ? JSON.stringify(body) : undefined });
52    return { status: response.status, data: await response.json() };
53  }
54  try {
55    for (let i = 0; i < 80; i++) { try { if ((await call('/api/models')).status === 200) break; } catch {} await new Promise(r => setTimeout(r, 100)); }
56    assert.equal((await call('/api/setup/complete', 'POST')).status, 409);
57    await call('/api/setup/step', 'POST', { step: 3, dismissed: true, choices: { variantId: 'qwen38-q4_k_m', contextLength: '8k', profile: 'performance', batch: 1024, batchAuto: false } });
58    let setup = (await call('/api/setup')).data;
59    assert.equal(setup.complete, false); assert.equal(setup.step, 2); assert.equal(setup.dismissed, true); assert.equal(setup.choices.contextLength, '8k'); assert.equal(setup.choices.profile, 'performance'); assert.equal(setup.choices.batch, 1024); assert.equal(setup.choices.batchAuto, false);
60    const before = (await call('/api/engine')).data;
61    const expert = before.expert.map(p => ({ id: p.id, value: p.id === 'perf.batch' ? 1024 : p.id === 'sample.temp' ? 0.9 : p.value }));
62    expert.push({ id: 'custom.future-option', value: 77 });
63    assert.equal((await call('/api/engine', 'PATCH', { beginner: before.beginner, expert, replaceExpert: true, extra: { futureAdapter: 'preserved' } })).status, 200);
64    const invalid = await call('/api/engine', 'PATCH', { expert: [{ id: 'sample.temp', value: 99 }] });
65    assert.equal(invalid.status, 400);
66    assert.equal((await call('/api/engine')).data.expert.find(p => p.id === 'sample.temp').value, 0.9);
67    await call('/api/engine', 'PATCH', { expert: before.expert.filter(p => p.id.startsWith('sample.')).map(p => ({ id: p.id, value: p.recommended })) });
68    const after = (await call('/api/engine')).data;
69    assert.equal(after.expert.find(p => p.id === 'sample.temp').value, 0.6);
70    assert.equal(after.expert.find(p => p.id === 'perf.batch').value, 1024);
71    assert.equal(after.expert.find(p => p.id === 'custom.future-option').value, 77);
72    assert.equal(after.extra.futureAdapter, 'preserved');
73    assert.equal((await call('/api/engine/restart', 'POST')).status, 500);
74    const installing = await call('/api/models/qwen38-q4_k_m/install', 'POST');
75    assert.equal(installing.data.mode, 'simulated'); assert.ok(Array.isArray(installing.data.variants));
76    assert.equal(installing.data.loaded, null);
77    assert.equal((await call('/api/setup/complete', 'POST')).status, 409);
78    await call('/api/models/qwen38-q4_k_m/cancel', 'POST');
79    assert.equal((await call('/api/models')).data.variants.find(v => v.id === 'qwen38-q4_k_m').state, 'available');
80    await call('/api/models/qwen38-q4_k_m/install', 'POST');
81    let installed = false;
82    for (let i = 0; i < 120; i++) { const lib = (await call('/api/models')).data; if (lib.variants.find(v => v.id === 'qwen38-q4_k_m').state === 'installed') { installed = true; break; } await new Promise(r => setTimeout(r, 100)); }
83    assert.ok(installed, logs);
84    const loadingPromise = call('/api/models/qwen38-q4_k_m/load', 'POST');
85    await new Promise(r => setTimeout(r, 100));
86    // Simulated runtime placement can complete synchronously; native loads expose loading until healthy.
87    assert.ok(['loading','loaded'].includes((await call('/api/models')).data.variants.find(v => v.id === 'qwen38-q4_k_m').state));
88    assert.equal((await loadingPromise).data.loaded, 'qwen38-q4_k_m');
89    assert.equal((await call('/api/setup/complete', 'POST')).data.complete, true);
90    await call('/api/setup/step', 'POST', { step: 3, dismissed: true, choices: { contextLength: '16k' } });
91    const resumed = (await call('/api/setup')).data;
92    assert.equal(resumed.complete, false);
93    assert.equal(resumed.step, 2);
94    assert.equal(resumed.choices.contextLength, '16k'); assert.equal(resumed.choices.profile, 'performance'); assert.equal(resumed.choices.batch, 1024);
95    const monitor = (await call('/api/monitor')).data;
96    assert.equal(monitor.telemetry.memory, 'demo'); assert.equal(monitor.telemetry.thermals, 'demo');
97    const skills = (await call('/api/skills')).data;
98    await call('/api/skills/' + skills[0].id, 'PATCH', { enabled: false, onlyIn: 'root' });
99    const fs = await import('node:fs/promises');
100    const persisted = JSON.parse(await fs.readFile(join(home, 'data/state.json'), 'utf8'));
101    assert.equal(persisted.skillPreferences[skills[0].id].enabled, false);
102    assert.equal(persisted.skillPreferences[skills[0].id].onlyIn, 'root');
103    const changedSkill = { name: 'Review helper', description: 'Checks the draft.', body: 'Find missing evidence. Explain each finding.', triggers: ['check draft', 'review text'] };
104    assert.equal((await call('/api/skills/' + skills[0].id, 'PATCH', changedSkill)).status, 200);
105    const rescannedSkill = (await call('/api/skills')).data.find(s => s.id === skills[0].id);
106    assert.equal(rescannedSkill.body, changedSkill.body); assert.equal(rescannedSkill.name, changedSkill.name);
107    assert.equal(rescannedSkill.enabled, false); assert.equal(rescannedSkill.onlyIn, 'root');
108    assert.equal((await call('/api/skills/' + skills[0].id, 'PATCH', { body: '' })).status, 400);
109    assert.equal((await call('/api/skills/not-found', 'PATCH', changedSkill)).status, 404);
110    assert.equal((await call('/api/skills')).data.find(s => s.id === skills[0].id).body, changedSkill.body);
111    const savedEdits = JSON.parse(await fs.readFile(join(home, 'data/state.json'), 'utf8'));
112    assert.deepEqual(savedEdits.skillEdits[skills[0].id], changedSkill);
113    await call('/api/models/unload', 'POST');
114    assert.equal((await call('/api/models')).data.loaded, null);
115    assert.equal((await call('/api/setup/complete', 'POST')).status, 409);
116  } finally {
117    host.kill('SIGTERM'); await new Promise(r => host.once('exit', r)); await rm(home, { recursive: true, force: true });
118  }
119});