okami.mom/strata

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

Niko1221Merge f-0213-guidata (final 1d5096beb) into f-0213-int85269ca15

main
10.6 KiB158 linesraw
1/**
2 * A reload does not stop an agent turn. The page that comes back takes the running turn over again: it shows as running (the Stop button), the
3 * rest of the answer streams in, the tool card that waits for a yes is there to answer, and the failure the page wrote when it lost the stream
4 * goes. A turn that ended while the page was away is shown whole. Nothing to take over leaves the reply as it was.
5 */
6import test from 'node:test';
7import assert from 'node:assert/strict';
8import { build } from 'esbuild';
9import { fileURLToPath } from 'node:url';
10import { mkdtempSync, rmSync } from 'node:fs';
11import { tmpdir } from 'node:os';
12import { join } from 'node:path';
13import { createChatStore } from '../server/chat-store.mjs';
14import { installFakeHostFetch } from './helpers/fake-host-chats.mjs';
15
16const here = (p) => fileURLToPath(new URL(p, import.meta.url));
17async function bundle(entry, plugins = []) {
18  const result = await build({
19    entryPoints: [here(entry)], bundle: true, format: 'esm', platform: 'node', write: false, logLevel: 'silent',
20    alias: { react: here('./helpers/react-stub.mjs') }, loader: { '.json': 'json' }, plugins,
21  });
22  // A different text each time: the same text would give the same module, with the first test's state in it.
23  return import(`data:text/javascript;base64,${Buffer.from(`${result.outputFiles[0].text}
24// ${Math.random()}`).toString('base64')}`);
25}
26
27const NETWORK = 'Network error. Try sending the message again.';
28const chatWithCutOffReply = (id, requestId, extra = {}) => ({
29  id, title: `Chat ${id}`, createdAt: '2026-11-04T10:00:00.000Z', updatedAt: '2026-11-04T10:01:00.000Z', workspace: 'C:/w', tokensIn: 0, tokensOut: 0,
30  messages: [
31    { id: `${id}-u`, role: 'user', content: 'build the thing', at: '2026-11-04T10:00:00.000Z' },
32    { id: `${id}-a`, role: 'assistant', content: 'I will start by', at: '2026-11-04T10:00:05.000Z', requestId, streaming: false, error: NETWORK, ...extra },
33  ],
34});
35
36async function pageOn(chatStore, { active = [], attach }) {
37  const fake = installFakeHostFetch(chatStore);
38  globalThis.window ??= globalThis;
39  globalThis.document ??= { addEventListener() {}, hasFocus: () => true, visibilityState: 'visible', documentElement: { dataset: {}, style: { setProperty() {} }, classList: { toggle() {}, add() {}, remove() {} } } };
40  const memory = new Map();
41  globalThis.localStorage = { get length() { return memory.size; }, key: (i) => [...memory.keys()][i] ?? null, getItem: (k) => memory.get(k) ?? null, setItem: (k, v) => { memory.set(k, v); }, removeItem: (k) => memory.delete(k) };
42  globalThis.navigator ??= { language: 'en' };
43  globalThis.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
44  globalThis.__attach = attach;
45  globalThis.__active = active;
46  globalThis.__attachCalls = [];
47  const mockClient = {
48    name: 'mock-client',
49    setup(b) {
50      b.onResolve({ filter: /\/client$/ }, () => ({ path: 'mock-client', namespace: 'mock' }));
51      b.onLoad({ filter: /.*/, namespace: 'mock' }, () => ({ loader: 'js', contents: `
52        export class ApiError extends Error { constructor(m, status, body) { super(m); this.status = status; this.body = body; } }
53        const reject = async () => { throw new Error('offline'); };
54        export const api = { get: async (path) => { if (path === '/api/chat/active') return { turns: globalThis.__active }; if (path.startsWith('/api/agent/pending')) return { pending: [] }; throw new Error('offline'); }, post: async () => ({}), put: reject, patch: reject, del: reject, delete: reject };
55        export function onEvent() { return () => {}; }
56        export async function streamPost(path, body, onFrame, signal) {
57          globalThis.__attachCalls.push({ path, body });
58          if (path !== '/api/chat/attach') return;
59          await globalThis.__attach(body, onFrame, signal, ApiError);
60        }` }));
61    },
62  };
63  const store = await bundle('../src/lib/store.ts', [mockClient]);
64  return { store, fake };
65}
66const until = async (check, what) => { for (let i = 0; i < 300; i++) { if (check()) return; await new Promise((r) => setTimeout(r, 10)); } assert.fail(`timed out waiting for ${what} (attach calls: ${JSON.stringify(globalThis.__attachCalls)})`); };
67
68test('reload in the middle of an agent turn: the chat shows as running with a Stop button, streams the rest, keeps the approval card, and ends whole', async () => {
69  const dir = mkdtempSync(join(tmpdir(), 'strata-reattach-'));
70  const chatStore = createChatStore({ dir });
71  let page;
72  try {
73    // What the page saved before it went away: the question, a cut-off reply, the failure it wrote when the stream broke.
74    await chatStore.save('s_run', JSON.stringify(chatWithCutOffReply('s_run', 'req-run')));
75    let release;
76    const finished = new Promise((r) => { release = r; });
77    page = await pageOn(chatStore, {
78      active: [{ chatId: 's_run', sessionId: 'sess-1', requestId: 'req-run', mode: 'manual', pending: [{ callId: 'call-9' }] }],
79      attach: async (body, onFrame) => {
80        assert.deepEqual(body, { sessionId: 's_run' }, 'a running turn is asked for by chat only');
81        onFrame({ type: 'start', model: 'm', contextMax: 8192, agent: true, resumed: true, requestId: 'req-run', sessionId: 'sess-1', mode: 'manual', skills: [] });
82        onFrame({ type: 'resync', content: 'I will start by reading the folder, then', reasoning: 'thinking so far' });
83        onFrame({ type: 'agent-tool', tool: { id: 'call-9', name: 'write', verb: 'Write', target: 'out.txt', args: {}, state: 'proposed', effect: 'Needs your approval.' } });
84        await finished;   // the turn goes on after the page is back
85        onFrame({ type: 'delta', text: ' writing the file.' });
86        onFrame({ type: 'agent-tool', tool: { id: 'call-9', name: 'write', verb: 'Write', target: 'out.txt', args: {}, state: 'done', result: 'wrote out.txt' } });
87        onFrame({ type: 'done', tokensIn: 10, tokensOut: 20, durationMs: 684000, usageSource: 'reported' });
88      },
89    });
90    const { store } = page;
91    await store.loadChatsFromHost();
92    await until(() => page.fake.calls.length && globalThis.__attachCalls.length === 1, 'the attach request');
93    store.selectSession('s_run');
94    const chat = () => store.useStore((s) => s.sessions).find((s) => s.id === 's_run');
95    const reply = () => chat().messages.at(-1);
96
97    // running again: this is what shows the Stop button (the page treats a chat with a live turn as streaming)
98    assert.equal(store.useStore((s) => s.streaming), true, 'the Stop button is there');
99    assert.equal(reply().streaming, true, 'the reply is running');
100    await until(() => reply().content.startsWith('I will start by reading the folder'), 'the catch-up text');
101    assert.equal(reply().error, undefined, 'the failure the page wrote is gone');
102    assert.equal(reply().reasoning, 'thinking so far');
103    const card = reply().tools.find((t) => t.id === 'call-9');
104    assert.equal(card.state, 'proposed', 'the approval waiting on the host is there to answer');
105    assert.equal(chat().messages.length, 2, 'no second reply was added');
106
107    // the rest of the turn streams into the same reply
108    release();
109    await until(() => reply().streaming === false, 'the end of the turn');
110    assert.equal(reply().content, 'I will start by reading the folder, then writing the file.');
111    assert.equal(reply().tools.find((t) => t.id === 'call-9').state, 'done');
112    assert.equal(store.useStore((s) => s.streaming), false, 'the Stop button goes away when the turn ends');
113    await store.flushSessions();
114    const saved = JSON.parse(await chatStore.read('s_run')).session.messages.at(-1);
115    assert.equal(saved.content, 'I will start by reading the folder, then writing the file.', 'and the whole answer is what is saved');
116    assert.equal(saved.streaming, false);
117  } finally { page?.fake.restore(); rmSync(dir, { recursive: true, force: true }); }
118});
119
120test('a turn that ended while the page was away is shown whole; a chat with nothing to take over keeps its reply and gets no error', async () => {
121  const dir = mkdtempSync(join(tmpdir(), 'strata-reattach2-'));
122  const chatStore = createChatStore({ dir });
123  let page;
124  try {
125    await chatStore.save('s_done', JSON.stringify(chatWithCutOffReply('s_done', 'req-done')));
126    await chatStore.save('s_gone', JSON.stringify(chatWithCutOffReply('s_gone', 'req-gone', { error: 'Response interrupted. Ask again to retry; the partial answer is kept.' })));
127    page = await pageOn(chatStore, {
128      active: [],
129      attach: async (body, onFrame, _signal, ApiError) => {
130        if (body.requestId === 'req-done') {
131          onFrame({ type: 'start', model: 'm', contextMax: 8192, agent: true, resumed: true, requestId: 'req-done', sessionId: 'sess-2', skills: [] });
132          onFrame({ type: 'resync', content: 'I will start by reading the folder. Done: 3 files changed.', reasoning: '' });
133          onFrame({ type: 'agent-tool', tool: { id: 'c1', name: 'write', verb: 'Write', target: 'a.txt', args: {}, state: 'done', result: 'ok' } });
134          onFrame({ type: 'done', tokensIn: 1, tokensOut: 2, durationMs: 5000, usageSource: 'reported' });
135          return;
136        }
137        throw new ApiError('{"error":"There is no turn to take over.","code":"no-turn"}', 404);   // the host holds nothing for this reply
138      },
139    });
140    const { store } = page;
141    await store.loadChatsFromHost();
142    await until(() => globalThis.__attachCalls.length >= 2, 'both asked about');
143    const sessions = () => store.useStore((s) => s.sessions);
144    await until(() => sessions().find((s) => s.id === 's_done').messages.at(-1).usageSource === 'reported', 'the finished turn');
145    const done = sessions().find((s) => s.id === 's_done').messages.at(-1);
146    assert.equal(done.content, 'I will start by reading the folder. Done: 3 files changed.');
147    assert.equal(done.error, undefined);
148    assert.equal(done.streaming, false);
149    assert.equal(done.tools[0].state, 'done');
150    await until(() => !store.useStore((s) => s.sessions).find((s) => s.id === 's_gone').messages.at(-1).streaming, 'the unanswered one settles');
151    const gone = sessions().find((s) => s.id === 's_gone').messages.at(-1);
152    assert.equal(gone.content, 'I will start by', 'its reply is as the page had it');
153    assert.equal(gone.error, 'Response interrupted. Ask again to retry; the partial answer is kept.', 'its error stays');
154    assert.equal(store.useStore((s) => s.toasts).length, 0, 'no failure is announced');
155    assert.deepEqual(globalThis.__attachCalls.map((c) => c.body.requestId).sort(), ['req-done', 'req-gone'], JSON.stringify(globalThis.__attachCalls));
156    assert.equal(store.useStore((s) => s.streaming), false);
157  } finally { page?.fake.restore(); rmSync(dir, { recursive: true, force: true }); }
158});