okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-nv (97b3d614f)1306424be

main
8.1 KiB93 linesraw
1/** Disposable UI fixture for the Tune model dialog: the real native control over fake models, and a pretend `strata` command that
2 * reports progress and a result after a few seconds. No weights, no engine. Needs the demo host on 5161 and a built dist. */
3import http from 'node:http';
4import { readFile, writeFile } from 'node:fs/promises';
5import { writeFileSync } from 'node:fs';
6import { resolve, extname } from 'node:path';
7import { nativeFixture } from '../helpers/native-fixture.mjs';
8
9const arg = (a, n) => { const i = a.indexOf(n); return i < 0 ? undefined : a[i + 1]; };
10let saved = [];
11const slot = 'fixture-slot';
12function status() {
13  const active = saved.find(p => p.active) ?? null;
14  return { ok: true, slot, suggested_name: 'IQ2_XS 32K – Work', active, state: active ? 'soft' : null, reasons: active ? ['the graphics driver changed'] : [], presets: saved, can_undo: saved.length > 0 };
15}
16const stages = [[0, 'Measuring your current settings', 9], [2000, 'Trying: Run the control thread on the last CPU core (round 1 of 2)', 7], [4000, 'Trying: Pin memory only when needed (round 2 of 2)', 3]];
17const handler = (child, args) => {
18  const cmd = args.slice(args.findIndex(a => String(a).endsWith('strata.py')) + 1);
19  const out = json => { child.stdout.emit('data', Buffer.from(JSON.stringify(json))); child.exitCode = 0; child.emit('exit', 0); child.emit('close', 0); };
20  if (cmd[0] === 'presets') {
21    if (cmd[1] === 'status') return out(status());
22    if (cmd[1] === 'list') return out({ ok: true, presets: saved });
23    const id = cmd[2];
24    if (cmd[1] === 'apply') saved = saved.map(p => ({ ...p, active: p.id === id }));
25    if (cmd[1] === 'delete') saved = saved.filter(p => p.id !== id);
26    if (cmd[1] === 'rename') saved = saved.map(p => p.id === id ? { ...p, name: cmd[3] } : p);
27    if (cmd[1] === 'undo') saved = saved.slice(1);
28    return out({ ok: true });
29  }
30  if (cmd[0] === 'tune') {
31    const sf = arg(cmd, '--status-file');
32    stages.forEach(([at, step, left], i) => setTimeout(() => { try { writeFileSync(sf, JSON.stringify({ state: 'running', stage: 'rounds', text: `Finding the fastest settings for your PC… about ${left} min left`, minutes_left: left, runs_done: i * 2 + 1, runs_planned: 8, message: step })); } catch { /* gone */ } }, at));
33    setTimeout(() => {
34      const preset = { id: 'c'.repeat(32), name: 'IQ2_XS 32K – Work', active: true, gain_pct: 11.6, answers: { class: 'exact', fields: [] } };
35      saved = [preset, ...saved.map(p => ({ ...p, active: false }))];
36      out({ ok: true, result: { outcome: 'improved', gain_pct: 11.6, seconds: 1100, preset, answers: { class: 'exact', fields: [] }, base: { decode_tok_s: 54.2 }, chosen: { decode_tok_s: 60.5 }, pairs: 2, faster_pairs: 2 } });
37    }, 7000);
38  }
39};
40const fixture = nativeFixture({ tuneHandler: handler });
41const control = fixture.control, root = resolve(import.meta.dirname, '../../dist'), upstream = process.env.TUNE_UPSTREAM ?? 'http://127.0.0.1:5161';
42// POST /__fixture/status-mode {mode: 'ok' | 'slow' | 'fail'}: how the saved-tunings read answers (the slow and failing cases of the greyed-out Start tuning, #4804).
43let statusMode = 'ok';
44// POST /__fixture/ask {on: true}: the next chat turn asks the person two questions and waits; the answer (or skip) is recorded and ends the turn.
45let askMode = false, askStream = null, askCall = 'call-ask-1';
46const asked = [];
47const askQuestions = [
48  { id: 'q1', header: 'Colour', question: 'Which colour should the page be?', detail: 'It sets the whole theme of the page.', options: [{ label: 'Red', description: 'Warm and strong' }, { label: 'Blue', description: 'Calm and neutral' }] },
49  { id: 'q2', question: 'Which extras do you want?', multiSelect: true, options: [{ label: 'Dark mode' }, { label: 'A print style' }, { label: 'Animations' }] },
50];
51await control.refresh(true);
52const server = http.createServer(async (req, res) => {
53  try {
54    const url = new URL(req.url, 'http://fixture'), path = url.pathname;
55    let text = ''; if (req.method !== 'GET') for await (const chunk of req) text += chunk;
56    const body = text ? JSON.parse(text) : {};
57    const json = value => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(value)); };
58    if (path === '/__fixture/capture' && req.method === 'POST') { await writeFile(process.env.TUNE_SHOT_DIR + '/' + body.name + '.png', Buffer.from(body.data, 'base64')); return json({ ok: true }); }
59    if (path === '/__fixture/ask' && req.method === 'POST') { askMode = body.on === true; return json({ ok: true }); }
60    if (path === '/__fixture/asked' && req.method === 'GET') return json(asked);
61    if (path === '/api/chat/stream' && req.method === 'POST' && askMode) {
62      res.writeHead(200, { 'content-type': 'application/x-ndjson', 'cache-control': 'no-cache' });
63      askStream = res;
64      res.write(JSON.stringify({ type: 'agent-question', callId: askCall, questions: askQuestions }) + '\n');
65      return;
66    }
67    if (path === '/api/chat/answer' && req.method === 'POST' && askMode) {
68      asked.push(body);
69      if (body.refuse) { res.writeHead(400, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ error: 'Answer every question, or skip them.' })); }
70      askStream?.write(JSON.stringify({ type: 'agent-question-end', callId: body.callId }) + '\n' + JSON.stringify({ type: 'done', durationMs: 10 }) + '\n');
71      askStream?.end(); askStream = null;
72      return json({ ok: true });
73    }
74    if (path === '/__fixture/status-mode' && req.method === 'POST') { statusMode = body.mode; return json({ ok: true }); }
75    if (path === '/api/native' && req.method === 'GET') return json(await control.refresh());
76    if (path === '/api/native/operations') return json(control.operation(body.kind, body.args));
77    if (path === '/api/native/tune/status' && statusMode === 'slow') await new Promise(r => setTimeout(r, 60000));
78    if (path === '/api/native/tune/status' && statusMode === 'fail') { res.writeHead(500, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ error: 'The tuning store did not answer.' })); }
79    if (path === '/api/native/tune/status') return json(await control.tuneStatus({ model: url.searchParams.get('model'), resourceProfile: url.searchParams.get('resourceProfile') || undefined, vision: url.searchParams.get('vision') || undefined }));
80    if (path === '/api/native/tune/undo') return json(await control.tunePresets.undoFor(body));
81    let m = /^\/api\/native\/tune\/presets\/([0-9a-f]+)\/(apply|rename|delete|undo)$/.exec(path); if (m) return json(await control.tunePresets.action(m[2], m[1], body));
82    m = /^\/api\/native\/operations\/([^/]+)\/cancel$/.exec(path); if (m) return json(await control.cancel(m[1]));
83    if (path === '/api/native/benchmark') return json(control.benchmarkReport());
84    if (path === '/api/hardware') { const v = await (await fetch(upstream + path)).json(); return json({ ...v, gpus: [{ index: 0, id: 'gpu-0', vendor: 'nvidia', name: 'NVIDIA RTX 4090', vramGb: 24, backend: 'cuda', unified: false }] }); }
85    if (path.startsWith('/api/')) { const r = await fetch(upstream + req.url, { method: req.method, headers: text ? { 'content-type': 'application/json' } : {}, body: text || undefined }); res.writeHead(r.status, { 'content-type': r.headers.get('content-type') ?? 'application/json' }); res.end(Buffer.from(await r.arrayBuffer())); return; }
86    const file = path === '/' ? '/index.html' : path; if (file.includes('..')) throw new Error('Invalid fixture path');
87    const content = await readFile(root + file);
88    res.writeHead(200, { 'content-type': ({ '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.png': 'image/png' })[extname(file)] ?? 'application/octet-stream' }); res.end(content);
89  } catch (e) { res.writeHead(400, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: e.message })); }
90});
91server.listen(Number(process.env.TUNE_UI_PORT ?? 5270), '127.0.0.1', () => console.log('Tune UI fixture ready'));
92let stopping = false; async function stop() { if (stopping) return; stopping = true; server.closeAllConnections(); server.close(); await fixture.cleanup(); process.exit(0); }
93process.on('SIGTERM', stop); process.on('SIGINT', stop);