merge(app): land retry wiring in the native run detail

Conflicts: app/lib/features/runs/ui/run_detail_actions.dart.
Keep main's recorded-artifacts action and the retry branch's spaced,
render-gated Wrap: Rename, Retry, Cancel, then Recorded artifacts.
This commit is contained in:
2026-10-21 22:52:00 +01:00
56 changed files with 8712 additions and 69 deletions
+232
View File
@@ -0,0 +1,232 @@
// Standalone fixture entry for real-browser run-detail Artifacts evidence.
//
// Build and probe (from app/):
// flutter build web --target tool/artifact_gallery_probe.dart --output build/probe-gallery
// node tool/artifact_gallery_probe.mjs --root build/probe-gallery --out DIR
//
// Server-shaped fixtures only: a fake gateway answers the same get_run envelope
// the app consumes. The recorded urls point at the probe's own loopback origin,
// so the external Open action has a real target. 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';
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 _file(
String name, {
required String url,
required String contentType,
required int sizeBytes,
}) => <String, dynamic>{
'name': name,
'url': url,
'content_type': contentType,
'size_bytes': sizeBytes,
};
/// The recorded steps for one probe state. `default` carries two visits that
/// both record `result.csv` plus a partial capture on the second visit.
List<JsonMap> _steps(String origin, String state) {
if (state == 'unavailable') {
return <JsonMap>[
<String, dynamic>{
'stage': 'implementer',
'sequence': 1,
'status': 'completed',
'control': <String, dynamic>{'visit': 1},
},
];
}
if (state == 'empty') {
return <JsonMap>[
<String, dynamic>{
'stage': 'implementer',
'sequence': 1,
'status': 'completed',
'control': <String, dynamic>{'visit': 1},
'artifacts': const <JsonMap>[],
},
];
}
if (state == 'unsafe' || state == 'nourl') {
return <JsonMap>[
<String, dynamic>{
'stage': 'reviewer',
'sequence': 1,
'status': 'completed',
'control': <String, dynamic>{'visit': 1},
'artifacts': [
_file(
'result.csv',
url: state == 'unsafe' ? '//evil.test/result.csv' : '',
contentType: 'text/csv',
sizeBytes: 2048,
),
],
},
];
}
return <JsonMap>[
<String, dynamic>{
'stage': 'implementer',
'sequence': 1,
'status': 'completed',
'control': <String, dynamic>{'visit': 1},
'artifacts': [
_file(
'build.log',
url: '$origin/fixture/build.log',
contentType: 'text/plain; charset=utf-8',
sizeBytes: 2337,
),
],
},
<String, dynamic>{
'stage': 'reviewer',
'sequence': 2,
'status': 'completed',
'control': <String, dynamic>{'visit': 1},
'artifacts': [
_file(
'result.csv',
url: '$origin/fixture/result.csv',
contentType: 'text/csv',
sizeBytes: 2048,
),
_file(
'shot.png',
url: '$origin/fixture/shot.png',
contentType: 'image/png',
sizeBytes: 80544,
),
],
},
<String, dynamic>{
'stage': 'reviewer',
'sequence': 3,
'status': 'completed',
'control': <String, dynamic>{'visit': 2},
'artifacts': [
_file(
'result.csv',
url: '$origin/fixture/result-2.csv',
contentType: 'text/csv',
sizeBytes: 4096,
),
],
'artifacts_skipped': 2,
},
];
}
JsonMap _run(String origin, String state) => <String, dynamic>{
'id': 31,
'title': 'Artifacts gallery probe',
'name': 'gallery',
'status': 'succeeded',
'steps': _steps(origin, state),
};
void main() {
final params = Uri.base.queryParameters;
final cupertino = params['platform'] == 'cupertino';
final theme = params['theme'] == 'dark' ? Brightness.dark : Brightness.light;
final origin = params['origin'] ?? 'https://artifacts.invalid';
final state = params['state'] ?? 'default';
// Browser text scaling is a fixture input like platform and theme.
final textScale = double.tryParse(params['scale'] ?? '') ?? 1;
final body = _ProbeBody(run: _run(origin, state));
Widget scaled(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
);
if (cupertino) {
runApp(
CupertinoApp(
title: 'Artifacts probe',
theme: CupertinoThemeData(brightness: theme),
builder: (context, app) => Theme(
data: ThemeData(platform: TargetPlatform.iOS),
child: scaled(context, app),
),
home: body,
),
);
} else {
runApp(
MaterialApp(
title: 'Artifacts probe',
theme: ThemeData(brightness: theme, platform: TargetPlatform.android),
builder: scaled,
home: body,
),
);
}
}
class _ProbeBody extends StatefulWidget {
const _ProbeBody({required this.run});
final JsonMap run;
@override
State<_ProbeBody> createState() => _ProbeBodyState();
}
class _ProbeBodyState extends State<_ProbeBody> {
late final _FakeGateway _gateway = _FakeGateway(widget.run);
late final RunsController _controller = RunsController(
RunsRepository(_gateway),
);
@override
void initState() {
super.initState();
_controller.select(31);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final detail = RunDetailView(
controller: _controller,
gateway: _gateway,
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,
);
}
}
+421
View File
@@ -0,0 +1,421 @@
// Real-browser evidence for the run-detail Artifacts action and gallery page.
//
// Usage (from app/):
// flutter build web --target tool/artifact_gallery_probe.dart --output build/probe-gallery
// node tool/artifact_gallery_probe.mjs --root build/probe-gallery --out DIR
//
// Serves the built fixture on an OS-assigned loopback port, drives headless
// Chrome, and records the actual recorded rows, the selection dialog, the safe
// external Open, the empty/unavailable states, both native hosts, dark
// Cupertino and the 320/2x states. 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-gallery');
const out = resolve(args.get('out') ?? 'build/artifact-gallery-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) => {
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
if (pathname.startsWith('/fixture/')) {
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
res.end(`recorded artifact ${pathname}\n`);
return;
}
try {
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(), 'a1w-chrome-'));
const chrome = spawn(
chromePath,
['--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu',
'--disable-popup-blocking', '--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 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' });
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('Browser.grantPermissions', {
origin,
permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
});
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 clickExact = async (label) => {
const clicked = await evaluate(`(() => {
const wanted = ${JSON.stringify(label)};
const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim();
const nodes = [...document.querySelectorAll('flt-semantics')];
const tappable = nodes.filter(x => x.hasAttribute('flt-tappable'));
// The tappable node is the one the engine listens to; a labelled wrapper
// above it would swallow a synthetic click.
const node = tappable.find(x => text(x) === wanted)
|| tappable.find(x => text(x).startsWith(wanted))
|| nodes.find(x => text(x) === 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);
};
// The lowest matching row is the later visit's duplicate filename.
const clickLowestPrefix = async (prefix) => {
const clicked = await evaluate(`(() => {
const wanted = ${JSON.stringify(prefix)};
const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim();
const candidates = [...document.querySelectorAll('flt-semantics')]
.filter(x => text(x).startsWith(wanted))
.filter(x => x.hasAttribute('flt-tappable'));
if (!candidates.length) return false;
candidates.sort((a, b) => b.getBoundingClientRect().y - a.getBoundingClientRect().y);
candidates[0].click();
return true;
})()`);
if (!clicked) throw new Error(`No tappable label starting ${JSON.stringify(prefix)}: ${JSON.stringify(await labels())}`);
await delay(600);
};
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('Artifacts gallery 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);
};
const rectOfPrefix = (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);
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;
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;
}
return { max, width: img.width, height: img.height };
})()`);
};
const openGallery = async (query) => {
await navigate(`${origin}/?${query}`);
if (!(await hasLabel('Artifacts'))) {
throw new Error(`Run detail has no Artifacts action: ${JSON.stringify(await labels())}`);
}
await clickExact('Artifacts');
await delay(600);
};
// Material: recorded rows, duplicate filename, visit-2 capture facts and the
// safe external Open.
await navigate(`${origin}/?origin=${encodeURIComponent(origin)}`);
if (!(await hasLabel('Artifacts'))) {
throw new Error(`Material run detail has no Artifacts action: ${JSON.stringify(await labels())}`);
}
evidence.checks.push({ check: 'the run detail offers the native Artifacts action', value: true });
await capture('a1w-material-detail');
await clickExact('Artifacts');
const galleryBody = await bodyText();
for (const recorded of ['build.log', 'shot.png', 'text/csv', 'implementer · visit 1', 'reviewer · visit 2']) {
if (!galleryBody.includes(recorded)) {
throw new Error(`Gallery is missing recorded row ${recorded}: ${JSON.stringify(galleryBody)}`);
}
}
if (!galleryBody.includes('Artifacts · 4 recorded')) {
throw new Error(`Gallery summary missing: ${JSON.stringify(galleryBody)}`);
}
const resultRows = (await labels()).filter((label) => label.startsWith('result.csv')).length;
if (resultRows < 2) {
throw new Error(`Duplicate result.csv rows missing: ${JSON.stringify(await labels())}`);
}
evidence.checks.push({ check: 'the gallery lists the actual recorded rows, not nav labels', value: true });
await capture('a1w-material-gallery');
await clickLowestPrefix('result.csv');
const selectedBody = await bodyText();
for (const fact of ['reviewer · visit 2', 'text/csv · 4.0\u00a0KiB', 'Artifacts · 1 recorded · partial capture', '2 files excluded from artifact capture.']) {
if (!selectedBody.includes(fact)) {
throw new Error(`Selected visit-2 facts missing ${fact}: ${JSON.stringify(selectedBody)}`);
}
}
if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) {
throw new Error(`Selection offers no Open/Copy link: ${JSON.stringify(await labels())}`);
}
evidence.checks.push({ check: 'the duplicate filename selected visit 2 with its own capture facts', value: true });
await capture('a1w-material-selected');
// The selection offers the safe external Open and a separate Copy link.
// Headless Chrome cannot carry a user activation through a synthetic
// semantics click, so the tab itself is proven by the widget test that
// records the exact uri handed to the opener; the browser proves the actions
// appear only for a url that resolves through the safe rules.
if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) {
throw new Error(`Selection offers no Open/Copy link: ${JSON.stringify(await labels())}`);
}
evidence.checks.push({
check: 'the selection offers the native Open and separate Copy link for a safe recorded url',
value: true,
});
await capture('a1w-material-open');
await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=unsafe`);
await clickExact('Artifacts');
await clickLowestPrefix('result.csv');
const unsafeBody = await bodyText();
if (!unsafeBody.includes('The recorded artifact URL cannot be opened safely.')) {
throw new Error(`Unsafe url wording missing: ${JSON.stringify(unsafeBody)}`);
}
if ((await hasLabel('Open')) || (await hasLabel('Copy link'))) {
throw new Error(`Unsafe url still offered an action: ${JSON.stringify(await labels())}`);
}
evidence.checks.push({ check: 'a protocol-relative url offers no open or copy action', value: true });
await capture('a1w-material-unsafe');
await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=nourl`);
await clickExact('Artifacts');
await clickLowestPrefix('result.csv');
const nourlBody = await bodyText();
if (!nourlBody.includes('No artifact URL recorded.')) {
throw new Error(`No-url wording missing: ${JSON.stringify(nourlBody)}`);
}
if ((await hasLabel('Open')) || (await hasLabel('Copy link'))) {
throw new Error(`A url-less record still offered an action: ${JSON.stringify(await labels())}`);
}
evidence.checks.push({ check: 'a record with no url is explicit and offers no action', value: true });
await capture('a1w-material-nourl');
await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=empty`);
await clickExact('Artifacts');
const emptyBody = await bodyText();
if (!emptyBody.includes('No artifacts recorded for this run.')) {
throw new Error(`Recorded empty capture wording missing: ${JSON.stringify(emptyBody)}`);
}
evidence.checks.push({ check: 'a recorded empty capture says nothing was recorded', value: true });
await capture('a1w-material-empty');
await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=unavailable`);
await clickExact('Artifacts');
const unavailableBody = await bodyText();
if (!unavailableBody.includes('Artifacts · capture unavailable')) {
throw new Error(`Unavailable capture wording missing: ${JSON.stringify(unavailableBody)}`);
}
if (unavailableBody.includes('No artifacts recorded for this run.')) {
throw new Error('Unavailable capture claimed nothing was recorded');
}
evidence.checks.push({ check: 'an unavailable capture is never reported as empty', value: true });
await capture('a1w-material-unavailable');
// Cupertino light: the tinted action, the native dialog and its actions.
await openGallery(`platform=cupertino&theme=light&origin=${encodeURIComponent(origin)}`);
const cupertinoBody = await bodyText();
if (!cupertinoBody.includes('shot.png') || !cupertinoBody.includes('reviewer · visit 2')) {
throw new Error(`Cupertino gallery missing recorded rows: ${JSON.stringify(cupertinoBody)}`);
}
evidence.checks.push({ check: 'Cupertino lists the same recorded rows', value: true });
await capture('a1w-cupertino-gallery');
await clickLowestPrefix('result.csv');
if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) {
throw new Error(`Cupertino selection offers no actions: ${JSON.stringify(await labels())}`);
}
const cupertinoSelected = await bodyText();
if (!cupertinoSelected.includes('Artifacts · 1 recorded · partial capture')) {
throw new Error(`Cupertino selection lost its capture facts: ${JSON.stringify(cupertinoSelected)}`);
}
evidence.checks.push({ check: 'Cupertino selection shows the recorded facts and native actions', value: true });
await capture('a1w-cupertino-selected');
// Cupertino dark: the gallery and its dialog on the dark host.
await openGallery(`platform=cupertino&theme=dark&origin=${encodeURIComponent(origin)}`);
await capture('a1w-cupertino-dark-gallery');
await clickLowestPrefix('result.csv');
const darkLabels = await labels();
const darkTitle = darkLabels.find((label) => label.startsWith('result.csv'));
const titleRect = await rectOfPrefix('result.csv');
const darkText = [await bodyText(), ...darkLabels].join('\n');
if (!darkText.includes('Artifacts · 1 recorded · partial capture')) {
throw new Error(`Dark Cupertino dialog did not render: ${JSON.stringify(darkText)}`);
}
if (!titleRect) throw new Error(`Dark Cupertino dialog title missing: ${JSON.stringify(darkLabels)}`);
const luminance = await brightestPixel(titleRect);
if (luminance.max < 0.5) {
throw new Error(`Dark Cupertino dialog text is not light: ${JSON.stringify(luminance)}`);
}
evidence.checks.push({
check: 'dark Cupertino dialog text is light on the popup surface',
value: true,
luminance: luminance.max,
title: darkTitle,
});
await capture('a1w-cupertino-dark-selected');
// 320 px at 2x text on both hosts: the recorded rows and facts stay whole.
const openScaled = async (platform, prefix) => {
await openGallery(`platform=${platform}&theme=light&scale=2&origin=${encodeURIComponent(origin)}`);
const scaled = await bodyText();
for (const recorded of ['build.log', 'shot.png', 'reviewer · visit 2']) {
if (!scaled.includes(recorded)) {
throw new Error(`2x gallery missing ${recorded}: ${JSON.stringify(scaled)}`);
}
}
await capture(`${prefix}-gallery`, 320, 720, 1);
await clickLowestPrefix('result.csv');
const facts = await bodyText();
if (!facts.includes('Artifacts · 1 recorded · partial capture')) {
throw new Error(`2x selection lost its facts: ${JSON.stringify(facts)}`);
}
if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) {
throw new Error(`2x selection lost its actions: ${JSON.stringify(await labels())}`);
}
await capture(`${prefix}-selected`, 320, 720, 1);
};
await openScaled('material', 'a1w-material-2x-320');
evidence.checks.push({ check: 'Material 2x/320 keeps the recorded rows, facts and actions', value: true });
await openScaled('cupertino', 'a1w-cupertino-2x-320');
evidence.checks.push({ check: 'Cupertino 2x/320 keeps the recorded rows, facts and actions', 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 });
}
+60 -17
View File
@@ -260,35 +260,75 @@ try {
await assertBody('Original prompt');
await assertBody('Timeline');
await assertBody('build · visit 3');
captures.push(await capture('i1-runs-phone-detail'));
await assertOcr(captures[5], 'fixture prompt with spaces');
const detailCapture = await capture('i1-runs-phone-detail');
captures.push(detailCapture);
await assertOcr(detailCapture, 'fixture prompt with spaces');
// The recorded Changes action opens the landed viewer for this run's steps:
// the recorded file, its rendered diff, and back to the same detail.
await clickText('Changes');
await assertBody('1 file changed');
await assertBody('lib/features/fixture.dart');
captures.push(await capture('changes-phone-list'));
await clickText('lib/features/fixture.dart', { contains: true });
await assertBody('Rendered');
await assertBody('added fixture line');
await assertBody('removed fixture line');
captures.push(await capture('changes-phone-diff'));
await clickText('Close diff');
await assertBody('lib/features/fixture.dart');
await delay(600);
await clickText('Back', { contains: true });
await assertBody('Original prompt');
// The recorded artifacts action lists each visit's own files, keeps a
// repeated filename distinct, and shows the selected record's facts.
await clickText('Artifacts');
await assertBody('build · visit 1');
await assertBody('test · visit 1');
await assertBody('build-report.html');
await assertBody('result.csv');
captures.push(await capture('artifacts-phone-list'));
await delay(500);
await clickText('result.csv', { contains: true });
await assertBody('text/csv');
await assertBody('4.0');
captures.push(await capture('artifacts-phone-selected'));
await clickText('Close');
await delay(400);
await clickText('Back', { contains: true });
await assertBody('Original prompt');
await setSize(1280, 800);
await assertBody('Original prompt');
captures.push(await capture('i1-runs-desktop-detail'));
await assertOcr(captures[6], 'fixture prompt with spaces');
const desktopDetail = await capture('i1-runs-desktop-detail');
captures.push(desktopDetail);
await assertOcr(desktopDetail, 'fixture prompt with spaces');
await setSize(390, 844);
await clickText('Input');
await wheel(250);
await delay(300);
captures.push(await capture('i1-runs-phone-detail-input'));
await assertOcr(captures[7], 'input payload');
const inputCapture = await capture('i1-runs-phone-detail-input');
captures.push(inputCapture);
await assertOcr(inputCapture, 'input payload');
await scrollUntil('Output');
await clickText('Output');
await wheel(250);
await delay(300);
captures.push(await capture('i1-runs-phone-detail-output'));
await assertOcr(captures[8], 'answer');
const outputCapture = await capture('i1-runs-phone-detail-output');
captures.push(outputCapture);
await assertOcr(outputCapture, 'answer');
await scrollUntil('Metrics');
await clickText('Metrics');
await wheel(300);
await delay(300);
captures.push(await capture('i1-runs-phone-detail-metrics'));
await assertOcr(captures[9], 'Total tokens');
await assertOcr(captures[9], 'Reported cost');
const metricsCapture = await capture('i1-runs-phone-detail-metrics');
captures.push(metricsCapture);
await assertOcr(metricsCapture, 'Total tokens');
await assertOcr(metricsCapture, 'Reported cost');
// Browser Back/Forward move between the in-app routes, not out of the app.
const path = () => evaluate('location.pathname');
@@ -305,8 +345,9 @@ try {
async () => (await semanticText()).includes('Fixture live run'),
'browser Back to the runs list',
);
captures.push(await capture('i1-runs-phone-browser-back-list'));
await assertOcr(captures[10], 'Fixture live run');
const backListCapture = await capture('i1-runs-phone-browser-back-list');
captures.push(backListCapture);
await assertOcr(backListCapture, 'Fixture live run');
await evaluate('history.forward()');
await waitFor(
@@ -333,8 +374,9 @@ try {
if (duringDrop.includes(raw)) throw new Error(`Raw transport text shown: ${raw}`);
}
if ((await path()) !== '/runs/1') throw new Error(`Drop moved the URL to ${await path()}`);
captures.push(await capture('i1-reconnect-detail-retained-phone'));
await assertOcr(captures[13], 'Original prompt');
const retainedCapture = await capture('i1-reconnect-detail-retained-phone');
captures.push(retainedCapture);
await assertOcr(retainedCapture, 'Original prompt');
// Accepting again plus Retry restores the same detail without a remount.
const accepted = await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' });
@@ -359,12 +401,13 @@ try {
for (const raw of ['WebSocketException', 'WebSocketChannelException', 'Failed to connect']) {
if (gate.includes(raw)) throw new Error(`Gate printed raw transport text: ${raw}`);
}
captures.push(await capture('i1-gate-unavailable-friendly-phone'));
const gateCapture = await capture('i1-gate-unavailable-friendly-phone');
captures.push(gateCapture);
await delay(1500);
if (!(await semanticText()).includes('Pipelines server unavailable')) {
throw new Error('Gate left the unavailable state while retrying');
}
await assertOcr(captures[15], 'Pipelines server unavailable');
await assertOcr(gateCapture, 'Pipelines server unavailable');
await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' });
await clickText('Retry');
+36
View File
@@ -110,6 +110,34 @@ function detail(id, live, canceled = false) {
status: 'completed',
outcome: 'success',
target: '#success',
file_changes: {
status: 'complete',
scope: 'Git tracked and nonignored files in the run directory',
files: [
{
path: 'lib/features/fixture.dart',
kind: 'modified',
patch:
'--- a/lib/features/fixture.dart\n' +
'+++ b/lib/features/fixture.dart\n' +
'@@ -1,2 +1,2 @@\n' +
' context line\n' +
'-removed fixture line\n' +
'+added fixture line\n',
},
],
skipped: 0,
omitted: 0,
diagnostic: '',
},
artifacts: [
{
name: 'build-report.html',
size_bytes: 2048,
content_type: 'text/html; charset=utf-8',
url: '/artifacts/1/3/build-report.html',
},
],
},
{
stage: 'test',
@@ -117,6 +145,14 @@ function detail(id, live, canceled = false) {
status: status === 'failed' ? 'failed' : 'completed',
outcome: status === 'failed' ? 'failure' : 'success',
target: status === 'failed' ? '#failure' : '#success',
artifacts: [
{
name: 'result.csv',
size_bytes: 4096,
content_type: 'text/csv',
url: '/artifacts/1/4/result.csv',
},
],
},
],
};
+368
View File
@@ -0,0 +1,368 @@
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 { join, extname, resolve, sep } from 'node:path';
import { tmpdir } from 'node:os';
import { deepStrictEqual } from 'node:assert/strict';
// Real-browser acceptance for the native saved-schedule form.
//
// flutter build web -t tool/schedule_editor_probe_app.dart \
// -o build/schedule_editor_probe_web
// OPENCODE_ARTIFACT_DIR=<dir> node tool/schedule_editor_probe.mjs
//
// The fixture callback and record are in-process; no Pipelines server,
// authentication or real schedule is contacted.
const root = resolve(process.env.PROBE_WEB_ROOT ?? 'build/schedule_editor_probe_web');
const output = process.env.OPENCODE_ARTIFACT_DIR;
if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures');
await mkdir(output, { recursive: true });
const chromePath = process.env.CHROME_PATH
?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const mime = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json',
'.wasm': 'application/wasm',
'.png': 'image/png',
'.otf': 'font/otf',
'.ttf': 'font/ttf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ico': 'image/x-icon',
'.bin': 'application/octet-stream',
};
const server = createServer(async (req, res) => {
try {
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
const path = resolve(root, `.${pathname}`);
if (path !== root && !path.startsWith(root + sep)) {
return res.writeHead(403).end();
}
const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path;
const file = await readFile(filePath);
res
.writeHead(200, {
'content-type': mime[extname(filePath)] ?? 'application/octet-stream',
'cache-control': 'no-store',
})
.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(), 's1-form-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, label, attempts = 220) => {
for (let i = 0; i < attempts; i++) {
const value = await fn();
if (value) return value;
await delay(100);
}
throw new Error(`Timed out waiting for ${label}\n${stderr.slice(-1200)}`);
};
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();
const pageErrors = [];
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') {
pageErrors.push(message.params?.exceptionDetails?.exception?.description ?? 'page exception');
}
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 target = created.result.targetId;
const session = (
await send('Target.attachToTarget', { targetId: target, flatten: true })
).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
let width = 390;
let height = 844;
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)}`);
if (response.result?.exceptionDetails) {
throw new Error(`Runtime exception: ${JSON.stringify(response.result.exceptionDetails)}`);
}
return response.result?.result?.value;
};
const text = () => 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);
}
for (const el of document.querySelectorAll('input, textarea')) {
if (el.getAttribute('aria-label')) chunks.push(el.getAttribute('aria-label') + '=' + el.value);
}
if (document.body?.innerText) chunks.push(document.body.innerText);
return [...new Set(chunks)].join('\\n');
})()`);
const assertText = async (needle) => {
try {
await waitFor(async () => (await text()).includes(needle), `text ${JSON.stringify(needle)}`);
} catch (error) {
throw new Error(`${error.message}\nText now:\n${(await text()).slice(0, 3000)}`);
}
};
const click = async (needle, optional = false) => {
const clicked = await evaluate(`(() => {
const wanted = ${JSON.stringify(needle)};
const nodes = [...document.querySelectorAll('flt-semantics')];
const node = nodes.find((x) => (x.getAttribute('aria-label') || '').trim() === wanted)
|| nodes.find((x) => (x.innerText || '').trim() === wanted)
|| nodes.find((x) => (x.getAttribute('aria-label') || x.innerText || '').trim().startsWith(wanted));
if (!node) return false;
node.click();
return true;
})()`);
if (!clicked && !optional) {
throw new Error(`Could not click ${JSON.stringify(needle)}\n${(await text()).slice(0, 3000)}`);
}
await delay(350);
return clicked;
};
const inputs = () => evaluate(`[...document.querySelectorAll('input,textarea')].map((el) => ({
label: el.getAttribute('aria-label') || '',
value: el.value,
disabled: el.disabled,
}))`);
const typeField = async (label, value) => {
const focused = await evaluate(`(() => {
const wanted = ${JSON.stringify(label)};
const el = [...document.querySelectorAll('input, textarea')].find((input) => {
const name = input.getAttribute('aria-label') || '';
return name === wanted || name.startsWith(wanted + '\\n');
});
if (!el) return false;
el.focus();
el.select?.();
el.setSelectionRange?.(0, (el.value || '').length);
return true;
})()`);
if (!focused) throw new Error(`No field ${JSON.stringify(label)}\n${(await text()).slice(0, 3000)}`);
await delay(250);
await send('Input.insertText', { text: value }, session);
await delay(350);
};
const state = () => evaluate('globalThis.scheduleEditorProbe ?? null');
const wheel = async (delta) => {
await send(
'Input.dispatchMouseEvent',
{ type: 'mouseWheel', x: Math.floor(width / 2), y: Math.floor(height / 2), deltaX: 0, deltaY: delta },
session,
);
await delay(400);
};
const capture = async (name) => {
const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data;
const file = `${name}.png`;
await writeFile(join(output, file), Buffer.from(data, 'base64'));
captures.push({ name, file, width, height });
return file;
};
const load = async (query, nextWidth, nextHeight) => {
width = nextWidth;
height = nextHeight;
await send(
'Emulation.setDeviceMetricsOverride',
{ width, height, deviceScaleFactor: 1, mobile: width < 600 },
session,
);
const navigation = await send('Page.navigate', { url: `${origin}/?${query}` }, session);
if (navigation.error || navigation.result?.errorText) {
throw new Error(`Navigation failed: ${JSON.stringify(navigation)}`);
}
await waitFor(
() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"),
'semantics placeholder',
);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(1200);
await assertText('Add schedule');
};
const checks = [];
const captures = [];
// Material phone: invalid -> valid -> refusal -> exact record.
await load('host=material&scale=1', 390, 844);
await assertText('Future runs only; does not publish or change the workflow.');
await assertText('Weekdays (none means every day)');
await assertText('Enabled schedules start future runs automatically');
await click('Save schedule');
await delay(500);
let current = await state();
let fields = await inputs();
const nameField = fields.find((field) => field.label.startsWith('Name'));
const promptField = fields.find((field) => field.label.startsWith('Prompt'));
if (current?.submits !== 0) throw new Error(`Invalid form submitted: ${JSON.stringify(current)}`);
if (!nameField?.label.includes('Enter a schedule name.')) {
throw new Error(`Name error missing: ${JSON.stringify(fields)}`);
}
if (!promptField?.label.includes('Enter a prompt.')) {
throw new Error(`Prompt error missing: ${JSON.stringify(fields)}`);
}
await capture('s1-form-material-390-invalid');
checks.push({
check: 'invalid submit showed both field errors and sent nothing',
submits: current.submits,
fields,
});
await typeField('Name', 'Probe schedule');
await typeField('Prompt', 'Summarise the release notes.');
await click('Save schedule');
await delay(200);
current = await state();
if (current?.pending !== true || current?.submits !== 1) {
throw new Error(`First submit did not enter the sending state: ${JSON.stringify(current)}`);
}
await click('Saving…', true);
await delay(150);
current = await state();
if (current?.submits !== 1) {
throw new Error(`A second submit escaped while sending: ${JSON.stringify(current)}`);
}
checks.push({ check: 'sending disabled a duplicate submit', submits: current.submits });
await delay(1100);
current = await state();
fields = await inputs();
if (current?.pending !== false || current?.records !== 0) {
throw new Error(`Refusal state drifted: ${JSON.stringify(current)}`);
}
if (current?.lastError !== 'conflict: revision 13 is stale') {
throw new Error(`Refusal was not the fixture's: ${JSON.stringify(current)}`);
}
if (
fields.find((field) => field.label.startsWith('Name'))?.value !== 'Probe schedule'
|| fields.find((field) => field.label.startsWith('Prompt'))?.value
!== 'Summarise the release notes.'
) {
throw new Error(`Refusal lost typed values: ${JSON.stringify(fields)}`);
}
await wheel(900);
await assertText('Your draft is preserved.');
await capture('s1-form-material-390-refusal');
checks.push({
check: 'refusal kept both typed values, showed the preservation copy and re-enabled the form',
lastError: current.lastError,
refusalCopy: 'Your draft is preserved.',
values: fields.map((field) => [field.label.split('\n')[0], field.value]),
});
await click('Save schedule');
await waitFor(async () => (await state())?.records === 1, 'the accepted record');
current = await state();
deepStrictEqual(current.lastRecord, {
id: 0,
name: 'Probe schedule',
pipeline_id: 4,
version: 2,
enabled: true,
input: { prompt: 'Summarise the release notes.' },
workspace: '/srv/research',
rule: { every: '24h', timezone: 'Europe/London' },
notify_mode: 'auto',
});
await delay(500);
await wheel(1400);
await capture('s1-form-material-390-record');
checks.push({
check: 'retry submitted the exact create record once',
submits: current.submits,
records: current.records,
record: current.lastRecord,
});
// Narrow phone at 2x text: labels and helpers wrap, nothing overflows.
await load('host=material&scale=2', 320, 844);
await click('Save schedule');
await delay(600);
await capture('s1-form-material-320-2x-top');
for (let i = 0; i < 5; i++) await wheel(600);
await capture('s1-form-material-320-2x-bottom');
await assertText('Enabled schedules start future runs automatically');
await assertText('Save schedule');
checks.push({ check: '320px at 2x text kept every label and the actions', width: 320, scale: 2 });
// Actual Cupertino dark host, not a Material fallback.
await load('host=cupertino&brightness=dark&scale=1', 390, 844);
await assertText('Add schedule');
await capture('s1-form-cupertino-dark-390-top');
for (let i = 0; i < 3; i++) await wheel(600);
await capture('s1-form-cupertino-dark-390-bottom');
await assertText('Notifications');
checks.push({ check: 'Cupertino dark rendered the native form', host: 'cupertino', brightness: 'dark' });
if (pageErrors.length) throw new Error(`Page exceptions: ${JSON.stringify(pageErrors)}`);
const manifest = {
url: origin,
fixture: 'tool/schedule_editor_probe_app.dart',
output,
checks,
captures,
};
await writeFile(join(output, 'manifest.json'), JSON.stringify(manifest, null, 2));
console.log(JSON.stringify(manifest, 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 });
}
+170
View File
@@ -0,0 +1,170 @@
import 'dart:convert';
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/schedules/domain/editor/schedule_draft.dart';
import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_form.dart';
/// Isolated browser fixture for the native saved-schedule form.
///
/// flutter build web -t tool/schedule_editor_probe_app.dart
///
/// Query: `host=cupertino`, `brightness=dark`, `scale=2`. The injected callback
/// refuses the first valid submit and accepts the retry; it never opens a
/// socket or touches a real schedule. Its counters/record are published at
/// `globalThis.scheduleEditorProbe` for the Chrome probe.
void main() => runApp(const _ProbeApp());
class _ProbeApp extends StatelessWidget {
const _ProbeApp();
@override
Widget build(BuildContext context) {
final parameters = Uri.base.queryParameters;
final cupertino = parameters['host'] == 'cupertino';
final dark = parameters['brightness'] == 'dark';
final scale = double.tryParse(parameters['scale'] ?? '') ?? 1.0;
Widget media(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(scale)),
child: app!,
);
final home = _ProbeHome(cupertino: cupertino);
if (cupertino) {
return CupertinoApp(
theme: CupertinoThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
),
builder: media,
home: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Schedule editor probe'),
),
child: SafeArea(child: home),
),
);
}
return MaterialApp(
theme: ThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
platform: TargetPlatform.android,
),
builder: media,
home: Scaffold(
appBar: AppBar(title: const Text('Schedule editor probe')),
body: SafeArea(child: home),
),
);
}
}
class _Refusal implements Exception {
const _Refusal();
@override
String toString() => 'conflict: revision 13 is stale';
}
class _ProbeHome extends StatefulWidget {
const _ProbeHome({required this.cupertino});
final bool cupertino;
@override
State<_ProbeHome> createState() => _ProbeHomeState();
}
class _ProbeHomeState extends State<_ProbeHome> {
final _draft = ScheduleDraft.create(
pipelineId: 4,
version: '2',
workspace: '/srv/research',
timezone: 'Europe/London',
);
int _submits = 0;
int _records = 0;
bool _pending = false;
bool _refuseNext = true;
String? _lastError;
JsonMap? _lastRecord;
@override
void initState() {
super.initState();
_publish();
}
void _publish() {
globalContext.setProperty(
'scheduleEditorProbe'.toJS,
<String, Object?>{
'submits': _submits,
'records': _records,
'pending': _pending,
'lastError': _lastError,
'lastRecord': _lastRecord,
}.jsify(),
);
}
Future<void> _submit(JsonMap record) async {
_submits++;
_pending = true;
_publish();
if (mounted) setState(() {});
await Future<void>.delayed(const Duration(milliseconds: 900));
if (_refuseNext) {
_refuseNext = false;
_pending = false;
_lastError = 'conflict: revision 13 is stale';
_publish();
if (mounted) setState(() {});
throw const _Refusal();
}
_pending = false;
_records++;
_lastRecord = record;
_publish();
if (mounted) setState(() {});
}
@override
Widget build(BuildContext context) {
final record = _lastRecord;
return SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 640),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ScheduleEditorForm(
draft: _draft,
onSubmit: _submit,
onCancel: () {},
),
if (record != null) ...[
const SizedBox(height: 24),
Text(
'Submitted record',
style: widget.cupertino
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
SelectableText(
const JsonEncoder.withIndent(' ').convert(record),
),
],
],
),
),
),
);
}
}
+148
View File
@@ -0,0 +1,148 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart';
import 'package:pipelines_app/ui/adaptive/host.dart';
/// A definition with an authored stage (including an unknown future field), a
/// declared route to a terminal, and no declaration for `ghost`.
JsonMap _graph() => <String, dynamic>{
'stages': <dynamic>[
<String, dynamic>{
'key': 'plan',
'type': 'model',
'prompt': 'Plan the change.',
'output': 'A short plan.',
'edges': <String, String?>{'success': 'build', 'error': '#'},
'fallback_error': true,
'configs': <String, dynamic>{
'provider': 'openai',
'model': 'gpt-5',
'budget_usd': 12.5,
},
'blocks': <String, dynamic>{'tools': 'shell\nread_file'},
'limits': <String, dynamic>{
'max_visits': 2,
'on': <String>['error'],
},
'memory': <String, dynamic>{'context': 'latest'},
'notify': <String, dynamic>{
'on': <String>['failure'],
'destination': 'ops@example.test',
'artifacts': <String>['run.log'],
},
'future_field': <String, dynamic>{'kept': true},
},
<String, dynamic>{
'key': 'build',
'type': 'shell',
'edges': <String, String?>{'success': '#success', 'error': '#failure'},
},
],
};
/// Isolated browser fixture for the read-only stage definition pane.
///
/// `style=cupertino` selects the Cupertino host, `dark=1` its dark theme,
/// `scale=2` a real 2x text scale. Every button opens the exact helper the
/// pipeline graph hook will call; nothing contacts a server or reads a run.
void main() {
final parameters = Uri.base.queryParameters;
runApp(
_ProbeApp(
cupertino: parameters['style'] == 'cupertino',
dark: parameters['dark'] == '1',
scale: double.tryParse(parameters['scale'] ?? '') ?? 1,
),
);
}
class _ProbeApp extends StatelessWidget {
const _ProbeApp({
required this.cupertino,
required this.dark,
required this.scale,
});
final bool cupertino;
final bool dark;
final double scale;
@override
Widget build(BuildContext context) {
Widget scaled(BuildContext context, Widget? child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(scale)),
child: child ?? const SizedBox.shrink(),
);
if (cupertino) {
return CupertinoApp(
theme: CupertinoThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
),
builder: scaled,
home: const CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Stage definition fixture'),
),
child: SafeArea(child: _Launcher()),
),
);
}
return MaterialApp(
theme: ThemeData(
platform: TargetPlatform.android,
brightness: Brightness.light,
),
darkTheme: ThemeData(
platform: TargetPlatform.android,
brightness: Brightness.dark,
),
themeMode: dark ? ThemeMode.dark : ThemeMode.light,
builder: scaled,
home: Scaffold(
appBar: AppBar(title: const Text('Stage definition fixture')),
body: const SafeArea(child: _Launcher()),
),
);
}
}
class _Launcher extends StatelessWidget {
const _Launcher();
void _open(BuildContext context, String key) => openStageDefinition(
context,
graph: _graph(),
stageKey: key,
pipelineId: 41,
pipelineName: 'Demo pipeline',
version: 7,
);
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
return ListView(
padding: const EdgeInsets.all(16),
children: [
const Text('Fixture home'),
for (final key in <String>['plan', '#failure', 'ghost'])
Padding(
padding: const EdgeInsets.only(top: 8),
child: cupertino
? CupertinoButton.filled(
onPressed: () => _open(context, key),
child: Text('$key definition'),
)
: FilledButton(
onPressed: () => _open(context, key),
child: Text('$key definition'),
),
),
],
);
}
}
+380
View File
@@ -0,0 +1,380 @@
// Browser acceptance for the isolated read-only stage definition pane.
//
// Serves the probe build (`flutter build web -t tool/stage_definition_probe.dart`)
// on an OS-assigned loopback port, drives real headless Chrome, opens the pane
// through the same native helper the manager graph hook uses, asserts the
// pinned identity, actual field values, outcomes, raw unknown fields, terminal
// and unknown-stage states, closes it with Back on both hosts, and writes
// captures.
//
// PROBE_VARIANT=material|cupertino PROBE_SCHEME=dark|light PROBE_SCALE=1|2 \
// PROBE_WIDTH=1280 PROBE_HEIGHT=900 PROBE_WEB_ROOT=<probe build> \
// OPENCODE_ARTIFACT_DIR=<dir> node tool/stage_definition_probe.mjs
import { createServer } from 'node:http';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { setTimeout as delay } from 'node:timers/promises';
import { join, extname, resolve, sep } from 'node:path';
import { tmpdir } from 'node:os';
import { createHash } from 'node:crypto';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
const root = resolve(
process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/stage_definition_probe_web'),
);
const variant = process.env.PROBE_VARIANT ?? 'material';
const scheme = process.env.PROBE_SCHEME ?? 'dark';
const scale = process.env.PROBE_SCALE ?? '1';
const width = Number(process.env.PROBE_WIDTH ?? 1280);
const height = Number(process.env.PROBE_HEIGHT ?? 900);
const chromePath = process.env.CHROME_PATH ??
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const artifactDir = process.env.OPENCODE_ARTIFACT_DIR;
if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures');
await mkdir(artifactDir, { recursive: true });
const prefix = `stage-definition-${variant}-${scheme}-${scale}x` +
(width === 1280 && height === 900 ? '' : `-${width}x${height}`);
const mime = {
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.wasm': 'application/wasm',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.otf': 'font/otf',
'.ttf': 'font/ttf',
};
const server = createServer(async (req, res) => {
try {
const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname));
if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end();
const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path;
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 port = server.address().port;
const profile = await mkdtemp(join(tmpdir(), 'stage-definition-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) => {
for (let i = 0; i < 140; i++) {
const value = await fn();
if (value) return value;
await delay(100);
}
throw new Error('Timed out waiting for Chrome DevTools');
};
let ws;
try {
const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]);
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.method === 'Runtime.exceptionThrown') {
console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails?.exception?.description));
}
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' });
const target = created.result.targetId;
const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
await send('Emulation.setEmulatedMedia', {
features: [{ name: 'prefers-color-scheme', value: scheme }],
}, session);
await send('Emulation.setDeviceMetricsOverride', {
width, height, deviceScaleFactor: 1, mobile: false,
}, session);
const query = `?style=${variant}&dark=${scheme === 'dark' ? 1 : 0}&scale=${scale}`;
const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/${query}` }, session);
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
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;
};
await delay(3500);
const loaded = await evaluate('({url:location.href, ready:document.readyState})');
if (!loaded?.url.includes(`127.0.0.1:${port}/${query}`)) {
throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`);
}
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(2200);
const labels = () => evaluate(
"[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||(x.innerText||'').trim()).filter(Boolean)",
);
const bodyText = async () => [await evaluate('document.body.innerText'), ...(await labels())].join('\n');
const clickExact = async (label) => {
const point = await evaluate(`(() => {
const e = [...document.querySelectorAll('flt-semantics')].find(x =>
(x.getAttribute('aria-label')||(x.innerText||'').trim()).trim() === ${JSON.stringify(label)});
if (!e) return null;
const r = e.getBoundingClientRect();
return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
})()`);
if (!point) throw new Error(`Missing control ${label}: ${JSON.stringify(await labels())}`);
await send('Input.dispatchMouseEvent', {
type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1,
}, session);
await send('Input.dispatchMouseEvent', {
type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1,
}, session);
await delay(1000);
};
const capture = async (name) => {
const data = (await send('Page.captureScreenshot', {
format: 'png', captureBeyondViewport: false,
}, session)).result.data;
const buffer = Buffer.from(data, 'base64');
const file = `${prefix}-${name}.png`;
await writeFile(join(artifactDir, file), buffer);
return { file, sha1: createHash('sha1').update(buffer).digest('hex') };
};
const visible = async (needle, exact = false) => evaluate(`(() => {
const found = [...document.querySelectorAll('flt-semantics')].filter(x => {
const label = (x.getAttribute('aria-label')||(x.innerText||'')).trim();
return ${exact ? `label === ${JSON.stringify(needle)}` : `label.includes(${JSON.stringify(needle)})`};
});
if (!found.length) return null;
found.sort((a, b) => {
const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect();
return ra.width * ra.height - rb.width * rb.height;
});
const r = found[0].getBoundingClientRect();
return { x: r.x, y: r.y, width: r.width, height: r.height,
visible: r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < innerHeight };
})()`);
// Scroll by the measured delta instead of fixed steps: a fixed gesture can
// stop with a target half-entered (and its neighbours not built), which is
// exactly what made the raw-section check fail on shorter content.
const scrollTo = async (needle, { exact = false, maxTop = null } = {}) => {
for (let attempt = 0; attempt < 24; attempt++) {
const r = await visible(needle, exact);
const fullyVisible = r && r.width > 0 && r.height > 0 &&
r.y >= 32 && r.y + r.height <= height - 32;
if (fullyVisible && (maxTop == null || r.y <= maxTop)) return r;
// Scroll down until the target is fully in view; for a target that must
// sit high (the raw title above its JSON), keep scrolling until it does.
const wanted = r
? Math.round(r.y - (maxTop ?? height / 2))
: Math.round(height / 3);
const distance = Math.sign(wanted || 1) *
Math.max(60, Math.min(400, Math.abs(wanted)));
await send('Input.synthesizeScrollGesture', {
x: Math.round(width / 2), y: Math.round(height / 2),
yDistance: -distance, gestureSourceType: 'mouse', speed: 900,
preventFling: true,
}, session);
await delay(300);
}
throw new Error(
`${needle} never scrolled into view: ${JSON.stringify(await bodyText())}`,
);
};
// The raw section is one selectable block whose whole value must be
// inspected. Scroll to the pane's end so the JSON tail (the unknown fields
// the raw section exists for) is really on screen, not just built.
const scrollToRaw = async () => {
let previous = null;
for (let attempt = 0; attempt < 16; attempt++) {
const r = await visible('future_field');
if (r && previous != null && Math.abs(r.y - previous) < 1) {
if (!r.visible || r.y + r.height > height + 1) {
throw new Error(`The raw JSON did not settle in view: ${JSON.stringify(r)}`);
}
return r;
}
previous = r?.y ?? null;
await send('Input.synthesizeScrollGesture', {
x: Math.round(width / 2), y: Math.round(height / 2),
yDistance: -600, gestureSourceType: 'mouse', speed: 900,
preventFling: true,
}, session);
await delay(300);
}
throw new Error(
`The raw JSON never settled: ${JSON.stringify(await bodyText())}`,
);
};
const evidence = { variant, scheme, scale, checks: [], captures: [] };
const expectText = async (needle, context) => {
const text = await bodyText();
if (!text.includes(needle)) throw new Error(`${context}: missing ${JSON.stringify(needle)}\n${text}`);
};
await expectText('Fixture home', 'fixture home');
await clickExact('plan definition');
for (const needle of [
'Demo pipeline · v7',
'Plan the change.',
'A short plan.',
'success → build',
'error → FAILURE (terminal)',
]) {
await expectText(needle, 'declared stage');
}
// Two two-line blocks must share the host line rhythm. A fallback font for
// the outcomes arrow must not stretch only that block, so compare the whole
// label+value block: equal line counts mean equal heights.
if (width >= 1000) {
const blockHeight = async (prefixText) => evaluate(`(() => {
const found = [...document.querySelectorAll('flt-semantics')].filter(x =>
(x.getAttribute('aria-label')||(x.innerText||'')).trim().startsWith(${JSON.stringify(prefixText)}));
if (!found.length) return null;
found.sort((a, b) => {
const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect();
return ra.width * ra.height - rb.width * rb.height;
});
const r = found[0].getBoundingClientRect();
return { height: r.height, width: r.width };
})()`);
const outcomes = await blockHeight('Outcomes');
const tools = await blockHeight('Tools');
const ratio = outcomes && tools ? outcomes.height / tools.height : 0;
if (!(ratio >= 0.8 && ratio <= 1.25)) {
throw new Error(
`Outcomes line rhythm differs from Tools: ${JSON.stringify({ outcomes, tools, ratio })}`,
);
}
evidence.rhythm = {
outcomesHeight: outcomes.height,
toolsHeight: tools.height,
ratio,
};
evidence.checks.push({
check: 'the outcomes block keeps the host line rhythm of other two-line blocks',
value: ratio,
});
}
evidence.checks.push({
check: 'declared stage shows pinned identity and the web field values',
value: true,
});
const declaredCapture = await capture('declared');
evidence.captures.push(declaredCapture);
// Remaining declared fields, reached by scrolling so the probe also covers
// viewports shorter than the full pane.
for (const needle of [
'Provider', 'openai', 'Model', 'gpt-5', 'Budget (USD)', '12.5',
'Tools', 'shell', 'read_file', 'Max visits', 'Limit on', 'Memory',
'context: latest',
]) {
await scrollTo(needle);
await expectText(needle, 'declared stage');
}
evidence.checks.push({
check: 'every declared field value is present in the rendered pane',
value: true,
});
await scrollTo('Notify destination');
for (const needle of ['Notify on', 'failure', 'Notify destination', 'ops@example.test', 'Notify artifacts', 'run.log']) {
await expectText(needle, 'notify definition');
}
const rawJson = await scrollToRaw();
evidence.rawJsonRect = rawJson;
evidence.rawSectionSeen = (await bodyText()).includes('Raw stage definition');
for (const needle of ['future_field', 'kept', 'fallback_error']) {
await expectText(needle, 'raw unknown fields');
}
evidence.checks.push({
check: 'unknown stage fields remain in the selectable raw JSON',
value: true,
});
const rawCapture = await capture('raw');
if (rawCapture.sha1 === declaredCapture.sha1) {
throw new Error('The raw capture is identical to the unscrolled pane');
}
evidence.captures.push(rawCapture);
await clickExact('Back');
await expectText('Fixture home', 'Back');
evidence.checks.push({ check: 'Back returned to the graph host', value: true });
await clickExact('#failure definition');
const terminalText = await bodyText();
if (terminalText.includes('#failure')) {
throw new Error(`The terminal title still exposes the raw key: ${terminalText}`);
}
await expectText('Failure definition', 'terminal title');
for (const needle of [
'Success and Failure are definition targets, not recorded visits.',
'Incoming routes',
'plan · error* → FAILURE',
'build · error → FAILURE',
]) {
await expectText(needle, 'terminal definition');
}
evidence.checks.push({
check: 'the terminal page is titled with its display label, not the protocol key',
value: true,
});
evidence.checks.push({
check: 'terminal explains definition routes without claiming a visit',
value: true,
});
evidence.captures.push(await capture('terminal'));
await clickExact('Back');
await expectText('Fixture home', 'terminal Back');
await clickExact('ghost definition');
await expectText(
'This stage is not declared in this pipeline version.',
'unknown stage',
);
const unknown = await bodyText();
if (unknown.includes('Raw stage definition') || unknown.includes('Incoming routes')) {
throw new Error(`Unknown stage invented definition content: ${unknown}`);
}
evidence.checks.push({
check: 'unknown stage has an explicit missing state with no defaults',
value: true,
});
evidence.captures.push(await capture('unknown'));
await clickExact('Back');
await expectText('Fixture home', 'unknown Back');
evidence.checks.push({ check: 'every open used one native bar and Back', value: true });
evidence.captures.push(await capture('closed'));
console.log(JSON.stringify(evidence, null, 2));
} finally {
if (ws?.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ id: 2147483647, method: 'Browser.close' }));
}
await Promise.race([once(chrome, 'exit'), delay(3000)]);
ws?.close();
if (chrome.exitCode === null) chrome.kill('SIGTERM');
chrome.stderr.destroy();
chrome.unref();
await new Promise((resolveClose) => {
server.close(resolveClose);
server.closeAllConnections();
});
await rm(profile, { recursive: true, force: true });
}
+178
View File
@@ -0,0 +1,178 @@
import 'dart:async';
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/templates/screen.dart';
/// Browser capture entrypoint for the reusable Templates gallery.
///
/// The fixture gateway is in-process and records every request; nothing here
/// opens a socket or contacts a real server. Query parameters:
/// `host=material|cupertino`, `scale=<text scale>` and
/// `scenario=default|empty|refresh-refusal`. The state published at
/// `globalThis.templatesGalleryProbe` is read by the driver.
const _source = ' name: "release"\n\tstages:\n - key: "añadir" 😀 \n';
const _galleryRows = [
{
'key': 'release',
'name': 'Release workflow',
'description': 'Ship a version',
'source': _source,
'scheduled': true,
},
{
'key': 'blank',
'name': '',
'description': 'No display name',
'source': 'name: "unnamed"\n',
'scheduled': false,
},
];
class _ProbeGateway implements ApiGateway {
_ProbeGateway(
this.publish, {
required this.empty,
required this.failingRefresh,
});
final VoidCallback publish;
final bool empty;
final bool failingRefresh;
int listCalls = 0;
int validates = 0;
int submits = 0;
final List<JsonMap> created = [];
String? lastSource;
JsonMap? lastSubmit;
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
if (type == 'list_templates') {
listCalls++;
publish();
if (failingRefresh) {
// The catalogue loads, then a Refresh from the open template refuses so
// the driver can prove the failure is visible above that detail.
if (listCalls == 2) {
await Future<void>.delayed(const Duration(milliseconds: 250));
throw const ProtocolError('fixture refresh unavailable');
}
return {'templates': _galleryRows};
}
if (listCalls == 1 && !empty) {
// The first read refuses, so the driver can exercise the honest error
// state and Retry on a real host.
await Future<void>.delayed(const Duration(milliseconds: 250));
throw const ProtocolError('fixture catalogue unavailable');
}
if (listCalls == 2) {
// Enough time to capture the loading state after Retry.
await Future<void>.delayed(const Duration(milliseconds: 1200));
}
if (empty) return {'templates': const []};
return {
'templates': [
..._galleryRows,
if (listCalls >= 3)
{
'key': 'added',
'name': 'Added after refresh',
'description': 'Proves the catalogue was re-read',
'source': 'name: "added"\n',
'scheduled': false,
},
],
};
}
if (type == 'validate') {
validates++;
lastSource = fields['source'] as String?;
publish();
await Future<void>.delayed(const Duration(milliseconds: 200));
return {
'graph': {'stages': const []},
};
}
if (type == 'submit') {
submits++;
lastSubmit = Map<String, dynamic>.from(fields);
publish();
return {
'detail': {'id': 41, 'name': 'Probe created'},
};
}
throw StateError('The templates probe does not implement $type');
}
}
void main() => runApp(const _ProbeApp());
class _ProbeApp extends StatefulWidget {
const _ProbeApp();
@override
State<_ProbeApp> createState() => _ProbeAppState();
}
class _ProbeAppState extends State<_ProbeApp> {
late final _params = Uri.base.queryParameters;
late final _cupertino = _params['host'] == 'cupertino';
late final _scale = double.tryParse(_params['scale'] ?? '') ?? 1;
late final _gateway = _ProbeGateway(
_publish,
empty: _params['scenario'] == 'empty',
failingRefresh: _params['scenario'] == 'refresh-refusal',
);
void _publish() {
globalContext.setProperty(
'templatesGalleryProbe'.toJS,
<String, Object?>{
'listCalls': _gateway.listCalls,
'validates': _gateway.validates,
'submits': _gateway.submits,
'created': _gateway.created,
'lastSource': _gateway.lastSource,
'lastSubmit': _gateway.lastSubmit,
}.jsify(),
);
}
void _created(JsonMap detail) {
_gateway.created.add(detail);
_publish();
}
@override
Widget build(BuildContext context) {
Widget scaled(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(_scale)),
child: app!,
);
final screen = TemplatesScreen(gateway: _gateway, onCreated: _created);
if (_cupertino) {
return CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.dark),
builder: scaled,
home: screen,
);
}
return MaterialApp(
theme: ThemeData(brightness: Brightness.dark),
builder: scaled,
home: screen,
);
}
}
+386
View File
@@ -0,0 +1,386 @@
import { createServer } from 'node:http';
import { readFile, mkdir, mkdtemp, 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 { join, extname, resolve, sep } from 'node:path';
import { tmpdir } from 'node:os';
// Real-browser acceptance for the reusable Templates gallery.
//
// Usage (from app/):
// flutter build web --target=tool/templates_gallery_probe.dart \
// -o build/templates_gallery_probe_web
// OPENCODE_ARTIFACT_DIR=<dir> node tool/templates_gallery_probe.mjs
//
// PROBE_HOST (material|cupertino), PROBE_SCALE, PROBE_WIDTH/PROBE_HEIGHT,
// PROBE_SCENARIO (default|empty|refresh-refusal) and PROBE_CAPTURE_PREFIX
// select the host and evidence. The fixture gateway is in-process: no socket
// is opened and no real Pipelines server is contacted.
const root = resolve(process.env.PROBE_WEB_ROOT ?? 'build/templates_gallery_probe_web');
const artifactDir = process.env.OPENCODE_ARTIFACT_DIR;
if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures');
await mkdir(artifactDir, { recursive: true });
const width = Number(process.env.PROBE_WIDTH ?? 390);
const height = Number(process.env.PROBE_HEIGHT ?? 844);
const textScale = process.env.PROBE_SCALE ?? '1';
const host = process.env.PROBE_HOST ?? 'material';
const scenario = process.env.PROBE_SCENARIO ?? 'default';
const capturePrefix = process.env.PROBE_CAPTURE_PREFIX ?? 't1-gallery';
const deviceScaleFactor = Number(process.env.PROBE_DPR ?? 1);
const MIME = {
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.wasm': 'application/wasm',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.otf': 'font/otf',
'.ttf': 'font/ttf',
};
const server = createServer(async (req, res) => {
try {
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
const path = resolve(root, `.${pathname}`);
if (path !== root && !path.startsWith(root + sep)) {
res.writeHead(403).end();
return;
}
const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path;
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(), 'templates-gallery-chrome-'));
const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [
'--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;
});
async function waitFor(check, label, attempts = 160) {
for (let attempt = 0; attempt < attempts; attempt++) {
const value = await check();
if (value) return value;
await delay(100);
}
throw new Error(`Timed out waiting for ${label}\n${stderr.slice(-1200)}`);
}
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.method === 'Runtime.exceptionThrown') {
console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails?.exception?.description));
}
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 target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId;
const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
await send(
'Emulation.setDeviceMetricsOverride',
{ width, height, deviceScaleFactor, mobile: true },
session,
);
await send(
'Emulation.setEmulatedMedia',
{ features: [{ name: 'prefers-color-scheme', value: 'dark' }] },
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)}`);
if (response.result?.exceptionDetails) {
throw new Error(`Page exception: ${JSON.stringify(response.result.exceptionDetails)}`);
}
return response.result?.result?.value;
};
const semanticText = () =>
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);
}
for (const el of document.querySelectorAll('input, textarea')) {
if (el.getAttribute('aria-label')) chunks.push(el.getAttribute('aria-label'));
if (el.value) chunks.push(String(el.value));
}
if (document.body?.innerText) chunks.push(document.body.innerText);
return [...new Set(chunks)].join('\\n');
})()`);
const labels = () =>
evaluate(
"[...document.querySelectorAll('flt-semantics')].map((el) => (el.getAttribute('aria-label') || el.innerText || '').trim()).filter(Boolean)",
);
const assertBody = async (text) => {
try {
await waitFor(
async () => (await semanticText()).includes(text),
`body to contain ${JSON.stringify(text)}`,
);
} catch (error) {
throw new Error(`${error.message}\nBody now:\n${(await semanticText()).slice(0, 3000)}`);
}
};
const clickLabel = async (label, { contains = false } = {}) => {
const point = await evaluate(`(() => {
const needle = ${JSON.stringify(label)};
const candidates = [...document.querySelectorAll('flt-semantics')].filter((el) => {
const text = (el.getAttribute('aria-label') || el.innerText || '').trim();
return ${contains ? 'text.includes(needle)' : 'text === needle'};
});
const target = candidates.find((el) =>
['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')),
) ?? candidates[0];
if (!target) return null;
const r = target.getBoundingClientRect();
if (r.width === 0 || r.height === 0) return null;
return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
})()`);
if (!point) {
throw new Error(`Could not click ${JSON.stringify(label)}. Labels: ${JSON.stringify(await labels())}`);
}
await send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session);
await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session);
await delay(400);
};
const typeName = async (value) => {
const focused = await evaluate(`(() => {
const input = document.querySelector('input');
if (!input) return false;
input.focus();
input.select?.();
input.setSelectionRange?.(0, (input.value || '').length);
return true;
})()`);
if (!focused) throw new Error('The name field was not exposed as a semantics input');
await delay(300);
await send('Input.insertText', { text: value }, session);
await delay(400);
};
const state = () => evaluate('globalThis.templatesGalleryProbe ?? null');
const capture = async (name) => {
const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data;
const path = join(artifactDir, `${name}.png`);
await writeFile(path, Buffer.from(data, 'base64'));
return path;
};
const checks = [];
const captures = [];
await send(
'Page.navigate',
{ url: `${origin}/?scale=${textScale}&host=${host}&scenario=${scenario}` },
session,
);
await waitFor(
() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"),
'semantics placeholder',
);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(900);
if (scenario === 'empty') {
await assertBody('No templates are available on this server.');
const emptyState = await state();
if (emptyState?.listCalls !== 1) {
throw new Error(`The empty catalogue made unexpected requests: ${JSON.stringify(emptyState)}`);
}
captures.push(await capture(`${capturePrefix}-empty`));
checks.push({ check: 'empty catalogue stated honestly', state: emptyState });
} else if (scenario === 'refresh-refusal') {
// The catalogue loads, a template is open, and Refresh genuinely refuses:
// the refusal must stay visible above that detail, with Retry.
await assertBody('Release workflow');
await clickLabel('Release workflow', { contains: true });
await assertBody('Definition source');
const before = await state();
if (before?.listCalls !== 1 || before?.validates !== 0 || before?.submits !== 0) {
throw new Error(`Opening the template made unexpected requests: ${JSON.stringify(before)}`);
}
await clickLabel('Refresh');
await assertBody('fixture refresh unavailable');
await assertBody('Retry');
await assertBody('Definition source');
await assertBody('Create pipeline from this template');
const refused = await state();
if (refused?.listCalls !== 2 || refused?.validates !== 0 || refused?.submits !== 0) {
throw new Error(`The failed refresh did not stay read-only: ${JSON.stringify(refused)}`);
}
captures.push(await capture(`${capturePrefix}-detail-refresh-error`));
checks.push({ check: 'failed refresh visible above the open template', state: refused });
await clickLabel('Retry');
await waitFor(
async () => !(await semanticText()).includes('fixture refresh unavailable'),
'the refusal banner to clear after Retry',
);
await assertBody('Definition source');
const retried = await state();
if (retried?.listCalls !== 3) {
throw new Error(`Retry did not re-read exactly once: ${JSON.stringify(retried)}`);
}
captures.push(await capture(`${capturePrefix}-detail-refresh-retried`));
checks.push({ check: 'Retry re-read while keeping the template open', state: retried });
} else {
// The first read genuinely refuses; the screen must say so and retry.
await assertBody('fixture catalogue unavailable');
await assertBody('Retry');
const failed = await state();
if (failed?.listCalls !== 1) {
throw new Error(`The refusal state made unexpected requests: ${JSON.stringify(failed)}`);
}
captures.push(await capture(`${capturePrefix}-error`));
checks.push({ check: 'catalogue refusal shown with Retry', state: failed });
await clickLabel('Retry');
await assertBody('Loading templates…');
captures.push(await capture(`${capturePrefix}-loading`));
await assertBody('Release workflow');
await assertBody('(unnamed template)');
await assertBody('Ship a version');
const gallery = await state();
if (gallery?.listCalls !== 2) {
throw new Error(`Retry did not re-read exactly once: ${JSON.stringify(gallery)}`);
}
captures.push(await capture(`${capturePrefix}-gallery`));
checks.push({ check: 'retry loaded the actual catalogue rows', state: gallery });
await clickLabel('Release workflow', { contains: true });
await assertBody('Definition source');
await assertBody('Key');
await assertBody('Includes a schedule');
await assertBody('Create pipeline from this template');
const detail = await state();
if (detail?.validates !== 0 || detail?.submits !== 0) {
throw new Error(`Opening a template sent a write: ${JSON.stringify(detail)}`);
}
captures.push(await capture(`${capturePrefix}-detail`));
checks.push({ check: 'selected template shows metadata and verbatim source', state: detail });
await clickLabel('Back');
await assertBody('Release workflow');
await clickLabel('Refresh');
await assertBody('Added after refresh');
const refreshed = await state();
if (refreshed?.listCalls !== 3) {
throw new Error(`Refresh made unexpected requests: ${JSON.stringify(refreshed)}`);
}
captures.push(await capture(`${capturePrefix}-refreshed`));
checks.push({ check: 'native back returned and refresh re-read the catalogue', state: refreshed });
await clickLabel('Release workflow', { contains: true });
await assertBody('Create pipeline from this template');
await clickLabel('Create pipeline from this template');
await assertBody('Create from Release workflow');
await assertBody('New pipeline name (required)');
captures.push(await capture(`${capturePrefix}-create-blank`));
await typeName('Probe release');
await clickLabel('Cancel');
await waitFor(async () => !(await semanticText()).includes('Create from Release workflow'), 'the prompt to close');
const cancelled = await state();
if (cancelled?.validates !== 0 || cancelled?.submits !== 0 || cancelled?.created?.length !== 0) {
throw new Error(`Cancel sent a request: ${JSON.stringify(cancelled)}`);
}
checks.push({ check: 'Cancel sent nothing', state: cancelled });
await waitFor(
async () => (await semanticText()).includes('Create pipeline from this template'),
'the detail after the prompt closed',
);
await clickLabel('Create pipeline from this template');
await assertBody('Create from Release workflow');
await typeName('Probe release');
await clickLabel('Create');
await assertBody('Created "Probe created". It is in the Pipelines list.');
const created = await state();
if (created?.validates !== 1 || created?.submits !== 1 || created?.created?.length !== 1) {
throw new Error(`The accepted create was not reported exactly once: ${JSON.stringify(created)}`);
}
if (created.lastSubmit?.name !== 'Probe release' || created.lastSubmit?.create_only !== true) {
throw new Error(`Submit payload drifted: ${JSON.stringify(created.lastSubmit)}`);
}
const verbatim = ' name: "release"\n\tstages:\n - key: "añadir" 😀 \n';
if (created.lastSubmit?.source !== created.lastSource || created.lastSource !== verbatim) {
throw new Error(`Source was not sent verbatim: ${JSON.stringify(created)}`);
}
captures.push(await capture(`${capturePrefix}-created`));
checks.push({
check: 'accepted create forwarded the detail once with the verbatim source',
state: created,
});
await clickLabel('Close');
await waitFor(async () => !(await semanticText()).includes('Create from Release workflow'), 'the prompt to close');
const closed = await state();
if (closed?.created?.length !== 1 || closed?.submits !== 1) {
throw new Error(`Close changed the request counts: ${JSON.stringify(closed)}`);
}
checks.push({ check: 'Close dismissed without another request', state: closed });
}
console.log(JSON.stringify({
ok: true,
origin,
viewport: { width, height },
deviceScaleFactor,
textScale,
host,
scenario,
checks,
captures,
}, 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 });
}