// 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= 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 }); }