feat(app): add native authored stage definition pane

This commit is contained in:
2026-10-21 22:26:34 +01:00
parent 76fb2cdd87
commit d88213deb4
7 changed files with 1529 additions and 0 deletions
+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 });
}