merge(app): land native create-from-template prompt

This commit is contained in:
2026-10-21 20:57:34 +01:00
57 changed files with 5574 additions and 381 deletions
+188
View File
@@ -0,0 +1,188 @@
// Standalone fixture entry for real-browser run-detail Changes wiring evidence.
//
// Build and probe (from app/):
// flutter build web --target tool/diff_wiring_probe.dart --output build/probe-wire
// node tool/diff_wiring_probe.mjs --root build/probe-wire --out DIR
//
// Server-shaped fixtures only: a fake gateway answers the same get_run envelope
// the app consumes. No server or operator run is touched.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/data/runs_repository.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_view.dart';
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
const _patch =
'--- "a/lib/features/runs/ui/run_changes_action.dart"\n'
'+++ "b/lib/features/runs/ui/run_changes_action.dart"\n'
'@@ -1,3 +1,4 @@\n'
' import package:flutter/material.dart;\n'
'-const label = "Old";\n'
'+const label = "Changes";\n'
'+const recorded = true;\n'
' // end\n';
class _FakeGateway implements ApiGateway {
_FakeGateway(this.detail);
final JsonMap detail;
@override
Stream<JsonMap> get frames => const Stream<JsonMap>.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type != 'get_run') throw UnsupportedError(type);
return Future.value({'run_detail': detail});
}
}
JsonMap _run({
required bool unavailable,
String status = 'succeeded',
String stepStatus = 'completed',
}) => {
'id': 12,
'title': 'Changes wiring probe',
'name': 'probe',
'status': status,
'steps': [
{
'stage': 'implementer',
'sequence': 1,
'status': stepStatus,
'file_changes': unavailable
? {
'status': 'unavailable',
'skipped': 0,
'omitted': 0,
'diagnostic':
'Workspace snapshot unavailable; changes could not be '
'compared.',
'files': <JsonMap>[],
}
: status == 'running'
? null
: {
'status': 'complete',
'scope': 'Git tracked and nonignored files in the run directory',
'skipped': 0,
'omitted': 0,
'diagnostic': '',
'files': [
{
'path': 'lib/features/runs/ui/run_changes_action.dart',
'kind': 'modified',
'patch': _patch,
},
],
},
},
],
};
void main() {
final params = Uri.base.queryParameters;
final cupertino = params['platform'] == 'cupertino';
final stepsUnavailable = params['capture'] == 'unavailable';
final status = params['run'] == 'failed'
? 'failed'
: params['run'] == 'running'
? 'running'
: 'succeeded';
final stepStatus = status == 'running' ? 'running' : 'completed';
final theme = params['theme'] == 'light' ? Brightness.light : Brightness.dark;
// Browser text scaling is a fixture input like platform and theme: the
// accessibility states are otherwise unreachable from CDP metrics alone.
final textScale = double.tryParse(params['scale'] ?? '') ?? 1;
final body = _ProbeBody(
unavailable: stepsUnavailable,
status: status,
stepStatus: stepStatus,
);
Widget scaled(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
);
if (cupertino) {
runApp(
CupertinoApp(
title: 'Run changes probe',
theme: CupertinoThemeData(brightness: theme),
builder: (context, app) => Theme(
data: ThemeData(platform: TargetPlatform.iOS),
child: scaled(context, app),
),
home: body,
),
);
} else {
runApp(
MaterialApp(
title: 'Run changes probe',
theme: ThemeData(brightness: theme, platform: TargetPlatform.android),
builder: scaled,
home: body,
),
);
}
}
class _ProbeBody extends StatefulWidget {
const _ProbeBody({
required this.unavailable,
required this.status,
required this.stepStatus,
});
final bool unavailable;
final String status;
final String stepStatus;
@override
State<_ProbeBody> createState() => _ProbeBodyState();
}
class _ProbeBodyState extends State<_ProbeBody> {
late final RunsController _controller = RunsController(
RunsRepository(
_FakeGateway(
_run(
unavailable: widget.unavailable,
status: widget.status,
stepStatus: widget.stepStatus,
),
),
),
);
@override
void initState() {
super.initState();
_controller.select(12);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final detail = RunDetailView(controller: _controller, onBack: () {});
if (Theme.of(context).platform == TargetPlatform.iOS) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text('Runs')),
child: SafeArea(child: detail),
);
}
return Scaffold(
appBar: AppBar(title: const Text('Runs')),
body: detail,
);
}
}
+498
View File
@@ -0,0 +1,498 @@
// Real-browser evidence for the run-detail Changes action wiring.
//
// Usage (from app/):
// flutter build web --target tool/diff_wiring_probe.dart --output build/probe-wire
// node tool/diff_wiring_probe.mjs --root build/probe-wire --out DIR
//
// The fixture serves the actual RunDetailView over a fake gateway, then drives
// headless Chrome over loopback: the native Changes button, the recorded file,
// its diff, Close diff, Back, the failed-run evidence without a run-wide
// summary, the absent action while executing, and the Cupertino raw/dark
// surfaces. No server or operator run is touched.
import { createServer } from 'node:http';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { setTimeout as delay } from 'node:timers/promises';
import { extname, join, resolve, sep } from 'node:path';
import { tmpdir } from 'node:os';
const args = new Map();
for (let i = 2; i < process.argv.length; i++) {
const value = process.argv[i];
if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]);
}
const root = resolve(args.get('root') ?? 'build/probe-wire');
const out = resolve(args.get('out') ?? 'build/diff-wiring-probe');
const chromePath =
process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
await mkdir(out, { recursive: true });
const mime = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.wasm': 'application/wasm',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.bin': 'application/octet-stream',
'.frag': 'application/octet-stream',
};
const server = createServer(async (req, res) => {
try {
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
let filePath = resolve(root, '.' + pathname);
if (filePath !== root && !filePath.startsWith(root + sep)) {
res.writeHead(403).end();
return;
}
if (pathname === '/' || pathname.endsWith('/')) filePath = join(filePath, 'index.html');
const file = await readFile(filePath);
res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file);
} catch {
res.writeHead(404).end('not found');
}
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const origin = `http://127.0.0.1:${server.address().port}`;
const profile = await mkdtemp(join(tmpdir(), 'd1-wire-chrome-'));
const chrome = spawn(
chromePath,
['--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu',
'--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'],
{ stdio: ['ignore', 'ignore', 'pipe'] },
);
let stderr = '';
chrome.stderr.on('data', (data) => {
stderr += data;
});
const waitFor = async (fn, what) => {
for (let i = 0; i < 120; i++) {
const value = await fn();
if (value) return value;
await delay(100);
}
throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`);
};
const file = 'lib/features/runs/ui/run_changes_action.dart';
const rowPrefix = `Open diff for ${file}`;
const evidence = { origin, captures: [], checks: [] };
let ws;
try {
const endpoint = await waitFor(
() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1],
'Chrome DevTools',
);
ws = new WebSocket(endpoint);
await once(ws, 'open');
let id = 0;
const pending = new Map();
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.id && pending.has(message.id)) {
pending.get(message.id)(message);
pending.delete(message.id);
}
});
const send = (method, params = {}, sessionId) =>
new Promise((resolveCall) => {
const callId = ++id;
pending.set(callId, resolveCall);
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
});
const created = await send('Target.createTarget', { url: 'about:blank' });
if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`);
const session = (await send('Target.attachToTarget', {
targetId: created.result.targetId,
flatten: true,
})).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
await send('Emulation.setDeviceMetricsOverride', {
width: 390, height: 844, deviceScaleFactor: 1, mobile: true,
}, session);
const evaluate = async (expression) => {
const response = await send(
'Runtime.evaluate',
{ expression, returnByValue: true, awaitPromise: true },
session,
);
if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
return response.result?.result?.value;
};
const labels = () =>
evaluate(
"[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || (x.innerText || '').trim()).filter(Boolean)",
);
const bodyText = () => evaluate('document.body.innerText');
const hasLabel = async (label) => (await labels()).includes(label);
const hasPrefix = async (prefix) =>
(await labels()).some((label) => label.startsWith(prefix));
const clickExact = async (label) => {
const clicked = await evaluate(`(() => {
const wanted = ${JSON.stringify(label)};
const nodes = [...document.querySelectorAll('flt-semantics')];
const node = nodes.find(x => x.getAttribute('aria-label') === wanted)
|| nodes.find(x => (x.innerText || '').trim() === wanted);
if (!node) return false;
node.click();
return true;
})()`);
if (!clicked) throw new Error(`No exact semantics label ${JSON.stringify(label)}: ${JSON.stringify(await labels())}`);
await delay(500);
};
const clickPrefix = async (prefix) => {
const clicked = await evaluate(`(() => {
const wanted = ${JSON.stringify(prefix)};
const nodes = [...document.querySelectorAll('flt-semantics')];
const candidates = nodes.filter((x) =>
(x.getAttribute('aria-label') || '').startsWith(wanted)
|| (x.innerText || '').trim().startsWith(wanted));
if (candidates.length === 0) return false;
// Click the actionable row, not an ancestor semantics container whose
// innerText happens to start with the same text.
const actionable = candidates.filter((x) => x.hasAttribute('flt-tappable'));
const target = (actionable.length > 0 ? actionable : candidates)
.sort((a, b) => (a.innerText || '').length - (b.innerText || '').length)[0];
target.click();
return true;
})()`);
if (!clicked) throw new Error(`No semantics label starting ${JSON.stringify(prefix)}: ${JSON.stringify(await labels())}`);
await delay(500);
};
const activate = async () => {
await delay(3200);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(900);
const current = await labels();
if (!current.some((label) => label.includes('Changes wiring probe'))) {
throw new Error(`Flutter semantics unavailable: ${JSON.stringify(current)}`);
}
};
const navigate = async (url) => {
const navigation = await send('Page.navigate', { url }, session);
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
await activate();
};
const capture = async (name, width = 390, height = 844, scale = 1) => {
await send('Emulation.setDeviceMetricsOverride', {
width, height, deviceScaleFactor: scale, mobile: width < 600,
}, session);
await delay(350);
const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data;
const path = join(out, `${name}.png`);
await writeFile(path, Buffer.from(data, 'base64'));
evidence.captures.push(path);
};
// Semantics expose a widget's box in CSS pixels; the pixel probe then reads
// the rendered screen so a text colour can be asserted, not just presence.
const rectOfLabel = (prefix) =>
evaluate(`(() => {
const wanted = ${JSON.stringify(prefix)};
const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim();
const node = [...document.querySelectorAll('flt-semantics')]
.find(x => text(x).startsWith(wanted));
if (!node) return null;
const r = node.getBoundingClientRect();
return { x: r.x, y: r.y, width: r.width, height: r.height };
})()`);
const brightestPixel = async (rect) => {
const shot = await send('Page.captureScreenshot', {
format: 'png',
clip: { ...rect, scale: 2 },
}, session);
if (!shot.result?.data) throw new Error(`Screenshot clip failed: ${JSON.stringify(shot)}`);
return evaluate(`(async () => {
const img = new Image();
img.src = 'data:image/png;base64,${shot.result.data}';
await img.decode();
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const data = ctx.getImageData(0, 0, img.width, img.height).data;
let max = 0;
let bright = 0;
for (let i = 0; i < data.length; i += 4) {
const lum = (0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2]) / 255;
if (lum > max) max = lum;
if (lum > 0.5) bright++;
}
return { max, bright, pixels: data.length / 4, width: img.width, height: img.height };
})()`);
};
await navigate(`${origin}/`);
const detailBody = await bodyText();
if (!detailBody.includes('Changes wiring probe')) {
throw new Error(`Run detail did not render: ${JSON.stringify(detailBody)}`);
}
if (!(await hasLabel('Changes'))) {
throw new Error(`Run detail has no Changes action: ${JSON.stringify(await labels())}`);
}
evidence.checks.push({ check: 'run detail shows the native Changes action', value: true });
await capture('d1-wire-material-detail');
await clickExact('Changes');
const changesBody = await bodyText();
if (changesBody === detailBody) throw new Error('Changes did not open a new page');
if (!changesBody.includes(file)) throw new Error(`Recorded filename missing: ${JSON.stringify(changesBody)}`);
if (!changesBody.includes('1 file changed · +2 -1')) {
throw new Error(`Recorded stat missing: ${JSON.stringify(changesBody)}`);
}
evidence.checks.push({ check: 'Changes opened the recorded filename and stat', value: true });
await capture('d1-wire-material-changes');
await delay(1200);
await clickPrefix(rowPrefix);
const diffBody = await bodyText();
if (!diffBody.includes('const recorded = true;')
|| !diffBody.includes('const label = "Old";')) {
throw new Error(`Recorded diff lines missing: ${JSON.stringify(diffBody)}`);
}
for (const label of ['Rendered', 'Raw patch', 'Copy patch', 'Close diff']) {
if (!(await hasLabel(label))) throw new Error(`Diff is missing ${label}: ${JSON.stringify(await labels())}`);
}
evidence.checks.push({ check: 'the recorded file opened its actual diff', value: true });
await capture('d1-wire-material-diff');
await clickExact('Close diff');
if (!(await bodyText()).includes(file)) throw new Error('Close diff did not return to Changes');
await clickExact('Back');
const backBody = await bodyText();
if (!backBody.includes('Changes wiring probe') || !(await hasLabel('Changes'))) {
throw new Error(`Back did not return to the run detail: ${JSON.stringify(backBody)}`);
}
evidence.checks.push({ check: 'Close diff and Back returned to the previous pages', value: true });
await capture('d1-wire-material-back');
await navigate(`${origin}/?capture=unavailable`);
await clickExact('Changes');
const unavailableBody = await bodyText();
if (!unavailableBody.includes('Changes · capture unavailable')) {
throw new Error(`Unavailable capture wording missing: ${JSON.stringify(unavailableBody)}`);
}
if (!unavailableBody.includes('Workspace snapshot unavailable; changes could not be compared.')) {
throw new Error('Unavailable diagnostic missing');
}
if (unavailableBody.includes('No changes observed')) {
throw new Error('Unavailable capture claimed no changes');
}
evidence.checks.push({ check: 'unavailable capture keeps its gap wording', value: true });
await capture('d1-wire-material-unavailable');
await navigate(`${origin}/?run=failed`);
await clickExact('Changes');
await capture('d1-wire-material-failed');
const failedBody = await bodyText();
const failedText = [failedBody, ...(await labels())].join('\n');
if (!failedText.includes(file)) {
throw new Error(`Failed run lost its visit capture: ${JSON.stringify(failedText)}`);
}
if (failedText.includes('file changed')) {
throw new Error(`Failed run showed a settled run-wide summary: ${JSON.stringify(failedText)}`);
}
if (!failedText.includes('Visit 1')) {
throw new Error(`Failed run visit section missing: ${JSON.stringify(failedText)}`);
}
evidence.checks.push({ check: 'a failed run keeps visit evidence without a summary', value: true });
await navigate(`${origin}/?run=running`);
if (await hasLabel('Changes')) {
throw new Error('An executing run offered the snapshot Changes page');
}
const runningBody = await bodyText();
if (!runningBody.includes('running')) {
throw new Error(`Running run detail did not render its status: ${JSON.stringify(runningBody)}`);
}
evidence.checks.push({ check: 'an executing run offers no snapshot Changes page', value: true });
await capture('d1-wire-material-running');
await navigate(`${origin}/?platform=cupertino&theme=light`);
if (!(await hasLabel('Changes'))) {
throw new Error(`Cupertino run detail has no Changes action: ${JSON.stringify(await labels())}`);
}
await capture('d1-wire-cupertino-detail');
await clickExact('Changes');
const cupertinoChanges = await bodyText();
if (!cupertinoChanges.includes(file)) {
throw new Error(`Cupertino Changes did not open the recorded file: ${JSON.stringify(cupertinoChanges)}`);
}
evidence.checks.push({ check: 'Cupertino Changes opened the recorded file', value: true });
await capture('d1-wire-cupertino-changes');
await clickPrefix(rowPrefix);
if (!(await bodyText()).includes('const recorded = true;')) {
throw new Error('Cupertino recorded diff missing');
}
await capture('d1-wire-cupertino-diff');
await clickExact('Raw patch');
const rawLabels = await labels();
const rawBody = await bodyText();
if (!rawLabels.some((label) => label.includes('Raw patch for'))
&& !rawBody.includes('const recorded = true;')) {
throw new Error(`Cupertino raw patch did not render: ${JSON.stringify(rawLabels)}`);
}
if (!(await hasLabel('Copy patch'))) {
throw new Error(`Cupertino raw view lost its actions: ${JSON.stringify(await labels())}`);
}
evidence.checks.push({ check: 'Cupertino Raw patch uses a native selectable body', value: true });
await capture('d1-wire-cupertino-raw');
await clickExact('Close diff');
await delay(600);
await clickExact('Back');
await delay(800);
if (!(await bodyText()).includes('Changes wiring probe')) {
throw new Error('Cupertino Back did not return to the run detail');
}
evidence.checks.push({ check: 'Cupertino diff and Back returned', value: true });
await capture('d1-wire-cupertino-back');
await navigate(`${origin}/?platform=cupertino&theme=dark`);
await clickExact('Changes');
const darkText = [await bodyText(), ...(await labels())].join('\n');
if (!darkText.includes(file) || !darkText.includes('file changed')) {
throw new Error(`Cupertino dark Changes did not render: ${JSON.stringify(darkText)}`);
}
evidence.checks.push({ check: 'Cupertino dark Changes renders the recorded summary', value: true });
await capture('d1-wire-cupertino-dark-changes');
await clickPrefix(rowPrefix);
if (!(await bodyText()).includes('const recorded = true;')) {
throw new Error('Cupertino dark recorded diff missing');
}
// The header is a merged semantics label, so anchor the pixel crop on the
// controls below it: the form control and the title share the 16 px inset,
// and the close control shares the header's top line.
const formRect = await rectOfLabel('Rendered');
const closeRect = await rectOfLabel('Close diff');
if (!formRect || !closeRect) {
throw new Error(`Dark diff controls are missing: ${JSON.stringify(await labels())}`);
}
const titleLuminance = await brightestPixel({
x: formRect.x,
y: closeRect.y,
width: 60,
height: 22,
});
if (titleLuminance.max < 0.5) {
throw new Error(`Dark Cupertino diff header is not light: ${JSON.stringify(titleLuminance)}`);
}
evidence.checks.push({
check: 'Cupertino dark diff header text is light on the popup surface',
value: true,
luminance: titleLuminance.max,
});
evidence.checks.push({ check: 'Cupertino dark diff renders its recorded lines', value: true });
await capture('d1-wire-cupertino-dark-diff');
// A 320-px host at 2x text is the narrowest documented state. The native
// controls must keep the whole browser words; the strip scrolls and reveals
// the selected segment instead of clipping or breaking a label.
const scroll = async ({ x, y, deltaX = 0, deltaY = 0 }) => {
await send('Input.dispatchMouseEvent', {
type: 'mouseWheel', x, y, deltaX, deltaY,
}, session);
await delay(400);
};
const openScaledDiff = async ({ platform, prefix }) => {
await send('Emulation.setDeviceMetricsOverride', {
width: 320, height: 720, deviceScaleFactor: 1, mobile: true,
}, session);
const query = platform === 'cupertino'
? '?platform=cupertino&theme=light&scale=2'
: '?theme=light&scale=2';
await navigate(`${origin}/${query}`);
await clickExact('Changes');
// The 2x summary pushes the recorded file below the fold: scroll the
// Changes list until its row is built and offered.
for (let i = 0; i < 8 && !(await hasPrefix(rowPrefix)); i++) {
await scroll({ x: 160, y: 600, deltaY: 400 });
}
if (!(await hasPrefix(rowPrefix))) {
throw new Error(`2x Changes did not offer the recorded file: ${JSON.stringify(await labels())}`);
}
await clickPrefix(rowPrefix);
await delay(800);
const body = await bodyText();
if (!body.includes('const recorded = true;')) {
throw new Error(`2x diff did not render: ${JSON.stringify(body)}`);
}
for (const label of ['Copy patch', 'Close diff', 'Diff form']) {
if (!(await hasLabel(label))) {
throw new Error(`2x diff is missing ${label}: ${JSON.stringify(await labels())}`);
}
}
await capture(`${prefix}-diff`, 320, 720, 1);
// The native menu carries both fixed words on a host too narrow for the
// segmented control; the sheet/list must show each of them whole. A real
// pointer tap is used because the Cupertino label sits on a semantic
// wrapper above the actual button.
const menuRect = await rectOfLabel('Diff form');
if (!menuRect) {
throw new Error(`2x diff has no Diff form control: ${JSON.stringify(await labels())}`);
}
const tap = {
x: menuRect.x + menuRect.width / 2,
y: menuRect.y + menuRect.height / 2,
};
await send('Input.dispatchMouseEvent', {
type: 'mousePressed', ...tap, button: 'left', clickCount: 1,
}, session);
await send('Input.dispatchMouseEvent', {
type: 'mouseReleased', ...tap, button: 'left', clickCount: 1,
}, session);
await delay(900);
for (const label of ['Rendered', 'Raw patch']) {
if (!(await hasLabel(label))) {
throw new Error(`2x diff menu is missing ${label}: ${JSON.stringify(await labels())}`);
}
}
await capture(`${prefix}-menu`, 320, 720, 1);
await clickExact('Raw patch');
await delay(900);
const raw = await bodyText();
const rawLabels = await labels();
if (!rawLabels.some((label) => label.includes('Raw patch for'))
&& !raw.includes('const recorded = true;')) {
throw new Error(`2x Raw patch did not render: ${JSON.stringify(rawLabels)}`);
}
await capture(`${prefix}-raw`, 320, 720, 1);
await clickExact('Close diff');
await delay(600);
};
await openScaledDiff({ platform: 'material', prefix: 'd1-wire-material-2x-320' });
evidence.checks.push({
check: 'Material 2x/320 diff keeps its controls and opens Raw patch',
value: true,
});
await openScaledDiff({ platform: 'cupertino', prefix: 'd1-wire-cupertino-2x-320' });
evidence.checks.push({
check: 'Cupertino 2x/320 diff keeps its controls and opens Raw patch',
value: true,
});
console.log(JSON.stringify(evidence, null, 2));
} finally {
ws?.close();
chrome.kill('SIGTERM');
await Promise.race([once(chrome, 'exit'), delay(3000)]);
server.close();
await rm(profile, { recursive: true, force: true });
}
+236
View File
@@ -0,0 +1,236 @@
// Real-Chrome acceptance for the Pipelines destination in the normal app.
//
// The bundle is `tool/pipelines_wiring_probe_entry.dart`, i.e. the same
// composition as main; the isolated loopback fixture answers the protocol.
// Both native hosts are exercised by changing the browser platform user agent.
//
// Usage: node tool/pipelines_wiring_probe.mjs <build-dir> <capture-dir>
import { execFile } from 'node:child_process';
import { mkdir, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { promisify } from 'node:util';
import {
connect,
launchChrome,
sleep,
waitForPage,
waitForPort,
} from './pipelines_probe_cdp_lib.mjs';
import {
assertName,
axNodes,
capture,
click,
enableSemantics,
waitFor,
} from './pipelines_probe_cdp_input.mjs';
import { startWiringFixture } from './pipelines_wiring_probe_server.mjs';
const CHROME =
process.env.CHROME_PATH ??
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const buildDir = resolve(process.argv[2] ?? 'build/wiring_web');
const captureDir = resolve(process.argv[3] ?? 'p1-wire-captures');
const fixture = await startWiringFixture({ root: buildDir, refuse: true });
await mkdir(captureDir, { recursive: true });
const profile = join(tmpdir(), `pipelines-wiring-chrome-${process.pid}`);
const chrome = launchChrome(CHROME, profile, 'about:blank');
let connection;
const log = { url: fixture.url, captures: [], checks: [], states: [] };
const semanticText = () =>
connection.evaluate(`(() => {
const chunks = [];
for (const el of document.querySelectorAll('flt-semantics')) {
const label = el.getAttribute('aria-label');
if (label) chunks.push(label);
if (!el.children.length && el.innerText) chunks.push(el.innerText);
}
if (document.body?.innerText) chunks.push(document.body.innerText);
return [...new Set(chunks)].join('\\n');
})()`);
const assertBody = async (text) => {
const ok = await waitFor(
async () => (await semanticText()).includes(text),
12000,
);
if (!ok) {
throw new Error(`Missing text ${JSON.stringify(text)}:\n${(await semanticText()).slice(0, 3000)}`);
}
log.checks.push(`text: ${text}`);
};
const noBody = async (text) => {
if ((await semanticText()).includes(text)) {
throw new Error(`Unexpected text ${JSON.stringify(text)}`);
}
log.checks.push(`absent: ${text}`);
};
const state = async () => fixture.state();
const waitForState = async (check, label) => {
const value = await waitFor(async () => {
const current = await state();
return check(current) ? current : false;
}, 12000);
if (!value) throw new Error(`Timed out waiting for ${label}: ${JSON.stringify(await state())}`);
log.states.push({ label, ...value });
return value;
};
const ocr = async (path) => {
const { stdout } = await promisify(execFile)('tesseract', [path, 'stdout']);
return stdout;
};
const assertOcr = async (name, text) => {
const read = await ocr(join(captureDir, `${name}.png`));
if (!read.toLowerCase().includes(text.toLowerCase())) {
throw new Error(`OCR of ${name} lacks ${JSON.stringify(text)}:\n${read.slice(0, 3000)}`);
}
log.checks.push(`ocr ${name}: ${text}`);
};
const navigate = async (url) => {
await connection.send('Page.navigate', { url });
await waitFor(
() => connection.evaluate("document.querySelector('flutter-view') !== null"),
20000,
);
await sleep(1200);
await enableSemantics(connection);
};
try {
const devtoolsPort = await waitForPort(join(profile, 'DevToolsActivePort'));
const target = await waitForPage(devtoolsPort);
connection = await connect(target.webSocketDebuggerUrl);
await connection.send('Page.enable');
await connection.send('Runtime.enable');
await connection.send('DOM.enable');
await connection.send('Accessibility.enable');
await connection.send('Emulation.setDeviceMetricsOverride', {
width: 1200,
height: 900,
deviceScaleFactor: 1,
mobile: false,
});
// Material host: Linux platform, light mode.
await connection.send('Emulation.setUserAgentOverride', {
userAgent:
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
platform: 'Linux x86_64',
});
await navigate(`${fixture.url}/pipelines`);
// The first connection is refused: the honest gate must appear and nothing
// may be requested while there is no socket.
await assertBody('Pipelines server unavailable');
const initial = await state();
if (initial.listPipelines !== 0 || initial.listRuns !== 0 || initial.getPipeline !== 0) {
throw new Error(`Premature requests before connection: ${JSON.stringify(initial)}`);
}
log.checks.push('no requests before first connection');
await capture(connection, captureDir, log, '01-gate-refused-material');
await assertOcr('01-gate-refused-material', 'Pipelines server unavailable');
await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' });
await click(connection, 'Retry');
await assertName(connection, 'Release verification', 'real pipeline row', log);
await assertName(connection, 'Nightly documentation', 'second real row', log);
await noBody('Pipelines — Not implemented');
const loaded = await waitForState(
(value) => value.listPipelines >= 1 && value.listRuns >= 1,
'pipeline list after retry',
);
log.checks.push('shell lists real rows');
await capture(connection, captureDir, log, '02-list-material');
await assertOcr('02-list-material', 'Release verification');
await click(connection, 'Release verification');
await assertName(connection, 'Content hash', 'real pipeline detail', log);
await capture(connection, captureDir, log, '03-detail-material');
await assertOcr('03-detail-material', 'sha256:fixture-3-v3');
await click(connection, 'Source');
await capture(connection, captureDir, log, '04-source-material');
await assertOcr('04-source-material', 'name: Release verification');
await assertOcr('04-source-material', 'type: model');
await click(connection, 'Summary');
await assertName(connection, 'Content hash', 'summary restored', log);
// A drop keeps the open detail visible and, once the socket returns, the
// same list and detail are re-read without remounting or losing selection.
await fetch(`${fixture.url}/fixture/refuse`, { method: 'POST' });
await assertBody('Reconnecting to Pipelines…');
await assertName(connection, 'Content hash', 'detail retained after drop', log);
if ((await connection.evaluate('location.pathname')) !== '/pipelines') {
throw new Error(`Drop moved the route to ${await connection.evaluate('location.pathname')}`);
}
await capture(connection, captureDir, log, '05-drop-detail-retained-material');
await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' });
await click(connection, 'Retry');
await waitForState(
(value) =>
value.listPipelines > loaded.listPipelines &&
value.getPipeline > loaded.getPipeline,
'reconnect reload of list and open detail',
);
await assertName(connection, 'Content hash', 'detail refreshed in place', log);
await noBody('Pipelines server unavailable');
await capture(connection, captureDir, log, '06-reconnect-detail-refreshed-material');
// Cupertino host: macOS platform, dark appearance.
await connection.send('Emulation.setUserAgentOverride', {
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
platform: 'MacIntel',
});
await connection.send('Emulation.setEmulatedMedia', {
features: [{ name: 'prefers-color-scheme', value: 'dark' }],
});
await navigate(`${fixture.url}/pipelines`);
await assertName(connection, 'Release verification', 'cupertino dark row', log);
await noBody('Pipelines — Not implemented');
await capture(connection, captureDir, log, '07-list-cupertino-dark');
await assertOcr('07-list-cupertino-dark', 'Release verification');
await click(connection, 'Release verification');
await assertName(connection, 'Content hash', 'cupertino dark detail', log);
await capture(connection, captureDir, log, '08-detail-cupertino-dark');
await assertOcr('08-detail-cupertino-dark', 'Content hash');
await click(connection, 'Source');
await capture(connection, captureDir, log, '09-source-cupertino-dark');
await assertOcr('09-source-cupertino-dark', 'name: Release verification');
await assertOcr('09-source-cupertino-dark', 'type: model');
const final = await state();
if (final.connections < 1) throw new Error('No shared socket');
log.checks.push('both native hosts rendered real rows, detail and source');
log.final = final;
} catch (error) {
log.error = String(error?.stack ?? error);
try {
log.failureAx = (await axNodes(connection))
.filter((node) => node.name?.value)
.map((node) => `${node.role?.value}: ${node.name.value}`)
.slice(0, 120);
} catch {
// The browser may already be gone; the error itself is still recorded.
}
process.exitCode = 1;
} finally {
await writeFile(join(captureDir, 'probe.json'), JSON.stringify(log, null, 2));
connection?.close();
chrome.kill('SIGTERM');
await fixture.close();
}
@@ -0,0 +1,8 @@
import 'package:pipelines_app/application/bootstrap.dart';
/// Browser acceptance entrypoint for the Pipelines destination wiring.
///
/// It is exactly the normal application composition; every reply comes from the
/// isolated loopback fixture in `tool/pipelines_wiring_probe_server.mjs`, not
/// from app-side fake data and not from a production server.
void main() => runPipelinesApp();
+394
View File
@@ -0,0 +1,394 @@
import { createHash } from 'node:crypto';
import { createServer } from 'node:http';
import { readFile, realpath, stat } from 'node:fs/promises';
import { extname, join, resolve, sep } from 'node:path';
import { once } from 'node:events';
// Isolated loopback fixture for the Pipelines wiring probe. It serves the
// normal application composition and answers the read-only protocol with
// deterministic data. No production server, database or operator data.
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.wasm': 'application/wasm',
'.css': 'text/css; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
const PIPELINES = [
{
id: 3,
name: 'Release verification',
version: 3,
stages: 4,
created_at: '2026-09-28T10:12:00',
updated_at: '2026-10-21T09:40:00',
scheduled: true,
schedule_count: 2,
enabled_schedule_count: 1,
},
{
id: 7,
name: 'Nightly documentation',
version: 1,
stages: 2,
created_at: '2026-10-02T18:20:00',
updated_at: '2026-10-20T22:05:00',
scheduled: true,
schedule_count: 1,
enabled_schedule_count: 1,
},
];
const RUNS = [
{
id: 488,
pipeline_id: 3,
status: 'succeeded',
created_at: '2026-10-21T09:30:00',
finished_at: '2026-10-21T09:34:12',
executing: false,
},
{
id: 487,
pipeline_id: 7,
status: 'running',
created_at: '2026-10-21T09:20:00',
finished_at: '',
executing: true,
},
];
const VERSIONS = [
{ version: 1, stages: 2, created_at: '2026-09-28T10:12:00' },
{ version: 2, stages: 3, created_at: '2026-10-08T15:44:00' },
{ version: 3, stages: 4, created_at: '2026-10-21T09:12:00' },
];
const SOURCE = `name: Release verification
stages:
inspect:
type: model
output: report
verify:
type: model
output: verdict
`;
const SOURCE_V2 = `${SOURCE} # selected version 2
`;
function detail(id, requestedVersion) {
const summary = PIPELINES.find((pipeline) => pipeline.id === id) ?? PIPELINES[0];
const versions = id === 3 ? VERSIONS : VERSIONS.slice(0, 1);
const latest = versions[versions.length - 1].version;
const version = requestedVersion > 0 ? requestedVersion : latest;
return {
...summary,
version,
stages: versions.find((row) => row.version === version)?.stages ?? summary.stages,
latest_version: id === 3 ? latest : 1,
version_created_at:
versions.find((row) => row.version === version)?.created_at ?? summary.created_at,
content_hash: `sha256:fixture-${id}-v${version}`,
source: id === 3 && version === 2 ? SOURCE_V2 : SOURCE,
versions,
};
}
function accept(key) {
return createHash('sha1')
.update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
.digest('base64');
}
function frame(opcode, payload) {
const length = payload.length;
let header;
if (length < 126) {
header = Buffer.from([0x80 | opcode, length]);
} else if (length < 65536) {
header = Buffer.alloc(4);
header[0] = 0x80 | opcode;
header[1] = 126;
header.writeUInt16BE(length, 2);
} else {
header = Buffer.alloc(10);
header[0] = 0x80 | opcode;
header[1] = 127;
header.writeBigUInt64BE(BigInt(length), 2);
}
return Buffer.concat([header, payload]);
}
class Connection {
constructor(socket, owner) {
this.socket = socket;
this.owner = owner;
this.buffer = Buffer.alloc(0);
this.fragments = [];
this.fragmentOpcode = 0;
}
push(chunk) {
if (chunk?.length) this.buffer = Buffer.concat([this.buffer, chunk]);
this.parse();
}
parse() {
while (this.buffer.length >= 2) {
const first = this.buffer[0];
const second = this.buffer[1];
const fin = (first & 0x80) !== 0;
const opcode = first & 0x0f;
const masked = (second & 0x80) !== 0;
let length = second & 0x7f;
let offset = 2;
if (length === 126) {
if (this.buffer.length < 4) return;
length = this.buffer.readUInt16BE(2);
offset = 4;
} else if (length === 127) {
if (this.buffer.length < 10) return;
length = Number(this.buffer.readBigUInt64BE(2));
offset = 10;
}
const maskOffset = offset;
if (masked) {
if (this.buffer.length < offset + 4) return;
offset += 4;
}
if (this.buffer.length < offset + length) return;
let payload = Buffer.from(this.buffer.subarray(offset, offset + length));
if (masked) {
const mask = this.buffer.subarray(maskOffset, maskOffset + 4);
for (let index = 0; index < payload.length; index++) {
payload[index] ^= mask[index % 4];
}
}
this.buffer = this.buffer.subarray(offset + length);
this.handleFrame(fin, opcode, payload);
}
}
handleFrame(fin, opcode, payload) {
if (opcode === 0x8) return this.close();
if (opcode === 0x9) return void this.socket.write(frame(0x0a, payload));
if (opcode === 0x0a) return;
if (opcode === 0x0) {
this.fragments.push(payload);
if (fin) {
const data = Buffer.concat(this.fragments);
this.fragments = [];
this.message(this.fragmentOpcode, data);
}
return;
}
if (opcode !== 0x1) return;
if (!fin) {
this.fragmentOpcode = opcode;
this.fragments = [payload];
return;
}
this.message(opcode, payload);
}
message(_opcode, payload) {
let request;
try {
request = JSON.parse(payload.toString('utf8'));
} catch {
return;
}
this.owner.onMessage(this, request);
}
send(value) {
if (!this.socket.destroyed) {
this.socket.write(frame(0x1, Buffer.from(JSON.stringify(value))));
}
}
close() {
if (!this.socket.destroyed) this.socket.end();
}
}
async function staticFile(base, pathname, req, res) {
let file = resolve(base, `.${pathname}`);
if (file !== base && !file.startsWith(base + sep)) {
res.writeHead(403).end();
return;
}
try {
if ((await stat(file)).isDirectory()) file = join(file, 'index.html');
} catch {
if (extname(pathname)) {
res.writeHead(404).end('not found');
return;
}
file = join(base, 'index.html');
}
try {
const body = await readFile(file);
res
.writeHead(200, {
'content-type': MIME[extname(file)] ?? 'application/octet-stream',
'cache-control': 'no-store',
})
.end(req.method === 'HEAD' ? undefined : body);
} catch {
res.writeHead(404).end('not found');
}
}
export async function startWiringFixture({ root, refuse = false }) {
const base = await realpath(root);
const connections = new Set();
const sockets = new Set();
const counts = { subscribed: 0, listPipelines: 0, listRuns: 0, getPipeline: 0, dropped: 0 };
let refusing = refuse;
const dropConnections = () => {
for (const connection of connections) connection.close();
connections.clear();
counts.dropped++;
};
const server = createServer(async (req, res) => {
const pathname = new URL(req.url, 'http://fixture').pathname;
if (pathname === '/fixture/drop' && req.method === 'POST') {
dropConnections();
res.writeHead(200).end('{"ok":true}');
return;
}
if (pathname === '/fixture/refuse' && req.method === 'POST') {
refusing = true;
dropConnections();
res.writeHead(200).end('{"ok":true}');
return;
}
if (pathname === '/fixture/accept' && req.method === 'POST') {
refusing = false;
res.writeHead(200).end('{"ok":true}');
return;
}
if (pathname === '/fixture/state') {
res
.writeHead(200, { 'content-type': 'application/json' })
.end(JSON.stringify({ ...counts, connections: connections.size, refusing }));
return;
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.writeHead(405).end();
return;
}
await staticFile(base, pathname, req, res);
});
server.on('upgrade', (req, socket, head) => {
if (refusing) {
socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n');
return;
}
const url = new URL(req.url, 'http://fixture');
if (
url.pathname !== '/connect' ||
req.headers.upgrade?.toLowerCase() !== 'websocket' ||
!req.headers['sec-websocket-key']
) {
socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
return;
}
socket.write(
'HTTP/1.1 101 Switching Protocols\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
`Sec-WebSocket-Accept: ${accept(req.headers['sec-websocket-key'])}\r\n\r\n`,
);
const connection = new Connection(socket, {
onMessage: (client, request) => {
switch (request.type) {
case 'subscribe':
counts.subscribed++;
return;
case 'unsubscribe':
return;
case 'list_pipelines':
counts.listPipelines++;
client.send({ id: request.id, type: 'pipelines', pipelines: PIPELINES });
return;
case 'list_runs':
counts.listRuns++;
client.send({ id: request.id, type: 'runs', runs: RUNS });
return;
case 'get_pipeline': {
counts.getPipeline++;
const id = request.pipeline_id;
if (!PIPELINES.some((pipeline) => pipeline.id === id)) {
client.send({
id: request.id,
type: 'error',
error: `Fixture pipeline ${id} is unavailable`,
});
return;
}
client.send({
id: request.id,
type: 'pipeline',
detail: detail(id, request.version),
});
return;
}
case 'ping':
client.send({
id: request.id,
type: 'pong',
build: { version: 'Fixture wiring build' },
time: '2026-10-21T12:00:00Z',
});
return;
default:
client.send({
id: request.id,
type: 'error',
error: `Fixture does not implement ${request.type}`,
});
}
},
});
connections.add(connection);
socket.on('data', (chunk) => connection.push(chunk));
socket.on('close', () => connections.delete(connection));
socket.on('error', () => connections.delete(connection));
connection.push(head);
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
server.on('connection', (socket) => {
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
});
return {
server,
url: `http://127.0.0.1:${server.address().port}`,
state: async () => (await fetch(`http://127.0.0.1:${server.address().port}/fixture/state`)).json(),
close: () =>
new Promise((resolveClose) => {
for (const connection of connections) connection.close();
server.close(() => resolveClose());
for (const socket of sockets) socket.destroy();
}),
};
}
+60 -2
View File
@@ -110,7 +110,7 @@ try {
const semanticText = () => evaluate(`(() => {
const chunks = [];
for (const el of document.querySelectorAll('flt-semantics')) {
for (const el of document.querySelectorAll('flt-semantics, [aria-label], [aria-valuetext]')) {
const label = el.getAttribute('aria-label');
if (label) chunks.push(label);
const value = el.getAttribute('aria-valuetext');
@@ -153,7 +153,7 @@ try {
return label === wanted || (${contains} && label.includes(wanted));
});
const interactive = candidates.find((el) =>
['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')),
['button', 'tab', 'link', 'checkbox', 'radio', 'menuitem'].includes(el.getAttribute('role')),
);
const target = interactive ?? candidates[0];
if (!target) return false;
@@ -377,6 +377,25 @@ try {
if ((await path()) !== '/settings') throw new Error('Settings did not update route');
captures.push(await capture('settings-cupertino-registered-phone'));
await clickText('Runs');
await clickText('Fixture cancel run', { contains: true });
await assertBody('Original prompt');
await clickText('Cancel run');
await assertBody('Cancel run 4?');
captures.push(await capture('cancel-cupertino-confirm'));
await clickText('Keep');
await assertBody('Original prompt');
const kept = await (await fetch(`${fixture.url}/fixture/state`)).json();
if (kept.cancelRequests.length) throw new Error('Keep sent a cancellation');
await clickText('Back', { contains: true });
await clickText('Fixture human run', { contains: true });
captures.push(await capture('decision-cupertino-card'));
await assertBody('Waiting for your decision');
await clickText('Decide');
await assertBody('Please review this recorded checkpoint.');
captures.push(await capture('decision-cupertino-confirm'));
await clickText('Cancel');
// Material host: the same deep link and route must render standard Material
// controls (the Cupertino host was selected by the macOS browser above).
await send(
@@ -408,7 +427,46 @@ try {
}
captures.push(await capture('settings-material-registered-phone'));
await clickText('Runs');
await clickText('Fixture cancel run', { contains: true });
await assertBody('Original prompt');
await clickText('Cancel run');
await assertBody('Cancel run 4?');
captures.push(await capture('cancel-material-confirm'));
await clickText('Cancel run');
await assertBody('canceled');
captures.push(await capture('cancel-material-accepted'));
await clickText('Back to list');
await assertBody('Fixture cancel run');
await assertBody('canceled');
await clickText('Fixture human run', { contains: true });
await assertBody('Waiting for your decision');
captures.push(await capture('decision-material-card'));
await clickText('Decide');
await assertBody('Please review this recorded checkpoint.');
captures.push(await capture('decision-material-confirm'));
const pendingDecision = await (await fetch(`${fixture.url}/fixture/state`)).json();
if (pendingDecision.decisionRequests.length) throw new Error('Opening decision sent a reply');
await clickText('approve', { contains: true });
await clickText('Confirm decision');
await assertBody('succeeded');
if ((await semanticText()).includes('Waiting for your decision')) {
throw new Error('Accepted human decision left the waiting card behind');
}
captures.push(await capture('decision-material-accepted'));
await clickText('Back to list');
await assertBody('Fixture cancel run');
await assertBody('canceled');
const fixtureState = await (await fetch(`${fixture.url}/fixture/state`)).json();
if (JSON.stringify(fixtureState.decisionRequests) !==
JSON.stringify([{ run_id: 5, stage: 'gate', option: 'approve' }])) {
throw new Error('Decision sent the wrong payload or repeated the request');
}
if (JSON.stringify(fixtureState.cancelRequests) !== JSON.stringify([{ run_id: 4 }])) {
throw new Error('Cancel sent the wrong payload or repeated the request');
}
if (fixtureState.subscribed < 2) throw new Error(`App never resubscribed: ${JSON.stringify(fixtureState)}`);
if (fixtureState.listRuns < 2) throw new Error(`App never reloaded: ${JSON.stringify(fixtureState)}`);
if (fixtureState.getRun < 2) throw new Error(`Detail was not rehydrated: ${JSON.stringify(fixtureState)}`);
+51 -4
View File
@@ -45,8 +45,30 @@ const RUNS = [
created_at: '2026-10-21T10:00:00Z',
pipeline_id: 10,
},
{
id: 4, title: 'Fixture cancel run', name: 'fixture-cancel',
status: 'running', executing: true,
created_at: '2026-10-21T09:00:00Z', pipeline_id: 10,
},
{
id: 5, title: 'Fixture human run', name: 'fixture-human',
status: 'waiting', executing: false,
created_at: '2026-10-21T08:00:00Z', pipeline_id: 10,
},
];
function humanDetail(accepted) {
return {
...RUNS.find((run) => run.id === 5),
status: accepted ? 'succeeded' : 'waiting', current_stage: 'gate',
input: { prompt: 'Fixture human decision' },
graph: { stages: [{ key: 'gate', type: 'human', edges: { approve: '#success' } }] },
steps: [{ sequence: 1, stage: 'gate', status: accepted ? 'completed' : 'waiting',
output: { prompt: 'Please review this recorded checkpoint.', options: ['approve'] },
}],
};
}
const LIVE_EVENT = {
type: 'run_event',
run_id: 1,
@@ -57,13 +79,15 @@ const LIVE_EVENT = {
finished_at: '2026-10-21T12:05:00Z',
};
function detail(id, live) {
const status = id === 1 && live ? 'succeeded' : id === 3 ? 'failed' : 'running';
function detail(id, live, canceled = false) {
const status = canceled ? 'canceled'
: id === 1 && live ? 'succeeded' : id === 3 ? 'failed' : 'running';
return {
id,
title: RUNS.find((run) => run.id === id)?.title ?? `Run ${id}`,
name: 'fixture-pipeline',
status,
executing: status === 'running',
input: {
prompt: ' fixture prompt with spaces ',
note: 'input payload',
@@ -260,6 +284,10 @@ export async function startFixture({ root }) {
let dropped = 0;
let listRuns = 0;
let getRun = 0;
const canceled = new Set();
const cancelRequests = [];
let decisionAccepted = false;
const decisionRequests = [];
const dropConnections = () => {
for (const connection of connections) connection.close();
@@ -306,6 +334,8 @@ export async function startFixture({ root }) {
dropped,
listRuns,
getRun,
cancelRequests,
decisionRequests,
}));
return;
}
@@ -355,7 +385,9 @@ export async function startFixture({ root }) {
}
if (request.type === 'list_runs') {
listRuns++;
client.send({ id: request.id, type: 'runs', runs: RUNS, usage: null });
client.send({ id: request.id, type: 'runs', runs: RUNS.map((run) =>
canceled.has(run.id) ? { ...run, status: 'canceled', executing: false }
: run.id === 5 && decisionAccepted ? { ...run, status: 'succeeded' } : run), usage: null });
return;
}
if (request.type === 'get_run') {
@@ -377,7 +409,22 @@ export async function startFixture({ root }) {
});
return;
}
client.send({ id: request.id, type: 'run', run_detail: detail(id, live) });
client.send({ id: request.id, type: 'run', run_detail: id === 5
? humanDetail(decisionAccepted) : detail(id, live, canceled.has(id)) });
return;
}
if (request.type === 'cancel_run' && request.run_id === 4) {
cancelRequests.push({ run_id: request.run_id });
canceled.add(4);
client.send({ id: request.id, type: 'run', run_detail: detail(4, live, true) });
return;
}
if (request.type === 'decide_run' && request.run_id === 5 &&
request.stage === 'gate' && request.option === 'approve') {
decisionRequests.push({ run_id: request.run_id, stage: request.stage,
option: request.option, ...(request.feedback ? { feedback: request.feedback } : {}) });
decisionAccepted = true;
client.send({ id: request.id, type: 'run', run_detail: humanDetail(true) });
return;
}
client.send({