/** * Opt-in live MODEL evaluation of multi-step browser tasks. Not a unit test and not part of CI. * * A real model drives the production browser MCP entry (list_tools / call_tool) against a real * headless Chrome through the browser runtime, on local fixture pages served by this script. * A = the browser tool layer at --baseline-ref; C = the current working tree. * Every run gets fresh random answers, variants are interleaved, and every run is kept (no picking). * Reported per variant and task: pass rate, model turns, browser tool calls, cost, wall time. * * The model is driven by the local `claude` CLI in print mode with its own sign-in; this script * reads no credentials. Each run costs real usage, so it only starts with --live. * * Usage: * node --import tsx scripts/eval-browser-tasks.mjs --live --baseline-ref origin/main \ * [--model claude-sonnet-5-5] [--repeats 3] [--only form,vault] [--variants A,C] [--parallel 3] * node --import tsx scripts/eval-browser-tasks.mjs --check * No model and no usage: drives batch and cdp through the MCP entry on the same real browser and * fixture pages, and fails if a result is wrong. Run it after touching either action. * node --import tsx scripts/eval-browser-tasks.mjs --serve * Only serves the fixture pages and prints their address, one run id and its answers, for trying * the sidebar and "My browser" by hand from a running Cindy. /__state?run= shows what the * pages recorded. * * Limits: the dedicated-browser runtime only (no sidebar, no "My browser"), fixture pages rather * than real sites, one harness (Claude Code print mode with only the browser tools). Results are * evidence for the changed paths, not a general success rate. */ import fs from 'node:fs/promises'; import { appendFileSync, readFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import net from 'node:net'; import { createServer as createHttpServer } from 'node:http'; import { execFileSync, spawn } from 'node:child_process'; import { randomBytes, randomInt } from 'node:crypto'; import { parseArgs } from 'node:util'; import { fileURLToPath, pathToFileURL } from 'node:url'; const { values } = parseArgs({ options: { live: { type: 'boolean' }, mcp: { type: 'boolean' }, check: { type: 'boolean' }, serve: { type: 'boolean' }, 'baseline-ref': { type: 'string' }, model: { type: 'string', default: 'claude-sonnet-5-5' }, repeats: { type: 'string', default: '3' }, only: { type: 'string' }, variants: { type: 'string', default: 'A,C' }, parallel: { type: 'string', default: '3' }, variant: { type: 'string' }, 'runtime-dir': { type: 'string' }, trace: { type: 'string' }, 'cdp-port': { type: 'string' }, } }); const root = fileURLToPath(new URL('..', import.meta.url)); const browserDir = 'packages/lizi-mcps/src/browser'; // --------------------------------------------------------------------------------------------- // MCP child: one variant of the production browser MCP server over stdio, on its own headless Chrome. // --------------------------------------------------------------------------------------------- if (values.mcp) { process.env.XDT_BROWSER_RUNTIME_DIR = values['runtime-dir']; const { createServer } = await import('vite'); const { StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js'); const baseline = new Map(); if (values.variant === 'A') { const changed = execFileSync('git', ['diff', '--name-only', values['baseline-ref'], '--', browserDir], { cwd: root, encoding: 'utf8' }) .split('\n').filter(Boolean); for (const file of changed) { try { baseline.set(path.join(root, file), execFileSync('git', ['show', `${values['baseline-ref']}:${file}`], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })); } catch { /* New in the working tree: the baseline never imports it. */ } } } const vite = await createServer({ root, configFile: false, logLevel: 'silent', appType: 'custom', optimizeDeps: { noDiscovery: true, include: [], entries: [] }, server: { middlewareMode: true, watch: null, hmr: false, ws: false }, ssr: { noExternal: [/^@cindy\//, /^@jackwener\//] }, plugins: [{ name: 'evaluation-baseline-source', enforce: 'pre', load(id) { const [file, query] = id.split('?'); if (!baseline.has(file)) return undefined; return query === 'raw' ? `export default ${JSON.stringify(baseline.get(file))}` : baseline.get(file); } }], }); const { createBrowserMcpServer } = await vite.ssrLoadModule(`/${browserDir}/server.ts`); const { createBrowserControlRuntime } = await import(pathToFileURL(path.join(root, 'packages/browser-control-runtime/src/runtime.ts')).href); const runtime = createBrowserControlRuntime({ config: { browser: { enabled: true, headless: true, defaultProfile: 'eval', profiles: { eval: { cdpPort: Number(values['cdp-port']), color: '#00D9C5' } }, ssrfPolicy: { dangerouslyAllowPrivateNetwork: true } } }, logSink: () => {}, }); const traced = { call: async (request) => { const started = performance.now(); const result = await runtime.call(request); appendFileSync(values.trace, `${JSON.stringify({ action: request.action, kind: request.request?.kind, method: request.recipeCommand?.method, ok: result.ok, ms: Math.round(performance.now() - started) })}\n`); return result; } }; await runtime.call({ action: 'start' }); const server = createBrowserMcpServer({ getRuntime: () => traced, getBackendKind: () => 'external', resolveScreenshot: async (result) => { const data = result.data ?? {}; const buffer = typeof data.data === 'string' ? Buffer.from(data.data, 'base64') : await fs.readFile(data.path); return { buffer, mimeType: buffer[0] === 0xff ? 'image/jpeg' : 'image/png' }; }, }); let closing = false; const shutdown = async () => { if (closing) return; closing = true; await runtime.call({ action: 'stop' }).catch(() => {}); await vite.close().catch(() => {}); process.exit(0); }; process.stdin.on('end', shutdown); process.stdin.on('close', shutdown); process.on('SIGTERM', shutdown); process.on('SIGINT', shutdown); await server.connect(new StdioServerTransport()); await new Promise(() => {}); } // --------------------------------------------------------------------------------------------- // Driver // --------------------------------------------------------------------------------------------- const repeats = Number(values.repeats); const parallel = Number(values.parallel); if (!values.check && !values.serve && (!values.live || !values['baseline-ref'] || !Number.isInteger(repeats) || repeats < 1 || !Number.isInteger(parallel) || parallel < 1)) { throw new Error('Require --check, --serve, or --live with --baseline-ref and positive --repeats / --parallel'); } const variants = values.variants.split(','); if (variants.some((variant) => !['A', 'C'].includes(variant))) throw new Error('Invalid --variants'); const token = (prefix) => `${prefix}-${randomBytes(4).toString('hex').toUpperCase()}`; const page = (title, body) => `${title}

${title}

${body}`; const PRODUCTS = ['Alpha Lamp', 'Birch Stool', 'Cobalt Desk', 'Dune Rug', 'Echo Chair', 'Fern Planter', 'Garnet Shelf', 'Harbor Clock']; const PEOPLE = ['Abara', 'Bianchi', 'Castillo', 'Dvorak', 'Eriksen', 'Fontaine', 'Gupta', 'Haddad', 'Ivanov', 'Jensen', 'Kowalski', 'Lindqvist', 'Moreau', 'Nakamura', 'Okafor', 'Petrov', 'Quintero', 'Rossi', 'Sato', 'Tanaka', 'Usman', 'Varga', 'Weber', 'Xu', 'Yilmaz', 'Zhou']; /** Per-run answers and what the pages recorded; the checks read only this and the final reply. */ const runs = new Map(); function newRun() { const id = randomBytes(6).toString('hex'); const refundedIndex = 18 + randomInt(6); // page 4 of 5 const state = { id, form: { note: token('NOTE'), code: token('CONF'), submitted: null }, skus: Object.fromEntries(PRODUCTS.map((name) => [name, token('SKU')])), orders: Array.from({ length: 30 }, (_, index) => ({ id: token('ORD'), amount: `${randomInt(20, 900)}.${String(randomInt(100)).padStart(2, '0')}`, status: index === refundedIndex ? 'REFUNDED' : ['PAID', 'SHIPPED', 'PENDING'][index % 3] })), vault: token('VAULT'), badge: { employee: `E-${randomInt(10000, 99999)}`, pin: String(randomInt(1000, 9999)), code: token('BADGE'), submitted: null }, report: `${randomInt(10, 99)},${String(randomInt(1000)).padStart(3, '0')}`, settings: { receipt: token('RCPT'), saved: null }, support: token('SUP'), extensions: Object.fromEntries(PEOPLE.map((name) => [name, String(randomInt(2000, 9999))])), }; runs.set(id, state); return state; } function readBody(req) { return new Promise((resolve) => { let data = ''; req.on('data', (chunk) => { data += chunk; }); req.on('end', () => resolve(data)); }); } async function handle(req, res, ports) { const url = new URL(req.url, 'http://fixture'); const state = runs.get(url.searchParams.get('run') ?? ''); const send = (body, type = 'text/html; charset=utf-8', status = 200) => { res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' }); res.end(body); }; if (!state) return send('unknown run', 'text/plain', 404); const q = `run=${state.id}`; if (values.serve && url.pathname === '/__state') return send(JSON.stringify(state), 'application/json'); switch (url.pathname) { case '/form': return send(page('Create account', `
Region${['EU', 'US', 'APAC'].map((region) => ``).join('')}
`)); case '/form/submit': { state.form.submitted = Object.fromEntries(new URLSearchParams(await readBody(req))); return send(page('Account created', `

Thanks, ${state.form.submitted.name ?? ''}. Your confirmation code is ${state.form.code}.

`)); } case '/catalog': return send(page('Catalog', ``)); case '/product': { const name = PRODUCTS[Number(url.searchParams.get('p'))]; if (!name) return send('no such product', 'text/plain', 404); return send(page(name, `
SKU
${state.skus[name]}
Stock
${randomInt(1, 60)} units

Back to catalog

`)); } case '/orders': return send(page('Orders', `
OrderAmountStatus

`)); case '/orders/data': { const pageNo = Math.max(1, Math.min(5, Number(url.searchParams.get('page')) || 1)); return send(JSON.stringify(state.orders.slice((pageNo - 1) * 6, pageNo * 6)), 'application/json'); } case '/vault': return send(page('Vault', `

The access code is shown after pressing the button in the panel below.

`)); case '/vault.js': return send(`customElements.define('vault-box', class extends HTMLElement { connectedCallback() { const root = this.attachShadow({ mode: 'closed' }); root.innerHTML = '

'; root.querySelector('button').addEventListener('click', async (event) => { if (!event.isTrusted) return; const reply = await fetch('/vault/code?${q}', { method: 'POST' }); root.querySelector('p').textContent = 'Access code: ' + await reply.text(); }); } });`, 'text/javascript'); case '/vault/code': return req.method === 'POST' ? send(state.vault, 'text/plain') : send('method not allowed', 'text/plain', 405); case '/badge': return send(page('Badge desk', `

Fill in the panel below to issue a visitor badge.

`)); case '/badge.js': return send(`customElements.define('badge-form', class extends HTMLElement { connectedCallback() { const root = this.attachShadow({ mode: 'closed' }); root.innerHTML = '

'; root.querySelector('button').addEventListener('click', async (event) => { if (!event.isTrusted) return; const body = { employee: root.querySelector('#employee').value, pin: root.querySelector('#pin').value }; const reply = await fetch('/badge/issue?${q}', { method: 'POST', body: JSON.stringify(body) }); root.querySelector('p').textContent = await reply.text(); }); } });`, 'text/javascript'); case '/badge/issue': { state.badge.submitted = JSON.parse(await readBody(req) || '{}'); const ok = state.badge.submitted.employee === state.badge.employee && state.badge.submitted.pin === state.badge.pin; return send(ok ? `Badge issued: ${state.badge.code}` : 'Rejected: employee ID or PIN does not match.', 'text/plain'); } case '/report': return send(page('Quarterly report', `

`)); case '/report/data': return setTimeout(() => send(state.report, 'text/plain'), 2500); case '/settings': return send(page('Workspace', `

`)); case '/settings/save': state.settings.saved = JSON.parse(await readBody(req) || '{}'); return send(state.settings.receipt, 'text/plain'); case '/embed': return send(page('Help center', `

Your support panel is embedded below.

`)); case '/panel': return send(page('Support panel', `

Support code: ${state.support}

`)); case '/directory': return send(page('Staff directory', ` `)); case '/directory/search': { const needle = (url.searchParams.get('q') ?? '').toLowerCase(); return send(JSON.stringify(needle.length < 2 ? [] : PEOPLE.filter((name) => name.toLowerCase().includes(needle)).map((name) => ({ name, ext: state.extensions[name] }))), 'application/json'); } default: return send('not found', 'text/plain', 404); } } const listen = (server) => new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server.address().port))); const freePort = async () => { const probe = net.createServer(); const port = await listen(probe); await new Promise((resolve) => probe.close(resolve)); return port; }; const ports = {}; const servers = [createHttpServer((req, res) => handle(req, res, ports).catch(() => { res.statusCode = 500; res.end(); })), createHttpServer((req, res) => handle(req, res, ports).catch(() => { res.statusCode = 500; res.end(); }))]; ports.main = await listen(servers[0]); ports.frame = await listen(servers[1]); const base = `http://127.0.0.1:${ports.main}`; /** What each task asks and how it is judged. `sequence` marks the paths this change targets; the rest are controls. */ const TASKS = [ { id: 'form', focus: 'sequence', prompt: (s) => `打开 ${base}/form?run=${s.id} ,用下面的信息填表并提交:姓名 Ada Lovelace,邮箱 ada@example.test,套餐 Team,席位 7,地区 APAC,勾选订阅产品更新,备注填 ${s.form.note}。然后告诉我提交后页面显示的确认码。`, check: (s, final) => final.includes(s.form.code) && !!s.form.submitted && s.form.submitted.name === 'Ada Lovelace' && s.form.submitted.email === 'ada@example.test' && s.form.submitted.plan === 'Team' && s.form.submitted.seats === '7' && s.form.submitted.region === 'APAC' && s.form.submitted.newsletter === 'yes' && s.form.submitted.notes === s.form.note }, { id: 'catalog', focus: 'sequence', prompt: (s) => `打开 ${base}/catalog?run=${s.id} ,查出 Alpha Lamp、Cobalt Desk、Echo Chair、Garnet Shelf 这四件商品各自的 SKU(SKU 只在商品详情页上),列给我。`, check: (s, final) => ['Alpha Lamp', 'Cobalt Desk', 'Echo Chair', 'Garnet Shelf'].every((name) => final.includes(s.skus[name])) }, { id: 'orders', focus: 'sequence', prompt: (s) => `打开 ${base}/orders?run=${s.id} ,订单表分 5 页。找出状态是 REFUNDED 的那一单,告诉我订单号和金额。`, check: (s, final) => { const order = s.orders.find((item) => item.status === 'REFUNDED'); return final.includes(order.id) && final.includes(order.amount); } }, { id: 'report', focus: 'sequence', prompt: (s) => `打开 ${base}/report?run=${s.id} ,生成报告,告诉我报告里的 Total 是多少。`, check: (s, final) => final.includes(s.report) }, { id: 'settings', focus: 'sequence', prompt: (s) => `打开 ${base}/settings?run=${s.id} ,从 More 菜单进入通知设置:关掉 Email notifications,打开 Weekly digest,Frequency 改成 Monthly,保存。告诉我保存后显示的回执号。`, check: (s, final) => final.includes(s.settings.receipt) && !!s.settings.saved && s.settings.saved.email === false && s.settings.saved.digest === true && s.settings.saved.sms === false && s.settings.saved.frequency === 'Monthly' }, { id: 'vault', focus: 'escape-hatch', prompt: (s) => `打开 ${base}/vault?run=${s.id} ,按页面上的按钮显示访问码,告诉我访问码是多少。`, check: (s, final) => final.includes(s.vault) }, { id: 'badge', focus: 'escape-hatch', prompt: (s) => `打开 ${base}/badge?run=${s.id} ,在页面的面板里把 Employee ID 填成 ${s.badge.employee}、Door PIN 填成 ${s.badge.pin},点 Issue badge,告诉我页面显示的 badge 编号。`, check: (s, final) => final.includes(s.badge.code) && s.badge.submitted?.employee === s.badge.employee && s.badge.submitted?.pin === s.badge.pin }, { id: 'iframe', focus: 'control', prompt: (s) => `打开 ${base}/embed?run=${s.id} ,页面里嵌入的支持面板显示的支持码是多少?`, check: (s, final) => final.includes(s.support) }, { id: 'directory', focus: 'control', prompt: (s) => `打开 ${base}/directory?run=${s.id} ,在通讯录里搜索 Okafor,告诉我这个人的分机号。`, check: (s, final) => final.includes(s.extensions.Okafor) }, ].filter((task) => !values.only || values.only.split(',').includes(task.id)); if (!TASKS.length) throw new Error('No tasks selected'); if (values.serve) { const state = newRun(); console.log(JSON.stringify({ base, run: state.id, pages: ['form', 'catalog', 'orders', 'report', 'settings', 'vault', 'badge', 'embed', 'directory'] .map((name) => `${base}/${name}?run=${state.id}`), state: `${base}/__state?run=${state.id}`, answers: state }, null, 2)); await new Promise(() => {}); } const out = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-browser-task-eval-')); // --------------------------------------------------------------------------------------------- // --check: no model. The working tree's batch and cdp against the real browser and fixture pages. // --------------------------------------------------------------------------------------------- if (values.check) { const { Client } = await import('@modelcontextprotocol/sdk/client/index.js'); const { StdioClientTransport } = await import('@modelcontextprotocol/sdk/client/stdio.js'); const trace = path.join(out, 'runtime-trace.jsonl'); await fs.writeFile(trace, ''); const client = new Client({ name: 'browser-task-check', version: '1' }); await client.connect(new StdioClientTransport({ command: process.execPath, args: ['--import', import.meta.resolve('tsx'), fileURLToPath(import.meta.url), '--mcp', '--variant', 'C', '--runtime-dir', path.join(out, 'runtime'), '--trace', trace, '--cdp-port', String(await freePort())], stderr: 'inherit' })); const browser = async (args) => JSON.parse((await client.callTool({ name: 'call_tool', arguments: { name: 'browser', args } })).content[0].text); const state = newRun(); const failures = []; const expect = (name, ok, detail) => { console.log(`${ok ? 'ok ' : 'FAIL'} ${name}`); if (!ok) failures.push({ name, detail }); }; const nodeId = (listing, label) => Number(listing.split('\n').find((line) => line.includes(label))?.match(/^\[(\d+)\]/)?.[1]); const refOf = (snapshot, label) => snapshot.split('\n').find((line) => line.includes(label))?.match(/\[ref=([^\]]+)\]/)?.[1]; try { const listed = JSON.parse((await client.callTool({ name: 'list_tools', arguments: { category: 'browser' } })).content[0].text); expect('rules are tailored and carry no markers', !listed.rules['browser-workflow'].includes('