Files
pipelines/app/tool/shell_probe.mjs
T

95 lines
5.9 KiB
JavaScript

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