okami.mom/strata

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

Niko1221Functional-test fixes: agent tok/s and context, plain tool rows, Thinking Off proof, profile used, no download wording for installed models, plain chat, smaller agent prompt394de9291

main
15.6 KiB253 linesraw
1/**
2 * The host's HTTP surface for agent chats, against a real host process, the real Harness and a
3 * scripted worker standing in as an API model.
4 *
5 * Needs STRATA_HARNESS_DIR (a built Harness) for everything except the "component missing" test.
6 * What is exercised: /api/chat/stream (NDJSON), /api/chat/approval, /api/chat/stop, /api/agent/status,
7 * resume across a host restart, two chats at once, and the visible fallback when the component is absent.
8 */
9import test from 'node:test';
10import assert from 'node:assert/strict';
11import { spawn, spawnSync } from 'node:child_process';
12import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
13import { createServer } from 'node:net';
14import { tmpdir } from 'node:os';
15import { join, resolve } from 'node:path';
16import { startScriptedWorker } from './helpers/scripted-worker.mjs';
17import { resolveHarness } from '../server/agent/harness-runtime.mjs';
18
19const HARNESS = process.env.STRATA_HARNESS_DIR;
20const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
21const HOST = resolve(import.meta.dirname, '..', 'server', 'index.mjs');
22
23const freePort = () => new Promise(r => { const s = createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); }); });
24const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* the Harness sandbox leaves access entries; best effort */ } };
25const sleep = ms => new Promise(r => setTimeout(r, ms));
26
27async function startHost(t, { home, ws, harness = HARNESS } = {}) {
28  const port = await freePort();
29  const env = { ...process.env, STRATA_HOME: home, STRATA_PORT: String(port), STRATA_WORKSPACE: ws, STRATA_REAL_ENGINE: '0', STRATA_COMPONENTS_DIR: join(home, 'components') };
30  if (harness) env.STRATA_HARNESS_DIR = harness; else delete env.STRATA_HARNESS_DIR;
31  const child = spawn(process.execPath, [HOST], { env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
32  let log = '';
33  child.stdout.on('data', d => { log += d; }); child.stderr.on('data', d => { log += d; });
34  const stop = async () => {
35    if (child.exitCode !== null) return;
36    if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true });
37    else child.kill('SIGTERM');
38    await new Promise(r => child.once('exit', r));
39  };
40  t.after(stop);
41  const base = `http://127.0.0.1:${port}`;
42  for (let i = 0; i < 100; i++) {
43    try { if ((await fetch(`${base}/api/agent/status`)).ok) break; } catch { /* not up yet */ }
44    if (child.exitCode !== null) throw new Error(`the host exited: ${log.slice(-500)}`);
45    await sleep(200);
46  }
47  const post = async (path, body) => { const res = await fetch(`${base}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); return { status: res.status, body: await res.json().catch(() => null) }; };
48  /** Stream one chat turn; `onFrame` may react while it runs. Resolves with every frame. */
49  const chat = async (body, onFrame = () => {}) => {
50    const res = await fetch(`${base}/api/chat/stream`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
51    assert.equal(res.status, 200, `chat/stream: ${res.status}`);
52    const frames = []; let buffer = '';
53    const decoder = new TextDecoder();
54    for await (const chunk of res.body) {
55      buffer += decoder.decode(chunk, { stream: true });
56      let i;
57      while ((i = buffer.indexOf('\n')) >= 0) {
58        const line = buffer.slice(0, i).trim(); buffer = buffer.slice(i + 1);
59        if (line) { const f = JSON.parse(line); frames.push(f); onFrame(f); }
60      }
61    }
62    return frames;
63  };
64  return { base, port, post, chat, stop, log: () => log, status: async () => (await fetch(`${base}/api/agent/status`)).json() };
65}
66
67async function setup(t, { harness = HARNESS, reuse } = {}) {
68  const worker = reuse?.worker ?? await startScriptedWorker({ model: 'cloud-model' });
69  const home = reuse?.home ?? mkdtempSync(join(tmpdir(), 'strata-host-'));
70  const ws = join(home, 'workspace'); mkdirSync(ws, { recursive: true });
71  const host = await startHost(t, { home, ws, harness });
72  let connectionId = reuse?.connectionId;
73  if (!connectionId) {
74    const saved = await host.post('/api/model-providers', { 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 }] });
75    assert.equal(saved.status, 200, JSON.stringify(saved.body));
76    connectionId = saved.body.connections[0].id;
77  }
78  if (!reuse) t.after(async () => { await worker.close(); cleanup(home); });
79  const remoteModel = { connectionId, modelId: 'cloud-model' };
80  const send = (host, sessionId, message, onFrame) => host.chat({ sessionId, message, remoteModel, workspaceId: null, history: [] }, onFrame);
81  return { worker, home, ws, host, connectionId, remoteModel, send: (sessionId, message, onFrame) => send(host, sessionId, message, onFrame) };
82}
83
84const toolStates = (frames, id) => frames.filter(f => f.type === 'agent-tool' && (!id || f.tool.id === id)).map(f => f.tool.state);
85const text = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');
86const lines = file => readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean).length;
87
88test('status names the component and the routes, and carries no secret', { skip }, async t => {
89  const s = await setup(t);
90  const status = await s.host.status();
91  assert.equal(status.harness.version, '0.2.1-alpha.3');
92  assert.ok(status.routes.some(r => r.kind === 'api' && r.modelId === 'cloud-model'));
93  assert.ok(!JSON.stringify(status).includes('sk-host-test'));
94});
95
96test('A03 over HTTP: the card waits for Approve, the answer reaches the Harness, the tool runs once', { skip }, async t => {
97  const s = await setup(t);
98  let answered = false;
99  const frames = await s.send('chat-h-a03', 'SCRIPT:tool http.txt hi', async f => {
100    if (f.type === 'agent-tool' && f.tool.state === 'proposed' && !answered) {
101      answered = true;
102      const r = await s.host.post('/api/chat/approval', { sessionId: 'chat-h-a03', toolId: f.tool.id, decision: 'approve' });
103      assert.equal(r.status, 200, JSON.stringify(r.body));
104    }
105  });
106  assert.ok(answered, 'an approval request must have reached the client');
107  const id = frames.find(f => f.type === 'agent-tool').tool.id;
108  assert.deepEqual([...new Set(toolStates(frames, id))], ['running', 'proposed', 'done']);
109  assert.equal(lines(join(s.ws, 'http.txt')), 1);
110  assert.equal(frames.at(-1).type, 'done');
111  // A second answer to the same approval is refused: it is no longer pending.
112  const again = await s.host.post('/api/chat/approval', { sessionId: 'chat-h-a03', toolId: id, decision: 'approve' });
113  assert.equal(again.status, 409);
114});
115
116test('A04 over HTTP: Deny means the tool never runs', { skip }, async t => {
117  const s = await setup(t);
118  const frames = await s.send('chat-h-a04', 'SCRIPT:tool never-http.txt x', async f => {
119    if (f.type === 'agent-tool' && f.tool.state === 'proposed') await s.host.post('/api/chat/approval', { sessionId: 'chat-h-a04', toolId: f.tool.id, decision: 'deny' });
120  });
121  assert.equal(toolStates(frames).at(-1), 'denied');
122  assert.equal(existsSync(join(s.ws, 'never-http.txt')), false);
123  assert.equal(frames.at(-1).type, 'done');
124});
125
126test('A05 over HTTP: /api/chat/stop ends that chat only and answers after the turn ended', { skip }, async t => {
127  const s = await setup(t);
128  let live = 0, stopResult = null;
129  const slow = s.send('chat-h-a05-a', 'SCRIPT:slow 400', async f => {
130    if (f.type === 'delta' && ++live === 3) stopResult = await s.host.post('/api/chat/stop', { sessionId: 'chat-h-a05-a' });
131  });
132  const other = s.send('chat-h-a05-b', 'SCRIPT:slow 50');
133  const [a, b] = await Promise.all([slow, other]);
134  assert.equal(stopResult.status, 200);
135  assert.equal(stopResult.body.stopped, true); assert.equal(stopResult.body.ended, 'aborted');
136  assert.equal(a.at(-1).finishReason, 'aborted');
137  assert.equal(b.at(-1).finishReason, 'stop'); assert.equal(b.filter(f => f.type === 'delta').length, 50);
138  assert.ok(s.worker.aborted >= 1);
139  // Nothing to stop afterwards.
140  const none = await s.host.post('/api/chat/stop', { sessionId: 'chat-h-a05-a' });
141  assert.equal(none.body.stopped, false);
142});
143
144test('a client that disconnects does not stop the turn; the tool still waits for its approval', { skip }, async t => {
145  const s = await setup(t);
146  const controller = new AbortController();
147  const res = await fetch(`${s.host.base}/api/chat/stream`, { method: 'POST', headers: { 'content-type': 'application/json' }, signal: controller.signal, body: JSON.stringify({ sessionId: 'chat-h-detach', message: 'SCRIPT:tool detach.txt d', remoteModel: s.remoteModel, history: [] }) });
148  const reader = res.body.getReader(); let seen = '';
149  while (!seen.includes('"proposed"')) { const { value, done } = await reader.read(); if (done) break; seen += new TextDecoder().decode(value); }
150  assert.match(seen, /"proposed"/);
151  controller.abort();                                            // the tab closes
152  await sleep(500);
153  assert.equal(existsSync(join(s.ws, 'detach.txt')), false, 'a closed tab is not an approval');
154  const pending = await (await fetch(`${s.host.base}/api/agent/pending?chatId=chat-h-detach`)).json();
155  assert.equal(pending.pending.length, 1, 'the approval is still waiting for someone');
156  // Someone comes back and answers it; the turn finishes in the background.
157  const r = await s.host.post('/api/chat/approval', { sessionId: 'chat-h-detach', toolId: pending.pending[0].callId, decision: 'approve' });
158  assert.equal(r.status, 200);
159  for (let i = 0; i < 100 && !existsSync(join(s.ws, 'detach.txt')); i++) await sleep(100);
160  assert.equal(lines(join(s.ws, 'detach.txt')), 1);
161});
162
163test('A06 over HTTP: after the host restarts, the same chat resumes its session and nothing is replayed', { skip }, async t => {
164  const first = await setup(t);
165  const frames1 = await first.send('chat-h-a06', 'SCRIPT:tool again.txt once', async f => {
166    if (f.type === 'agent-tool' && f.tool.state === 'proposed') await first.host.post('/api/chat/approval', { sessionId: 'chat-h-a06', toolId: f.tool.id, decision: 'approve' });
167  });
168  assert.equal(frames1.at(-1).type, 'done');
169  const sessionBefore = JSON.parse(readFileSync(join(first.home, 'data', 'agent', 'sessions.json'), 'utf8'))['chat-h-a06'].sessionId;
170  await first.host.stop();
171  const second = await setup(t, { reuse: { worker: first.worker, home: first.home, connectionId: first.connectionId } });
172  const frames2 = await second.send('chat-h-a06', 'SCRIPT:echo back again');
173  assert.equal(text(frames2), 'back again');
174  assert.equal(frames2.filter(f => f.type === 'agent-tool').length, 0);
175  assert.equal(lines(join(second.ws, 'again.txt')), 1, 'the first turn\'s tool did not run a second time');
176  const sessionAfter = JSON.parse(readFileSync(join(second.home, 'data', 'agent', 'sessions.json'), 'utf8'))['chat-h-a06'].sessionId;
177  assert.equal(sessionAfter, sessionBefore);
178  t.after(() => { cleanup(first.home); });
179  await first.worker.close().catch(() => {});
180});
181
182test('A08 over HTTP: two chats stream at the same time without mixing', { skip }, async t => {
183  const s = await setup(t);
184  const [a, b] = await Promise.all([s.send('chat-h-a08-a', 'SCRIPT:slow 30'), s.send('chat-h-a08-b', 'SCRIPT:echo only b')]);
185  assert.equal(a.filter(f => f.type === 'delta').length, 30);
186  assert.equal(text(b), 'only b');
187  assert.ok(!text(a).includes('only b') && !text(b).includes('w0'));
188  assert.notEqual(a.find(f => f.type === 'start').sessionId, b.find(f => f.type === 'start').sessionId);
189});
190
191test('/goal over HTTP: shown, set with rounds that stream into the chat, and refused when one is unfinished', { skip }, async t => {
192  const s = await setup(t);
193  const status = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');
194  assert.match(status(await s.send('chat-h-goal', '/goal')), /No goal is set/);
195  assert.match(status(await s.send('chat-h-goal', '/goal edit nothing')), /no goal in this chat yet/i);
196  assert.equal((await s.host.status()).activeTurns, 0);
197});
198
199test('without the agent component the chat says so and still uses the model the user chose', async t => {
200  const s = await setup(t, { harness: null });
201  const status = await s.host.status();
202  assert.equal(status.state, 'unavailable'); assert.match(status.reason, /coding assistant/i);
203  const frames = await s.send('chat-h-fallback', 'SCRIPT:hello');
204  const notice = frames.find(f => f.type === 'notice');
205  assert.equal(notice.code, 'agent-unavailable'); assert.match(notice.message, /coding assistant isn.t installed/); assert.match(notice.message, /Chat works without it/);
206  assert.match(notice.details, /agent component/, 'the technical text is kept apart as details');
207  assert.equal(frames.filter(f => f.type === 'agent-tool').length, 0);
208  assert.match(text(frames), /Hello from the scripted worker/);
209  // The direct path used the API model the chat picked, nothing else.
210  assert.ok(s.worker.requests.length >= 1 && s.worker.requests.every(q => q.model === 'cloud-model'));
211});
212
213test('Mode over HTTP: the chat body carries the Mode menu choice; Plan refuses a write, Bypass writes, Manual asks', { skip }, async t => {
214  const s = await setup(t);
215  const body = (sessionId, message, mode) => ({ sessionId, message, remoteModel: s.remoteModel, workspaceId: null, history: [], ...(mode ? { mode } : {}) });
216
217  const plan = await s.host.chat(body('chat-h-plan', 'SCRIPT:retrywrite plan-http.txt x', 'plan'));
218  assert.equal(plan.find(f => f.type === 'start').mode, 'plan');
219  assert.equal(existsSync(join(s.ws, 'plan-http.txt')), false);
220  assert.ok(!toolStates(plan).includes('proposed'));
221  assert.equal(toolStates(plan).at(-1), 'denied');
222
223  const bypass = await s.host.chat(body('chat-h-bypass', 'SCRIPT:retrywrite bypass-http.txt x', 'bypass'));
224  assert.equal(lines(join(s.ws, 'bypass-http.txt')), 1);
225  assert.ok(!toolStates(bypass).includes('proposed'));
226
227  // No mode in the body (an older page) is Manual: it asks.
228  let asked = false;
229  const manual = await s.host.chat(body('chat-h-manual', 'SCRIPT:retrywrite manual-http.txt x'), async f => {
230    if (f.type === 'agent-tool' && f.tool.state === 'proposed' && !asked) {
231      asked = true;
232      assert.equal(existsSync(join(s.ws, 'manual-http.txt')), false);
233      await s.host.post('/api/chat/approval', { sessionId: 'chat-h-manual', toolId: f.tool.id, decision: 'approve' });
234    }
235  });
236  assert.ok(asked);
237  assert.equal(manual.find(f => f.type === 'start').mode, 'manual');
238  assert.equal(lines(join(s.ws, 'manual-http.txt')), 1);
239  assert.equal(manual.filter(f => f.type === 'agent-tool').at(-1).tool.approved, true);
240});
241
242test('item 9: a chat that asks for no tools never runs one (agent:false and tools:false answer directly)', { skip }, async t => {
243  const s = await setup(t);
244  for (const [chatId, flag] of [['chat-plain-a', { agent: false }], ['chat-plain-t', { tools: false }]]) {
245    s.worker.requests.length = 0;
246    const frames = await s.host.chat({ sessionId: chatId, message: 'SCRIPT:tool plain-never.txt x', remoteModel: s.remoteModel, workspaceId: null, history: [], ...flag });
247    assert.equal(frames.filter(f => f.type === 'agent-tool').length, 0, `${chatId}: no tool card`);
248    assert.ok(!frames.some(f => f.type === 'start' && f.agent === true), `${chatId}: not an agent turn`);
249    assert.ok(!frames.some(f => f.type === 'notice' && f.code === 'agent-skipped'), `${chatId}: asking for plain chat is not a surprise to explain`);
250    assert.equal(existsSync(join(s.ws, 'plain-never.txt')), false);
251    assert.ok(s.worker.requests.length >= 1 && s.worker.requests.every(r => r.toolNames.length === 0), `${chatId}: the model was offered no tool`);
252  }
253});