Files
pipelines/app/tool/graph_zoom_probe.mjs
T

373 lines
13 KiB
JavaScript

// Real-browser acceptance for the graph viewport (pan, zoom, expanded).
//
// Serves the probe build (`flutter build web -t tool/graph_zoom_probe.dart`) on
// an OS-assigned loopback port, drives a real headless Chrome against the
// actual DefinitionGraphView / RunGraphView, and asserts that a drag pans, a
// wheel zooms, Fit restores the fitted scale, Expand opens the same canvas with
// the selected node, and Close returns to the previous place and selection.
//
// PROBE_VARIANT=material|cupertino PROBE_VIEW=pipeline|run \
// PROBE_SCHEME=dark|light PROBE_SCALE=1|2 PROBE_WIDTH=1280 PROBE_HEIGHT=800 \
// PROBE_WEB_ROOT=<probe build> OPENCODE_ARTIFACT_DIR=<dir> \
// node tool/graph_zoom_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/probe-graph-zoom'),
);
const variant = process.env.PROBE_VARIANT ?? 'material';
const view = process.env.PROBE_VIEW ?? 'pipeline';
const scheme = process.env.PROBE_SCHEME ?? 'dark';
const scale = process.env.PROBE_SCALE ?? '1';
const width = Number(process.env.PROBE_WIDTH ?? 1280);
const height = Number(process.env.PROBE_HEIGHT ?? 800);
const artifactDir =
process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'graph-zoom-capture');
const chromePath =
process.env.CHROME_PATH ??
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const title = view === 'run' ? 'Run graph' : 'Pipeline graph';
const prefix = `${view}-${variant}-${scheme}-${scale}x-${width}x${height}`;
const mime = {
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.wasm': 'application/wasm',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.otf': 'font/otf',
'.ttf': 'font/ttf',
};
await mkdir(artifactDir, { recursive: true });
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-zoom-chrome-'));
const chrome = spawn(
chromePath,
[
'--headless=new',
'--no-first-run',
'--no-default-browser-check',
'--disable-gpu',
'--remote-debugging-port=0',
`--user-data-dir=${profile}`,
'about:blank',
],
{ stdio: ['ignore', 'ignore', 'pipe'] },
);
let stderr = '';
chrome.stderr.on('data', (data) => {
stderr += data;
});
const waitFor = async (fn) => {
for (let i = 0; i < 120; i++) {
const value = await fn();
if (value) return value;
await delay(100);
}
throw new Error('Timed out waiting for Chrome DevTools');
};
let ws;
try {
const endpoint = await waitFor(() =>
stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1],
);
ws = new WebSocket(endpoint);
await once(ws, 'open');
let id = 0;
const pending = new Map();
ws.addEventListener('message', (event) => {
const msg = JSON.parse(event.data);
if (msg.id && pending.has(msg.id)) {
pending.get(msg.id)(msg);
pending.delete(msg.id);
}
});
const send = (method, params = {}, sessionId) =>
new Promise((done) => {
const callId = ++id;
pending.set(callId, done);
ws.send(
JSON.stringify({
id: callId,
method,
params,
...(sessionId ? { sessionId } : {}),
}),
);
});
const created = await send('Target.createTarget', { url: 'about:blank' });
const target = created.result.targetId;
const session = (
await send('Target.attachToTarget', { targetId: target, flatten: true })
).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
await send(
'Emulation.setEmulatedMedia',
{ features: [{ name: 'prefers-color-scheme', value: scheme }] },
session,
);
const url =
`http://127.0.0.1:${port}/?style=${variant}&view=${view}` +
`&scale=${scale}`;
const navigation = await send('Page.navigate', { url }, session);
if (navigation.error || navigation.result?.errorText) {
throw new Error(JSON.stringify(navigation));
}
await send(
'Emulation.setDeviceMetricsOverride',
{ width, height, deviceScaleFactor: 1, mobile: width < 600 },
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;
};
await delay(4000);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(2000);
const semantics = () =>
evaluate(
"[...document.querySelectorAll('flt-semantics')].map(x=>({label:(x.getAttribute('aria-label')||x.innerText||'').trim(), current:x.getAttribute('aria-current')}))",
);
const nodeAt = (needle) =>
`[...document.querySelectorAll('flt-semantics')].find(x => { const l=(x.getAttribute('aria-label')||x.innerText||'').trim(); return l === ${JSON.stringify(needle)} || l.startsWith(${JSON.stringify(needle + ' ')}) || l.startsWith(${JSON.stringify(needle + '\n')}); })`;
const rectOf = async (needle) =>
evaluate(
`(() => { const e=${nodeAt(needle)}; if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()`,
);
const clickLabel = async (label, startsWith = false) => {
const point = await evaluate(
`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => { const l=(x.getAttribute('aria-label')||x.innerText||'').trim(); return ${startsWith ? `l.startsWith(${JSON.stringify(label)})` : `l === ${JSON.stringify(label)}`}; }); if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`,
);
if (!point) throw new Error(`No semantics control ${label}`);
await send(
'Input.dispatchMouseEvent',
{ type: 'mousePressed', ...point, button: 'left', clickCount: 1 },
session,
);
await send(
'Input.dispatchMouseEvent',
{ type: 'mouseReleased', ...point, button: 'left', clickCount: 1 },
session,
);
await delay(700);
};
// Activates the control through its own semantics DOM element, the path a
// screen reader uses. A labelled node without a tap action does nothing.
const semanticsClick = async (label) => {
const clicked = await evaluate(
`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => { const l=(x.getAttribute('aria-label')||x.innerText||'').trim(); return l === ${JSON.stringify(label)}; }); if (!e) return false; e.click(); return true; })()`,
);
if (!clicked) throw new Error(`No semantics control ${label}`);
await delay(700);
};
const drag = async (start, dx, dy) => {
await send(
'Input.dispatchMouseEvent',
{ type: 'mousePressed', ...start, button: 'left', buttons: 1, clickCount: 1 },
session,
);
for (let step = 1; step <= 8; step += 1) {
await send(
'Input.dispatchMouseEvent',
{
type: 'mouseMoved',
x: start.x + (dx * step) / 8,
y: start.y + (dy * step) / 8,
button: 'left',
buttons: 1,
},
session,
);
await delay(30);
}
await send(
'Input.dispatchMouseEvent',
{
type: 'mouseReleased',
x: start.x + dx,
y: start.y + dy,
button: 'left',
clickCount: 1,
},
session,
);
await delay(500);
};
const wheel = async (point, deltaY) => {
await send(
'Input.dispatchMouseEvent',
{ type: 'mouseWheel', ...point, deltaX: 0, deltaY },
session,
);
await delay(600);
};
const capture = async (name) => {
const data = (
await send(
'Page.captureScreenshot',
{ format: 'png', captureBeyondViewport: false },
session,
)
).result.data;
const file = `${prefix}-${name}.png`;
await writeFile(`${artifactDir}/${file}`, Buffer.from(data, 'base64'));
return file;
};
const currentSelection = async () => {
const items = await semantics();
const current = items.find((item) => item.current === 'true');
if (!current) throw new Error(`No selected node announced: ${JSON.stringify(items)}`);
return current.label;
};
const body = await evaluate('document.body.innerText');
if (!body.includes('Selected: build')) {
throw new Error(`Initial selection missing: ${body}`);
}
const selected = await currentSelection();
if (!selected.startsWith('build')) {
throw new Error(`build is not announced selected: ${selected}`);
}
const initial = await rectOf('build');
if (!initial || initial.width <= 0) throw new Error('build node is not visible');
const captures = [await capture('initial')];
// Pan: a real drag inside the canvas moves the node.
const start = { x: width / 2, y: height * 0.6 };
await drag(start, 80, 40);
const panned = await rectOf('build');
if (
!panned ||
(Math.abs(panned.x - initial.x) < 20 && Math.abs(panned.y - initial.y) < 20)
) {
throw new Error(`Drag did not pan: ${JSON.stringify({ initial, panned })}`);
}
captures.push(await capture('panned'));
if (!(await currentSelection()).startsWith('build')) {
throw new Error('Panning lost the selected node');
}
// Zoom: the host wheel zooms about the pointer.
await wheel(
{ x: panned.x + panned.width / 2, y: panned.y + panned.height / 2 },
-120,
);
const zoomed = await rectOf('build');
if (!zoomed || zoomed.width <= panned.width * 1.05) {
throw new Error(`Wheel did not zoom: ${JSON.stringify({ panned, zoomed })}`);
}
captures.push(await capture('zoomed'));
if (!(await currentSelection()).startsWith('build')) {
throw new Error('Zooming lost the selected node');
}
// Fit restores the fitted scale. This activation goes through the control's
// semantics element, so a labelled button with no tap action fails here (the
// Cupertino regression).
await semanticsClick('Fit graph to view');
const fitted = await rectOf('build');
if (!fitted || Math.abs(fitted.width - initial.width) > initial.width * 0.03) {
throw new Error(`Fit did not restore: ${JSON.stringify({ initial, fitted })}`);
}
captures.push(await capture('fitted'));
// Expanded opens the same canvas with the same selection.
const beforeExpand = await rectOf('build');
await clickLabel('Expand graph');
const expandedBody = await evaluate('document.body.innerText');
if (!expandedBody.includes(title)) {
throw new Error(`Expanded title missing: ${expandedBody}`);
}
const expandedSelection = await currentSelection();
if (!expandedSelection.startsWith('build')) {
throw new Error(`Expanded lost the selection: ${expandedSelection}`);
}
if (!(await rectOf('build'))) {
throw new Error('Expanded canvas did not draw the graph');
}
captures.push(await capture('expanded'));
// Close returns to the inline canvas, selection and place intact.
await clickLabel('Close');
const closedBody = await evaluate('document.body.innerText');
if (closedBody.includes(title)) {
throw new Error(`Expanded presentation stayed open: ${closedBody}`);
}
if (!(await currentSelection()).startsWith('build')) {
throw new Error('Closing the expanded view lost the selected node');
}
const restored = await rectOf('build');
if (
!restored ||
Math.abs(restored.x - beforeExpand.x) > 2 ||
Math.abs(restored.y - beforeExpand.y) > 2
) {
throw new Error(
`Closing did not restore the inline place: ${JSON.stringify({ beforeExpand, restored })}`,
);
}
captures.push(await capture('restored'));
console.log(
JSON.stringify(
{ view, variant, scheme, scale, width, height, initial, panned, zoomed, restored, captures },
null,
2,
),
);
} finally {
if (ws?.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ id: 2147483647, method: 'Browser.close' }));
}
await Promise.race([once(chrome, 'exit'), delay(3000)]);
ws?.close();
if (chrome.exitCode === null) chrome.kill('SIGTERM');
chrome.stderr.destroy();
chrome.unref();
await new Promise((done) => {
server.close(done);
server.closeAllConnections();
});
await rm(profile, { recursive: true, force: true });
}