okami.mom/strata

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

Niko1221Merge f-023-int into f-023-guifcb0c2d0e

main
11.5 KiB155 linesraw
1/**
2 * Fixes from the real-engine functional test of the integrated build (notes-split-uitest.md, "Functional (real engine)"):
3 * tok/s and context in the agent path, plain-language tool rows, a launch that reports success, and the size and wording of
4 * what the agent sends to the model. The model is scripted; the Harness, the bridge and the projector are real.
5 */
6import test from 'node:test';
7import assert from 'node:assert/strict';
8import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
9import { tmpdir } from 'node:os';
10import { join } from 'node:path';
11import { TurnProjector, outcomeText, toolVerb } from '../server/agent/events.mjs';
12import { AGENT_PROMPT } from '../server/agent/preset.mjs';
13import { startScriptedWorker } from './helpers/scripted-worker.mjs';
14import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
15import { resolveHarness } from '../server/agent/harness-runtime.mjs';
16
17const HARNESS = process.env.STRATA_HARNESS_DIR;
18const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
19const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } };
20const ev = (type, data, seq = 1, time = 1000) => ({ type: 'event', event: { type, seq, time, data } });
21const chunk = (c, attemptId = 'a:1') => ({ type: 'assistant-stream', frame: { type: 'chunk', attemptId, chunk: c } });
22
23/** Run `fn` with a clock the test moves by hand. */
24function withClock(fn) {
25  const real = Date.now; let now = 1_000_000;
26  Date.now = () => now;
27  try { return fn(ms => { now += ms; }); } finally { Date.now = real; }
28}
29
30test('item 1: the agent path reports live tok/s while it streams and a final tok/s, not null', () => withClock(tick => {
31  const p = new TurnProjector({ startedAt: Date.now() });
32  const frames = [];
33  // 60 chunks of one token each, 25 ms apart: 40 tokens per second.
34  for (let i = 0; i < 60; i++) { tick(25); frames.push(...p.consume(chunk({ type: 'text-delta', index: 0, text: 'ab' }))); }
35  const stats = frames.filter(f => f.type === 'stats');
36  assert.ok(stats.length >= 2, 'live speed frames while the answer streams');
37  const last = stats.at(-1);
38  assert.equal(last.source, 'stream');
39  assert.ok(last.tps > 30 && last.tps < 50, `live tps ${last.tps}`);
40  p.consume(chunk({ type: 'usage', usage: { inputTokens: 900, outputTokens: 60 } }));
41  p.consume(ev('turn/end', { turn: 1, reason: { kind: 'completed' } }));
42  const done = p.finish({ model: 'M', contextMax: 65536 }).find(f => f.type === 'done');
43  assert.ok(done.tps > 30 && done.tps < 50, `final tps ${done.tps}`);
44  assert.equal(done.tokensOut, 60);
45}));
46
47test('item 1: reasoning tokens count towards the speed too (a thinking model streams reasoning first)', () => withClock(tick => {
48  const p = new TurnProjector({ startedAt: Date.now() });
49  for (let i = 0; i < 40; i++) { tick(20); p.consume(chunk({ type: 'reasoning-delta', index: 0, text: 'x' })); }
50  p.consume(ev('turn/end', { turn: 1, reason: { kind: 'completed' } }));
51  const done = p.finish({}).find(f => f.type === 'done');
52  assert.ok(done.tps > 40 && done.tps < 60, `tps ${done.tps}`);
53}));
54
55test('item 2: the context is the LAST request (prompt + reply), not the sum of every step', () => {
56  const p = new TurnProjector({ startedAt: 0 });
57  p.consume(chunk({ type: 'usage', usage: { inputTokens: 5000, outputTokens: 100 } }, 'a:1'));
58  p.consume(chunk({ type: 'usage', usage: { inputTokens: 5200, outputTokens: 300 } }, 'a:2'));
59  p.consume(chunk({ type: 'usage', usage: { inputTokens: 5600, outputTokens: 50 } }, 'a:3'));
60  p.consume(ev('turn/end', { turn: 1, reason: { kind: 'completed' } }));
61  const done = p.finish({ model: 'M', contextMax: 65536 }).find(f => f.type === 'done');
62  assert.equal(done.contextTokens, 5650, 'what the context holds after the turn');
63  assert.equal(done.tokensIn, 15800, 'the billed sum is still reported separately');
64});
65
66test('item 3: a prompt the server already held counts towards the context (the Harness reports it apart from the input)', () => {
67  const p = new TurnProjector({ startedAt: 0 });
68  // The shape of a real Swift 64K run: the last request had a prompt of 8,042 tokens of which 7,317 came from the conversation cache.
69  p.consume(chunk({ type: 'usage', usage: { inputTokens: 5800, outputTokens: 40, cacheReadTokens: 0 } }, 'a:1'));
70  p.consume(chunk({ type: 'usage', usage: { inputTokens: 725, outputTokens: 110, cacheReadTokens: 7317 } }, 'a:2'));
71  p.consume(ev('turn/end', { turn: 1, reason: { kind: 'completed' } }));
72  const done = p.finish({ model: 'M', contextMax: 65536 }).find(f => f.type === 'done');
73  assert.equal(done.contextTokens, 8152, 'prompt (input + cache) + reply of the last request, which is what the engine held');
74  assert.equal(done.tokensIn, 5800 + 725 + 7317);
75});
76
77test('item 7: tool rows say what happened in plain words, with what it was about', () => {
78  const p = new TurnProjector({ startedAt: 0 });
79  const call = p.consume(ev('tool/call', { callId: 'w1', name: 'write', arguments: JSON.stringify({ file_path: 'C:/work/notes.md', content: 'x' }) }))[0].tool;
80  assert.equal(call.verb, 'Writing a file'); assert.equal(call.target, 'C:/work/notes.md');
81  const asked = p.consume(ev('approval/asked', { id: 'a1', callId: 'w1', reason: 'Create or replace the file C:/work/notes.md' }))[0].tool;
82  assert.equal(asked.state, 'proposed'); assert.equal(asked.target, 'C:/work/notes.md', 'the approval card shows the file');
83  const ok = p.consume(ev('tool/result', { message: { toolCallId: 'w1', content: [{ type: 'text', text: 'written' }] } }))[0].tool;
84  assert.equal(ok.verb, 'Wrote a file');
85  p.consume(ev('tool/call', { callId: 'w2', name: 'write', arguments: JSON.stringify({ file_path: 'D:/x.txt' }) }));
86  const bad = p.consume(ev('tool/result', { message: { toolCallId: 'w2', isError: true, content: [{ type: 'text', text: 'denied' }] } }))[0].tool;
87  assert.equal(bad.state, 'error'); assert.equal(bad.verb, "Couldn't write the file");
88  const sh = p.consume(ev('tool/call', { callId: 's1', name: 'pwsh', arguments: JSON.stringify({ command: 'Get-ChildItem C:/work' }) }))[0].tool;
89  assert.equal(sh.verb, 'Running a command'); assert.equal(sh.target, 'Get-ChildItem C:/work');
90  const g = p.consume(ev('tool/call', { callId: 'g1', name: 'glob', arguments: JSON.stringify({ pattern: '**/*.md' }) }))[0].tool;
91  assert.equal(g.verb, 'Searching for files'); assert.equal(g.target, '**/*.md');
92  assert.equal(toolVerb('glob', 'done'), 'Searched for files');
93  assert.equal(toolVerb('some_connected_tool', 'running'), 'Using a tool');
94  for (const name of ['write', 'edit', 'read', 'glob', 'grep', 'pwsh', 'bash', 'web_fetch', 'todo_write']) {
95    for (const state of ['running', 'done', 'error']) assert.ok(!/^(write|edit|read|glob|grep|pwsh|bash|web_fetch|todo_write)\b/.test(toolVerb(name, state)), `${name} ${state}: no raw tool name`);
96  }
97});
98
99test('item 8 / T9: starting a program that prints nothing is reported as started, never as opened', () => {
100  for (const command of ['Start-Process explorer.exe C:\\work', 'explorer.exe C:\\work', 'start notepad', 'Invoke-Item C:\\work\\a.pdf', 'ii .', 'xdg-open .', 'open .']) {
101    const said = outcomeText('pwsh', '(no output)', { command });
102    assert.match(said, /^The command finished without an error, so the program was started\./, command);
103    assert.match(said, /cannot confirm that a window or page actually opened/, command);
104    assert.ok(!/was opened|is open/i.test(said), command);
105  }
106  assert.match(outcomeText('pwsh', '(no output)', { command: 'New-Item x.txt | Out-Null' }), /finished without any error/, 'other silent commands keep their wording');
107  assert.equal(outcomeText('pwsh', 'hello', { command: 'echo hello' }), 'hello', 'a command that printed something shows it');
108  const p = new TurnProjector({ startedAt: 0 });
109  p.consume(ev('tool/call', { callId: 'e1', name: 'pwsh', arguments: JSON.stringify({ command: 'Start-Process explorer.exe C:\\work' }) }));
110  const res = p.consume(ev('tool/result', { message: { toolCallId: 'e1', content: [{ type: 'text', text: '(no output)' }] } }))[0].tool;
111  assert.match(res.result, /cannot confirm that a window or page actually opened/); assert.equal(res.verb, 'Ran a command');
112});
113
114test('item 7/10: our prompt has no internal terms and is short', () => {
115  assert.ok(AGENT_PROMPT.length < 1600, `${AGENT_PROMPT.length} chars`);
116  assert.doesNotMatch(AGENT_PROMPT, /DSH|DeepSeek|sandbox|isolated session|file policy|Harness/i);
117  // O6 / #3576: the prompt points at the present tool for local files and never tells the model to claim a window opened
118  assert.match(AGENT_PROMPT, /use the present tool/);
119  assert.match(AGENT_PROMPT, /Never say a window opened, a page rendered/);
120  assert.doesNotMatch(AGENT_PROMPT, /say plainly that it is open|do not say you could not confirm/i);
121});
122
123test('items 3, 7, 10: what the agent sends the model is small, plain, and carries Thinking Off', { skip }, async t => {
124  const worker = await startScriptedWorker({});
125  const dir = mkdtempSync(join(tmpdir(), 'strata-fx-'));
126  const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
127  const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 65536 }];
128  const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });
129  t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
130  worker.requests.length = 0;
131  await bridge.runTurn({ chatId: 'fx-1', message: 'SCRIPT:echo hi', workspacePath: ws, mode: 'plan', thinking: 'Off', onFrame: () => {} });
132  const req = worker.requests.find(r => r.toolNames.length);
133  assert.ok(req, 'a request with tools');
134  assert.equal(req.params.chat_template_kwargs.enable_thinking, false, 'Thinking Off reaches the model request');
135  for (const kept of ['pwsh', 'read', 'write', 'edit', 'glob', 'grep', 'workflow', 'create_goal', 'update_goal', 'get_goal', 'skill', 'subagent_fork']) assert.ok(req.toolNames.includes(kept), `${kept} is offered (owner decision: the goal, skill, workflow and fork tools stay)`);
136});
137
138// The Reasoning menu in the agent: every level reaches the model server as chat_template_kwargs, and an unset menu is Medium (owner decision).
139for (const [level, thinking, effort] of [['Off', 'Off', undefined], ['Low', 'Low', 'low'], ['Medium', 'Medium', 'medium'], ['High', 'High', 'high'], ['unset (Medium)', undefined, 'medium']]) {
140  test(`agent Reasoning ${level}: the request carries chat_template_kwargs ${effort ? `enable_thinking true, reasoning_effort ${effort}` : 'enable_thinking false and no effort'}`, { skip }, async t => {
141    const worker = await startScriptedWorker({});
142    const dir = mkdtempSync(join(tmpdir(), 'strata-eff-'));
143    const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
144    const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 65536 }];
145    const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });
146    t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
147    worker.requests.length = 0;
148    await bridge.runTurn({ chatId: `eff-${level}`, message: 'SCRIPT:echo hi', workspacePath: ws, mode: 'plan', ...(thinking ? { thinking } : {}), onFrame: () => {} });
149    const req = worker.requests.find(r => r.toolNames.length);
150    assert.ok(req, 'a request with tools');
151    const kwargs = req.params.chat_template_kwargs;
152    assert.equal(kwargs.enable_thinking, effort !== undefined);
153    assert.equal(kwargs.reasoning_effort, effort);
154  });
155}