Merge branch 'main' into flutter/f4-chat

This commit is contained in:
2026-10-21 17:42:42 +01:00
225 changed files with 28552 additions and 160 deletions
+24
View File
@@ -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.
+202
View File
@@ -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; });
}
+423
View File
@@ -0,0 +1,423 @@
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')) {
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'));
// 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 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}`);
}
+8
View File
@@ -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();
+410
View File
@@ -0,0 +1,410 @@
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 === '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();
}),
};
}
+252
View File
@@ -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 });
}
+110
View File
@@ -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();
}
+190
View File
@@ -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',
},
},
];
+246
View File
@@ -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 });
}
+71
View File
@@ -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.
}),
);
});
}
}
}
+318
View File
@@ -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();
}
+103
View File
@@ -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');
});
}
+94
View File
@@ -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 });
}