test(app): verify streaming chat and stage debugging in the browser
This commit is contained in:
@@ -0,0 +1,161 @@
|
||||
// Real normal-app interaction against isolated, deterministic protocol data.
|
||||
// node tool/chat_stage_debug_probe.mjs <web-build> <evidence-dir>
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
|
||||
import { once } from 'node:events';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { startFixture } from './runs_probe_server.mjs';
|
||||
import { launchChrome, waitForPort, waitForPage, connect, sleep } from './pipelines_probe_cdp_lib.mjs';
|
||||
import { enableSemantics, assertName, capture, waitFor, axNodes, clickAt } from './pipelines_probe_cdp_input.mjs';
|
||||
|
||||
const output = resolve(process.argv[3] ?? 'build/chat-stage-debug-evidence');
|
||||
await mkdir(output, { recursive: true });
|
||||
const files = {
|
||||
'/artifacts/77/1/input.md': '# Raw input\nExact original harness input.\n',
|
||||
'/artifacts/77/1/output.md': '# Raw output\nExact original harness output.\n',
|
||||
'/artifacts/77/1/memory.md': '# Memory\nExact memory read by the stage.\n',
|
||||
'/artifacts/77/1/session.html': '<!doctype html><title>Recorded session</title><p>Exact session export</p>',
|
||||
};
|
||||
const step = {
|
||||
sequence: 1, stage: 'plan', status: 'completed', outcome: 'success',
|
||||
input: { prompt: 'Parsed stage input, initially hidden' },
|
||||
output: { result: 'Parsed stage output, initially hidden' },
|
||||
session_id: 'stage-debug-session',
|
||||
session_export: { html: 'session.html', status: 'complete', messages: 3, html_bytes: 100 },
|
||||
artifacts: Object.entries(files).map(([url, text]) => ({
|
||||
name: url.split('/').at(-1), url, size_bytes: Buffer.byteLength(text),
|
||||
content_type: url.endsWith('.html') ? 'text/html' : 'text/markdown',
|
||||
})),
|
||||
};
|
||||
const fixture = await startFixture({
|
||||
root: resolve(process.argv[2] ?? 'build/chat_stage_debug_web'), files,
|
||||
runDetail: {
|
||||
id: 77, title: 'Stage debugging fixture', status: 'succeeded',
|
||||
graph: { stages: [{ key: 'plan', type: 'model', edges: { success: '#success' } }] },
|
||||
steps: [step],
|
||||
},
|
||||
});
|
||||
const profile = await mkdtemp(join(tmpdir(), 'chat-stage-debug-'));
|
||||
const chrome = launchChrome('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', profile, 'about:blank');
|
||||
const log = { checks: [], captures: [] };
|
||||
let connection;
|
||||
try {
|
||||
const port = await waitForPort(join(profile, 'DevToolsActivePort'));
|
||||
connection = await connect((await waitForPage(port)).webSocketDebuggerUrl);
|
||||
await connection.send('Page.enable');
|
||||
await connection.send('Emulation.setDeviceMetricsOverride', {
|
||||
width: 390, height: 844, deviceScaleFactor: 1, mobile: true,
|
||||
});
|
||||
const visit = async (path) => {
|
||||
await connection.send('Page.navigate', { url: fixture.url + path });
|
||||
assert.ok(await waitFor(() => connection.evaluate(
|
||||
"Boolean(document.querySelector('flt-semantics-placeholder'))"), 12000));
|
||||
await enableSemantics(connection);
|
||||
};
|
||||
const click = async (label, prefix = false) => {
|
||||
const target = (await axNodes(connection)).find(node =>
|
||||
(node.name?.value === label || (prefix && node.name?.value?.startsWith(label))) && node.backendDOMNodeId &&
|
||||
['button', 'tab', 'group', 'link'].includes(node.role?.value));
|
||||
assert.ok(target, `No accessible control named ${label}`);
|
||||
const { model } = await connection.send('DOM.getBoxModel', { backendNodeId: target.backendDOMNodeId });
|
||||
const [x1, y1, , , x3, y3] = model.content;
|
||||
await clickAt(connection, (x1 + x3) / 2, (y1 + y3) / 2);
|
||||
};
|
||||
const event = async (body) => {
|
||||
const response = await fetch(fixture.url + '/fixture/chat-event', {
|
||||
method: 'POST', body: JSON.stringify(body),
|
||||
});
|
||||
assert.equal(response.status, 200);
|
||||
await sleep(300);
|
||||
};
|
||||
// Flutter web paints SelectableText reasoning/raw documents on its canvas;
|
||||
// those bodies are not consistently present in Chrome's accessibility tree.
|
||||
const assertPainted = async (text, label, name) => {
|
||||
await capture(connection, output, log, name);
|
||||
const { stdout } = await promisify(execFile)('tesseract', [
|
||||
log.captures.at(-1), 'stdout',
|
||||
]);
|
||||
const normalize = value => value.toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||
assert.ok(normalize(stdout).includes(normalize(text)), `${label}: ${stdout}`);
|
||||
log.checks.push(label);
|
||||
};
|
||||
await visit('/chat/ses_probechat');
|
||||
await assertName(connection, 'Stored probe answer.', 'stored chat loaded', log);
|
||||
await event({ kind: 'step', step: { status: 'running', turn_id: 'stream-turn' } });
|
||||
await event({ kind: 'reasoning', message_id: 'live-answer',
|
||||
part: { id: 'reasoning-0', type: 'reasoning' }, delta: 'Checking the recorded evidence.' });
|
||||
await event({ kind: 'text', message_id: 'live-answer',
|
||||
part: { id: 'text-0', type: 'text' }, delta: 'The answer is arriving.' });
|
||||
await assertPainted('Checking the recorded evidence.', 'reasoning visible while text streams', 'chat-live-reasoning');
|
||||
await assertName(connection, 'The answer is arriving.', 'streamed answer visible', log);
|
||||
const field = (await axNodes(connection)).find(node => node.role?.value === 'textbox');
|
||||
assert.ok(field, 'composer text field');
|
||||
const { model } = await connection.send('DOM.getBoxModel', { backendNodeId: field.backendDOMNodeId });
|
||||
const [x1, y1, , , x3, y3] = model.content;
|
||||
await clickAt(connection, (x1 + x3) / 2, (y1 + y3) / 2);
|
||||
await connection.send('Input.insertText', { text: 'A follow-up while you work' });
|
||||
// The empty Cupertino hint is two lines; typing shrinks the field to one.
|
||||
// Wait for that layout before taking the Send control's bounds.
|
||||
await sleep(300);
|
||||
await click('Send');
|
||||
assert.ok(await waitFor(async () => {
|
||||
const state = await (await fetch(fixture.url + '/fixture/state')).json();
|
||||
return state.chatPrompts.length === 1;
|
||||
}, 12000));
|
||||
const state = await (await fetch(fixture.url + '/fixture/state')).json();
|
||||
assert.equal(state.chatPrompts[0].text, 'A follow-up while you work');
|
||||
assert.equal(state.chatInterrupts, 0);
|
||||
assert.equal(state.chatRunning, true);
|
||||
log.checks.push('follow-up sent while running, without interrupting');
|
||||
await assertName(connection, 'Queued', 'server queue acknowledgement visible', log);
|
||||
await capture(connection, output, log, 'chat-queued-follow-up');
|
||||
await event({ kind: 'reasoning', message_id: 'live-answer',
|
||||
part: { id: 'reasoning-0', type: 'reasoning' }, delta: ' The reasoning continues live.' });
|
||||
await assertPainted('The reasoning continues live.', 'reasoning keeps updating after follow-up', 'chat-reasoning-updated');
|
||||
|
||||
// Stage-specific acceptance is completed alongside the Session-tab widget.
|
||||
await visit('/runs/77/stage/plan?visit=0');
|
||||
await assertName(connection, 'Input', 'stage summary loaded', log);
|
||||
const names = (await axNodes(connection)).map(node => node.name?.value ?? '').join('\n');
|
||||
assert.ok(!names.includes('Parsed stage input, initially hidden'));
|
||||
assert.ok(!names.includes('Parsed stage output, initially hidden'));
|
||||
log.checks.push('stage input/output initially collapsed');
|
||||
await capture(connection, output, log, 'stage-summary-collapsed');
|
||||
await click('Session');
|
||||
await assertName(connection, 'stage-debug-session', 'exact session identity visible', log);
|
||||
await assertName(connection, 'Open session.html', 'recorded session export available', log);
|
||||
await capture(connection, output, log, 'stage-session-debug');
|
||||
for (const [name, text] of [
|
||||
['input.md', 'Exact original harness input.'],
|
||||
['output.md', 'Exact original harness output.'],
|
||||
['memory.md', 'Exact memory read by the stage.'],
|
||||
]) {
|
||||
await click(name, true);
|
||||
await sleep(700);
|
||||
await assertPainted(text, `${name} exact raw document readable`, `stage-${name.replace('.', '-')}`);
|
||||
await click('Back');
|
||||
await assertName(connection, 'stage-debug-session', `${name} Back restores same visit`, log);
|
||||
}
|
||||
const finalState = await (await fetch(fixture.url + '/fixture/state')).json();
|
||||
for (const name of ['input.md', 'output.md', 'memory.md']) {
|
||||
assert.ok(finalState.fileReads.includes(`/artifacts/77/1/${name}`), name);
|
||||
}
|
||||
log.checks.push('all raw document fetches use this exact recorded visit');
|
||||
console.log(JSON.stringify(log, null, 2));
|
||||
} catch (error) {
|
||||
if (connection) {
|
||||
await capture(connection, output, log, 'failure');
|
||||
await writeFile(join(output, 'failure-ax.json'), JSON.stringify(await axNodes(connection), null, 2));
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
await writeFile(join(output, 'result.json'), JSON.stringify(log, null, 2));
|
||||
connection?.close();
|
||||
const exited = once(chrome, 'exit');
|
||||
chrome.kill();
|
||||
await exited;
|
||||
await fixture.close();
|
||||
}
|
||||
@@ -310,7 +310,7 @@ async function staticFile(base, pathname, req, res) {
|
||||
* It serves the built probe bundle and upgrades /connect on the same origin, so
|
||||
* the normal web composition infers this server from Uri.base.
|
||||
*/
|
||||
export async function startFixture({ root, runs = RUNS }) {
|
||||
export async function startFixture({ root, runs = RUNS, runDetail, files = {} }) {
|
||||
const base = await realpath(root);
|
||||
const connections = new Set();
|
||||
const sockets = new Set();
|
||||
@@ -327,6 +327,9 @@ export async function startFixture({ root, runs = RUNS }) {
|
||||
let chatSubscribed = 0;
|
||||
let chatHistory = 0;
|
||||
const chatPrompts = [];
|
||||
const fileReads = [];
|
||||
let chatRunning = false;
|
||||
let chatInterrupts = 0;
|
||||
const searchRequests = [];
|
||||
const CHAT_SESSION = {
|
||||
id: 'ses_probechat',
|
||||
@@ -348,6 +351,22 @@ export async function startFixture({ root, runs = RUNS }) {
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
const pathname = new URL(req.url, 'http://fixture').pathname;
|
||||
if (pathname === '/fixture/chat-event' && req.method === 'POST') {
|
||||
const chunks = [];
|
||||
for await (const chunk of req) chunks.push(chunk);
|
||||
const event = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||
if (event.kind === 'step') chatRunning = event.step?.status !== 'ended';
|
||||
broadcast({ type: 'chat_event', chat_event: {
|
||||
session_id: CHAT_SESSION.id, ...event,
|
||||
} });
|
||||
res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}');
|
||||
return;
|
||||
}
|
||||
if (Object.hasOwn(files, pathname)) {
|
||||
fileReads.push(pathname);
|
||||
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' }).end(files[pathname]);
|
||||
return;
|
||||
}
|
||||
if (pathname === '/fixture/live' && req.method === 'POST') {
|
||||
live = true;
|
||||
broadcast(LIVE_EVENT);
|
||||
@@ -386,6 +405,9 @@ export async function startFixture({ root, runs = RUNS }) {
|
||||
chatSubscribed,
|
||||
chatHistory,
|
||||
chatPrompts,
|
||||
chatRunning,
|
||||
chatInterrupts,
|
||||
fileReads,
|
||||
searchRequests,
|
||||
}));
|
||||
return;
|
||||
@@ -443,6 +465,10 @@ export async function startFixture({ root, runs = RUNS }) {
|
||||
}
|
||||
if (request.type === 'get_run') {
|
||||
getRun++;
|
||||
if (runDetail) {
|
||||
client.send({ id: request.id, type: 'run', run_detail: runDetail });
|
||||
return;
|
||||
}
|
||||
const id = request.run_id;
|
||||
if (id === 2) {
|
||||
// Deliberately slow so the browser sees the pending/Back state;
|
||||
@@ -521,7 +547,16 @@ export async function startFixture({ root, runs = RUNS }) {
|
||||
const body = request.chat_prompt ?? {};
|
||||
chatPrompts.push({ session_id: body.session_id, text: body.text,
|
||||
operation_id: body.operation_id, native_message_id: body.native_message_id });
|
||||
setTimeout(() => client.send({ id: request.id, type: 'chat_prompt' }), 300);
|
||||
setTimeout(() => client.send({ id: request.id, type: 'chat_prompt', chat_queued: chatRunning }), 300);
|
||||
return;
|
||||
}
|
||||
if (request.type === 'chat_shells') {
|
||||
client.send({ id: request.id, type: 'chat_shells', chat_shells: [] });
|
||||
return;
|
||||
}
|
||||
if (request.type === 'chat_interrupt') {
|
||||
chatInterrupts++;
|
||||
client.send({ id: request.id, type: 'chat_interrupt' });
|
||||
return;
|
||||
}
|
||||
if (request.type === 'chat_messages') {
|
||||
|
||||
Reference in New Issue
Block a user