okami.mom/strata

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

Niko1221merge f-split-s4b 0edf5cb9f (Harness in the app chat, Manual approvals, request slots) into f-split-inta16109803

main
9.4 KiB161 linesraw
1/**
2 * Drive the real app through the S4b flow on a real model and take screenshots (playwright-core + installed Chrome).
3 *
4 *   STRATA_URL=http://127.0.0.1:8791 SHOTS=./shots METRICS=http://127.0.0.1:18797/metrics node scripts/agent-flow-s4b.mjs
5 *
6 * Against a host that has the Harness and one API connection saved (the model server), in Manual mode:
7 *   1. a coding task that starts two helper agents; the Subagents popover shows two rows; the engine metrics show both running together;
8 *      each helper's change to a file arrives as an Approve card, one card per change;
9 *   2. an edit to a file approved through one card (no blocked-attempt card, no sandbox text anywhere);
10 *   3. a web page fetch (a tool call), or its plain failure when offline;
11 *   4. Stop during helpers: rows stop, the host reports no active turn.
12 *
13 * Environment: STRATA_URL (required), SHOTS, MODEL (picker text), METRICS (engine /metrics URL, optional, with Authorization from KEY),
14 * PROMPT_HELPERS, PROMPT_EDIT, PROMPT_WEB, PROMPT_STOP, WORKDIR (the folder the agent works in, to check files), CHROME.
15 */
16import { chromium } from 'playwright-core';
17import { existsSync, mkdirSync, readFileSync } from 'node:fs';
18import { join, resolve } from 'node:path';
19
20const BASE = process.env.STRATA_URL;
21if (!BASE) { console.error('STRATA_URL is required'); process.exit(2); }
22const SHOTS = resolve(process.env.SHOTS ?? 'agent-shots-s4b');
23mkdirSync(SHOTS, { recursive: true });
24const MODEL = process.env.MODEL ?? 'Cloud model';
25const WORKDIR = process.env.WORKDIR;
26const PROMPT_HELPERS = process.env.PROMPT_HELPERS ?? 'Use two helper agents at the same time, one for each file. Helper one creates hello.py that prints the word hello. Helper two creates README.txt with one sentence about hello.py. Start both helpers right away with the subagent tool, then tell me when they are done.';
27const PROMPT_EDIT = process.env.PROMPT_EDIT ?? 'Read hello.py and then change it so it prints "hello world" instead of "hello". Use the edit tool.';
28const PROMPT_WEB = process.env.PROMPT_WEB ?? 'Use the web_fetch tool to open https://example.com and tell me the page title in one sentence.';
29const PROMPT_STOP = process.env.PROMPT_STOP ?? 'Start two helper agents with the subagent tool at once. Each one writes a long, detailed essay of at least 1500 words (one on the history of clocks, one on the history of bridges) and saves nothing. Tell me when they finish.';
30const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome'].find(existsSync);
31
32let failed = false;
33const check = (ok, label) => { console.log(`${ok ? 'ok  ' : 'FAIL'} ${label}`); if (!ok) failed = true; };
34const shot = async (page, name) => { await page.screenshot({ path: join(SHOTS, `${name}.png`) }); console.log(`shot ${name}.png`); };
35const browser = await chromium.launch({ executablePath: CHROME, headless: true });
36const page = await browser.newPage({ viewport: { width: 1512, height: 1000 } });
37const problems = [];
38page.on('pageerror', e => problems.push(`pageerror: ${e.message}`));
39page.on('console', m => { if (m.type() === 'error') problems.push(`console: ${m.text().slice(0, 200)}`); });
40
41const send = async text => { await page.locator('textarea').first().fill(text); await page.getByRole('button', { name: 'Send' }).click(); };
42const idle = async (ms = 600000) => page.waitForFunction(() => document.documentElement.dataset.streaming !== 'true', null, { timeout: ms });
43const agentsButton = () => page.locator('.chat-agents').first();
44const sandboxTalk = () => page.evaluate(() => /sandbox|Constrained|language mode|access denied/i.test(document.body.innerText));
45
46// the engine's own count of requests in flight, sampled once a second while a step runs
47let peak = 0, sampler = null;
48const startSampling = () => {
49  if (!process.env.METRICS) return;
50  peak = 0;
51  sampler = setInterval(async () => {
52    try {
53      const res = await fetch(process.env.METRICS, { headers: process.env.KEY ? { authorization: `Bearer ${process.env.KEY}` } : {} });
54      const m = await res.json();
55      const running = m.live?.running?.length ?? (Array.isArray(m.live?.slots) ? m.live.slots.filter(s => s.state && s.state !== 'idle').length : 0);
56      peak = Math.max(peak, running);
57    } catch { /* tunnel hiccup */ }
58  }, 1000);
59};
60const stopSampling = () => { clearInterval(sampler); sampler = null; };
61
62/** Click Approve on every card that asks, until the turn is over. Returns how many cards asked. */
63async function approveUntilIdle(label) {
64  let asked = 0;
65  const seen = new Set();
66  for (;;) {
67    const streaming = await page.evaluate(() => document.documentElement.dataset.streaming === 'true');
68    const cards = page.locator('.toolcard[data-state="proposed"]');
69    const n = await cards.count();
70    for (let i = 0; i < n; i++) {
71      const card = cards.nth(i);
72      const key = (await card.innerText()).slice(0, 200);
73      if (!seen.has(key)) { seen.add(key); asked++; await shot(page, `${label}-card-${asked}`); }
74      await card.getByRole('button', { name: 'Approve' }).click().catch(() => {});
75    }
76    if (!streaming && n === 0) break;
77    await page.waitForTimeout(400);
78  }
79  return asked;
80}
81
82try {
83  await page.goto(`${BASE}/#/chat`);
84  await page.waitForTimeout(2000);
85  const skip = page.getByText('Go straight to the app');
86  if (await skip.count()) { await skip.click(); await page.waitForTimeout(600); }
87  await page.getByRole('button', { name: 'New chat' }).first().click();
88  await page.waitForTimeout(600);
89  await page.getByRole('button', { name: /Choose model/ }).first().click();
90  await page.waitForTimeout(300);
91  await page.getByRole('menuitemradio', { name: new RegExp(MODEL) }).first().click();
92  await page.waitForTimeout(300);
93
94  // 1. two helpers
95  startSampling();
96  await send(PROMPT_HELPERS);
97  await page.waitForFunction(() => document.documentElement.dataset.streaming === 'true');
98  await page.waitForFunction(() => /[12] subagents? running/.test(document.querySelector('.chat-agents')?.getAttribute('title') ?? ''), null, { timeout: 600000 }).catch(() => {});
99  await agentsButton().click().catch(() => {});
100  await page.waitForTimeout(500);
101  await shot(page, '01-helpers-popover');
102  await page.keyboard.press('Escape');
103  const asked = await approveUntilIdle('01');
104  stopSampling();
105  await page.waitForTimeout(500);
106  await agentsButton().click().catch(() => {});
107  await page.waitForTimeout(500);
108  await shot(page, '02-helpers-done');
109  const popover = await page.locator('[role="dialog"], .popover').first().innerText().catch(() => '');
110  console.log('popover text:', popover.replace(/\s+/g, ' ').slice(0, 400));
111  await page.keyboard.press('Escape');
112  check(/2 /.test(popover) || (popover.match(/Completed|Done|Finished/gi) ?? []).length >= 2 || /Helper|helper/.test(popover) || popover.length > 40, 'the Subagents popover lists the helpers');
113  check(asked >= 1, `the helpers' changes reached the person as Approve cards (${asked})`);
114  if (process.env.METRICS) check(peak >= 2, `the engine ran at least 2 requests at the same time (peak ${peak})`);
115  if (WORKDIR) check(existsSync(join(WORKDIR, 'hello.py')), 'hello.py was written after the approval');
116  check(!(await sandboxTalk()), 'no sandbox or PowerShell error text anywhere in the chat');
117  check(await page.locator('.toolcard').count() === 0, 'no card is left waiting');
118
119  // 2. one edit, one card
120  await send(PROMPT_EDIT);
121  const editAsked = await approveUntilIdle('03-edit');
122  await page.waitForTimeout(500);
123  await shot(page, '04-edit-done');
124  check(editAsked >= 1, `the edit asked through a card (${editAsked} card(s) in total, one per change)`);
125  check(!(await sandboxTalk()), 'still no sandbox or PowerShell error text');
126  if (WORKDIR && existsSync(join(WORKDIR, 'hello.py'))) check(/hello world/i.test(readFileSync(join(WORKDIR, 'hello.py'), 'utf8')), 'hello.py now says hello world');
127
128  // 3. a web page
129  await send(PROMPT_WEB);
130  await approveUntilIdle('05-web');
131  await shot(page, '06-web-done');
132  check(await page.getByText(/web_fetch/).count() >= 1, 'a web_fetch card is in the chat');
133
134  // 4. Stop during helpers
135  await send(PROMPT_STOP);
136  await page.waitForFunction(() => document.documentElement.dataset.streaming === 'true');
137  await page.waitForFunction(() => /[12] subagents? running/.test(document.querySelector('.chat-agents')?.getAttribute('title') ?? ''), null, { timeout: 600000 });
138  await page.waitForTimeout(3000);
139  await shot(page, '07-stop-running');
140  const stop = page.getByRole('button', { name: /^Stop/ }).first();
141  check(await stop.count() === 1, 'a Stop button is visible while the helpers run');
142  const t0 = Date.now();
143  await stop.click();
144  await idle(120000);
145  await page.waitForTimeout(500);
146  const took = Date.now() - t0;
147  await shot(page, '08-after-stop');
148  const status = await (await fetch(`${BASE}/api/agent/status`)).json();
149  check(status.activeTurns === 0, 'the host reports no active turn after Stop');
150  check(!/[12] subagents? running/.test((await agentsButton().getAttribute('title')) ?? ''), 'no helper is shown as running after Stop');
151  check(took < 60000, `Stop finished the run in ${Math.round(took / 1000)} s`);
152  check(problems.length === 0, `no page errors (${problems.join(' | ') || 'none'})`);
153} catch (error) {
154  failed = true;
155  console.log(`FAIL ${error.message}`);
156  await page.screenshot({ path: join(SHOTS, 'zz-failure.png') }).catch(() => {});
157} finally {
158  stopSampling();
159  await browser.close();
160}
161process.exit(failed ? 1 : 0);