Merge branch 'main' into flutter/p1-pipelines
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart';
|
||||
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
|
||||
import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart';
|
||||
|
||||
/// A fixture entry point for browser captures of [ArtifactVisitList]. It never
|
||||
/// contacts a server: the groups below are recorded shapes, and the selection
|
||||
/// line only echoes the widget's callback.
|
||||
///
|
||||
/// Query parameters:
|
||||
/// platform=ios render the Cupertino host instead of Material
|
||||
/// scale=1.5 large-text check
|
||||
/// state=empty no recorded groups
|
||||
/// state=disabled rows rendered without a selection callback
|
||||
/// state=unrecorded a record with no name, url or content type
|
||||
void main() {
|
||||
final params = Uri.base.queryParameters;
|
||||
runApp(
|
||||
_ProbeApp(cupertino: params['platform'] == 'ios', state: params['state']),
|
||||
);
|
||||
}
|
||||
|
||||
ArtifactRecord _record(
|
||||
String name, {
|
||||
required String url,
|
||||
required String contentType,
|
||||
required int sizeBytes,
|
||||
}) {
|
||||
return ArtifactRecord.fromJson(<String, dynamic>{
|
||||
'name': name,
|
||||
'url': url,
|
||||
'content_type': contentType,
|
||||
'size_bytes': sizeBytes,
|
||||
});
|
||||
}
|
||||
|
||||
const longName =
|
||||
'a-very-long-recorded-artifact-file-name-that-must-wrap-across-'
|
||||
'several-lines-at-large-text-sizes.xlsx';
|
||||
|
||||
final List<ArtifactGroup> _groups = <ArtifactGroup>[
|
||||
ArtifactGroup(
|
||||
stageKey: 'build',
|
||||
visit: 1,
|
||||
artifacts: <ArtifactRecord>[
|
||||
_record(
|
||||
longName,
|
||||
url: '/artifacts/7/3/$longName',
|
||||
contentType:
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
sizeBytes: 123456,
|
||||
),
|
||||
],
|
||||
),
|
||||
ArtifactGroup(
|
||||
stageKey: 'review',
|
||||
visit: 1,
|
||||
artifacts: <ArtifactRecord>[
|
||||
_record(
|
||||
'result.csv',
|
||||
url: '/artifacts/7/1/result.csv',
|
||||
contentType: 'text/csv',
|
||||
sizeBytes: 2048,
|
||||
),
|
||||
_record(
|
||||
'notes.md',
|
||||
url: '/artifacts/7/1/notes.md',
|
||||
contentType: 'text/markdown',
|
||||
sizeBytes: 812,
|
||||
),
|
||||
],
|
||||
),
|
||||
ArtifactGroup(
|
||||
stageKey: 'review',
|
||||
visit: 2,
|
||||
artifacts: <ArtifactRecord>[
|
||||
_record(
|
||||
'result.csv',
|
||||
url: '/artifacts/7/2/result.csv',
|
||||
contentType: 'text/csv',
|
||||
sizeBytes: 4096,
|
||||
),
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
/// Records the server sent without a name, url or content type. The list must
|
||||
/// show the honest fallbacks rather than infer any of them.
|
||||
final List<ArtifactGroup> _unrecordedGroups = <ArtifactGroup>[
|
||||
ArtifactGroup(
|
||||
stageKey: 'review',
|
||||
visit: 1,
|
||||
artifacts: <ArtifactRecord>[
|
||||
ArtifactRecord.fromJson(const <String, dynamic>{
|
||||
'name': '',
|
||||
'url': '',
|
||||
'content_type': '',
|
||||
'size_bytes': 0,
|
||||
}),
|
||||
ArtifactRecord.fromJson(const <String, dynamic>{
|
||||
'name': 'notes.md',
|
||||
'url': '/artifacts/7/1/notes.md',
|
||||
'content_type': '',
|
||||
'size_bytes': 812,
|
||||
}),
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
List<ArtifactGroup> _groupsFor(String? state) => switch (state) {
|
||||
'empty' => const <ArtifactGroup>[],
|
||||
'unrecorded' => _unrecordedGroups,
|
||||
_ => _groups,
|
||||
};
|
||||
|
||||
class _ProbeApp extends StatefulWidget {
|
||||
const _ProbeApp({required this.cupertino, this.state});
|
||||
|
||||
final bool cupertino;
|
||||
final String? state;
|
||||
|
||||
@override
|
||||
State<_ProbeApp> createState() => _ProbeAppState();
|
||||
}
|
||||
|
||||
class _ProbeAppState extends State<_ProbeApp> {
|
||||
ArtifactGroup? _selectedGroup;
|
||||
ArtifactRecord? _selectedArtifact;
|
||||
|
||||
String? get _selectedIdentity => _selectedGroup == null
|
||||
? null
|
||||
: artifactVisitIdentity(_selectedGroup!, _selectedArtifact!);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scale =
|
||||
double.tryParse(Uri.base.queryParameters['scale'] ?? '') ?? 1.0;
|
||||
final selected = _selectedGroup == null
|
||||
? 'Selected: none'
|
||||
: 'Selected: ${_selectedGroup!.stageKey} · visit '
|
||||
'${_selectedGroup!.visit} · ${_selectedArtifact!.name}';
|
||||
final groups = _groupsFor(widget.state);
|
||||
final selectable = widget.state != 'disabled';
|
||||
final body = Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 0),
|
||||
child: Text('Artifact visit list probe'),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 0),
|
||||
child: Text(selected),
|
||||
),
|
||||
Expanded(
|
||||
child: ArtifactVisitList(
|
||||
groups: groups,
|
||||
selectedIdentity: _selectedIdentity,
|
||||
onSelected: selectable
|
||||
? (group, artifact) => setState(() {
|
||||
_selectedGroup = group;
|
||||
_selectedArtifact = artifact;
|
||||
})
|
||||
: null,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
Widget scaled(BuildContext context, Widget? child) => MediaQuery(
|
||||
data: MediaQuery.of(
|
||||
context,
|
||||
).copyWith(textScaler: TextScaler.linear(scale)),
|
||||
child: child ?? const SizedBox.shrink(),
|
||||
);
|
||||
if (widget.cupertino) {
|
||||
return CupertinoApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
builder: scaled,
|
||||
home: CupertinoPageScaffold(
|
||||
// Sections paint the grouped background; the page must match it or a
|
||||
// white seam shows below the last section in light mode.
|
||||
backgroundColor: CupertinoColors.systemGroupedBackground,
|
||||
child: body,
|
||||
),
|
||||
);
|
||||
}
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
builder: scaled,
|
||||
home: Scaffold(body: body),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
// Real-browser evidence for the Changes viewer fixture.
|
||||
//
|
||||
// Usage (from app/):
|
||||
// flutter build web --target tool/changes_probe_entry.dart --output build/probe-web
|
||||
// node tool/changes_probe.mjs --root build/probe-web --out DIR
|
||||
//
|
||||
// Serves the fixture over loopback with an explicit text/html index, drives
|
||||
// headless Chrome through the Chrome DevTools Protocol, enables Flutter
|
||||
// semantics, clicks exact labels, verifies the body/labels change, copies the
|
||||
// raw patch and writes real PNG captures at phone and desktop widths.
|
||||
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-web');
|
||||
const out = resolve(args.get('out') ?? 'build/changes-probe');
|
||||
const chromePath =
|
||||
process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
||||
await mkdir(out, { recursive: true });
|
||||
|
||||
const mime = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.wasm': 'application/wasm',
|
||||
'.png': 'image/png',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.ico': 'image/x-icon',
|
||||
'.ttf': 'font/ttf',
|
||||
'.otf': 'font/otf',
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2',
|
||||
'.bin': 'application/octet-stream',
|
||||
'.frag': 'application/octet-stream',
|
||||
};
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
|
||||
let filePath = resolve(root, '.' + pathname);
|
||||
if (filePath !== root && !filePath.startsWith(root + sep)) {
|
||||
res.writeHead(403).end();
|
||||
return;
|
||||
}
|
||||
if (pathname === '/' || pathname.endsWith('/')) {
|
||||
filePath = join(filePath, 'index.html');
|
||||
}
|
||||
const file = await readFile(filePath);
|
||||
const type = mime[extname(filePath)] ?? 'application/octet-stream';
|
||||
res.writeHead(200, { 'content-type': type }).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 origin = `http://127.0.0.1:${port}`;
|
||||
|
||||
const profile = await mkdtemp(join(tmpdir(), 'd1-changes-chrome-'));
|
||||
const chrome = spawn(
|
||||
chromePath,
|
||||
[
|
||||
'--headless=new',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--disable-gpu',
|
||||
'--remote-debugging-port=0',
|
||||
`--user-data-dir=${profile}`,
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: ['ignore', 'ignore', 'pipe'] },
|
||||
);
|
||||
let stderr = '';
|
||||
chrome.stderr.on('data', (data) => {
|
||||
stderr += data;
|
||||
});
|
||||
|
||||
const waitFor = async (fn, what) => {
|
||||
for (let i = 0; i < 120; i++) {
|
||||
const value = await fn();
|
||||
if (value) return value;
|
||||
await delay(100);
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`);
|
||||
};
|
||||
|
||||
let ws;
|
||||
const evidence = { origin, captures: [], checks: [] };
|
||||
try {
|
||||
const endpoint = await waitFor(
|
||||
() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1],
|
||||
'Chrome DevTools',
|
||||
);
|
||||
ws = new WebSocket(endpoint);
|
||||
await once(ws, 'open');
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
ws.addEventListener('message', (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.id && pending.has(message.id)) {
|
||||
pending.get(message.id)(message);
|
||||
pending.delete(message.id);
|
||||
}
|
||||
});
|
||||
const send = (method, params = {}, sessionId) =>
|
||||
new Promise((resolveCall) => {
|
||||
const callId = ++id;
|
||||
pending.set(callId, resolveCall);
|
||||
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
|
||||
});
|
||||
|
||||
const created = await send('Target.createTarget', { url: 'about:blank' });
|
||||
if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`);
|
||||
const 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.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 nodes = [...document.querySelectorAll('flt-semantics')];
|
||||
const node = nodes.find(x => x.getAttribute('aria-label') === wanted)
|
||||
|| nodes.find(x => (x.innerText || '').trim() === wanted);
|
||||
if (!node) return false;
|
||||
node.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!clicked) throw new Error(`No exact semantics label ${JSON.stringify(label)}: ${JSON.stringify(await labels())}`);
|
||||
await delay(450);
|
||||
};
|
||||
// File rows announce their visible kind and meta after the path, so click by
|
||||
// the stable action+path prefix rather than a fully spelled label.
|
||||
const clickPrefix = async (prefix) => {
|
||||
const clicked = await evaluate(`(() => {
|
||||
const wanted = ${JSON.stringify(prefix)};
|
||||
const nodes = [...document.querySelectorAll('flt-semantics')];
|
||||
// A container's innerText also starts with its first row, so click the
|
||||
// most specific (shortest-text) node that starts with the row prefix.
|
||||
const candidates = nodes.filter((x) =>
|
||||
(x.getAttribute('aria-label') || '').startsWith(wanted)
|
||||
|| (x.innerText || '').trim().startsWith(wanted));
|
||||
if (candidates.length === 0) return false;
|
||||
candidates.sort((a, b) => (a.innerText || '').length - (b.innerText || '').length);
|
||||
candidates[0].click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!clicked) throw new Error(`No semantics label starting ${JSON.stringify(prefix)}: ${JSON.stringify(await labels())}`);
|
||||
await delay(450);
|
||||
};
|
||||
const activate = async () => {
|
||||
await delay(3500);
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
await delay(1000);
|
||||
const current = await labels();
|
||||
if (!current.some((label) => label.includes('Changes 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, height, 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 file = join(out, `${name}.png`);
|
||||
await writeFile(file, Buffer.from(data, 'base64'));
|
||||
evidence.captures.push(file);
|
||||
return file;
|
||||
};
|
||||
|
||||
await navigate(`${origin}/`);
|
||||
const contentType = await evaluate(
|
||||
"fetch('/').then(r => r.headers.get('content-type'))",
|
||||
);
|
||||
evidence.checks.push({ check: 'index content-type is text/html', value: contentType });
|
||||
if (!String(contentType).toLowerCase().startsWith('text/html')) {
|
||||
throw new Error(`Root index is not text/html: ${contentType}`);
|
||||
}
|
||||
|
||||
// Diff text inherits native host typography; it must not add a custom face.
|
||||
const manifest = await evaluate("fetch('/assets/FontManifest.json').then(r => r.json())");
|
||||
const codeEntry = (Array.isArray(manifest) ? manifest : []).find(
|
||||
(entry) => entry.family === 'RobotoMono',
|
||||
);
|
||||
if (codeEntry) throw new Error('Diff build still overrides native typography');
|
||||
evidence.checks.push({
|
||||
check: 'the web build does not register a custom diff font',
|
||||
});
|
||||
|
||||
const firstLabels = await labels();
|
||||
const firstBody = await bodyText();
|
||||
const firstRow = 'Open diff for lib/features/changes/domain/unified_patch.dart';
|
||||
const firstRowPresent = firstLabels.some((label) => label.startsWith(firstRow));
|
||||
const firstStates = ['Changes probe', 'Capture unavailable'].filter((label) =>
|
||||
firstBody.includes(label),
|
||||
);
|
||||
evidence.checks.push({
|
||||
check: 'run summary and capture states are present',
|
||||
value: firstStates,
|
||||
fileRow: firstRowPresent,
|
||||
});
|
||||
if (firstStates.length !== 2 || !firstRowPresent) {
|
||||
throw new Error(`Run summary or capture states missing: ${JSON.stringify(firstBody)}`);
|
||||
}
|
||||
await capture('d1-changes-phone-list', 390, 844);
|
||||
|
||||
const before = await bodyText();
|
||||
await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart');
|
||||
const after = await bodyText();
|
||||
if (after === before) throw new Error('Opening the diff did not change the document body');
|
||||
for (const label of ['Rendered', 'Raw patch', 'Copy patch', 'Close diff']) {
|
||||
if (!(await hasLabel(label))) throw new Error(`Open diff is missing ${label}: ${JSON.stringify(await labels())}`);
|
||||
}
|
||||
evidence.checks.push({ check: 'body changed and diff controls appeared', bodyChanged: true });
|
||||
const renderedFile = await capture('d1-changes-phone-diff', 390, 844);
|
||||
|
||||
const renderedBody = await bodyText();
|
||||
await clickExact('Raw patch');
|
||||
const rawSemantics = (await labels()).some((label) =>
|
||||
label.startsWith('Raw patch for lib/features/changes/domain/unified_patch.dart'),
|
||||
);
|
||||
if (!rawSemantics) {
|
||||
throw new Error(`Raw patch view semantics missing: ${JSON.stringify(await labels())}`);
|
||||
}
|
||||
const rawBody = await bodyText();
|
||||
const rawFile = await capture('d1-changes-phone-raw', 390, 844);
|
||||
const [renderedBytes, rawBytes] = await Promise.all([
|
||||
readFile(renderedFile),
|
||||
readFile(rawFile),
|
||||
]);
|
||||
if (renderedBytes.equals(rawBytes)) {
|
||||
throw new Error('Raw patch capture is identical to the rendered capture');
|
||||
}
|
||||
evidence.checks.push({
|
||||
check: 'Raw patch switched the body and the rendered pixels',
|
||||
bodyChanged: rawBody !== renderedBody,
|
||||
pixelsChanged: true,
|
||||
rawSemantics,
|
||||
});
|
||||
|
||||
await send('Browser.grantPermissions', {
|
||||
origin,
|
||||
permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
|
||||
});
|
||||
await clickExact('Copy patch');
|
||||
let clipboard = null;
|
||||
try {
|
||||
clipboard = await evaluate('navigator.clipboard.readText()');
|
||||
} catch (error) {
|
||||
evidence.checks.push({ check: 'clipboard readback unavailable', value: String(error) });
|
||||
}
|
||||
if (clipboard != null) {
|
||||
const startsWithHeader = String(clipboard).startsWith(
|
||||
'--- "a/lib/features/changes/domain/unified_patch.dart"',
|
||||
);
|
||||
if (!startsWithHeader) throw new Error('Clipboard did not contain the recorded raw patch');
|
||||
evidence.checks.push({
|
||||
check: 'Copy patch copied the raw patch',
|
||||
startsWithHeader,
|
||||
length: String(clipboard).length,
|
||||
});
|
||||
}
|
||||
await capture('d1-changes-phone-copied', 390, 844);
|
||||
|
||||
await clickExact('Close diff');
|
||||
if (await hasLabel('Raw patch')) throw new Error('Close diff left the viewer open');
|
||||
evidence.checks.push({ check: 'Close diff returned to the list', bodyChanged: (await bodyText()) !== after });
|
||||
|
||||
// Filter changed filenames through the real text field when Flutter exposes
|
||||
// it as a semantics input; record honestly when it does not.
|
||||
const focused = await evaluate(`(() => {
|
||||
const nodes = [...document.querySelectorAll('input, textarea')];
|
||||
const node = nodes.find(x => ((x.getAttribute('aria-label') || '') + ' ' + (x.placeholder || '')).toLowerCase().includes('filter changed files'));
|
||||
if (!node) return false;
|
||||
node.focus();
|
||||
node.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (focused) {
|
||||
await send('Input.insertText', { text: 'unified' }, session);
|
||||
await delay(500);
|
||||
const filtered = await labels();
|
||||
// A row is one single-line semantics node; a list container repeats its
|
||||
// rows with newlines and must not be counted as an extra match.
|
||||
const rows = (prefix) =>
|
||||
filtered.filter((label) => label.startsWith(prefix) && !label.includes('\n'));
|
||||
const unifiedRows = rows('Open diff for lib/features/changes/domain/unified_patch.dart');
|
||||
const binaryRows = rows('Open diff for assets/pipelines-mark.png');
|
||||
evidence.checks.push({
|
||||
check: 'filtering by changed filename',
|
||||
unifiedRows: unifiedRows.length,
|
||||
binaryRows: binaryRows.length,
|
||||
});
|
||||
if (unifiedRows.length === 0) {
|
||||
throw new Error('Filtering removed the matching file');
|
||||
}
|
||||
if (binaryRows.length !== 0) {
|
||||
throw new Error('Filtering left a non-matching file visible');
|
||||
}
|
||||
await capture('d1-changes-phone-filtered', 390, 844);
|
||||
} else {
|
||||
evidence.checks.push({ check: 'filter field not exposed as a semantics input', value: false });
|
||||
}
|
||||
|
||||
// Visit numbering: two stages appear twice in this compact fixture. The
|
||||
// implementer's visits are position-derived (1, 2); the resumed reviewer
|
||||
// visit records control.visit 6, which must win over its position.
|
||||
await navigate(`${origin}/?visits=1`);
|
||||
const visitText = await bodyText();
|
||||
const visitsFor = (stage) => [
|
||||
...visitText.matchAll(new RegExp(`${stage}\\s+Visit (\\d+)`, 'g')),
|
||||
].map((match) => match[1]);
|
||||
const implementerVisits = visitsFor('implementer');
|
||||
const reviewerVisits = visitsFor('reviewer');
|
||||
evidence.checks.push({
|
||||
check: 'repeated stages show their own visit numbers',
|
||||
implementerVisits,
|
||||
reviewerVisits,
|
||||
});
|
||||
if (implementerVisits.join(',') !== '1,2') {
|
||||
throw new Error(`implementer visits are not 1,2: ${JSON.stringify(visitText)}`);
|
||||
}
|
||||
if (reviewerVisits.join(',') !== '1,6') {
|
||||
throw new Error(`reviewer visits are not 1,6 (control.visit): ${JSON.stringify(visitText)}`);
|
||||
}
|
||||
const visitFile = await capture('d1-changes-phone-visits', 390, 844);
|
||||
|
||||
await navigate(`${origin}/`);
|
||||
await clickPrefix('Open diff for lib/features/changes/widgets/file_diff_viewer.dart');
|
||||
await capture('d1-changes-desktop-diff', 1280, 800);
|
||||
await clickExact('Close diff');
|
||||
await capture('d1-changes-desktop-list', 1280, 800);
|
||||
|
||||
// Presentation revision: the light theme and a narrow Cupertino surface, at
|
||||
// 2x so glyph advance, line tints and the popup inset are inspectable.
|
||||
await navigate(`${origin}/?theme=light`);
|
||||
await capture('d1-changes-phone-light-list', 390, 844);
|
||||
await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart');
|
||||
await capture('d1-changes-phone-light-diff', 390, 844);
|
||||
await clickExact('Raw patch');
|
||||
await capture('d1-changes-phone-light-raw', 390, 844);
|
||||
await clickExact('Rendered');
|
||||
// The 2x capture is last in its state: Chrome only re-lays out Flutter when
|
||||
// the CSS size changes, so scaling back down on the same page would capture a
|
||||
// half-size frame.
|
||||
await capture('d1-changes-phone-light-diff-2x', 390, 844, 2);
|
||||
|
||||
await navigate(`${origin}/?theme=light`);
|
||||
await capture('d1-changes-desktop-light-list', 1280, 800);
|
||||
await clickPrefix('Open diff for lib/features/changes/widgets/file_diff_viewer.dart');
|
||||
await capture('d1-changes-desktop-light-diff', 1280, 800);
|
||||
await clickExact('Close diff');
|
||||
|
||||
await navigate(`${origin}/?platform=cupertino&theme=light`);
|
||||
await capture('d1-changes-cupertino-light-list', 390, 844);
|
||||
await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart');
|
||||
await capture('d1-changes-cupertino-light-diff', 390, 844);
|
||||
await capture('d1-changes-cupertino-light-diff-2x', 390, 844, 2);
|
||||
|
||||
await navigate(`${origin}/?platform=cupertino`);
|
||||
const cupertinoLabels = await labels();
|
||||
if (!cupertinoLabels.some((label) => label.includes('Changes probe'))) {
|
||||
throw new Error('Cupertino fixture did not load');
|
||||
}
|
||||
await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart');
|
||||
await capture('d1-changes-cupertino-diff', 1280, 800);
|
||||
|
||||
evidence.checks.push({ check: 'Cupertino viewer opened', value: true });
|
||||
evidence.checks.push({ check: 'visit capture written', value: visitFile });
|
||||
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 });
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
// Standalone fixture entry for real-browser Changes evidence.
|
||||
//
|
||||
// Build and probe (from app/):
|
||||
// flutter build web --target tool/changes_probe_entry.dart --output build/probe-web
|
||||
// node tool/changes_probe.mjs --root build/probe-web --out DIR
|
||||
//
|
||||
// These are server-shaped fixtures for rendering only. They are not a live run
|
||||
// and never mutate a server.
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/changes/changes.dart';
|
||||
|
||||
const _multiHunkPatch =
|
||||
'--- "a/lib/features/changes/domain/unified_patch.dart"\n'
|
||||
'+++ "b/lib/features/changes/domain/unified_patch.dart"\n'
|
||||
'@@ -12,6 +12,7 @@\n'
|
||||
' class ParsedPatch {\n'
|
||||
' const ParsedPatch({\n'
|
||||
' required this.raw,\n'
|
||||
'+ required this.headerLines,\n'
|
||||
' required this.hunks,\n'
|
||||
' });\n'
|
||||
' \n'
|
||||
'@@ -48,5 +49,5 @@\n'
|
||||
'-PatchHunk? _parseHunkHeader(String line) {\n'
|
||||
'+_HunkStart? _parseHunkHeader(String line) {\n'
|
||||
" if (!line.startsWith('@@')) return null;\n"
|
||||
" final end = line.indexOf('@@', 2);\n"
|
||||
' if (end < 0) return null;\n'
|
||||
' final ranges = _tokenizeRanges(line.substring(2, end));\n';
|
||||
|
||||
const _addedPatch =
|
||||
'--- "/dev/null"\n'
|
||||
'+++ "b/lib/features/changes/widgets/file_diff_viewer.dart"\n'
|
||||
'@@ -0,0 +1,5 @@\n'
|
||||
'+class FileDiffViewer extends StatefulWidget {\n'
|
||||
'+ const FileDiffViewer({super.key, required this.file});\n'
|
||||
'+\n'
|
||||
'+ final FileChange file;\n'
|
||||
'+}\n';
|
||||
|
||||
const _deletedPatch =
|
||||
'--- "a/docs/legacy-notes.md"\n'
|
||||
'+++ "/dev/null"\n'
|
||||
'@@ -1,2 +0,0 @@\n'
|
||||
'-# Legacy notes\n'
|
||||
'-Removed with the viewer.\n';
|
||||
|
||||
const _truncatedPatch =
|
||||
'--- "a/logs/capture.log"\n'
|
||||
'+++ "b/logs/capture.log"\n'
|
||||
'@@ -1,2 +1,3 @@\n'
|
||||
'-capture started\n'
|
||||
'+capture started\n'
|
||||
'+and truncated mid-line';
|
||||
|
||||
List<JsonMap> probeSteps() => [
|
||||
{
|
||||
'sequence': 1,
|
||||
'stage': 'implementer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'partial',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'skipped': 2,
|
||||
'omitted': 0,
|
||||
'diagnostic':
|
||||
'Excluded protected, symlinked, oversized or unreadable files; this '
|
||||
'is not a complete workspace diff.',
|
||||
'files': [
|
||||
{
|
||||
'path': 'lib/features/changes/domain/unified_patch.dart',
|
||||
'kind': 'modified',
|
||||
'patch': _multiHunkPatch,
|
||||
'before_mode': '0644',
|
||||
'after_mode': '0644',
|
||||
},
|
||||
{
|
||||
'path': 'assets/pipelines-mark.png',
|
||||
'kind': 'modified',
|
||||
'binary': true,
|
||||
},
|
||||
{
|
||||
'path': 'scripts/capture.sh',
|
||||
'kind': 'modified',
|
||||
'before_mode': '0644',
|
||||
'after_mode': '0755',
|
||||
},
|
||||
{
|
||||
'path': 'docs/legacy-notes.md',
|
||||
'kind': 'deleted',
|
||||
'patch': _deletedPatch,
|
||||
'before_mode': '0644',
|
||||
},
|
||||
{
|
||||
'path': 'logs/capture.log',
|
||||
'kind': 'modified',
|
||||
'patch': _truncatedPatch,
|
||||
'truncated': true,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 2,
|
||||
'stage': 'reviewer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'skipped': 0,
|
||||
'omitted': 0,
|
||||
'diagnostic': '',
|
||||
'files': [
|
||||
{
|
||||
'path': 'lib/features/changes/widgets/file_diff_viewer.dart',
|
||||
'kind': 'added',
|
||||
'patch': _addedPatch,
|
||||
'after_mode': '0644',
|
||||
},
|
||||
{
|
||||
'path': 'lib/features/changes/domain/unified_patch.dart',
|
||||
'kind': 'modified',
|
||||
'patch': _multiHunkPatch,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 3,
|
||||
'stage': 'ui_reviewer',
|
||||
'status': 'completed',
|
||||
'file_changes': null,
|
||||
},
|
||||
{
|
||||
'sequence': 4,
|
||||
'stage': 'committer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'unavailable',
|
||||
'skipped': 0,
|
||||
'omitted': 0,
|
||||
'diagnostic':
|
||||
'Workspace snapshot unavailable; changes could not be compared.',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 5,
|
||||
'stage': 'verifier',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'skipped': 0,
|
||||
'omitted': 0,
|
||||
'diagnostic': '',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/// A compact fixture whose only purpose is visit numbering: the same stages
|
||||
/// appear more than once, one visit records an explicit `control.visit`, and
|
||||
/// every capture is empty so the sections stay on one phone screen.
|
||||
List<JsonMap> probeVisitSteps() => [
|
||||
{
|
||||
'sequence': 1,
|
||||
'stage': 'implementer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 2,
|
||||
'stage': 'reviewer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 3,
|
||||
'stage': 'implementer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 4,
|
||||
'stage': 'reviewer',
|
||||
'status': 'completed',
|
||||
'control': {'visit': 6},
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
void main() {
|
||||
final params = Uri.base.queryParameters;
|
||||
final cupertino = params['platform'] == 'cupertino';
|
||||
final brightness = params['theme'] == 'light'
|
||||
? Brightness.light
|
||||
: Brightness.dark;
|
||||
final steps = params['visits'] == '1' ? probeVisitSteps() : probeSteps();
|
||||
if (cupertino) {
|
||||
runApp(
|
||||
CupertinoApp(
|
||||
title: 'Changes probe',
|
||||
theme: CupertinoThemeData(brightness: brightness),
|
||||
home: _ProbeHome(cupertino: true, steps: steps),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
runApp(
|
||||
MaterialApp(
|
||||
title: 'Changes probe',
|
||||
theme: ThemeData(
|
||||
brightness: brightness,
|
||||
// Chrome on macOS reports a macOS default platform; the fixture
|
||||
// states Material explicitly so both control sets are capturable.
|
||||
platform: TargetPlatform.android,
|
||||
),
|
||||
home: _ProbeHome(cupertino: false, steps: steps),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProbeHome extends StatelessWidget {
|
||||
const _ProbeHome({required this.cupertino, required this.steps});
|
||||
|
||||
final bool cupertino;
|
||||
final List<JsonMap> steps;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final viewer = ChangesViewer(steps: steps);
|
||||
if (cupertino) {
|
||||
return CupertinoPageScaffold(
|
||||
navigationBar: const CupertinoNavigationBar(
|
||||
middle: Text('Changes probe'),
|
||||
),
|
||||
child: SafeArea(child: viewer),
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Changes probe')),
|
||||
body: viewer,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } 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 { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
||||
|
||||
const root = resolve(process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/web'));
|
||||
const variant = process.env.PROBE_VARIANT ?? 'material';
|
||||
const artifactDir = process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'chat-sessions-capture');
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' };
|
||||
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(), 'chat-sessions-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 < 100; 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.method?.includes('detached') || msg.method?.includes('crashed')) console.error('CDP event', JSON.stringify(msg));
|
||||
if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
|
||||
});
|
||||
const send = (method, params = {}, sessionId) => new Promise(resolve => {
|
||||
const callId = ++id; pending.set(callId, resolve);
|
||||
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);
|
||||
const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/` }, 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, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})");
|
||||
if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`);
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
await delay(2500);
|
||||
const clickLabel = async label => {
|
||||
const point = await evaluate(`(() => { const needle = ${JSON.stringify(label)}; const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === needle); if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`);
|
||||
if (!point) return false;
|
||||
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);
|
||||
return true;
|
||||
};
|
||||
const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)");
|
||||
if (!labels?.some(x => x.includes('New chat'))) throw new Error(`Chat fixture semantics unavailable: ${JSON.stringify(labels)}`);
|
||||
if (process.env.PROBE_DEBUG) console.log(JSON.stringify(labels));
|
||||
const capture = async (name, width, height) => {
|
||||
await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session);
|
||||
await delay(350);
|
||||
const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data;
|
||||
await (await import('node:fs/promises')).writeFile(`${artifactDir}/${variant}-${name}.png`, Buffer.from(data, 'base64'));
|
||||
};
|
||||
await capture('chat-sessions-desktop', 1280, 800);
|
||||
await capture('chat-sessions-phone', 390, 844);
|
||||
if (!await clickLabel('New chat')) throw new Error('Could not open create dialog');
|
||||
await delay(600);
|
||||
await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 195, y: 680, deltaY: 598 }, session);
|
||||
await delay(350);
|
||||
const changedBody = await evaluate('document.body.innerText');
|
||||
await capture('chat-sessions-create-dialog', 390, 844);
|
||||
if (!changedBody.includes('Server directory') || !changedBody.includes('Backend') || !changedBody.includes('New chats use the server default model.')) throw new Error(`Create dialog did not change rendered body to catalog controls: ${changedBody}`);
|
||||
if (!await clickLabel('Cancel')) throw new Error('Could not close create dialog');
|
||||
await delay(600);
|
||||
if (!await clickLabel('Chat actions for Open fixture')) throw new Error('Could not open row actions');
|
||||
await delay(600);
|
||||
const actionsBody = await evaluate('document.body.innerText');
|
||||
const actionLabels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || x.innerText || '').filter(Boolean)");
|
||||
await capture('chat-sessions-actions', 390, 844);
|
||||
if (!actionLabels.some(label => label.includes('Rename…'))) throw new Error(`Row actions unavailable: ${actionsBody} / ${actionLabels}`);
|
||||
console.log(JSON.stringify({ variant, labels, captures: [`${variant}-chat-sessions-desktop.png`, `${variant}-chat-sessions-phone.png`, `${variant}-chat-sessions-create-dialog.png`, `${variant}-chat-sessions-actions.png`], bodyChanged: true }, 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 });
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/session_screen.dart';
|
||||
|
||||
class _FixtureGateway implements ApiGateway {
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
if (type == 'chat_sessions') {
|
||||
return {
|
||||
'chat_sessions': [
|
||||
{
|
||||
'id': 'probe-open',
|
||||
'title': 'Open fixture',
|
||||
'directory': '/workspace/demo',
|
||||
'starred': true,
|
||||
},
|
||||
{
|
||||
'id': 'probe-closed',
|
||||
'title': 'Closed fixture',
|
||||
'directory': '/workspace/archive',
|
||||
'closed_at': '2026-01-01',
|
||||
},
|
||||
{
|
||||
'id': 'probe-stream',
|
||||
'title': 'Streaming fixture',
|
||||
'directory': '/workspace/demo',
|
||||
'running': true,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (type == 'chat_directories') {
|
||||
return {
|
||||
'chat_directories': ['/workspace/demo', '/workspace/archive'],
|
||||
};
|
||||
}
|
||||
if (type == 'chat_backends') {
|
||||
return {
|
||||
'chat_backends': ['opencode', 'codex'],
|
||||
};
|
||||
}
|
||||
if (type == 'chat_create') {
|
||||
return {
|
||||
'chat_session': {
|
||||
'id': 'probe-new',
|
||||
'title': 'New fixture',
|
||||
'directory': '/workspace/demo',
|
||||
},
|
||||
};
|
||||
}
|
||||
return {'chat_session': {}};
|
||||
}
|
||||
}
|
||||
|
||||
const _probeStyle = String.fromEnvironment(
|
||||
'CHAT_PROBE_STYLE',
|
||||
defaultValue: 'material',
|
||||
);
|
||||
|
||||
void main() {
|
||||
final home = ChatSessionsScreen(gateway: _FixtureGateway(), onOpen: (_) {});
|
||||
if (_probeStyle == 'cupertino') {
|
||||
runApp(CupertinoApp(home: home));
|
||||
return;
|
||||
}
|
||||
runApp(
|
||||
MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
home: home,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
|
||||
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
|
||||
import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart';
|
||||
import 'package:pipelines_app/features/graph/layout/layout_models.dart';
|
||||
import 'package:pipelines_app/features/graph/painting/graph_edge_layer.dart';
|
||||
import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart';
|
||||
import 'package:pipelines_app/features/graph/routing/route_models.dart';
|
||||
|
||||
/// Browser-capture fixture for `GraphEdgeLayer` only.
|
||||
///
|
||||
/// It composes caller-measured cards, the landed node layout, the landed
|
||||
/// orthogonal router and the edge layer. It is not wired into `main.dart`; the
|
||||
/// app shell, a real pipeline and any server stay untouched. Query parameter
|
||||
/// `theme=dark` selects the dark native theme and `case=same-rank` swaps in a
|
||||
/// two-node cycle that exercises same-rank edges between distinct nodes.
|
||||
void main() => runApp(const GraphEdgeProbeApp());
|
||||
|
||||
const Map<String, dynamic> _definition = <String, dynamic>{
|
||||
'stages': <dynamic>[
|
||||
<String, dynamic>{
|
||||
'key': 'ingest',
|
||||
'edges': <String, String?>{'success': 'build', 'error': '#failure'},
|
||||
},
|
||||
<String, dynamic>{
|
||||
'key': 'build',
|
||||
'edges': <String, String?>{'success': 'verify', 'retry': 'build'},
|
||||
},
|
||||
<String, dynamic>{
|
||||
'key': 'verify',
|
||||
'edges': <String, String?>{'success': '#success', 'rework': 'ingest'},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/// A two-node cycle: both nodes share one rank and both edges are same-rank
|
||||
/// without being self loops.
|
||||
const Map<String, dynamic> _sameRankDefinition = <String, dynamic>{
|
||||
'stages': <dynamic>[
|
||||
<String, dynamic>{
|
||||
'key': 'review',
|
||||
'edges': <String, String?>{'success': 'approve'},
|
||||
},
|
||||
<String, dynamic>{
|
||||
'key': 'approve',
|
||||
'edges': <String, String?>{'success': 'review'},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
class GraphEdgeProbeApp extends StatelessWidget {
|
||||
const GraphEdgeProbeApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dark = Uri.base.queryParameters['theme'] == 'dark';
|
||||
return MaterialApp(
|
||||
title: 'Graph edge layer probe',
|
||||
theme: ThemeData(
|
||||
brightness: dark ? Brightness.dark : Brightness.light,
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: Colors.indigo,
|
||||
brightness: dark ? Brightness.dark : Brightness.light,
|
||||
),
|
||||
),
|
||||
home: const _ProbePage(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProbePage extends StatelessWidget {
|
||||
const _ProbePage();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final scaler = MediaQuery.textScalerOf(context);
|
||||
final sameRankCase = Uri.base.queryParameters['case'] == 'same-rank';
|
||||
final definition = sameRankCase ? _sameRankDefinition : _definition;
|
||||
final nodes = graphNodes(definition);
|
||||
final edges = graphEdges(definition);
|
||||
final layout = layoutGraphNodes(
|
||||
nodes: nodes,
|
||||
edges: edges,
|
||||
extents: <String, NodeExtent>{
|
||||
for (final node in nodes)
|
||||
node.key: _nodeExtent(theme.textTheme.bodyMedium, node.label, scaler),
|
||||
},
|
||||
config: GraphLayoutConfig(columnGap: 120, rowGap: 24, padding: 16),
|
||||
);
|
||||
final routing = routeGraphEdges(
|
||||
layout: layout,
|
||||
edges: edges,
|
||||
labelExtents: <int, LabelExtent>{
|
||||
for (final edge in edges)
|
||||
edge.id: _labelExtent(theme.textTheme.labelSmall, edge.label, scaler),
|
||||
},
|
||||
config: RoutingConfig(
|
||||
nodeClearance: 8,
|
||||
laneSpacing: 28,
|
||||
corridorSpacing: 20,
|
||||
portSpacing: 12,
|
||||
labelGap: 4,
|
||||
boundsPadding: 8,
|
||||
),
|
||||
);
|
||||
final size = Size(routing.width, routing.height);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Graph edge layer')),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
sameRankCase
|
||||
? 'A two-node cycle in one rank: both arrows are same-rank '
|
||||
'and neither is a self loop.'
|
||||
: 'Measured cards and routed edges: same-rank cycle edges, '
|
||||
'forward edges to the terminals and a self loop, in the '
|
||||
'native outline color and stroke.',
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: SizedBox.fromSize(
|
||||
size: size,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
GraphEdgeLayer(
|
||||
routes: routing.routes,
|
||||
canvasSize: size,
|
||||
color: theme.colorScheme.outline,
|
||||
strokeWidth: theme.dividerTheme.thickness ?? 1,
|
||||
),
|
||||
for (final node in layout.nodes)
|
||||
Positioned(
|
||||
left: node.x,
|
||||
top: node.y,
|
||||
width: node.width,
|
||||
height: node.height,
|
||||
child: Card(
|
||||
margin: EdgeInsets.zero,
|
||||
child: Center(
|
||||
child: Text(
|
||||
nodeDisplayLabel(node.key),
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
NodeExtent _nodeExtent(TextStyle? style, String text, TextScaler scaler) {
|
||||
final painter = TextPainter(
|
||||
text: TextSpan(text: text, style: style),
|
||||
textDirection: TextDirection.ltr,
|
||||
textScaler: scaler,
|
||||
)..layout();
|
||||
return NodeExtent(width: painter.width + 32, height: painter.height + 20);
|
||||
}
|
||||
|
||||
LabelExtent _labelExtent(TextStyle? style, String text, TextScaler scaler) {
|
||||
final painter = TextPainter(
|
||||
text: TextSpan(text: text, style: style),
|
||||
textDirection: TextDirection.ltr,
|
||||
textScaler: scaler,
|
||||
)..layout();
|
||||
return LabelExtent(width: painter.width + 8, height: painter.height + 4);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
|
||||
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
|
||||
|
||||
const _longKey = 'implementer-with-an-unshortened-stage-label';
|
||||
const _oneXKey = 'narrow-one-x-stage-key-that-wraps';
|
||||
|
||||
/// Keys rendered in a 150 logical px box, with the text scale applied to them.
|
||||
const _scaled = {_longKey: 2.0, _oneXKey: 1.0};
|
||||
|
||||
const _nodes = [
|
||||
GraphNode(key: 'plan', terminal: false, stageIndex: 0),
|
||||
GraphNode(key: 'build', terminal: false, stageIndex: 1),
|
||||
GraphNode(key: _longKey, terminal: false, stageIndex: 2),
|
||||
GraphNode(key: _oneXKey, terminal: false, stageIndex: 3),
|
||||
GraphNode(key: '#success', terminal: true),
|
||||
GraphNode(key: '#failure', terminal: true),
|
||||
];
|
||||
|
||||
/// A fixture-only page: one measured node per definition identity, with the
|
||||
/// selected key reported so a browser click can prove the exact callback.
|
||||
class _Probe extends StatefulWidget {
|
||||
const _Probe({required this.cupertino});
|
||||
|
||||
final bool cupertino;
|
||||
|
||||
@override
|
||||
State<_Probe> createState() => _ProbeState();
|
||||
}
|
||||
|
||||
class _ProbeState extends State<_Probe> {
|
||||
String? _selected = 'build';
|
||||
|
||||
Widget _node(GraphNode node) {
|
||||
final child = GraphStageNode(
|
||||
node: node,
|
||||
recordedStatus: node.key == 'build' ? 'running' : null,
|
||||
selected: node.key == _selected,
|
||||
onSelected: (key) => setState(() => _selected = key),
|
||||
);
|
||||
final scale = _scaled[node.key];
|
||||
if (scale == null) return child;
|
||||
return MediaQuery(
|
||||
data: MediaQuery.of(
|
||||
context,
|
||||
).copyWith(textScaler: TextScaler.linear(scale)),
|
||||
child: SizedBox(width: 150, child: child),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final page = ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Text('Selected: ${_selected ?? 'none'}'),
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
children: [for (final node in _nodes) _node(node)],
|
||||
),
|
||||
],
|
||||
);
|
||||
return widget.cupertino
|
||||
? CupertinoPageScaffold(child: SafeArea(child: page))
|
||||
: Scaffold(body: SafeArea(child: page));
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
final cupertino = Uri.base.queryParameters['style'] == 'cupertino';
|
||||
runApp(
|
||||
cupertino
|
||||
? CupertinoApp(home: const _Probe(cupertino: true))
|
||||
: MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
// Stock dark theme so the forced `prefers-color-scheme` capture is
|
||||
// a real dark render rather than a duplicate light one.
|
||||
darkTheme: ThemeData(
|
||||
platform: TargetPlatform.android,
|
||||
brightness: Brightness.dark,
|
||||
),
|
||||
themeMode: ThemeMode.system,
|
||||
home: const _Probe(cupertino: false),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// Browser acceptance for the isolated GraphStageNode fixture.
|
||||
//
|
||||
// Serves the probe build (`flutter build web -t tool/graph_node_probe.dart`) on
|
||||
// an OS-assigned loopback port, drives a real headless Chrome, asserts labels,
|
||||
// selection identity and the selected ARIA state, and writes captures.
|
||||
//
|
||||
// PROBE_VARIANT=material|cupertino PROBE_SCHEME=dark|light \
|
||||
// OPENCODE_ARTIFACT_DIR=<dir> node tool/graph_node_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/web'));
|
||||
const variant = process.env.PROBE_VARIANT ?? 'material';
|
||||
const scheme = process.env.PROBE_SCHEME ?? 'dark';
|
||||
const artifactDir = process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'graph-node-capture');
|
||||
const prefix = scheme === 'light' ? 'light-' : '';
|
||||
const longKey = 'implementer-with-an-unshortened-stage-label';
|
||||
const oneXKey = 'narrow-one-x-stage-key-that-wraps';
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' };
|
||||
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(), 'graph-node-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 < 100; 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(resolve => {
|
||||
const callId = ++id; pending.set(callId, resolve);
|
||||
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);
|
||||
const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/?style=${variant}` }, 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'), role:x.getAttribute('role')}))");
|
||||
const nodeAt = label => `[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label')||x.innerText||'').trim() === ${JSON.stringify(label)})`;
|
||||
const initial = await semantics();
|
||||
const labels = initial.map(x => x.label);
|
||||
for (const needle of ['Selected: build', 'plan', 'build', 'running', 'Success', 'Failure']) {
|
||||
if (!labels.some(x => x.includes(needle))) throw new Error(`Missing semantics ${needle}: ${JSON.stringify(labels)}`);
|
||||
}
|
||||
// Flutter web maps Semantics(selected:) to aria-current, not aria-selected.
|
||||
const current = initial.find(x => x.selected === 'true');
|
||||
// The fixture's selected node carries its recorded status, so its accessible
|
||||
// label is 'build\nrunning'.
|
||||
if (!current?.label.startsWith('build')) throw new Error(`Selected node is not announced: ${JSON.stringify(initial)}`);
|
||||
if (process.env.PROBE_DEBUG) console.log(JSON.stringify(initial, null, 2));
|
||||
const clickLabel = async label => {
|
||||
const point = await evaluate(`(() => { const e=${nodeAt(label)}; if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`);
|
||||
if (!point) return false;
|
||||
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);
|
||||
return true;
|
||||
};
|
||||
const nodeRect = async label => evaluate(`(() => { const e=${nodeAt(label)}; if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()`);
|
||||
const capture = async (name, width, height, scale = 1) => {
|
||||
await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session);
|
||||
await delay(2500);
|
||||
const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data;
|
||||
await writeFile(`${artifactDir}/${prefix}${variant}-${name}.png`, Buffer.from(data, 'base64'));
|
||||
};
|
||||
await capture('nodes-phone', 390, 844);
|
||||
await capture('nodes-desktop', 1280, 800);
|
||||
// Enlarged crops of the wrapped cases: the reviewed Material defect was
|
||||
// glyph ink crossing the painted boundary at 2x.
|
||||
const crops = {};
|
||||
for (const [name, key] of [['long-2x', longKey], ['long-1x', oneXKey]]) {
|
||||
const rect = await nodeRect(key);
|
||||
if (!rect) throw new Error(`Missing node ${key}`);
|
||||
crops[name] = rect;
|
||||
const data = (await send('Page.captureScreenshot', {
|
||||
format: 'png',
|
||||
clip: { x: rect.x - 8, y: rect.y - 8, width: rect.width + 16, height: rect.height + 16, scale: 2 },
|
||||
captureBeyondViewport: false,
|
||||
}, session)).result.data;
|
||||
await writeFile(`${artifactDir}/${prefix}${variant}-${name}-crop.png`, Buffer.from(data, 'base64'));
|
||||
}
|
||||
if (!await clickLabel('plan')) throw new Error('Could not click plan node');
|
||||
await delay(600);
|
||||
const afterPlan = await evaluate('document.body.innerText');
|
||||
if (!afterPlan.includes('Selected: plan')) throw new Error(`plan callback did not carry its key: ${afterPlan}`);
|
||||
const planCurrent = (await semantics()).find(x => x.selected === 'true');
|
||||
if (planCurrent?.label !== 'plan') throw new Error(`plan is not announced selected: ${JSON.stringify(planCurrent)}`);
|
||||
await capture('nodes-selected-plan', 390, 844);
|
||||
if (!await clickLabel('Success')) throw new Error('Could not click Success terminal');
|
||||
await delay(600);
|
||||
const afterTerminal = await evaluate('document.body.innerText');
|
||||
if (!afterTerminal.includes('Selected: #success')) throw new Error(`terminal callback did not carry its key: ${afterTerminal}`);
|
||||
await capture('nodes-selected-terminal', 390, 844);
|
||||
console.log(JSON.stringify({
|
||||
variant, scheme, labels, crops,
|
||||
captures: [`${prefix}${variant}-nodes-phone.png`, `${prefix}${variant}-nodes-desktop.png`,
|
||||
`${prefix}${variant}-nodes-selected-plan.png`, `${prefix}${variant}-nodes-selected-terminal.png`,
|
||||
`${prefix}${variant}-long-2x-crop.png`, `${prefix}${variant}-long-1x-crop.png`],
|
||||
}, 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 });
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# Flutter web preview
|
||||
|
||||
Build and run from `app/`:
|
||||
|
||||
```sh
|
||||
/Users/alan/development/flutter/bin/flutter build web
|
||||
UPSTREAM=http://127.0.0.1:8095 node tool/preview/server.mjs --port 8096
|
||||
```
|
||||
|
||||
The preview binds to loopback by default and authenticates static requests by
|
||||
checking the upstream authenticated web proxy with the browser cookie. Unauthenticated
|
||||
HTML navigation goes to the proxy's `/login?next=...`; unauthenticated assets and
|
||||
WebSocket upgrades are refused. Login, logout and artifacts are streamed to the
|
||||
proxy without decoding compressed response bodies. `/connect` accepts only a
|
||||
same-origin browser Origin, checks the cookie, then maps Origin and Host to the
|
||||
configured upstream origin before upgrading. HTTP and HTTPS upstreams are
|
||||
supported using Node's normal TLS certificate verification. Set `UPSTREAM` to
|
||||
the authenticated proxy, never the raw control server. The root path and files
|
||||
must exist locally, and only GET, HEAD, and POST are supported. Tests use
|
||||
isolated loopback fixtures and port 0.
|
||||
|
||||
The persistent preview API is `start({ root, upstream, host, port })` from
|
||||
`tool/preview/server.mjs`; it resolves to `{ server, port, close }`. Call
|
||||
`close()` to stop accepting requests and close tracked upgraded sockets.
|
||||
@@ -0,0 +1,202 @@
|
||||
import { createServer, request as httpRequest } from 'node:http';
|
||||
import { request as httpsRequest } from 'node:https';
|
||||
import { realpath, stat, readFile } from 'node:fs/promises';
|
||||
import { extname, resolve, sep } from 'node:path';
|
||||
import net from 'node:net';
|
||||
import tls from 'node:tls';
|
||||
|
||||
const mime = {
|
||||
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8', '.wasm': 'application/wasm',
|
||||
'.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf',
|
||||
'.json': 'application/json', '.css': 'text/css; charset=utf-8',
|
||||
'.png': 'image/png', '.svg': 'image/svg+xml',
|
||||
};
|
||||
const noCache = { 'Cache-Control': 'no-store' };
|
||||
const timeoutMs = 5000;
|
||||
|
||||
function reply(res, status, body = '') {
|
||||
if (res.destroyed) return;
|
||||
if (!res.headersSent) res.writeHead(status, { ...noCache, 'Content-Type': 'text/plain; charset=utf-8' });
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
function inside(base, path) {
|
||||
return path === base || path.startsWith(base + sep);
|
||||
}
|
||||
|
||||
async function staticFile(base, pathname, req, res) {
|
||||
let file = resolve(base, `.${pathname}`);
|
||||
if (!inside(base, file)) return reply(res, 403);
|
||||
try {
|
||||
let real = await realpath(file);
|
||||
if (!inside(base, real)) return reply(res, 403);
|
||||
if ((await stat(real)).isDirectory()) {
|
||||
real = await realpath(resolve(real, 'index.html'));
|
||||
if (!inside(base, real)) return reply(res, 403);
|
||||
}
|
||||
file = real;
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') return reply(res, 403);
|
||||
if (extname(pathname)) return reply(res, 404, 'Not found');
|
||||
try {
|
||||
file = await realpath(resolve(base, 'index.html'));
|
||||
if (!inside(base, file)) return reply(res, 403);
|
||||
} catch { return reply(res, 404, 'Not found'); }
|
||||
}
|
||||
try {
|
||||
const body = await readFile(file);
|
||||
res.writeHead(200, { ...noCache, 'Content-Type': mime[extname(file)] ?? 'application/octet-stream' });
|
||||
res.end(req.method === 'HEAD' ? undefined : body);
|
||||
} catch { reply(res, 404, 'Not found'); }
|
||||
}
|
||||
|
||||
function upstreamRequest(target, options, callback) {
|
||||
return (target.protocol === 'https:' ? httpsRequest : httpRequest)(
|
||||
{ protocol: target.protocol, hostname: target.hostname, port: target.port || undefined,
|
||||
...options, timeout: timeoutMs }, callback,
|
||||
);
|
||||
}
|
||||
|
||||
function proxy(req, res, target) {
|
||||
const url = new URL(req.url, target);
|
||||
const headers = { ...req.headers, host: target.host };
|
||||
delete headers.connection;
|
||||
const upstream = upstreamRequest(target, { method: req.method, path: `${url.pathname}${url.search}`, headers }, (replyFromUpstream) => {
|
||||
const forwarded = { ...replyFromUpstream.headers, ...noCache };
|
||||
res.writeHead(replyFromUpstream.statusCode ?? 502, forwarded);
|
||||
replyFromUpstream.on('error', () => res.destroy());
|
||||
replyFromUpstream.pipe(res);
|
||||
});
|
||||
upstream.setTimeout(timeoutMs, () => upstream.destroy(new Error('upstream timeout')));
|
||||
upstream.on('error', () => reply(res, 502, 'Upstream unavailable'));
|
||||
req.on('aborted', () => upstream.destroy());
|
||||
res.on('close', () => { if (!res.writableEnded) upstream.destroy(); });
|
||||
if (req.method === 'GET' || req.method === 'HEAD') { req.resume(); upstream.end(); }
|
||||
else req.pipe(upstream);
|
||||
}
|
||||
|
||||
function authCheck(req, target, callback) {
|
||||
let completed = false;
|
||||
const finish = (result) => {
|
||||
if (completed) return;
|
||||
completed = true;
|
||||
req.removeListener('aborted', abort);
|
||||
req.socket.removeListener('close', abort);
|
||||
callback(result);
|
||||
};
|
||||
const abort = () => check.destroy();
|
||||
const check = upstreamRequest(target, { method: 'GET', path: '/', headers: {
|
||||
cookie: req.headers.cookie ?? '', accept: 'text/html', 'accept-encoding': 'identity',
|
||||
} }, (response) => {
|
||||
response.resume();
|
||||
finish(response.statusCode === 200);
|
||||
});
|
||||
check.setTimeout(timeoutMs, () => check.destroy(new Error('authentication check timeout')));
|
||||
check.on('error', () => finish(null));
|
||||
req.once('aborted', abort);
|
||||
req.socket.once('close', abort);
|
||||
check.end();
|
||||
}
|
||||
|
||||
function reject(socket, status, phrase = 'Forbidden') {
|
||||
if (!socket.destroyed) socket.end(`HTTP/1.1 ${status} ${phrase}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
||||
}
|
||||
|
||||
export async function start({ root = resolve('build/web'), upstream = 'http://127.0.0.1:8095', host = '127.0.0.1', port = 8096 } = {}) {
|
||||
const base = await realpath(root);
|
||||
const target = new URL(upstream);
|
||||
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) throw new Error('UPSTREAM must be credential-free HTTP(S)');
|
||||
const sockets = new Set();
|
||||
const upgrades = new Set();
|
||||
let closing = false;
|
||||
let closePromise;
|
||||
const server = createServer((req, res) => {
|
||||
let url;
|
||||
try {
|
||||
url = new URL(req.url, 'http://preview');
|
||||
if (!req.url.startsWith('/') || req.url.startsWith('//')) throw new Error('invalid path');
|
||||
decodeURIComponent(url.pathname);
|
||||
} catch { return reply(res, 400, 'Bad request'); }
|
||||
const pathname = decodeURIComponent(url.pathname);
|
||||
if (pathname.startsWith('//')) return reply(res, 400, 'Bad request');
|
||||
if (!['GET', 'HEAD', 'POST'].includes(req.method)) {
|
||||
res.setHeader('Allow', 'GET, HEAD, POST'); return reply(res, 405);
|
||||
}
|
||||
if (pathname === '/login' || pathname === '/logout' || pathname.startsWith('/artifacts/')) return proxy(req, res, target);
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') return reply(res, 405);
|
||||
authCheck(req, target, (authenticated) => {
|
||||
if (res.destroyed) return;
|
||||
if (authenticated === null) return reply(res, 502, 'Authentication upstream unavailable');
|
||||
if (!authenticated) {
|
||||
if (req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html') && !pathname.startsWith('/assets/')) {
|
||||
res.writeHead(302, { ...noCache, Location: `/login?next=${encodeURIComponent(`${url.pathname}${url.search}`)}` });
|
||||
return res.end();
|
||||
}
|
||||
return reply(res, 401, 'Authentication required');
|
||||
}
|
||||
staticFile(base, pathname, req, res);
|
||||
});
|
||||
});
|
||||
server.on('connection', (socket) => {
|
||||
sockets.add(socket);
|
||||
socket.on('close', () => sockets.delete(socket));
|
||||
});
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
upgrades.add(socket);
|
||||
socket.on('close', () => upgrades.delete(socket));
|
||||
let origin;
|
||||
try {
|
||||
if (req.url.split('?')[0] !== '/connect' || !req.headers.host || !req.headers.origin || !req.url.startsWith('/')) throw new Error();
|
||||
origin = new URL(req.headers.origin);
|
||||
if (!['http:', 'https:'].includes(origin.protocol) || origin.host.toLowerCase() !== req.headers.host.toLowerCase()) throw new Error();
|
||||
} catch { return reject(socket, 403); }
|
||||
authCheck(req, target, (authenticated) => {
|
||||
if (closing || socket.destroyed) return;
|
||||
if (authenticated === null) return reject(socket, 502, 'Bad Gateway');
|
||||
if (!authenticated) return reject(socket, 401, 'Unauthorized');
|
||||
const connect = target.protocol === 'https:' ? tls.connect : net.connect;
|
||||
const upstreamSocket = connect({ host: target.hostname, port: Number(target.port || (target.protocol === 'https:' ? 443 : 80)), ...(target.protocol === 'https:' ? { servername: target.hostname } : {}) });
|
||||
upgrades.add(upstreamSocket);
|
||||
upstreamSocket.on('close', () => upgrades.delete(upstreamSocket));
|
||||
upstreamSocket.setTimeout(timeoutMs, () => upstreamSocket.destroy(new Error('upgrade timeout')));
|
||||
// Bound establishment only. A healthy, idle chat socket stays connected.
|
||||
upstreamSocket.once('data', () => upstreamSocket.setTimeout(0));
|
||||
upstreamSocket.once(target.protocol === 'https:' ? 'secureConnect' : 'connect', () => {
|
||||
const headers = { ...req.headers, host: target.host, origin: target.origin };
|
||||
const lines = Object.entries(headers).filter(([, value]) => value != null)
|
||||
.map(([key, value]) => `${key}: ${Array.isArray(value) ? value.join(', ') : value}`).join('\r\n');
|
||||
upstreamSocket.write(`GET ${req.url} HTTP/1.1\r\n${lines}\r\n\r\n`);
|
||||
if (head.length) upstreamSocket.write(head);
|
||||
upstreamSocket.pipe(socket);
|
||||
socket.pipe(upstreamSocket);
|
||||
});
|
||||
upstreamSocket.on('error', () => socket.destroy());
|
||||
socket.on('error', () => upstreamSocket.destroy());
|
||||
socket.on('close', () => upstreamSocket.destroy());
|
||||
});
|
||||
});
|
||||
await new Promise((resolveListen, rejectListen) => {
|
||||
server.once('error', rejectListen);
|
||||
server.listen(port, host, resolveListen);
|
||||
});
|
||||
return {
|
||||
server, port: server.address().port,
|
||||
close: () => closePromise ??= new Promise((resolveClose, rejectClose) => {
|
||||
closing = true;
|
||||
for (const socket of upgrades) socket.destroy();
|
||||
server.close((error) => error ? rejectClose(error) : resolveClose());
|
||||
for (const socket of sockets) socket.destroy();
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
|
||||
const args = Object.fromEntries(process.argv.slice(2).reduce((result, value, index, all) => {
|
||||
if (value.startsWith('--')) result.push([value.slice(2), all[index + 1]]);
|
||||
return result;
|
||||
}, []));
|
||||
start({ root: args.root ?? 'build/web', upstream: process.env.UPSTREAM ?? args.upstream ?? 'http://127.0.0.1:8095', host: args.host ?? '127.0.0.1', port: Number(args.port ?? 8096) })
|
||||
.then((preview) => console.log(`preview http://${args.host ?? '127.0.0.1'}:${preview.port}`))
|
||||
.catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
import { spawn, execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
|
||||
import { once } from 'node:events';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
import { startFixture } from './runs_probe_server.mjs';
|
||||
|
||||
// Browser acceptance for the Runs destination.
|
||||
//
|
||||
// Build one of the bundles first, then run from app/:
|
||||
// flutter build web
|
||||
// flutter build web --target=tool/runs_probe_entry.dart -o build/probe_web
|
||||
// OPENCODE_ARTIFACT_DIR=<dir> node tool/runs_probe.mjs build/web
|
||||
//
|
||||
// Requires Google Chrome and Tesseract (OCR assertions cover canvas-rendered
|
||||
// selectable text that Flutter web does not expose through semantics).
|
||||
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 root = resolve(process.argv[2] ?? 'build/probe_web');
|
||||
const fixture = await startFixture({ root });
|
||||
|
||||
const html = await fetch(`${fixture.url}/`);
|
||||
const mime = html.headers.get('content-type') ?? '';
|
||||
if (html.status !== 200 || !mime.startsWith('text/html')) {
|
||||
throw new Error(`Fixture index must be HTML: ${html.status} ${mime}`);
|
||||
}
|
||||
await html.text();
|
||||
|
||||
const profile = await mkdtemp(join(tmpdir(), 'i1-runs-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; });
|
||||
|
||||
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?.includes('detached') || message.method?.includes('crashed')) {
|
||||
console.error('CDP event', JSON.stringify(message));
|
||||
}
|
||||
if (message.method === 'Runtime.exceptionThrown') {
|
||||
console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails));
|
||||
}
|
||||
if (message.method === 'Log.entryAdded') {
|
||||
console.error('PAGE LOG', JSON.stringify(message.params?.entry));
|
||||
}
|
||||
if (message.method === 'Runtime.consoleAPICalled') {
|
||||
console.error('PAGE CONSOLE', JSON.stringify(message.params));
|
||||
}
|
||||
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('Log.enable', {}, 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 enableSemantics = async () => {
|
||||
await waitFor(
|
||||
() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"),
|
||||
'Flutter semantics placeholder',
|
||||
);
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
await delay(600);
|
||||
};
|
||||
|
||||
const navigation = await send('Page.navigate', { url: `${fixture.url}/` }, session);
|
||||
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
|
||||
await enableSemantics();
|
||||
await waitFor(
|
||||
async () => (await evaluate('location.pathname')) === '/pipelines',
|
||||
'boot route correction to /pipelines',
|
||||
);
|
||||
|
||||
const semanticText = () => evaluate(`(() => {
|
||||
const chunks = [];
|
||||
for (const el of document.querySelectorAll('flt-semantics')) {
|
||||
const label = el.getAttribute('aria-label');
|
||||
if (label) chunks.push(label);
|
||||
const value = el.getAttribute('aria-valuetext');
|
||||
if (value) chunks.push(value);
|
||||
if (el.value) chunks.push(String(el.value));
|
||||
if (!el.children.length && el.innerText) chunks.push(el.innerText);
|
||||
}
|
||||
for (const el of document.querySelectorAll('input, textarea')) {
|
||||
const label = el.getAttribute('aria-label');
|
||||
if (label) chunks.push(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 assertBody = async (text) => {
|
||||
try {
|
||||
await waitFor(
|
||||
async () => (await semanticText()).includes(text),
|
||||
`body to contain ${JSON.stringify(text)}`,
|
||||
);
|
||||
} catch (error) {
|
||||
const textNow = await semanticText();
|
||||
let extra = '';
|
||||
if (process.env.PROBE_DEBUG) {
|
||||
extra = `\nNodes: ${JSON.stringify(await evaluate(`[...document.querySelectorAll('flt-semantics, input, textarea')]
|
||||
.map((el) => ({ tag: el.tagName, role: el.getAttribute('role'), label: el.getAttribute('aria-label'), value: el.getAttribute('aria-valuetext') ?? el.value, text: el.innerText }))
|
||||
.filter((item) => item.label || item.value || item.text)`))}`;
|
||||
}
|
||||
throw new Error(`${error.message}\nBody now:\n${textNow.slice(0, 3000)}${extra}`);
|
||||
}
|
||||
};
|
||||
|
||||
const clickText = async (text, { contains = false } = {}) => {
|
||||
const clicked = await evaluate(`(() => {
|
||||
const wanted = ${JSON.stringify(text)};
|
||||
const candidates = [...document.querySelectorAll('flt-semantics')].filter((el) => {
|
||||
const label = (el.getAttribute('aria-label') || el.innerText || '').trim();
|
||||
return label === wanted || (${contains} && label.includes(wanted));
|
||||
});
|
||||
const interactive = candidates.find((el) =>
|
||||
['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')),
|
||||
);
|
||||
const target = interactive ?? candidates[0];
|
||||
if (!target) return false;
|
||||
target.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!clicked) {
|
||||
const labels = await evaluate(`[...document.querySelectorAll('flt-semantics')]
|
||||
.map((el) => (el.getAttribute('aria-label') || '').trim()).filter(Boolean)`);
|
||||
throw new Error(`Could not click ${JSON.stringify(text)}. Labels: ${JSON.stringify(labels)}`);
|
||||
}
|
||||
await delay(300);
|
||||
};
|
||||
|
||||
const capture = async (name) => {
|
||||
const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data;
|
||||
const path = join(output, `${name}.png`);
|
||||
await writeFile(path, Buffer.from(data, 'base64'));
|
||||
return path;
|
||||
};
|
||||
|
||||
const ocr = async (path) => {
|
||||
const { stdout } = await promisify(execFile)('tesseract', [path, 'stdout']);
|
||||
return stdout;
|
||||
};
|
||||
|
||||
const assertOcr = async (path, text) => {
|
||||
const read = await ocr(path);
|
||||
if (!read.toLowerCase().includes(text.toLowerCase())) {
|
||||
throw new Error(`OCR of ${path} lacks ${JSON.stringify(text)}:\n${read.slice(0, 3000)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const wheel = (deltaY) => send('Input.dispatchMouseEvent', {
|
||||
type: 'mouseWheel',
|
||||
x: 195,
|
||||
y: 500,
|
||||
deltaX: 0,
|
||||
deltaY,
|
||||
}, session);
|
||||
|
||||
const scrollUntil = async (text) => {
|
||||
for (let attempt = 0; attempt < 20; attempt++) {
|
||||
if ((await semanticText()).includes(text)) return;
|
||||
await wheel(400);
|
||||
await delay(180);
|
||||
}
|
||||
throw new Error(`Could not scroll to ${JSON.stringify(text)}`);
|
||||
};
|
||||
|
||||
const setSize = async (width, height) => {
|
||||
await send('Emulation.setDeviceMetricsOverride', {
|
||||
width,
|
||||
height,
|
||||
deviceScaleFactor: 1,
|
||||
mobile: width < 600,
|
||||
}, session);
|
||||
await delay(500);
|
||||
};
|
||||
|
||||
await setSize(390, 844);
|
||||
await clickText('Runs');
|
||||
if ((await evaluate('location.pathname')) !== '/runs') {
|
||||
throw new Error(`Runs tab did not update the URL: ${await evaluate('location.pathname')}`);
|
||||
}
|
||||
await assertBody('Fixture live run');
|
||||
await assertBody('Fixture pending run');
|
||||
await assertBody('Fixture failing run');
|
||||
const captures = [await capture('i1-runs-phone-list')];
|
||||
await assertOcr(captures[0], 'Fixture live run');
|
||||
|
||||
await setSize(1280, 800);
|
||||
await assertBody('Fixture live run');
|
||||
captures.push(await capture('i1-runs-desktop-list'));
|
||||
await assertOcr(captures[1], 'Fixture live run');
|
||||
await setSize(390, 844);
|
||||
|
||||
const live = await fetch(`${fixture.url}/fixture/live`, { method: 'POST' });
|
||||
if (!live.ok) throw new Error(`Fixture live trigger failed: ${live.status}`);
|
||||
await assertBody('succeeded');
|
||||
captures.push(await capture('i1-runs-phone-list-live'));
|
||||
await assertOcr(captures[2], 'succeeded');
|
||||
|
||||
await clickText('Fixture pending run', { contains: true });
|
||||
await assertBody('Loading run details…');
|
||||
await assertBody('Back to list');
|
||||
captures.push(await capture('i1-runs-phone-pending'));
|
||||
await assertOcr(captures[3], 'Loading run details');
|
||||
await clickText('Back to list', { contains: true });
|
||||
await assertBody('Fixture failing run');
|
||||
|
||||
await clickText('Fixture failing run', { contains: true });
|
||||
await assertBody('Fixture detail failure: run 3 is unavailable');
|
||||
await assertBody('Back to list');
|
||||
captures.push(await capture('i1-runs-phone-error'));
|
||||
await assertOcr(captures[4], 'run 3 is unavailable');
|
||||
await clickText('Back to list', { contains: true });
|
||||
await assertBody('Fixture live run');
|
||||
|
||||
await clickText('Fixture live run', { contains: true });
|
||||
if ((await evaluate('location.pathname')) !== '/runs/1') {
|
||||
throw new Error(`Run selection did not update the URL: ${await evaluate('location.pathname')}`);
|
||||
}
|
||||
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');
|
||||
|
||||
await setSize(1280, 800);
|
||||
await assertBody('Original prompt');
|
||||
captures.push(await capture('i1-runs-desktop-detail'));
|
||||
await assertOcr(captures[6], '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');
|
||||
|
||||
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');
|
||||
|
||||
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');
|
||||
|
||||
// Browser Back/Forward move between the in-app routes, not out of the app.
|
||||
const path = () => evaluate('location.pathname');
|
||||
await evaluate('history.back()');
|
||||
await waitFor(
|
||||
async () => (await path()) === '/runs',
|
||||
'browser Back to /runs',
|
||||
);
|
||||
await waitFor(
|
||||
async () => (await semanticText()).includes('Fixture live run'),
|
||||
'browser Back to the runs list',
|
||||
);
|
||||
await waitFor(
|
||||
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');
|
||||
|
||||
await evaluate('history.forward()');
|
||||
await waitFor(
|
||||
async () => (await path()) === '/runs/1' && (await semanticText()).includes('Original prompt'),
|
||||
'browser Forward to /runs/1',
|
||||
);
|
||||
captures.push(await capture('i1-runs-phone-browser-forward-detail'));
|
||||
|
||||
// A direct /runs/1 load is a real deep link: the detail opens and the URL stays.
|
||||
await send('Page.navigate', { url: `${fixture.url}/runs/1` }, session);
|
||||
await enableSemantics();
|
||||
await assertBody('Original prompt');
|
||||
if ((await path()) !== '/runs/1') throw new Error(`Deep link moved to ${await path()}`);
|
||||
captures.push(await capture('i1-deeplink-run-1-phone'));
|
||||
|
||||
// A drop keeps the open detail, reports reconnecting rather than unavailable,
|
||||
// and has no raw transport exception anywhere on the page.
|
||||
const beforeDrop = await (await fetch(`${fixture.url}/fixture/state`)).json();
|
||||
const refused = await fetch(`${fixture.url}/fixture/refuse`, { method: 'POST' });
|
||||
if (!refused.ok) throw new Error(`Fixture refuse failed: ${refused.status}`);
|
||||
await assertBody('Reconnecting to Pipelines…');
|
||||
const duringDrop = await semanticText();
|
||||
for (const raw of ['WebSocketException', 'WebSocketChannelException', 'Failed to connect']) {
|
||||
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');
|
||||
|
||||
// Accepting again plus Retry restores the same detail without a remount.
|
||||
const accepted = await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' });
|
||||
if (!accepted.ok) throw new Error(`Fixture accept failed: ${accepted.status}`);
|
||||
await clickText('Retry');
|
||||
await waitFor(
|
||||
async () =>
|
||||
!(await semanticText()).includes('Reconnecting to Pipelines…') &&
|
||||
(await semanticText()).includes('Original prompt'),
|
||||
'detail restored after reconnect',
|
||||
);
|
||||
if ((await path()) !== '/runs/1') throw new Error(`Reconnect moved the URL to ${await path()}`);
|
||||
captures.push(await capture('i1-reconnect-detail-restored-phone'));
|
||||
|
||||
// A first connection while the server refuses upgrades is friendly: the gate
|
||||
// never prints the transport exception and does not flicker to "connecting".
|
||||
await fetch(`${fixture.url}/fixture/refuse`, { method: 'POST' });
|
||||
await send('Page.navigate', { url: `${fixture.url}/runs` }, session);
|
||||
await enableSemantics();
|
||||
await assertBody('Pipelines server unavailable');
|
||||
const gate = await semanticText();
|
||||
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'));
|
||||
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 fetch(`${fixture.url}/fixture/accept`, { method: 'POST' });
|
||||
await clickText('Retry');
|
||||
await assertBody('Fixture live run');
|
||||
captures.push(await capture('i1-gate-recovered-list-phone'));
|
||||
|
||||
await clickText('Settings');
|
||||
await assertBody('Server URL');
|
||||
await assertBody('Fixture settings build');
|
||||
if ((await path()) !== '/settings') throw new Error('Settings did not update route');
|
||||
captures.push(await capture('settings-cupertino-registered-phone'));
|
||||
|
||||
// Material host: the same deep link and route must render standard Material
|
||||
// controls (the Cupertino host was selected by the macOS browser above).
|
||||
await send(
|
||||
'Emulation.setUserAgentOverride',
|
||||
{
|
||||
userAgent:
|
||||
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' +
|
||||
'(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
|
||||
platform: 'Linux x86_64',
|
||||
},
|
||||
session,
|
||||
);
|
||||
await send('Page.navigate', { url: `${fixture.url}/runs/1` }, session);
|
||||
await enableSemantics();
|
||||
await assertBody('Original prompt');
|
||||
await assertBody('Back to list');
|
||||
if ((await path()) !== '/runs/1') {
|
||||
throw new Error(`Material deep link moved to ${await path()}`);
|
||||
}
|
||||
captures.push(await capture('i1-material-deeplink-run-1-phone'));
|
||||
|
||||
const beforeSettings = await (await fetch(`${fixture.url}/fixture/state`)).json();
|
||||
await clickText('Settings');
|
||||
await assertBody('Server URL');
|
||||
await assertBody('Fixture settings build');
|
||||
const afterSettings = await (await fetch(`${fixture.url}/fixture/state`)).json();
|
||||
if (beforeSettings.subscribed !== afterSettings.subscribed || afterSettings.connections !== 1) {
|
||||
throw new Error('Settings opened another connection instead of sharing the app socket');
|
||||
}
|
||||
captures.push(await capture('settings-material-registered-phone'));
|
||||
|
||||
const fixtureState = await (await fetch(`${fixture.url}/fixture/state`)).json();
|
||||
if (fixtureState.subscribed < 2) throw new Error(`App never resubscribed: ${JSON.stringify(fixtureState)}`);
|
||||
if (fixtureState.listRuns < 2) throw new Error(`App never reloaded: ${JSON.stringify(fixtureState)}`);
|
||||
if (fixtureState.getRun < 2) throw new Error(`Detail was not rehydrated: ${JSON.stringify(fixtureState)}`);
|
||||
if (fixtureState.dropped < 1) throw new Error(`Fixture never dropped: ${JSON.stringify(fixtureState)}`);
|
||||
console.log(JSON.stringify({
|
||||
ok: true,
|
||||
fixture: fixture.url,
|
||||
subscribed: fixtureState.subscribed,
|
||||
listRuns: fixtureState.listRuns,
|
||||
getRun: fixtureState.getRun,
|
||||
dropped: fixtureState.dropped,
|
||||
live: fixtureState.live,
|
||||
captures,
|
||||
}, null, 2));
|
||||
} finally {
|
||||
ws?.close();
|
||||
chrome.kill('SIGTERM');
|
||||
await Promise.race([once(chrome, 'exit'), delay(3000)]);
|
||||
await fixture.close();
|
||||
await rm(profile, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
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}`);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import 'package:pipelines_app/application/bootstrap.dart';
|
||||
|
||||
/// Browser acceptance entrypoint.
|
||||
///
|
||||
/// This is intentionally the same composition as `lib/main.dart`; the
|
||||
/// deterministic list/detail/error/live behavior comes from the isolated
|
||||
/// websocket fixture that serves this bundle, not from app-side fake data.
|
||||
void main() => runPipelinesApp();
|
||||
@@ -0,0 +1,418 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile, realpath, stat } from 'node:fs/promises';
|
||||
import { extname, join, resolve, sep } from 'node:path';
|
||||
import { once } from 'node:events';
|
||||
|
||||
const MIME = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.wasm': 'application/wasm',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.png': 'image/png',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.ico': 'image/x-icon',
|
||||
'.ttf': 'font/ttf',
|
||||
'.otf': 'font/otf',
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2',
|
||||
};
|
||||
|
||||
const RUNS = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Fixture live run',
|
||||
name: 'fixture-live',
|
||||
status: 'running',
|
||||
created_at: '2026-10-21T12:00:00Z',
|
||||
pipeline_id: 10,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'Fixture pending run',
|
||||
name: 'fixture-pending',
|
||||
status: 'running',
|
||||
created_at: '2026-10-21T11:00:00Z',
|
||||
pipeline_id: 10,
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'Fixture failing run',
|
||||
name: 'fixture-failing',
|
||||
status: 'failed',
|
||||
created_at: '2026-10-21T10:00:00Z',
|
||||
pipeline_id: 10,
|
||||
},
|
||||
];
|
||||
|
||||
const LIVE_EVENT = {
|
||||
type: 'run_event',
|
||||
run_id: 1,
|
||||
status: 'succeeded',
|
||||
outcome: 'success',
|
||||
completed_steps: 2,
|
||||
current_stage: 'test',
|
||||
finished_at: '2026-10-21T12:05:00Z',
|
||||
};
|
||||
|
||||
function detail(id, live) {
|
||||
const status = id === 1 && live ? 'succeeded' : id === 3 ? 'failed' : 'running';
|
||||
return {
|
||||
id,
|
||||
title: RUNS.find((run) => run.id === id)?.title ?? `Run ${id}`,
|
||||
name: 'fixture-pipeline',
|
||||
status,
|
||||
input: {
|
||||
prompt: ' fixture prompt with spaces ',
|
||||
note: 'input payload',
|
||||
},
|
||||
output: { answer: 42, nested: { ok: true } },
|
||||
usage: {
|
||||
stages: 2,
|
||||
tokens_total: 120,
|
||||
tokens_known_stages: 2,
|
||||
tokens_in: 70,
|
||||
tokens_out: 50,
|
||||
split_known: true,
|
||||
cost_known_stages: 2,
|
||||
cost_usd: 0.25,
|
||||
},
|
||||
steps: [
|
||||
{
|
||||
stage: 'build',
|
||||
sequence: 3,
|
||||
status: 'completed',
|
||||
outcome: 'success',
|
||||
target: '#success',
|
||||
},
|
||||
{
|
||||
stage: 'test',
|
||||
sequence: 4,
|
||||
status: status === 'failed' ? 'failed' : 'completed',
|
||||
outcome: status === 'failed' ? 'failure' : 'success',
|
||||
target: status === 'failed' ? '#failure' : '#success',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function accept(key) {
|
||||
return createHash('sha1')
|
||||
.update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
|
||||
.digest('base64');
|
||||
}
|
||||
|
||||
function frame(opcode, payload) {
|
||||
const length = payload.length;
|
||||
let header;
|
||||
if (length < 126) {
|
||||
header = Buffer.from([0x80 | opcode, length]);
|
||||
} else if (length < 65536) {
|
||||
header = Buffer.alloc(4);
|
||||
header[0] = 0x80 | opcode;
|
||||
header[1] = 126;
|
||||
header.writeUInt16BE(length, 2);
|
||||
} else {
|
||||
header = Buffer.alloc(10);
|
||||
header[0] = 0x80 | opcode;
|
||||
header[1] = 127;
|
||||
header.writeBigUInt64BE(BigInt(length), 2);
|
||||
}
|
||||
return Buffer.concat([header, payload]);
|
||||
}
|
||||
|
||||
class Connection {
|
||||
constructor(socket, owner) {
|
||||
this.socket = socket;
|
||||
this.owner = owner;
|
||||
this.buffer = Buffer.alloc(0);
|
||||
this.fragments = [];
|
||||
this.fragmentOpcode = 0;
|
||||
}
|
||||
|
||||
push(chunk) {
|
||||
if (chunk?.length) this.buffer = Buffer.concat([this.buffer, chunk]);
|
||||
this.parse();
|
||||
}
|
||||
|
||||
parse() {
|
||||
while (this.buffer.length >= 2) {
|
||||
const first = this.buffer[0];
|
||||
const second = this.buffer[1];
|
||||
const fin = (first & 0x80) !== 0;
|
||||
const opcode = first & 0x0f;
|
||||
const masked = (second & 0x80) !== 0;
|
||||
let length = second & 0x7f;
|
||||
let offset = 2;
|
||||
if (length === 126) {
|
||||
if (this.buffer.length < 4) return;
|
||||
length = this.buffer.readUInt16BE(2);
|
||||
offset = 4;
|
||||
} else if (length === 127) {
|
||||
if (this.buffer.length < 10) return;
|
||||
const big = this.buffer.readBigUInt64BE(2);
|
||||
if (big > BigInt(Number.MAX_SAFE_INTEGER)) return this.close();
|
||||
length = Number(big);
|
||||
offset = 10;
|
||||
}
|
||||
const maskOffset = offset;
|
||||
if (masked) {
|
||||
if (this.buffer.length < offset + 4) return;
|
||||
offset += 4;
|
||||
}
|
||||
if (this.buffer.length < offset + length) return;
|
||||
let payload = Buffer.from(this.buffer.subarray(offset, offset + length));
|
||||
if (masked) {
|
||||
const mask = this.buffer.subarray(maskOffset, maskOffset + 4);
|
||||
for (let index = 0; index < payload.length; index++) {
|
||||
payload[index] ^= mask[index % 4];
|
||||
}
|
||||
}
|
||||
this.buffer = this.buffer.subarray(offset + length);
|
||||
this.handleFrame(fin, opcode, payload);
|
||||
}
|
||||
}
|
||||
|
||||
handleFrame(fin, opcode, payload) {
|
||||
if (opcode === 0x8) return this.close();
|
||||
if (opcode === 0x9) return void this.socket.write(frame(0x0a, payload));
|
||||
if (opcode === 0x0a) return;
|
||||
if (opcode === 0x0) {
|
||||
this.fragments.push(payload);
|
||||
if (fin) {
|
||||
const data = Buffer.concat(this.fragments);
|
||||
this.fragments = [];
|
||||
this.message(this.fragmentOpcode, data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (opcode !== 0x1) return;
|
||||
if (!fin) {
|
||||
this.fragmentOpcode = opcode;
|
||||
this.fragments = [payload];
|
||||
return;
|
||||
}
|
||||
this.message(opcode, payload);
|
||||
}
|
||||
|
||||
message(_opcode, payload) {
|
||||
let request;
|
||||
try {
|
||||
request = JSON.parse(payload.toString('utf8'));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
this.owner.onMessage(this, request);
|
||||
}
|
||||
|
||||
send(value) {
|
||||
if (this.socket.destroyed) return;
|
||||
this.socket.write(frame(0x1, Buffer.from(JSON.stringify(value))));
|
||||
}
|
||||
|
||||
close() {
|
||||
if (!this.socket.destroyed) this.socket.end();
|
||||
}
|
||||
}
|
||||
|
||||
async function staticFile(base, pathname, req, res) {
|
||||
let file = resolve(base, `.${pathname}`);
|
||||
if (file !== base && !file.startsWith(base + sep)) {
|
||||
res.writeHead(403).end();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if ((await stat(file)).isDirectory()) file = join(file, 'index.html');
|
||||
} catch {
|
||||
if (extname(pathname)) {
|
||||
res.writeHead(404).end('not found');
|
||||
return;
|
||||
}
|
||||
file = join(base, 'index.html');
|
||||
}
|
||||
try {
|
||||
const body = await readFile(file);
|
||||
res
|
||||
.writeHead(200, {
|
||||
'content-type': MIME[extname(file)] ?? 'application/octet-stream',
|
||||
'cache-control': 'no-store',
|
||||
})
|
||||
.end(req.method === 'HEAD' ? undefined : body);
|
||||
} catch {
|
||||
res.writeHead(404).end('not found');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A deterministic, isolated Pipelines protocol fixture for the browser probe.
|
||||
* It serves the built probe bundle and upgrades /connect on the same origin, so
|
||||
* the normal web composition infers this server from Uri.base.
|
||||
*/
|
||||
export async function startFixture({ root }) {
|
||||
const base = await realpath(root);
|
||||
const connections = new Set();
|
||||
const sockets = new Set();
|
||||
let subscribed = 0;
|
||||
let live = false;
|
||||
let refuse = false;
|
||||
let dropped = 0;
|
||||
let listRuns = 0;
|
||||
let getRun = 0;
|
||||
|
||||
const dropConnections = () => {
|
||||
for (const connection of connections) connection.close();
|
||||
connections.clear();
|
||||
dropped++;
|
||||
};
|
||||
|
||||
const broadcast = (value) => {
|
||||
for (const connection of connections) connection.send(value);
|
||||
};
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
const pathname = new URL(req.url, 'http://fixture').pathname;
|
||||
if (pathname === '/fixture/live' && req.method === 'POST') {
|
||||
live = true;
|
||||
broadcast(LIVE_EVENT);
|
||||
res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}');
|
||||
return;
|
||||
}
|
||||
if (pathname === '/fixture/drop' && req.method === 'POST') {
|
||||
dropConnections();
|
||||
res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}');
|
||||
return;
|
||||
}
|
||||
if (pathname === '/fixture/refuse' && req.method === 'POST') {
|
||||
refuse = true;
|
||||
dropConnections();
|
||||
res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}');
|
||||
return;
|
||||
}
|
||||
if (pathname === '/fixture/accept' && req.method === 'POST') {
|
||||
refuse = false;
|
||||
res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}');
|
||||
return;
|
||||
}
|
||||
if (pathname === '/fixture/state') {
|
||||
res
|
||||
.writeHead(200, { 'content-type': 'application/json' })
|
||||
.end(JSON.stringify({
|
||||
subscribed,
|
||||
live,
|
||||
connections: connections.size,
|
||||
refuse,
|
||||
dropped,
|
||||
listRuns,
|
||||
getRun,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
res.writeHead(405).end();
|
||||
return;
|
||||
}
|
||||
await staticFile(base, pathname, req, res);
|
||||
});
|
||||
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
if (refuse) {
|
||||
socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n');
|
||||
return;
|
||||
}
|
||||
const url = new URL(req.url, 'http://fixture');
|
||||
if (
|
||||
url.pathname !== '/connect' ||
|
||||
req.headers.upgrade?.toLowerCase() !== 'websocket' ||
|
||||
!req.headers['sec-websocket-key']
|
||||
) {
|
||||
socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
|
||||
return;
|
||||
}
|
||||
socket.write(
|
||||
'HTTP/1.1 101 Switching Protocols\r\n' +
|
||||
'Upgrade: websocket\r\n' +
|
||||
'Connection: Upgrade\r\n' +
|
||||
`Sec-WebSocket-Accept: ${accept(req.headers['sec-websocket-key'])}\r\n\r\n`,
|
||||
);
|
||||
const connection = new Connection(socket, {
|
||||
onMessage: (client, request) => {
|
||||
if (request.type === 'subscribe') {
|
||||
// The real server may not acknowledge `subscribe`; keep it silent so
|
||||
// the app's send-only path is exercised.
|
||||
subscribed++;
|
||||
return;
|
||||
}
|
||||
if (request.type === 'unsubscribe') return;
|
||||
if (request.type === 'ping') {
|
||||
client.send({
|
||||
id: request.id, type: 'pong',
|
||||
build: { version: 'Fixture settings build' },
|
||||
time: '2026-10-21T12:00:00Z',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (request.type === 'list_runs') {
|
||||
listRuns++;
|
||||
client.send({ id: request.id, type: 'runs', runs: RUNS, usage: null });
|
||||
return;
|
||||
}
|
||||
if (request.type === 'get_run') {
|
||||
getRun++;
|
||||
const id = request.run_id;
|
||||
if (id === 2) {
|
||||
// Deliberately slow so the browser sees the pending/Back state;
|
||||
// it must still answer so the serialized request queue continues.
|
||||
setTimeout(() => {
|
||||
client.send({ id: request.id, type: 'run', run_detail: detail(2, live) });
|
||||
}, 2500);
|
||||
return;
|
||||
}
|
||||
if (id === 3) {
|
||||
client.send({
|
||||
id: request.id,
|
||||
type: 'error',
|
||||
error: 'Fixture detail failure: run 3 is unavailable',
|
||||
});
|
||||
return;
|
||||
}
|
||||
client.send({ id: request.id, type: 'run', run_detail: detail(id, live) });
|
||||
return;
|
||||
}
|
||||
client.send({
|
||||
id: request.id,
|
||||
type: 'error',
|
||||
error: `Fixture does not implement ${request.type}`,
|
||||
});
|
||||
},
|
||||
});
|
||||
connections.add(connection);
|
||||
socket.on('data', (chunk) => connection.push(chunk));
|
||||
socket.on('close', () => connections.delete(connection));
|
||||
socket.on('error', () => connections.delete(connection));
|
||||
connection.push(head);
|
||||
});
|
||||
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
server.on('connection', (socket) => {
|
||||
sockets.add(socket);
|
||||
socket.on('close', () => sockets.delete(socket));
|
||||
});
|
||||
const port = server.address().port;
|
||||
return {
|
||||
server,
|
||||
port,
|
||||
url: `http://127.0.0.1:${port}`,
|
||||
get subscribed() {
|
||||
return subscribed;
|
||||
},
|
||||
close: () =>
|
||||
new Promise((resolveClose) => {
|
||||
for (const connection of connections) connection.close();
|
||||
server.close(() => resolveClose());
|
||||
for (const socket of sockets) socket.destroy();
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
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';
|
||||
|
||||
// Serves the Flutter web build produced by:
|
||||
// flutter build web -t tool/schedules_list_probe_app.dart
|
||||
// The fixture is local-only: no Pipelines server, authentication or real
|
||||
// schedule is touched.
|
||||
const root = join(process.cwd(), 'build/web');
|
||||
const outputIndex = process.argv.indexOf('--out');
|
||||
const output = outputIndex >= 0
|
||||
? resolve(process.argv[outputIndex + 1])
|
||||
: resolve(process.env.OPENCODE_ARTIFACT_DIR ?? join(process.cwd(), 'build/schedules-captures'));
|
||||
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',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.ico': 'image/x-icon',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.ttf': 'font/ttf',
|
||||
'.otf': 'font/otf',
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2',
|
||||
'.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 = pathname.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 port = server.address().port;
|
||||
const profile = await mkdtemp(join(tmpdir(), 's1b-schedules-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 = 160) => {
|
||||
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}`);
|
||||
};
|
||||
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 msg = JSON.parse(event.data);
|
||||
if (msg.method === 'Runtime.exceptionThrown') {
|
||||
pageErrors.push(msg.params?.exceptionDetails?.text ?? 'page exception');
|
||||
}
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
pending.get(msg.id)(msg);
|
||||
pending.delete(msg.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);
|
||||
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;
|
||||
};
|
||||
await mkdir(output, { recursive: true });
|
||||
const cases = [
|
||||
{
|
||||
name: 's1b-schedules-material-390',
|
||||
theme: 'material',
|
||||
scale: 1,
|
||||
width: 390,
|
||||
height: 844,
|
||||
expect: ['4 schedules', 'Research batteries', 'Pipeline 4 · v2', 'Timer: Every 24h', 'Timezone: Europe/London', 'Next due:'],
|
||||
},
|
||||
{
|
||||
name: 's1b-schedules-material-390-2x',
|
||||
theme: 'material',
|
||||
scale: 2,
|
||||
width: 390,
|
||||
height: 844,
|
||||
expect: ['Research batteries', 'Pipeline 4 · v2', 'Workspace: /srv/research', 'Timer: Every 24h'],
|
||||
},
|
||||
{
|
||||
name: 's1b-schedules-material-390-dark',
|
||||
theme: 'material',
|
||||
brightness: 'dark',
|
||||
scale: 1,
|
||||
width: 390,
|
||||
height: 844,
|
||||
expect: ['4 schedules', 'Research batteries', 'Pipeline 4 · v2', 'Timezone: Europe/London', 'Next due:'],
|
||||
},
|
||||
{
|
||||
name: 's1b-schedules-cupertino-390',
|
||||
theme: 'cupertino',
|
||||
scale: 1,
|
||||
width: 390,
|
||||
height: 844,
|
||||
expect: ['Research batteries', 'Pipeline 4 · v2', 'Timezone: Europe/London'],
|
||||
},
|
||||
{
|
||||
name: 's1b-schedules-material-1100',
|
||||
theme: 'material',
|
||||
scale: 1,
|
||||
width: 1100,
|
||||
height: 800,
|
||||
expect: ['Research batteries', 'Nightly report', 'Weekly digest', 'Sparse server record'],
|
||||
},
|
||||
];
|
||||
const results = [];
|
||||
for (const item of cases) {
|
||||
const query = new URLSearchParams({ theme: item.theme, scale: String(item.scale) });
|
||||
if (item.brightness) query.set('brightness', item.brightness);
|
||||
const url = `http://127.0.0.1:${port}/?${query}`;
|
||||
const navigation = await send('Page.navigate', { url }, session);
|
||||
if (navigation.error || navigation.result?.errorText) {
|
||||
throw new Error(`Navigation failed: ${JSON.stringify(navigation)}`);
|
||||
}
|
||||
await send(
|
||||
'Emulation.setDeviceMetricsOverride',
|
||||
{
|
||||
width: item.width,
|
||||
height: item.height,
|
||||
deviceScaleFactor: 1,
|
||||
mobile: item.width < 600,
|
||||
},
|
||||
session,
|
||||
);
|
||||
await delay(2500);
|
||||
const placeholder = await waitFor(
|
||||
() => evaluate("!!document.querySelector('flt-semantics-placeholder')"),
|
||||
`${item.name} semantics placeholder`,
|
||||
);
|
||||
if (!placeholder) throw new Error(`${item.name}: no semantics placeholder`);
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
const labels = await waitFor(async () => {
|
||||
const current = await evaluate(
|
||||
"[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)",
|
||||
);
|
||||
return current?.some(label => label.includes('Research batteries')) ? current : null;
|
||||
}, `${item.name} schedule content`);
|
||||
const text = labels.join('\n');
|
||||
for (const expected of item.expect) {
|
||||
if (!text.includes(expected)) {
|
||||
throw new Error(`${item.name}: missing ${JSON.stringify(expected)} in ${JSON.stringify(labels)}`);
|
||||
}
|
||||
}
|
||||
if (/does not support|No schedules yet|socket closed/.test(text)) {
|
||||
throw new Error(`${item.name}: unexpected state text ${JSON.stringify(labels)}`);
|
||||
}
|
||||
await delay(400);
|
||||
const screenshot = await send(
|
||||
'Page.captureScreenshot',
|
||||
{ format: 'png', captureBeyondViewport: false },
|
||||
session,
|
||||
);
|
||||
const file = `${item.name}.png`;
|
||||
await writeFile(join(output, file), Buffer.from(screenshot.result.data, 'base64'));
|
||||
results.push({
|
||||
name: item.name,
|
||||
file,
|
||||
width: item.width,
|
||||
height: item.height,
|
||||
theme: item.theme,
|
||||
brightness: item.brightness ?? 'platform',
|
||||
checked: item.expect,
|
||||
labelCount: labels.length,
|
||||
});
|
||||
}
|
||||
if (pageErrors.length) {
|
||||
throw new Error(`Page exceptions: ${JSON.stringify(pageErrors)}`);
|
||||
}
|
||||
const manifest = {
|
||||
url: `http://127.0.0.1:${port}/`,
|
||||
fixture: 'tool/schedules_list_probe_app.dart',
|
||||
output,
|
||||
captures: results,
|
||||
};
|
||||
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 });
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/schedules/screen.dart';
|
||||
|
||||
/// Isolated browser fixture for the read-only schedules list.
|
||||
///
|
||||
/// Run with:
|
||||
/// flutter build web -t tool/schedules_list_probe_app.dart
|
||||
/// and open `/?theme=cupertino&scale=2`.
|
||||
void main() {
|
||||
final parameters = Uri.base.queryParameters;
|
||||
final cupertino = parameters['theme'] == 'cupertino';
|
||||
final dark = parameters['brightness'] == 'dark';
|
||||
final scale = double.tryParse(parameters['scale'] ?? '') ?? 1.0;
|
||||
final screen = SchedulesScreen(gateway: _FixtureGateway(), onOpen: (_) {});
|
||||
Widget media(BuildContext context, Widget? app) => MediaQuery(
|
||||
data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(scale)),
|
||||
child: app!,
|
||||
);
|
||||
if (cupertino) {
|
||||
runApp(
|
||||
CupertinoApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
builder: media,
|
||||
home: CupertinoPageScaffold(child: SafeArea(child: screen)),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
runApp(
|
||||
MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: dark ? ThemeData(brightness: Brightness.dark) : null,
|
||||
builder: media,
|
||||
home: Scaffold(
|
||||
appBar: AppBar(title: const Text('Schedules')),
|
||||
body: screen,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _FixtureGateway implements ApiGateway {
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
if (type != 'list_schedules') {
|
||||
throw StateError('The schedules list fixture only lists schedules.');
|
||||
}
|
||||
return {
|
||||
'type': 'schedules',
|
||||
'schedules': [
|
||||
{
|
||||
'id': 8,
|
||||
'revision': 3,
|
||||
'name': 'Research batteries',
|
||||
'pipeline_id': 4,
|
||||
'version': 2,
|
||||
'enabled': true,
|
||||
'input': {'prompt': 'Find battery chemistry sources'},
|
||||
'workspace': '/srv/research',
|
||||
'rule': {
|
||||
'every': '24h',
|
||||
'days': ['mon', 'wed'],
|
||||
'timezone': 'Europe/London',
|
||||
},
|
||||
'next_due': '2026-10-22T09:00:00Z',
|
||||
},
|
||||
{
|
||||
'id': 9,
|
||||
'revision': 1,
|
||||
'name': 'Nightly report',
|
||||
'pipeline_id': 7,
|
||||
'version': 5,
|
||||
'enabled': false,
|
||||
'input': {'prompt': 'Summarise the open issues'},
|
||||
'workspace': '/srv/reports',
|
||||
'rule': {
|
||||
'times': ['10:00', '18:30'],
|
||||
'days': <String>[],
|
||||
'timezone': 'Local',
|
||||
},
|
||||
},
|
||||
{
|
||||
'id': 10,
|
||||
'revision': 2,
|
||||
'name': 'Weekly digest',
|
||||
'pipeline_id': 12,
|
||||
'version': 1,
|
||||
'enabled': true,
|
||||
'input': {'prompt': 'Collect the week’s changes'},
|
||||
'workspace': '/srv/digest',
|
||||
'rule': {'every': '168h', 'days': <String>[]},
|
||||
'next_due': '2026-10-26T08:30:00+01:00',
|
||||
},
|
||||
{
|
||||
'id': 11,
|
||||
'revision': 1,
|
||||
'name': 'Sparse server record',
|
||||
'enabled': false,
|
||||
'input': <String, dynamic>{},
|
||||
'rule': <String, dynamic>{},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// Web-only fixture entrypoint for rendered search evidence. It is not part of
|
||||
// the application's `main.dart`; build it explicitly with:
|
||||
// flutter build web -t tool/search_fixture/main.dart
|
||||
// `?cupertino=1` renders the same screen inside a CupertinoApp.
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/search/search_screen.dart';
|
||||
|
||||
void main() {
|
||||
final cupertino = Uri.base.queryParameters['cupertino'] == '1';
|
||||
runApp(
|
||||
cupertino
|
||||
? const CupertinoApp(
|
||||
title: 'Search fixture',
|
||||
home: _FixtureHost(cupertino: true),
|
||||
)
|
||||
: const MaterialApp(
|
||||
title: 'Search fixture',
|
||||
home: _FixtureHost(cupertino: false),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _FixtureHost extends StatelessWidget {
|
||||
const _FixtureHost({required this.cupertino});
|
||||
|
||||
final bool cupertino;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => SearchScreen(
|
||||
gateway: const _FixtureGateway(),
|
||||
cupertino: cupertino,
|
||||
onOpen: (hit) {
|
||||
final route = cupertino
|
||||
? CupertinoPageRoute<void>(
|
||||
builder: (_) => _Opened(hit: hit, cupertino: true),
|
||||
)
|
||||
: MaterialPageRoute<void>(
|
||||
builder: (_) => _Opened(hit: hit, cupertino: false),
|
||||
);
|
||||
Navigator.of(context).push(route);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class _Opened extends StatelessWidget {
|
||||
const _Opened({required this.hit, required this.cupertino});
|
||||
|
||||
final JsonMap hit;
|
||||
final bool cupertino;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final body = Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(
|
||||
'Opened ${hit['kind']} target: ${hit['target']}',
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (cupertino) {
|
||||
return CupertinoPageScaffold(
|
||||
navigationBar: const CupertinoNavigationBar(middle: Text('Opened')),
|
||||
child: body,
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Opened')),
|
||||
body: body,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FixtureGateway implements ApiGateway {
|
||||
const _FixtureGateway();
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
if (type != 'search') throw StateError('unexpected request: $type');
|
||||
final request = Map<String, dynamic>.from(fields['search'] as Map);
|
||||
final query = '${request['query'] ?? ''}'.trim().toLowerCase();
|
||||
final kind = '${request['kind'] ?? ''}';
|
||||
await Future<void>.delayed(const Duration(milliseconds: 180));
|
||||
var hits = _fixtureHits
|
||||
.where((hit) {
|
||||
if (kind.isNotEmpty && hit['kind'] != kind) return false;
|
||||
if (query.isEmpty) return true;
|
||||
return jsonEncode(hit).toLowerCase().contains(query);
|
||||
})
|
||||
.toList(growable: false);
|
||||
return {
|
||||
'search_results': {
|
||||
'query': request['query'],
|
||||
'kind': kind,
|
||||
'results': hits,
|
||||
'truncated': true,
|
||||
'scanned_steps': 2000,
|
||||
'scanned_bytes': 1048576,
|
||||
'cap': 50,
|
||||
'scan_bound_bytes': 1048576,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
}
|
||||
|
||||
const _fixtureHits = <JsonMap>[
|
||||
{
|
||||
'kind': 'pipeline',
|
||||
'target': 'pipeline:24',
|
||||
'score': 3,
|
||||
'recency': '2026-10-20T09:18:00Z',
|
||||
'pipeline': {'id': 24, 'name': 'Plan and land', 'version': 5, 'stages': 4},
|
||||
},
|
||||
{
|
||||
'kind': 'run',
|
||||
'target': 'run:457',
|
||||
'score': 2,
|
||||
'recency': '2026-10-20T08:42:00Z',
|
||||
'run': {
|
||||
'id': 457,
|
||||
'pipeline_name': 'Plan and land',
|
||||
'status': 'succeeded',
|
||||
'workspace': '/Users/alan/repos/pipelines',
|
||||
'created_at': '2026-10-20T08:12:00Z',
|
||||
'finished_at': '2026-10-20T08:42:00Z',
|
||||
},
|
||||
},
|
||||
{
|
||||
'kind': 'field',
|
||||
'target': 'run:457:3:input',
|
||||
'score': 1,
|
||||
'matched_field': 'input',
|
||||
'recency': '2026-10-20T08:20:00Z',
|
||||
'field': {
|
||||
'run_id': 457,
|
||||
'sequence': 3,
|
||||
'field': 'input',
|
||||
'snippet': 'Plan the change before implementing it',
|
||||
},
|
||||
},
|
||||
{
|
||||
'kind': 'artifact',
|
||||
'target': '/artifacts/457/2/plan.md',
|
||||
'score': 1,
|
||||
'recency': '2026-10-20T08:24:00Z',
|
||||
'artifact': {
|
||||
'run_id': 457,
|
||||
'sequence': 2,
|
||||
'name': 'plan.md',
|
||||
'content_type': 'text/markdown',
|
||||
'size_bytes': 2048,
|
||||
'url': '/artifacts/457/2/plan.md',
|
||||
},
|
||||
},
|
||||
{
|
||||
'kind': 'version',
|
||||
'target': 'pipeline:22:v6',
|
||||
'score': 2,
|
||||
'recency': '2026-10-18T16:05:00Z',
|
||||
'version': {
|
||||
'pipeline_id': 22,
|
||||
'version': 6,
|
||||
'content_hash': '9f2c1ad',
|
||||
'created_at': '2026-10-18T16:05:00Z',
|
||||
},
|
||||
},
|
||||
{
|
||||
'kind': 'step',
|
||||
'target': 'run:457:1',
|
||||
'score': 1,
|
||||
'recency': '2026-10-20T08:14:00Z',
|
||||
'step': {
|
||||
'run_id': 457,
|
||||
'sequence': 1,
|
||||
'stage': 'planner',
|
||||
'visit': 1,
|
||||
'outcome': 'success',
|
||||
'target': '#success',
|
||||
'diagnostic': 'plan accepted',
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,246 @@
|
||||
// Real Chrome evidence for the Flutter search screen. Serves the fixture build
|
||||
// from build/web on an OS-assigned loopback port and drives the page through
|
||||
// Chrome DevTools Protocol, like tool/shell_probe.mjs. Usage:
|
||||
// flutter build web -t tool/search_fixture/main.dart
|
||||
// OPENCODE_ARTIFACT_DIR=<dir> node tool/search_probe.mjs
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile, 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';
|
||||
|
||||
const root = join(process.cwd(), 'build/web');
|
||||
const artifactDir = process.env.OPENCODE_ARTIFACT_DIR;
|
||||
if (!artifactDir) throw new Error('OPENCODE_ARTIFACT_DIR is required for captures');
|
||||
const mime = {
|
||||
'.html': 'text/html',
|
||||
'.js': 'text/javascript',
|
||||
'.json': 'application/json',
|
||||
'.wasm': 'application/wasm',
|
||||
'.png': 'image/png',
|
||||
'.ico': 'image/x-icon',
|
||||
'.ttf': 'font/ttf',
|
||||
'.otf': 'font/otf',
|
||||
};
|
||||
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(), 'x1-search-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 < 100; i++) {
|
||||
const value = await fn();
|
||||
if (value) return value;
|
||||
await delay(100);
|
||||
}
|
||||
throw new Error('Timed out waiting for Chrome DevTools');
|
||||
};
|
||||
const result = { captures: [], evidence: {} };
|
||||
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((resolve) => {
|
||||
const callId = ++id;
|
||||
pending.set(callId, resolve);
|
||||
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);
|
||||
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 clickMatching = (needle) =>
|
||||
evaluate(`(() => {
|
||||
const needle = ${JSON.stringify(needle)};
|
||||
const nodes = [...document.querySelectorAll('flt-semantics')];
|
||||
const e = nodes.find(x => x.hasAttribute('flt-tappable') &&
|
||||
(x.getAttribute('aria-label') || x.innerText || '').includes(needle));
|
||||
if (!e) return false;
|
||||
e.click();
|
||||
return true;
|
||||
})()`);
|
||||
const capture = async (name, width, height) => {
|
||||
await send(
|
||||
'Emulation.setDeviceMetricsOverride',
|
||||
{ width, height, deviceScaleFactor: 1, mobile: width < 600 },
|
||||
session,
|
||||
);
|
||||
await delay(350);
|
||||
const data = (
|
||||
await send(
|
||||
'Page.captureScreenshot',
|
||||
{ format: 'png', captureBeyondViewport: false },
|
||||
session,
|
||||
)
|
||||
).result.data;
|
||||
const path = join(artifactDir, `${name}.png`);
|
||||
await writeFile(path, Buffer.from(data, 'base64'));
|
||||
result.captures.push(path);
|
||||
};
|
||||
const load = async (url, width, height) => {
|
||||
await send(
|
||||
'Emulation.setDeviceMetricsOverride',
|
||||
{ width, height, deviceScaleFactor: 1, mobile: width < 600 },
|
||||
session,
|
||||
);
|
||||
const navigation = await send('Page.navigate', { url }, session);
|
||||
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
|
||||
await delay(3500);
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
await delay(900);
|
||||
};
|
||||
const typeText = async (query) => {
|
||||
const focused = await evaluate(`(() => {
|
||||
const input = document.querySelector('input[type="search"]') || document.querySelector('input.flt-text-editing');
|
||||
if (!input) return false; input.focus(); return true; })()`);
|
||||
if (!focused) throw new Error('Search input not found');
|
||||
await delay(400);
|
||||
const inserted = await send('Input.insertText', { text: query }, session);
|
||||
if (inserted.error) throw new Error(JSON.stringify(inserted));
|
||||
await delay(1400);
|
||||
return (await evaluate('document.body.innerText')).trim();
|
||||
};
|
||||
const typeQuery = async (query) => {
|
||||
const trimmed = await typeText(query);
|
||||
if (!trimmed.includes('Plan and land')) {
|
||||
throw new Error(`Results missing after typing: ${JSON.stringify(trimmed)}`);
|
||||
}
|
||||
return {
|
||||
typed: query,
|
||||
resultTitles: ['Plan and land', 'run #457 · Plan and land', 'run #457 · step 3 · input',
|
||||
'plan.md', 'run #457 · planner visit 1'].filter((title) => trimmed.includes(title)),
|
||||
showsServerSnippet: trimmed.includes('Plan the change before implementing it'),
|
||||
showsRecency: /\d{1,2} [A-Z][a-z]{2} \d{2}:\d{2}/.test(trimmed),
|
||||
showsBounds:
|
||||
trimmed.includes('Results truncated') &&
|
||||
trimmed.includes('cap 50') &&
|
||||
trimmed.includes('scanned 2000 steps'),
|
||||
};
|
||||
};
|
||||
const typeTruncatedEmpty = async (query) => {
|
||||
const text = await typeText(query);
|
||||
const emptyCopy = `No matches for "${query}" within the server's scan limit.`;
|
||||
const missing = [
|
||||
emptyCopy, 'Results truncated', '0 results',
|
||||
'scanned 2000 steps', 'scan limit 1.0 MiB',
|
||||
].filter((needle) => !text.includes(needle));
|
||||
if (missing.length) throw new Error(`Truncated empty missing ${JSON.stringify(missing)}`);
|
||||
return { typed: query, emptyCopy, showsTruncationWarning: true, showsBounds: true };
|
||||
};
|
||||
|
||||
const base = `http://127.0.0.1:${port}/`;
|
||||
await load(base, 390, 844);
|
||||
result.evidence.materialPhone = await typeQuery('plan');
|
||||
await capture('x1-search-material-phone', 390, 844);
|
||||
if (!(await clickMatching('Plan and land'))) {
|
||||
throw new Error('Could not open the pipeline row');
|
||||
}
|
||||
await delay(700);
|
||||
const opened = await evaluate('document.body.innerText');
|
||||
if (!opened.includes('pipeline:24')) {
|
||||
throw new Error(`Opened target missing: ${JSON.stringify(opened)}`);
|
||||
}
|
||||
result.evidence.opened = 'pipeline:24';
|
||||
await capture('x1-search-open-target', 390, 844);
|
||||
|
||||
await load(base, 1280, 800);
|
||||
result.evidence.materialDesktop = await typeQuery('plan');
|
||||
await capture('x1-search-material-desktop', 1280, 800);
|
||||
|
||||
await load(`${base}?cupertino=1`, 390, 844);
|
||||
result.evidence.cupertinoPhone = await typeQuery('plan');
|
||||
await capture('x1-search-cupertino-phone', 390, 844);
|
||||
|
||||
await load(base, 390, 844);
|
||||
result.evidence.materialTruncatedEmpty = await typeTruncatedEmpty('needle');
|
||||
await capture('x1-search-truncated-empty', 390, 844);
|
||||
|
||||
await load(`${base}?cupertino=1`, 390, 844);
|
||||
result.evidence.cupertinoTruncatedEmpty =
|
||||
await typeTruncatedEmpty('needle');
|
||||
await capture('x1-search-truncated-empty-cupertino', 390, 844);
|
||||
|
||||
console.log(JSON.stringify(result, 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 });
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pipelines_app/core/transport/pipelines_client.dart';
|
||||
import 'package:pipelines_app/features/settings/settings.dart';
|
||||
|
||||
/// A fixture entry point for browser captures of the Settings screen. It does
|
||||
/// not change `main.dart` or the shell, and it never uses the production
|
||||
/// preferences store: all persisted values live in a [MemorySettingsStore].
|
||||
///
|
||||
/// Query parameters:
|
||||
/// endpoint=ws://127.0.0.1:PORT/connect seed the URL field / connect target
|
||||
/// workspace=/srv/pipelines seed the saved workspace
|
||||
/// connect=1 explicitly connect after first frame
|
||||
/// platform=ios render the Cupertino controls
|
||||
/// theme=dark dark Material theme
|
||||
/// scale=1.5 large-text check
|
||||
void main() {
|
||||
final params = Uri.base.queryParameters;
|
||||
final endpoint = params['endpoint']?.trim();
|
||||
final client = PipelinesClient();
|
||||
final store = MemorySettingsStore(
|
||||
workspace: params['workspace']?.trim() ?? '',
|
||||
);
|
||||
final isIOS = params['platform'] == 'ios';
|
||||
final isDark = params['theme'] == 'dark';
|
||||
final scale = double.tryParse(params['scale'] ?? '') ?? 1;
|
||||
|
||||
runApp(
|
||||
MaterialApp(
|
||||
title: 'Pipelines Settings probe',
|
||||
theme: ThemeData(
|
||||
platform: isIOS ? TargetPlatform.iOS : TargetPlatform.android,
|
||||
brightness: isDark ? Brightness.dark : Brightness.light,
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: Colors.blue,
|
||||
brightness: isDark ? Brightness.dark : Brightness.light,
|
||||
),
|
||||
),
|
||||
builder: (context, child) => MediaQuery(
|
||||
data: MediaQuery.of(
|
||||
context,
|
||||
).copyWith(textScaler: TextScaler.linear(scale)),
|
||||
child: child ?? const SizedBox.shrink(),
|
||||
),
|
||||
home: SettingsScreen(
|
||||
client: client,
|
||||
initialEndpoint: (endpoint == null || endpoint.isEmpty)
|
||||
? null
|
||||
: Uri.tryParse(endpoint),
|
||||
store: store,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (params['connect'] == '1') {
|
||||
final target = (endpoint == null || endpoint.isEmpty)
|
||||
? defaultServerUrl()
|
||||
: endpoint;
|
||||
if (target.isNotEmpty) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
unawaited(
|
||||
client.connect(Uri.parse(target)).catchError((Object _) {
|
||||
// The screen renders the client's truthful state; an invalid
|
||||
// fixture endpoint must not take the probe down.
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
/// Drives the Settings probe in real headless Chrome through the DevTools
|
||||
/// protocol and writes PNG captures. It only talks to the local probe origin
|
||||
/// passed with `--url`; it never contacts the production server.
|
||||
///
|
||||
/// Usage:
|
||||
/// dart run tool/settings_probe_capture.dart \
|
||||
/// --url http://127.0.0.1:PORT/ --out /path/to/captures
|
||||
///
|
||||
/// Set CHROME_PATH if Chrome is not at the default macOS location.
|
||||
Future<void> main(List<String> arguments) async {
|
||||
final url = _argument(arguments, '--url');
|
||||
final outPath = _argument(arguments, '--out');
|
||||
if (url == null || outPath == null) {
|
||||
stderr.writeln('usage: ... --url URL --out DIRECTORY');
|
||||
exitCode = 64;
|
||||
return;
|
||||
}
|
||||
final out = Directory(outPath)..createSync(recursive: true);
|
||||
final chromePath =
|
||||
Platform.environment['CHROME_PATH'] ??
|
||||
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
||||
final profile = await Directory.systemTemp.createTemp('settings-probe-');
|
||||
final chrome = await Process.start(chromePath, <String>[
|
||||
'--headless=new',
|
||||
'--disable-gpu',
|
||||
'--hide-scrollbars',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--remote-debugging-port=0',
|
||||
'--user-data-dir=${profile.path}',
|
||||
'about:blank',
|
||||
]);
|
||||
final stderrLines = chrome.stderr
|
||||
.transform(utf8.decoder)
|
||||
.transform(const LineSplitter())
|
||||
.asBroadcastStream();
|
||||
try {
|
||||
final browserWs = await stderrLines
|
||||
.firstWhere((line) => line.contains('DevTools listening on '))
|
||||
.timeout(const Duration(seconds: 20));
|
||||
final browserUrl = browserWs.substring(browserWs.indexOf('ws://'));
|
||||
final parsed = Uri.parse(browserUrl);
|
||||
final pageWs = await _pageTarget(parsed);
|
||||
final cdp = Cdp(await WebSocket.connect(pageWs));
|
||||
await cdp.send('Page.enable');
|
||||
await cdp.send('Runtime.enable');
|
||||
|
||||
final scenarios = <String>[
|
||||
'idle',
|
||||
'connected',
|
||||
'validation',
|
||||
'workspace',
|
||||
'dark',
|
||||
'ios',
|
||||
'narrow',
|
||||
];
|
||||
for (final scenario in scenarios) {
|
||||
await _runScenario(cdp, url, out, scenario);
|
||||
stdout.writeln('captured $scenario');
|
||||
}
|
||||
await cdp.close();
|
||||
} finally {
|
||||
chrome.kill(ProcessSignal.sigterm);
|
||||
await profile.delete(recursive: true).catchError((_) => profile);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _runScenario(
|
||||
Cdp cdp,
|
||||
String base,
|
||||
Directory out,
|
||||
String scenario,
|
||||
) async {
|
||||
var target = base;
|
||||
var width = 1200;
|
||||
var height = 900;
|
||||
switch (scenario) {
|
||||
case 'idle':
|
||||
break;
|
||||
case 'connected':
|
||||
target = '$base?connect=1';
|
||||
break;
|
||||
case 'validation':
|
||||
target = '$base?endpoint=http%3A%2F%2Fexample.test';
|
||||
break;
|
||||
case 'workspace':
|
||||
target = '$base?connect=1';
|
||||
break;
|
||||
case 'dark':
|
||||
target = '$base?connect=1&theme=dark';
|
||||
break;
|
||||
case 'ios':
|
||||
target = '$base?connect=1&platform=ios';
|
||||
break;
|
||||
case 'narrow':
|
||||
width = 390;
|
||||
height = 844;
|
||||
target = '$base?connect=1&scale=1.6';
|
||||
}
|
||||
await cdp.send('Emulation.setDeviceMetricsOverride', <String, dynamic>{
|
||||
'width': width,
|
||||
'height': height,
|
||||
'deviceScaleFactor': 1,
|
||||
'mobile': false,
|
||||
});
|
||||
await cdp.send('Page.navigate', <String, dynamic>{'url': target});
|
||||
await Future<void>.delayed(const Duration(seconds: 4));
|
||||
if (scenario == 'validation' || scenario == 'workspace') {
|
||||
await _enableSemantics(cdp);
|
||||
if (scenario == 'validation') {
|
||||
await _click(cdp, 'Connect');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 800));
|
||||
} else {
|
||||
await _typeWorkspace(cdp, '/srv/pipelines');
|
||||
await _click(cdp, 'Save workspace');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 800));
|
||||
}
|
||||
}
|
||||
final shot = await cdp.send('Page.captureScreenshot', <String, dynamic>{
|
||||
'format': 'png',
|
||||
'captureBeyondViewport': false,
|
||||
});
|
||||
final data = (shot['result'] as Map)['data'] as String;
|
||||
File(
|
||||
'${out.path}/settings-$scenario.png',
|
||||
).writeAsBytesSync(base64Decode(data));
|
||||
}
|
||||
|
||||
Future<void> _enableSemantics(Cdp cdp) async {
|
||||
await cdp.evaluate('''
|
||||
(() => {
|
||||
const placeholder = document.querySelector('flt-semantics-placeholder');
|
||||
if (placeholder) {
|
||||
placeholder.click();
|
||||
return 'semantics requested';
|
||||
}
|
||||
return 'no placeholder';
|
||||
})()
|
||||
''');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 900));
|
||||
if (Platform.environment['DUMP_DOM'] == '1') {
|
||||
stdout.writeln(
|
||||
await cdp.evaluate(
|
||||
"document.querySelector('flt-semantics-host')?.innerHTML ?? 'none'",
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _click(Cdp cdp, String label) async {
|
||||
final result = await cdp.evaluate('''
|
||||
(() => {
|
||||
const byLabel = [...document.querySelectorAll('[aria-label]')]
|
||||
.find((element) => element.getAttribute('aria-label') === ${jsonEncode(label)});
|
||||
const byRole = [...document.querySelectorAll('[role="button"]')]
|
||||
.find((element) => (element.textContent || '').trim() === ${jsonEncode(label)});
|
||||
const target = byLabel || byRole;
|
||||
if (!target) {
|
||||
return 'missing; labels=' + [...document.querySelectorAll('[aria-label]')]
|
||||
.map((element) => element.getAttribute('aria-label')).join('|') +
|
||||
'; roles=' + [...document.querySelectorAll('[role="button"]')]
|
||||
.map((element) => (element.textContent || '').trim()).join('|');
|
||||
}
|
||||
target.click();
|
||||
return 'clicked ' + target.tagName + ' ' + (target.getAttribute('role') || '');
|
||||
})()
|
||||
''');
|
||||
stdout.writeln('click "$label": $result');
|
||||
}
|
||||
|
||||
Future<void> _typeWorkspace(Cdp cdp, String value) async {
|
||||
final found = await cdp.evaluate('''
|
||||
(() => {
|
||||
const target = [...document.querySelectorAll('[aria-label]')]
|
||||
.find((element) => (element.getAttribute('aria-label') || '')
|
||||
.startsWith('Workspace path'));
|
||||
if (!target) return 'missing';
|
||||
target.click();
|
||||
target.focus();
|
||||
return 'focused ' + target.tagName;
|
||||
})()
|
||||
''');
|
||||
stdout.writeln('workspace field: $found');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 400));
|
||||
final rect = await cdp.evaluate('''
|
||||
(() => {
|
||||
const target = [...document.querySelectorAll('[aria-label]')]
|
||||
.find((element) => (element.getAttribute('aria-label') || '')
|
||||
.startsWith('Workspace path'));
|
||||
if (!target) return null;
|
||||
const r = target.getBoundingClientRect();
|
||||
return {x: r.left + r.width / 2, y: r.top + r.height / 2};
|
||||
})()
|
||||
''');
|
||||
if (rect != 'null') {
|
||||
final match = RegExp(r'x: ([0-9.]+), y: ([0-9.]+)').firstMatch(rect);
|
||||
if (match != null) {
|
||||
final x = double.parse(match.group(1)!);
|
||||
final y = double.parse(match.group(2)!);
|
||||
for (final type in <String>['mousePressed', 'mouseReleased']) {
|
||||
await cdp.send('Input.dispatchMouseEvent', <String, dynamic>{
|
||||
'type': type,
|
||||
'x': x,
|
||||
'y': y,
|
||||
'button': 'left',
|
||||
'clickCount': 1,
|
||||
});
|
||||
}
|
||||
await Future<void>.delayed(const Duration(milliseconds: 300));
|
||||
}
|
||||
}
|
||||
await cdp.send('Input.insertText', <String, dynamic>{'text': value});
|
||||
await Future<void>.delayed(const Duration(milliseconds: 300));
|
||||
final typed = await cdp.evaluate('''
|
||||
(() => {
|
||||
const el = document.activeElement;
|
||||
if (!el) return 'no active element';
|
||||
if (el.value === ${jsonEncode(value)}) return 'insertText worked';
|
||||
el.value = ${jsonEncode(value)};
|
||||
el.dispatchEvent(new InputEvent('input', {
|
||||
bubbles: true,
|
||||
inputType: 'insertText',
|
||||
data: ${jsonEncode(value)},
|
||||
}));
|
||||
el.dispatchEvent(new Event('change', {bubbles: true}));
|
||||
return 'dispatched input; value=' + el.value;
|
||||
})()
|
||||
''');
|
||||
stdout.writeln('workspace input: $typed');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||||
}
|
||||
|
||||
Future<String> _pageTarget(Uri browserWs) async {
|
||||
final client = HttpClient();
|
||||
try {
|
||||
final request = await client.getUrl(
|
||||
Uri(
|
||||
scheme: 'http',
|
||||
host: browserWs.host,
|
||||
port: browserWs.port,
|
||||
path: '/json/list',
|
||||
),
|
||||
);
|
||||
final response = await request.close();
|
||||
final body = await response.transform(utf8.decoder).join();
|
||||
final targets = jsonDecode(body) as List<dynamic>;
|
||||
final page = targets.cast<Map<String, dynamic>>().firstWhere(
|
||||
(target) => target['type'] == 'page',
|
||||
);
|
||||
return page['webSocketDebuggerUrl'] as String;
|
||||
} finally {
|
||||
client.close(force: true);
|
||||
}
|
||||
}
|
||||
|
||||
String? _argument(List<String> arguments, String name) {
|
||||
final index = arguments.indexOf(name);
|
||||
if (index < 0 || index + 1 >= arguments.length) return null;
|
||||
return arguments[index + 1];
|
||||
}
|
||||
|
||||
class Cdp {
|
||||
Cdp(this._socket) {
|
||||
_socket.listen(_onMessage);
|
||||
}
|
||||
|
||||
final WebSocket _socket;
|
||||
final Map<int, Completer<Map<String, dynamic>>> _pending = {};
|
||||
int _next = 0;
|
||||
|
||||
Future<Map<String, dynamic>> send(
|
||||
String method, [
|
||||
Map<String, dynamic> params = const <String, dynamic>{},
|
||||
]) {
|
||||
final id = ++_next;
|
||||
final completer = Completer<Map<String, dynamic>>();
|
||||
_pending[id] = completer;
|
||||
_socket.add(
|
||||
jsonEncode(<String, dynamic>{
|
||||
'id': id,
|
||||
'method': method,
|
||||
'params': params,
|
||||
}),
|
||||
);
|
||||
return completer.future.timeout(const Duration(seconds: 30));
|
||||
}
|
||||
|
||||
Future<String> evaluate(String expression) async {
|
||||
final reply = await send('Runtime.evaluate', <String, dynamic>{
|
||||
'expression': expression,
|
||||
'returnByValue': true,
|
||||
'awaitPromise': true,
|
||||
});
|
||||
final result = reply['result'] as Map<String, dynamic>;
|
||||
return '${result['result']?['value']}';
|
||||
}
|
||||
|
||||
void _onMessage(dynamic data) {
|
||||
if (data is! String) return;
|
||||
final message = jsonDecode(data) as Map<String, dynamic>;
|
||||
final id = message['id'];
|
||||
if (id is! int) return;
|
||||
final completer = _pending.remove(id);
|
||||
if (completer == null) return;
|
||||
final error = message['error'];
|
||||
if (error != null) {
|
||||
completer.completeError(StateError('$error'));
|
||||
} else {
|
||||
completer.complete(message);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> close() => _socket.close();
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
/// An isolated loopback fixture for the Settings browser probe.
|
||||
///
|
||||
/// It serves the probe's `build/web` output and upgrades `/connect` to a
|
||||
/// websocket that answers `ping` with a deterministic pong (build + time), so
|
||||
/// the screen can be exercised in a real browser without the production server,
|
||||
/// authentication changes or any deployment. It binds loopback on an OS-assigned
|
||||
/// port unless `--port` is given.
|
||||
///
|
||||
/// Usage:
|
||||
/// dart run tool/settings_probe_server.dart --root build/probe_web
|
||||
Future<void> main(List<String> arguments) async {
|
||||
var rootPath = 'build/probe_web';
|
||||
var port = 0;
|
||||
for (var i = 0; i < arguments.length; i++) {
|
||||
if (arguments[i] == '--root' && i + 1 < arguments.length) {
|
||||
rootPath = arguments[++i];
|
||||
} else if (arguments[i] == '--port' && i + 1 < arguments.length) {
|
||||
port = int.parse(arguments[++i]);
|
||||
}
|
||||
}
|
||||
final root = Directory(rootPath).absolute;
|
||||
if (!root.existsSync()) {
|
||||
stderr.writeln('Probe build not found at ${root.path}');
|
||||
exitCode = 2;
|
||||
return;
|
||||
}
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, port);
|
||||
stdout.writeln('http://127.0.0.1:${server.port}/');
|
||||
await for (final request in server) {
|
||||
unawaited(_handle(request, root));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _handle(HttpRequest request, Directory root) async {
|
||||
if (request.uri.path == '/connect' &&
|
||||
WebSocketTransformer.isUpgradeRequest(request)) {
|
||||
final socket = await WebSocketTransformer.upgrade(request);
|
||||
stdout.writeln('connect');
|
||||
socket.listen((data) {
|
||||
if (data is! String) return;
|
||||
final Object? decoded;
|
||||
try {
|
||||
decoded = jsonDecode(data);
|
||||
} on FormatException {
|
||||
return;
|
||||
}
|
||||
if (decoded is! Map<String, dynamic>) return;
|
||||
if (decoded['type'] != 'ping') return;
|
||||
stdout.writeln('ping');
|
||||
socket.add(
|
||||
jsonEncode(<String, dynamic>{
|
||||
'id': decoded['id'],
|
||||
'type': 'pong',
|
||||
'protocol': 1,
|
||||
'build': <String, dynamic>{
|
||||
'version': 'probe-1.2.3',
|
||||
'commit': 'abc1234',
|
||||
},
|
||||
'time': '2026-10-21T12:00:00Z',
|
||||
}),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var relative = request.uri.path;
|
||||
if (relative.isEmpty || relative == '/') relative = '/index.html';
|
||||
final file = File('${root.path}${relative.replaceAll('..', '')}');
|
||||
if (!file.existsSync()) {
|
||||
request.response.statusCode = HttpStatus.notFound;
|
||||
await request.response.close();
|
||||
return;
|
||||
}
|
||||
request.response.headers.contentType = _contentType(relative);
|
||||
request.response.headers.set('Cache-Control', 'no-store');
|
||||
await request.response.addStream(file.openRead());
|
||||
await request.response.close();
|
||||
}
|
||||
|
||||
ContentType _contentType(String path) {
|
||||
final extension = path.split('.').last.toLowerCase();
|
||||
return switch (extension) {
|
||||
'html' => ContentType.html,
|
||||
'js' || 'mjs' => ContentType('text', 'javascript', charset: 'utf-8'),
|
||||
'css' => ContentType('text', 'css', charset: 'utf-8'),
|
||||
'json' || 'map' => ContentType.json,
|
||||
'png' => ContentType('image', 'png'),
|
||||
'svg' => ContentType('image', 'svg+xml'),
|
||||
'ico' => ContentType('image', 'x-icon'),
|
||||
'wasm' => ContentType('application', 'wasm'),
|
||||
'ttf' || 'otf' => ContentType('font', 'ttf'),
|
||||
_ => ContentType.binary,
|
||||
};
|
||||
}
|
||||
|
||||
void unawaited(Future<void> future) {
|
||||
future.catchError((Object error, StackTrace stack) {
|
||||
stderr.writeln('probe server: $error');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } 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 { mkdtemp, rm } from 'node:fs/promises';
|
||||
|
||||
const root = join(process.cwd(), 'build/web');
|
||||
const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' };
|
||||
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.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(), 'f2-shell-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 < 100; 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.method?.includes('detached') || msg.method?.includes('crashed')) console.error('CDP event', JSON.stringify(msg));
|
||||
if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
|
||||
});
|
||||
const send = (method, params = {}, sessionId) => new Promise(resolve => {
|
||||
const callId = ++id; pending.set(callId, resolve);
|
||||
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);
|
||||
const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/` }, 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, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})");
|
||||
if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`);
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
await delay(900);
|
||||
const clickLabel = async label => evaluate(`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === ${JSON.stringify(label)}); if (!e) return false; e.click(); return true; })()`);
|
||||
const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)");
|
||||
if (!labels?.some(x => x.includes('Pipelines'))) throw new Error(`Flutter semantics unavailable: ${JSON.stringify(labels)}`);
|
||||
const capture = async (name, width, height) => {
|
||||
await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session);
|
||||
await delay(350);
|
||||
const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data;
|
||||
await (await import('node:fs/promises')).writeFile(`${process.env.OPENCODE_ARTIFACT_DIR}/${name}.png`, Buffer.from(data, 'base64'));
|
||||
};
|
||||
await capture('f2-shell-phone', 390, 844);
|
||||
for (const label of ['Runs', 'Chat', 'Settings', 'Pipelines']) {
|
||||
if (!await clickLabel(label)) throw new Error(`Could not interact with ${label} navigation`);
|
||||
await delay(250);
|
||||
const current = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)");
|
||||
if (!current?.some(x => x.includes(label + ' — Not implemented'))) throw new Error(`${label} body missing after navigation: ${JSON.stringify(current)}`);
|
||||
if (label === 'Runs' || label === 'Settings') await capture(`f2-shell-phone-${label.toLowerCase()}`, 390, 844);
|
||||
}
|
||||
await capture('f2-shell-desktop', 1280, 800);
|
||||
console.log(JSON.stringify({ labels, captures: ['f2-shell-phone.png', 'f2-shell-phone-runs.png', 'f2-shell-phone-settings.png', 'f2-shell-desktop.png'], navigated: ['Runs', 'Chat', 'Settings', 'Pipelines'] }, 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 });
|
||||
}
|
||||
Reference in New Issue
Block a user