okami.mom/strata

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

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
9.3 KiB135 linesraw
1import { ROOMY_HOST } from './helpers/hardware.mjs';   // the demo model loads whatever the memory of the PC running the test (a 7 GB Mac runner did not)
2import assert from 'node:assert/strict';
3import { test } from 'node:test';
4import http from 'node:http';
5import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';
6import { tmpdir } from 'node:os';
7import { join } from 'node:path';
8import { spawn } from 'node:child_process';
9import { transform } from 'esbuild';
10import { RequestQueue } from '../server/request-queue.mjs';
11import { selectSkills, skillInstructions } from '../server/skill-selection.mjs';
12
13const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
14const listen = server => new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve(server.address().port)));
15const close = server => new Promise(resolve => server.close(resolve));
16
17test('a cancelled queued request never executes or interrupts the active task', async () => {
18  const queue = new RequestQueue();
19  const active = new AbortController(), queued = new AbortController();
20  let finish, ran = false;
21  const first = queue.run(active.signal, () => new Promise(resolve => { finish = resolve; }));
22  const second = queue.run(queued.signal, () => { ran = true; });
23  assert.equal(queue.waiting, 1);
24  queued.abort();
25  await assert.rejects(second, { name: 'AbortError' });
26  assert.equal(ran, false); assert.equal(active.signal.aborted, false);
27  finish('done'); assert.equal(await first, 'done');
28  assert.equal(await queue.run(new AbortController().signal, () => 'next'), 'next');
29});
30
31test('skill instructions require both enabled state and a matching workspace', () => {
32  const skills = [
33    { id: 'global', name: 'Global review', enabled: true, triggers: ['review'], body: 'Check correctness.' },
34    { id: 'scoped', name: 'Local review', enabled: true, onlyIn: 'a', triggers: ['review'], body: 'Check project rules.' },
35    { id: 'disabled', name: 'Disabled', enabled: false, onlyIn: 'a', triggers: ['review'], body: 'Never inject me.' },
36  ];
37  assert.deepEqual(selectSkills(skills, 'review this', 'a').map(s => s.id), ['global', 'scoped']);
38  assert.deepEqual(selectSkills(skills, 'review this', 'b').map(s => s.id), ['global']);
39  assert.deepEqual(selectSkills(skills, 'hello', 'a'), []);
40  assert.match(skillInstructions(selectSkills(skills, 'review this', 'a')), /Check project rules/);
41});
42
43test('stream usage comes from the server, includes reasoning latency and preserves instructions', async () => {
44  const home = await mkdtemp(join(tmpdir(), 'strata-stream-test-'));
45  process.env.STRATA_HOME = home;
46  process.env.STRATA_MODELS_DIR = join(home, 'models');
47  const { proxyCompletion } = await import('../server/inference.mjs');
48  let request;
49  const fixture = http.createServer(async (req, res) => {
50    let body = ''; for await (const chunk of req) body += chunk;
51    request = JSON.parse(body);
52    res.writeHead(200, { 'content-type': 'text/event-stream' });
53    // Deliberately split one SSE line and finish without a trailing newline.
54    res.write('data: {"choices":[{"delta":{"reasoning_content":"Check it"}}]}\n\n');
55    await wait(20);
56    res.write('data: {"choices":[{"delta":{"content":"Several words in a single');
57    res.write(' chunk"}}]}\n\n');
58    res.end('data: {"choices":[],"usage":{"prompt_tokens":31,"completion_tokens":9,"prompt_tokens_details":{"cached_tokens":7}}}');
59  });
60  const port = await listen(fixture);
61  try {
62    const frames = [];
63    const result = await proxyCompletion({ baseUrl: `http://127.0.0.1:${port}`, message: 'review', history: [{ role: 'system', content: 'Client instruction' }], systemPrompt: 'Skill: review\nCheck correctness.', onFrame: f => frames.push(f), signal: new AbortController().signal });
64    assert.equal(result.tokensOut, 9); assert.equal(result.tokensIn, 31); assert.equal(result.cachedTokens, 7);
65    assert.equal(result.usageSource, 'reported'); assert.ok(result.ttftMs < result.durationMs);
66    assert.match(request.messages[0].content, /Check correctness/); assert.equal(request.messages[1].content, 'Client instruction');
67    assert.equal(frames.filter(f => f.type === 'delta').length, 1);
68  } finally { await close(fixture); await rm(home, { recursive: true, force: true }); }
69});
70
71test('a stream without usage never presents chunks as tokens', async () => {
72  const { proxyCompletion } = await import('../server/inference.mjs');
73  const fixture = http.createServer((req, res) => { req.resume(); res.writeHead(200, { 'content-type': 'text/event-stream' }); res.end('data: {"choices":[{"delta":{"content":"many words"}}]}\n\ndata: [DONE]\n\n'); });
74  const port = await listen(fixture);
75  try {
76    const result = await proxyCompletion({ baseUrl: `http://127.0.0.1:${port}`, message: 'hello', onFrame: () => {}, signal: new AbortController().signal });
77    assert.equal(result.tokensIn, null); assert.equal(result.tokensOut, null); assert.equal(result.tps, null); assert.equal(result.usageSource, 'unavailable');
78  } finally { await close(fixture); }
79});
80
81test('Serving cancellation stops active and queued demo requests; test keys enforce access', { timeout: 90000 }, async () => {
82  const home = await mkdtemp(join(tmpdir(), 'strata-request-host-'));
83  await mkdir(join(home, 'data'));
84  const id = 'qwen38-q4_k_m';
85  await writeFile(join(home, 'data/state.json'), JSON.stringify({ installed: { [id]: { installedAt: new Date().toISOString(), bytes: 491400032, simulated:true } }, beginner:{priority:'balanced',contextLength:'32k',readImages:false,gpuIdle:'never'}, current: id, loaded: id }));
86  const socket = http.createServer(); const port = await listen(socket); await close(socket);
87  const host = spawn(process.execPath, ['server/index.mjs'], { cwd: join(import.meta.dirname, '..'), 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' });
88  const base = `http://127.0.0.1:${port}`;
89  const call = async (path, method = 'GET', body, key) => {
90    const res = await fetch(base + path, { method, headers: { 'content-type': 'application/json', ...(key ? { authorization: `Bearer ${key}` } : {}) }, body: body ? JSON.stringify(body) : undefined });
91    return { status: res.status, data: await res.json() };
92  };
93  try {
94    // A host started on a loaded computer can take many seconds to listen; wait for it, and say so if it never does (a 4 s wait made this test flaky).
95    let up = false;
96    for (let i = 0; i < 600 && !up; i++) { try { up = (await call('/api/health')).status === 200; } catch {} if (!up) await wait(50); }
97    assert.ok(up, 'the host did not start listening within 30 s');
98    const stream = () => fetch(base + '/api/chat/stream', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ message: 'Explain this test in detail' }) }).then(r => r.text());
99    const first = stream(); await wait(100); const second = stream(); await wait(100);
100    let rows = (await call('/api/serving')).data.requests;
101    const active = rows.find(r => r.state === 'generating'), queued = rows.find(r => r.state === 'queued');
102    assert.ok(active); assert.ok(queued);
103    await call(`/api/serving/requests/${queued.id}/cancel`, 'POST');
104    const secondFrames = (await second).trim().split('\n').map(JSON.parse);
105    assert.equal(secondFrames.some(f => f.type === 'done'), false); assert.ok(secondFrames.some(f => f.type === 'error'));
106    rows = (await call('/api/serving')).data.requests;
107    assert.equal(rows.find(r => r.id === active.id).state, 'generating');
108    await call(`/api/serving/requests/${active.id}/cancel`, 'POST');
109    const firstFrames = (await first).trim().split('\n').map(JSON.parse);
110    assert.equal(firstFrames.some(f => f.type === 'done'), false); assert.ok(firstFrames.some(f => f.type === 'error'));
111    rows = (await call('/api/serving')).data.requests;
112    assert.ok(rows.every(r => r.state === 'error' && !r.cancellable && r.durationMs > 0));
113    await call('/api/serving', 'PATCH', { apiKey: 'disposable-test-key' });
114    assert.equal((await call('/v1/models')).status, 401);
115    assert.equal((await call('/v1/models', 'GET', undefined, 'disposable-test-key')).status, 200);
116    await call('/api/serving', 'PATCH', { apiKey: null });
117    assert.equal((await call('/v1/models')).status, 200);
118  } finally {
119    const ended = new Promise(resolve => host.once('exit', resolve)); host.kill('SIGTERM'); await ended;
120    await rm(home, { recursive: true, force: true });
121  }
122});
123
124// Reproduces the browser-observed race: final SSE event arrives before the
125// slower HTTP response carrying the earlier Cancelling state.
126test('a late cancel response cannot overwrite a completed request event', async () => {
127  const source = await readFile(new URL('../src/lib/serving-state.ts', import.meta.url), 'utf8');
128  const compiled = await transform(source, { loader: 'ts', format: 'esm' });
129  const { newestServingState } = await import(`data:text/javascript;base64,${Buffer.from(compiled.code).toString('base64')}`);
130  const cancelling = { revision: 100, requests: [{ state: 'generating', cancelRequested: true }] };
131  const completed = { revision: 101, requests: [{ state: 'error', cancellable: false }] };
132  assert.equal(newestServingState(completed, cancelling), completed);
133  assert.equal(newestServingState(cancelling, completed), completed);
134  assert.equal(newestServingState(null, completed), completed);
135});