okami.mom/strata

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

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
12.1 KiB216 linesraw
1/**
2 * #4878: a quiet desktop chat stream stays open. The chat answer is NDJSON; during a long silence (prompt processing, a tool,
3 * an approval wait) a `{"type":"beat"}` frame goes out every 15 seconds so the web view does not drop the request at 60 s.
4 *  - the helper, with fake timers: a 60-second tool wait gives the beats, and the timer ends on finish, on close, on error and
5 *    on stop(), with no interval left behind;
6 *  - the real route, against a real host and a scripted API model that goes silent: beats arrive, a client that goes away
7 *    cancels the model request before the next beat, the next message works, and two chats stay independent.
8 * The frontend consumer (src/lib/store.ts) has no branch for an unknown frame type, so `beat` changes nothing there; the last
9 * test pins that.
10 */
11import test from 'node:test';
12import assert from 'node:assert/strict';
13import { EventEmitter } from 'node:events';
14import { spawn, spawnSync } from 'node:child_process';
15import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
16import { createServer } from 'node:net';
17import { tmpdir } from 'node:os';
18import { join, resolve } from 'node:path';
19import { startScriptedWorker } from './helpers/scripted-worker.mjs';
20import { BEAT_MS, beatInterval, keepStreamAlive } from '../server/stream-beat.mjs';
21
22/** A response stand-in: records writes, emits finish/close like http.ServerResponse. */
23function fakeResponse() {
24  const res = new EventEmitter();
25  res.writes = [];
26  res.writableEnded = false;
27  res.destroyed = false;
28  res.write = chunk => { res.writes.push(String(chunk)); return true; };
29  res.end = () => { res.writableEnded = true; res.emit('finish'); res.emit('close'); };
30  return res;
31}
32const beats = res => res.writes.filter(w => w === '{"type":"beat"}\n').length;
33const listeners = res => ['finish', 'close', 'error'].reduce((n, e) => n + res.listenerCount(e), 0);
34
35test('the interval is 15 s; a tester can shorten it; nonsense is the default', () => {
36  assert.equal(BEAT_MS, 15_000);
37  assert.equal(beatInterval({}), 15_000);
38  assert.equal(beatInterval({ STRATA_STREAM_BEAT_MS: '200' }), 200);
39  for (const bad of ['0', '-5', 'abc', '', '5', '999999', 'NaN']) assert.equal(beatInterval({ STRATA_STREAM_BEAT_MS: bad }), 15_000, bad);
40});
41
42test('a 60-second silent tool wait carries a beat every 15 s, each a whole NDJSON line', t => {
43  t.mock.timers.enable({ apis: ['setInterval'] });
44  const res = fakeResponse();
45  const stop = keepStreamAlive(res);
46  t.mock.timers.tick(14_999);
47  assert.equal(beats(res), 0, 'nothing before 15 s');
48  t.mock.timers.tick(1);
49  assert.equal(beats(res), 1);
50  t.mock.timers.tick(45_000);
51  assert.equal(beats(res), 4, 'four beats in 60 s');
52  for (const w of res.writes) assert.deepEqual(JSON.parse(w), { type: 'beat' });
53  assert.ok(res.writes.every(w => w.endsWith('\n') && w.indexOf('\n') === w.length - 1));
54  stop();
55});
56
57test('the timer is cleared on finish, on close, on error and by stop(): nothing beats afterwards, no listener is left', t => {
58  t.mock.timers.enable({ apis: ['setInterval'] });
59  for (const how of ['finish', 'close', 'error', 'stop', 'end']) {
60    const res = fakeResponse();
61    const stop = keepStreamAlive(res);
62    t.mock.timers.tick(15_000);
63    assert.equal(beats(res), 1, how);
64    if (how === 'stop') stop(); else if (how === 'end') res.end(); else res.emit(how, new Error('x'));
65    const after = res.writes.length;
66    t.mock.timers.tick(120_000);
67    assert.equal(res.writes.length, after, `${how}: no beat after the end`);
68    assert.equal(listeners(res), 0, `${how}: no listener left on the response`);
69    stop();   // calling it again is harmless
70  }
71});
72
73test('a response that was destroyed or ended without an event is not written to, and its timer goes at the next tick', t => {
74  t.mock.timers.enable({ apis: ['setInterval'] });
75  const a = fakeResponse(); keepStreamAlive(a); a.destroyed = true;
76  const b = fakeResponse(); keepStreamAlive(b); b.writableEnded = true;
77  const c = fakeResponse(); keepStreamAlive(c); c.write = () => { throw new Error('socket closed'); };
78  t.mock.timers.tick(15_000);
79  assert.equal(a.writes.length + b.writes.length, 0);
80  t.mock.timers.tick(120_000);
81  assert.equal(a.writes.length + b.writes.length, 0);
82  assert.equal(listeners(a) + listeners(b) + listeners(c), 0);
83});
84
85test('two responses beat independently: ending one leaves the other beating', t => {
86  t.mock.timers.enable({ apis: ['setInterval'] });
87  const one = fakeResponse(), two = fakeResponse();
88  keepStreamAlive(one); keepStreamAlive(two);
89  t.mock.timers.tick(30_000);
90  assert.equal(beats(one), 2); assert.equal(beats(two), 2);
91  one.emit('close');
92  t.mock.timers.tick(30_000);
93  assert.equal(beats(one), 2, 'the closed chat stops');
94  assert.equal(beats(two), 4, 'the other keeps going');
95});
96
97/* ---------------------------------------------------------------- the real route --- */
98
99const HOST = resolve(import.meta.dirname, '..', 'server', 'index.mjs');
100const freePort = () => new Promise(r => { const s = createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); }); });
101const sleep = ms => new Promise(r => setTimeout(r, ms));
102const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } };
103
104async function setup(t, beatMs) {
105  const worker = await startScriptedWorker({ model: 'cloud-model' });
106  const home = mkdtempSync(join(tmpdir(), 'strata-beat-'));
107  const ws = join(home, 'workspace'); mkdirSync(ws, { recursive: true });
108  const port = await freePort();
109  const env = {
110    ...process.env, STRATA_HOME: home, STRATA_PORT: String(port), STRATA_WORKSPACE: ws, STRATA_REAL_ENGINE: '0',
111    STRATA_COMPONENTS_DIR: join(home, 'components'), STRATA_STREAM_BEAT_MS: String(beatMs),
112    STRATA_SETTINGS_FILE: join(home, 'app-settings.json'), LOCALAPPDATA: join(home, 'Local'), APPDATA: join(home, 'Roaming'),
113    XDG_DATA_HOME: join(home, 'xdg-data'), XDG_STATE_HOME: join(home, 'xdg-state'), XDG_CONFIG_HOME: join(home, 'xdg-config'),
114    STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()),
115  };
116  delete env.STRATA_HARNESS_DIR;
117  const child = spawn(process.execPath, [HOST], { env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
118  let log = '';
119  child.stdout.on('data', d => { log += d; }); child.stderr.on('data', d => { log += d; });
120  t.after(async () => {
121    if (child.exitCode === null) {
122      if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true });
123      else child.kill('SIGTERM');
124      await new Promise(r => child.once('exit', r));
125    }
126    await worker.close(); cleanup(home);
127  });
128  const base = `http://127.0.0.1:${port}`;
129  for (let i = 0; i < 100; i++) {
130    try { if ((await fetch(`${base}/api/health`)).ok) break; } catch { /* not up yet */ }
131    if (child.exitCode !== null) throw new Error(`the host exited: ${log.slice(-500)}`);
132    await sleep(100);
133  }
134  const saved = await fetch(`${base}/api/model-providers`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ kind: 'custom', name: 'Scripted API', baseUrl: worker.url, protocol: 'openai-chat', apiKey: 'sk-host-test-0123456789', models: [{ id: 'cloud-model', name: 'Cloud model', contextMax: 64000 }] }) });
135  assert.equal(saved.status, 200);
136  const connectionId = (await saved.json()).connections[0].id;
137  const remoteModel = { connectionId, modelId: 'cloud-model' };
138  /** Open a chat stream; frames are handed to onFrame as they arrive; abort() drops the connection like a client that left. */
139  const chat = (sessionId, message, onFrame = () => {}) => {
140    const controller = new AbortController();
141    const frames = [];
142    const done = (async () => {
143      const res = await fetch(`${base}/api/chat/stream`, { method: 'POST', headers: { 'content-type': 'application/json' }, signal: controller.signal, body: JSON.stringify({ sessionId, message, remoteModel, history: [], agent: false }) });
144      assert.equal(res.status, 200);
145      let buffer = '';
146      const decoder = new TextDecoder();
147      for await (const chunk of res.body) {
148        buffer += decoder.decode(chunk, { stream: true });
149        let i;
150        while ((i = buffer.indexOf('\n')) >= 0) { const line = buffer.slice(0, i).trim(); buffer = buffer.slice(i + 1); if (line) { const f = JSON.parse(line); frames.push(f); onFrame(f); } }
151      }
152      return frames;
153    })();
154    return { frames, done, abort: () => controller.abort() };
155  };
156  return { worker, chat, alive: () => child.exitCode === null, log: () => log };
157}
158const until = async (fn, ms = 8000) => { const end = Date.now() + ms; while (Date.now() < end) { if (fn()) return true; await sleep(25); } return false; };
159
160test('route: a silent API model gets beats; a client that leaves cancels the model request before the next beat', { timeout: 40_000 }, async t => {
161  const s = await setup(t, 300);
162  let first = null;
163  const quiet = s.chat('chat-beat-a', 'SCRIPT:hang', f => { if (f.type === 'beat' && first === null) first = Date.now(); });
164  assert.ok(await until(() => quiet.frames.filter(f => f.type === 'beat').length >= 2), 'two beats while the model says nothing');
165  const framesBefore = quiet.frames.length;
166  quiet.abort();
167  await assert.rejects(quiet.done, { name: 'AbortError' });
168  // the next beat is 300 ms away: the model request must already be cancelled well before it
169  assert.ok(await until(() => s.worker.aborted >= 1, 1500), 'disconnect cancelled the direct model request');
170  assert.ok(framesBefore >= 2);
171  const next = s.chat('chat-beat-a', 'SCRIPT:echo still works');
172  const frames = await next.done;
173  assert.equal(frames.filter(f => f.type === 'delta').map(f => f.text).join(''), 'still works');
174  assert.equal(frames.at(-1).type, 'done');
175  assert.ok(s.alive(), 'the host is alive');
176});
177
178test('route: two chats at once are independent; leaving one does not touch the other', { timeout: 40_000 }, async t => {
179  const s = await setup(t, 250);
180  const a = s.chat('chat-beat-1', 'SCRIPT:hang');
181  const b = s.chat('chat-beat-2', 'SCRIPT:hang');
182  const count = c => c.frames.filter(f => f.type === 'beat').length;
183  assert.ok(await until(() => count(a) >= 2 && count(b) >= 2), 'both beat');
184  a.abort();
185  await assert.rejects(a.done, { name: 'AbortError' });
186  assert.ok(await until(() => s.worker.aborted === 1, 1500), 'exactly the one request was cancelled');
187  const frozen = count(a);
188  const bBefore = count(b);
189  assert.ok(await until(() => count(b) >= bBefore + 2), 'the other chat keeps getting beats');
190  assert.equal(count(a), frozen, 'the chat that left gets nothing more');
191  assert.equal(s.worker.aborted, 1, 'the other model request was not cancelled');
192  b.abort();
193  await assert.rejects(b.done, { name: 'AbortError' });
194  assert.ok(await until(() => s.worker.aborted === 2, 1500));
195  assert.ok(s.alive());
196});
197
198test('route: a normal answer is unchanged (beats only fill silence) and the stream still ends', { timeout: 40_000 }, async t => {
199  const s = await setup(t, 20_000);   // longer than the test: no beat should appear in a fast answer
200  const frames = await s.chat('chat-beat-fast', 'SCRIPT:echo hello there').done;
201  assert.equal(frames.filter(f => f.type === 'delta').map(f => f.text).join(''), 'hello there');
202  assert.equal(frames.filter(f => f.type === 'beat').length, 0);
203  assert.equal(frames.at(-1).type, 'done');
204});
205
206test('the desktop consumer ignores a frame type it does not know (so beat changes nothing there)', () => {
207  const store = readFileSync(resolve(import.meta.dirname, '..', 'src', 'lib', 'store.ts'), 'utf8');
208  const start = store.indexOf("if (type === 'delta' || type === 'reasoning') { queueText");
209  const doneAt = store.indexOf("} else if (type === 'done') {", start);
210  assert.ok(start > 0 && doneAt > start, 'found the frame handler');
211  // the chain is if / else if only and its last branch is `done`: no final `else` follows it, so an unknown type falls through silently
212  assert.match(store.slice(doneAt, doneAt + 2500), /flushSessions\(\);\s*\}\s*\},/);
213  assert.ok(!store.slice(start, doneAt).includes("type === 'beat'"), 'no special case is needed');
214  const client = readFileSync(resolve(import.meta.dirname, '..', 'src', 'lib', 'client.ts'), 'utf8');
215  assert.match(client, /onFrame\(JSON\.parse\(line\)/);
216});