import { createServer } from 'node:http'; import { readFile } from 'node:fs/promises'; import { spawn } from 'node:child_process'; import { once } from 'node:events'; import { setTimeout as delay } from 'node:timers/promises'; import { join, extname, resolve, sep } from 'node:path'; import { tmpdir } from 'node:os'; import { mkdir, mkdtemp, rm } from 'node:fs/promises'; const root = resolve(process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/web')); const variant = process.env.PROBE_VARIANT ?? 'material'; const artifactDir = process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'chat-sessions-capture'); await mkdir(artifactDir, { recursive: true }); const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' }; const server = createServer(async (req, res) => { try { const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end(); const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path; const file = await readFile(filePath); res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); } catch { res.writeHead(404).end('not found'); } }); server.listen(0, '127.0.0.1'); await once(server, 'listening'); const port = server.address().port; const profile = await mkdtemp(join(tmpdir(), 'chat-sessions-chrome-')); const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [ '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', ], { stdio: ['ignore', 'ignore', 'pipe'] }); let stderr = ''; chrome.stderr.on('data', data => { stderr += data; }); const waitFor = async fn => { for (let i = 0; i < 100; i++) { const value = await fn(); if (value) return value; await delay(100); } throw new Error('Timed out waiting for Chrome DevTools'); }; let ws; try { const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); ws = new WebSocket(endpoint); await once(ws, 'open'); let id = 0; const pending = new Map(); ws.addEventListener('message', event => { const msg = JSON.parse(event.data); if (msg.method?.includes('detached') || msg.method?.includes('crashed')) console.error('CDP event', JSON.stringify(msg)); if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } }); const send = (method, params = {}, sessionId) => new Promise(resolve => { const callId = ++id; pending.set(callId, resolve); ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); }); const created = await send('Target.createTarget', { url: 'about:blank' }); if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`); const target = created.result.targetId; const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; await send('Page.enable', {}, session); await send('Runtime.enable', {}, session); const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/` }, session); if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); const evaluate = async expression => { const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session); if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); return response.result?.result?.value; }; await delay(3500); const loaded = await evaluate("({url:location.href, ready:document.readyState, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})"); if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); await delay(2500); const clickLabel = async label => { const point = await evaluate(`(() => { const needle = ${JSON.stringify(label)}; const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === needle); if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`); if (!point) return false; await send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); return true; }; const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)"); if (!labels?.some(x => x.includes('New chat'))) throw new Error(`Chat fixture semantics unavailable: ${JSON.stringify(labels)}`); if (process.env.PROBE_DEBUG) console.log(JSON.stringify(labels)); const capture = async (name, width, height) => { await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session); await delay(350); const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; await (await import('node:fs/promises')).writeFile(`${artifactDir}/${variant}-${name}.png`, Buffer.from(data, 'base64')); }; await capture('chat-sessions-desktop', 1280, 800); await capture('chat-sessions-phone', 390, 844); if (!await clickLabel('New chat')) throw new Error('Could not open create dialog'); await delay(600); await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 195, y: 680, deltaY: 598 }, session); await delay(350); const changedBody = await evaluate('document.body.innerText'); await capture('chat-sessions-create-dialog', 390, 844); if (!changedBody.includes('Server directory') || !changedBody.includes('Backend') || !changedBody.includes('New chats use the server default model.')) throw new Error(`Create dialog did not change rendered body to catalog controls: ${changedBody}`); if (!await clickLabel('Cancel')) throw new Error('Could not close create dialog'); await delay(600); if (!await clickLabel('Chat actions for Open fixture')) throw new Error('Could not open row actions'); await delay(600); const actionsBody = await evaluate('document.body.innerText'); const actionLabels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || x.innerText || '').filter(Boolean)"); await capture('chat-sessions-actions', 390, 844); if (!actionLabels.some(label => label.includes('Rename…'))) throw new Error(`Row actions unavailable: ${actionsBody} / ${actionLabels}`); console.log(JSON.stringify({ variant, labels, captures: [`${variant}-chat-sessions-desktop.png`, `${variant}-chat-sessions-phone.png`, `${variant}-chat-sessions-create-dialog.png`, `${variant}-chat-sessions-actions.png`], bodyChanged: true }, null, 2)); } finally { ws?.close(); chrome.kill('SIGTERM'); await Promise.race([once(chrome, 'exit'), delay(3000)]); server.close(); await rm(profile, { recursive: true, force: true }); }