merge(app): land run-mode graph evidence component
This commit is contained in:
@@ -0,0 +1,200 @@
|
||||
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/run_graph_view.dart';
|
||||
|
||||
/// plan -> build -> audit with a taken path that stops at the running build and
|
||||
/// untaken routes to audit and both terminals.
|
||||
JsonMap _graph() => <String, dynamic>{
|
||||
'stages': <dynamic>[
|
||||
<String, dynamic>{
|
||||
'key': 'plan',
|
||||
'type': 'model',
|
||||
'edges': <String, String?>{'success': 'build', 'error': '#'},
|
||||
'fallback_error': true,
|
||||
},
|
||||
<String, dynamic>{
|
||||
'key': 'build',
|
||||
'type': 'shell',
|
||||
'edges': <String, String?>{'success': 'audit', 'error': '#'},
|
||||
},
|
||||
<String, dynamic>{
|
||||
'key': 'audit',
|
||||
'type': 'model',
|
||||
'edges': <String, String?>{'success': '#success', 'error': '#failure'},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
JsonMap _runningRun() {
|
||||
final started = DateTime.now().toUtc().subtract(
|
||||
const Duration(minutes: 2, seconds: 5),
|
||||
);
|
||||
return <String, dynamic>{
|
||||
'id': 42,
|
||||
'executing': true,
|
||||
'current_stage': 'build',
|
||||
'steps': <dynamic>[
|
||||
<String, dynamic>{
|
||||
'sequence': 1,
|
||||
'stage': 'plan',
|
||||
'status': 'completed',
|
||||
'outcome': 'success',
|
||||
'target': 'build',
|
||||
},
|
||||
<String, dynamic>{
|
||||
'sequence': 2,
|
||||
'stage': 'build',
|
||||
'status': 'running',
|
||||
'outcome': '',
|
||||
'target': '',
|
||||
'started_at': started.toIso8601String(),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
JsonMap _finishedRun() => <String, dynamic>{
|
||||
'id': 42,
|
||||
'executing': false,
|
||||
'current_stage': '',
|
||||
'steps': <dynamic>[
|
||||
<String, dynamic>{
|
||||
'sequence': 1,
|
||||
'stage': 'plan',
|
||||
'status': 'completed',
|
||||
'outcome': 'success',
|
||||
'target': 'build',
|
||||
},
|
||||
<String, dynamic>{
|
||||
'sequence': 2,
|
||||
'stage': 'build',
|
||||
'status': 'completed',
|
||||
'outcome': 'success',
|
||||
'target': 'audit',
|
||||
},
|
||||
<String, dynamic>{
|
||||
'sequence': 3,
|
||||
'stage': 'audit',
|
||||
'status': 'completed',
|
||||
'outcome': 'success',
|
||||
'target': '#',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/// Isolated browser fixture for `RunGraphView` only.
|
||||
///
|
||||
/// `style=cupertino` selects the Cupertino host, `dark=1` its dark theme and
|
||||
/// `scale=2` a real 2x text scale. `case=finished` records a resolved success
|
||||
/// terminal instead of the running path; `case=missing` omits the graph. A
|
||||
/// click reports the exact visited stage key; unvisited nodes report nothing.
|
||||
void main() {
|
||||
final parameters = Uri.base.queryParameters;
|
||||
runApp(
|
||||
_ProbeApp(
|
||||
cupertino: parameters['style'] == 'cupertino',
|
||||
dark: parameters['dark'] == '1',
|
||||
scale: double.tryParse(parameters['scale'] ?? '') ?? 1,
|
||||
fixture: parameters['case'] ?? 'running',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _ProbeApp extends StatelessWidget {
|
||||
const _ProbeApp({
|
||||
required this.cupertino,
|
||||
required this.dark,
|
||||
required this.scale,
|
||||
required this.fixture,
|
||||
});
|
||||
|
||||
final bool cupertino;
|
||||
final bool dark;
|
||||
final double scale;
|
||||
final String fixture;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final page = _ProbePage(
|
||||
scale: scale,
|
||||
graph: fixture == 'missing' ? null : _graph(),
|
||||
run: fixture == 'finished' ? _finishedRun() : _runningRun(),
|
||||
);
|
||||
if (cupertino) {
|
||||
return CupertinoApp(
|
||||
theme: CupertinoThemeData(
|
||||
brightness: dark ? Brightness.dark : Brightness.light,
|
||||
),
|
||||
home: CupertinoPageScaffold(
|
||||
navigationBar: const CupertinoNavigationBar(
|
||||
middle: Text('Run graph'),
|
||||
),
|
||||
child: SafeArea(child: page),
|
||||
),
|
||||
);
|
||||
}
|
||||
return MaterialApp(
|
||||
theme: ThemeData(
|
||||
platform: TargetPlatform.android,
|
||||
brightness: Brightness.light,
|
||||
),
|
||||
darkTheme: ThemeData(
|
||||
platform: TargetPlatform.android,
|
||||
brightness: Brightness.dark,
|
||||
),
|
||||
themeMode: dark ? ThemeMode.dark : ThemeMode.light,
|
||||
home: Scaffold(
|
||||
appBar: AppBar(title: const Text('Run graph')),
|
||||
body: SafeArea(child: page),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProbePage extends StatefulWidget {
|
||||
const _ProbePage({
|
||||
required this.scale,
|
||||
required this.graph,
|
||||
required this.run,
|
||||
});
|
||||
|
||||
final double scale;
|
||||
final JsonMap? graph;
|
||||
final JsonMap run;
|
||||
|
||||
@override
|
||||
State<_ProbePage> createState() => _ProbePageState();
|
||||
}
|
||||
|
||||
class _ProbePageState extends State<_ProbePage> {
|
||||
String? _selected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Selected: ${_selected ?? 'none'}'),
|
||||
const SizedBox(height: 8),
|
||||
Expanded(
|
||||
child: MediaQuery(
|
||||
data: MediaQuery.of(
|
||||
context,
|
||||
).copyWith(textScaler: TextScaler.linear(widget.scale)),
|
||||
child: RunGraphView(
|
||||
graph: widget.graph,
|
||||
run: widget.run,
|
||||
selectedStage: _selected,
|
||||
onStageSelected: (key) => setState(() => _selected = key),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
// Browser acceptance for the isolated RunGraphView fixture.
|
||||
//
|
||||
// Serves a probe build (`flutter build web -t tool/run_graph_probe.dart`) on an
|
||||
// OS-assigned loopback port, drives real headless Chrome, and checks the
|
||||
// recorded-run evidence: legend wording, visited statuses, the running elapsed
|
||||
// line, a visited-stage click, an unvisited node doing nothing, and (for the
|
||||
// finished fixture) no live line plus the resolved terminal's recorded outcome.
|
||||
//
|
||||
// PROBE_VARIANT=material|cupertino PROBE_SCHEME=dark|light PROBE_SCALE=1|2 \
|
||||
// PROBE_CASE=running|finished PROBE_WIDTH=1280 PROBE_HEIGHT=800 \
|
||||
// PROBE_WEB_ROOT=<probe build> OPENCODE_ARTIFACT_DIR=<dir> \
|
||||
// node tool/run_graph_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 { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
|
||||
const root = resolve(
|
||||
process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/run_graph_probe'),
|
||||
);
|
||||
const variant = process.env.PROBE_VARIANT ?? 'material';
|
||||
const scheme = process.env.PROBE_SCHEME ?? 'light';
|
||||
const scale = process.env.PROBE_SCALE ?? '1';
|
||||
const fixture = process.env.PROBE_CASE ?? 'running';
|
||||
const width = Number(process.env.PROBE_WIDTH ?? (scale === '2' ? 320 : 1280));
|
||||
const height = Number(process.env.PROBE_HEIGHT ?? (scale === '2' ? 700 : 800));
|
||||
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 = `run-graph-${variant}-${scheme}-${scale}x-${fixture}`;
|
||||
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(), 'run-graph-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; });
|
||||
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 msg = JSON.parse(event.data);
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
pending.get(msg.id)(msg);
|
||||
pending.delete(msg.id);
|
||||
}
|
||||
});
|
||||
const send = (method, params = {}, sessionId) => new Promise((done) => {
|
||||
const callId = ++id;
|
||||
pending.set(callId, done);
|
||||
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: width < 600,
|
||||
}, session);
|
||||
const url = `http://127.0.0.1:${port}/?style=${variant}&dark=${scheme === 'dark' ? 1 : 0}` +
|
||||
`&scale=${scale}&case=${fixture}`;
|
||||
const navigation = await send('Page.navigate', { url }, 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}/?style=${variant}`)) {
|
||||
throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`);
|
||||
}
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
await delay(2500);
|
||||
const semantics = () => evaluate(
|
||||
"[...document.querySelectorAll('flt-semantics')].map(x=>({label:(x.getAttribute('aria-label')||x.innerText||'').trim(), selected:x.getAttribute('aria-current')}))",
|
||||
);
|
||||
const body = await evaluate('document.body.innerText');
|
||||
for (const word of ['Executed', 'Not executed', 'Selected: none']) {
|
||||
if (!body.includes(word)) throw new Error(`Missing ${word}: ${body}`);
|
||||
}
|
||||
if (fixture === 'running' && !body.includes('Current stage build')) {
|
||||
throw new Error(`Missing live elapsed line: ${body}`);
|
||||
}
|
||||
if (fixture === 'finished' && body.includes('Current stage')) {
|
||||
throw new Error(`Finished run kept a live line: ${body}`);
|
||||
}
|
||||
const items = await semantics();
|
||||
const labels = items.map((item) => item.label);
|
||||
const need = (text) => {
|
||||
if (!labels.some((label) => label.split('\n')[0] === text || label.includes(text))) {
|
||||
throw new Error(`Missing semantics ${text}: ${JSON.stringify(labels)}`);
|
||||
}
|
||||
};
|
||||
need('plan');
|
||||
if (fixture === 'running') {
|
||||
if (!labels.some((label) => label.includes('completed'))) {
|
||||
throw new Error(`Plan status missing: ${JSON.stringify(labels)}`);
|
||||
}
|
||||
if (!labels.some((label) => label.includes('success'))) {
|
||||
throw new Error(`Executed route label missing: ${JSON.stringify(labels)}`);
|
||||
}
|
||||
} else if (!labels.some((label) => label.includes('completed'))) {
|
||||
throw new Error(`Finished plan status missing: ${JSON.stringify(labels)}`);
|
||||
}
|
||||
const nodeAt = (key) => items.find((item) => {
|
||||
const label = item.label;
|
||||
return label === key || label.startsWith(`${key}\n`) || label.startsWith(`${key} `);
|
||||
});
|
||||
const nodeRect = async (key) => evaluate(`(() => {
|
||||
const items=[...document.querySelectorAll('flt-semantics')];
|
||||
const e=items.find(x=>{const l=(x.getAttribute('aria-label')||x.innerText||'').trim();return l===${JSON.stringify(key)}||l.startsWith(${JSON.stringify(key)}+'\\n')||l.startsWith(${JSON.stringify(key)}+' ');});
|
||||
if (!e) return null;
|
||||
const r=e.getBoundingClientRect();
|
||||
return {x:r.x,y:r.y,width:r.width,height:r.height};
|
||||
})()`);
|
||||
const click = async (key) => {
|
||||
const rect = await nodeRect(key);
|
||||
if (!rect || rect.width === 0 || rect.height === 0) return false;
|
||||
const point = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
|
||||
await send('Input.dispatchMouseEvent', {
|
||||
type: 'mousePressed', ...point, button: 'left', clickCount: 1,
|
||||
}, session);
|
||||
await send('Input.dispatchMouseEvent', {
|
||||
type: 'mouseReleased', ...point, button: 'left', clickCount: 1,
|
||||
}, session);
|
||||
await delay(800);
|
||||
return true;
|
||||
};
|
||||
const drag = async (dx) => {
|
||||
const start = { x: width / 2, y: height / 2 };
|
||||
await send('Input.dispatchMouseEvent', {
|
||||
type: 'mousePressed', ...start, button: 'left', buttons: 1, clickCount: 1,
|
||||
}, session);
|
||||
for (let step = 1; step <= 5; step++) {
|
||||
await send('Input.dispatchMouseEvent', {
|
||||
type: 'mouseMoved', x: start.x + dx * step / 5, y: start.y,
|
||||
button: 'left', buttons: 1,
|
||||
}, session);
|
||||
await delay(40);
|
||||
}
|
||||
await send('Input.dispatchMouseEvent', {
|
||||
type: 'mouseReleased', x: start.x + dx, y: start.y,
|
||||
button: 'left', clickCount: 1,
|
||||
}, session);
|
||||
await delay(700);
|
||||
};
|
||||
const capture = async (name, w, h) => {
|
||||
await send('Emulation.setDeviceMetricsOverride', {
|
||||
width: w, height: h, deviceScaleFactor: 1, mobile: w < 600,
|
||||
}, session);
|
||||
await delay(2200);
|
||||
const data = (await send('Page.captureScreenshot', {
|
||||
format: 'png', captureBeyondViewport: false,
|
||||
}, session)).result.data;
|
||||
const file = `${prefix}-${name}.png`;
|
||||
await writeFile(`${artifactDir}/${file}`, Buffer.from(data, 'base64'));
|
||||
return file;
|
||||
};
|
||||
const captures = [await capture('initial', width, height)];
|
||||
if (!nodeAt('plan')) throw new Error(`plan node absent: ${JSON.stringify(labels)}`);
|
||||
if (!await click('plan')) throw new Error('Could not click plan');
|
||||
let after = await evaluate('document.body.innerText');
|
||||
if (!after.includes('Selected: plan')) throw new Error(`plan click missed: ${after}`);
|
||||
const current = (await semantics()).find((item) => item.selected === 'true');
|
||||
if (!current?.label.startsWith('plan')) {
|
||||
throw new Error(`Selection not announced: ${JSON.stringify(current)}`);
|
||||
}
|
||||
// A content-sized graph need not fit a 320px viewport. Pan with a real drag
|
||||
// until the remaining recorded stage is actually exposed, then check it.
|
||||
let panned = await semantics();
|
||||
for (let pass = 0; pass < 8; pass++) {
|
||||
const seen = panned.map((item) => item.label);
|
||||
if (seen.some((label) => label.includes('build') && label.includes('running'))) break;
|
||||
await drag(-220);
|
||||
panned = await semantics();
|
||||
}
|
||||
if (fixture === 'running' &&
|
||||
!panned.some((item) => item.label.includes('build') && item.label.includes('running'))) {
|
||||
throw new Error(`Build status missing after pan: ${JSON.stringify(panned)}`);
|
||||
}
|
||||
if (fixture === 'finished' &&
|
||||
!panned.some((item) => item.label.startsWith('Success') && item.label.includes('success'))) {
|
||||
throw new Error(`Resolved success terminal missing after pan: ${JSON.stringify(panned)}`);
|
||||
}
|
||||
const auditRect = fixture === 'running' ? await nodeRect('audit') : null;
|
||||
if (auditRect) {
|
||||
await click('audit');
|
||||
after = await evaluate('document.body.innerText');
|
||||
if (!after.includes('Selected: plan')) {
|
||||
throw new Error(`Unvisited node changed selection: ${after}`);
|
||||
}
|
||||
}
|
||||
if (fixture === 'finished') {
|
||||
if (await click('Success')) {
|
||||
after = await evaluate('document.body.innerText');
|
||||
if (!after.includes('Selected: plan')) {
|
||||
throw new Error(`Terminal fabricated a visit: ${after}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
captures.push(await capture('final', width, height));
|
||||
if (width > 400) captures.push(await capture('phone', 320, 700));
|
||||
console.log(JSON.stringify({ variant, scheme, scale, fixture, labels, captures }, 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((done) => {
|
||||
server.close(done);
|
||||
server.closeAllConnections();
|
||||
});
|
||||
await rm(profile, { recursive: true, force: true });
|
||||
}
|
||||
Reference in New Issue
Block a user