#!/usr/bin/env node /** * 用 Chrome DevTools Protocol 驱动无头浏览器做"真实交互"验证(截图 + 点击)。 * * node scripts/ui_probe.mjs [--url http://127.0.0.1:8787] [--out .run/ui] * * 为什么需要它:SSR 渲染测试覆盖不到"点击 chip → 抽屉 → 跳转到结果行", * 而这正是架构文档要求的交互。这里用 CDP 真点一遍并截图,产物可直接放进文档。 */ import { spawn, spawnSync } from 'node:child_process'; import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; import path from 'node:path'; const ROOT = path.resolve(import.meta.dirname, '..'); const args = process.argv.slice(2); const argOf = (name, fallback) => { const index = args.indexOf(name); return index >= 0 && args[index + 1] ? args[index + 1] : fallback; }; const BASE = argOf('--url', 'http://127.0.0.1:8787'); const OUT = path.resolve(ROOT, argOf('--out', '.run/ui')); const PORT = 9333; const CHROME_CANDIDATES = [ 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', 'C:/Program Files/Microsoft/Edge/Application/msedge.exe', '/usr/bin/google-chrome', '/usr/bin/chromium', ]; function findBrowser() { for (const candidate of CHROME_CANDIDATES) { if (existsSync(candidate)) return candidate; } return null; } const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); class Cdp { constructor(ws) { this.ws = ws; this.id = 0; this.pending = new Map(); ws.addEventListener('message', (event) => { const payload = JSON.parse(event.data); if (payload.id && this.pending.has(payload.id)) { const { resolve, reject } = this.pending.get(payload.id); this.pending.delete(payload.id); payload.error ? reject(new Error(JSON.stringify(payload.error))) : resolve(payload.result); } }); } send(method, params = {}) { const id = ++this.id; return new Promise((resolve, reject) => { this.pending.set(id, { resolve, reject }); this.ws.send(JSON.stringify({ id, method, params })); setTimeout(() => { if (this.pending.has(id)) { this.pending.delete(id); reject(new Error(`CDP 超时: ${method}`)); } }, 30000); }); } async evaluate(expression) { const result = await this.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true, }); if (result.exceptionDetails) throw new Error(result.exceptionDetails.text ?? '页面内异常'); return result.result?.value; } async screenshot(file) { const { data } = await this.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(file, Buffer.from(data, 'base64')); return file; } } /** 如果服务没起,就自己拉起来(方便 run_tests.ps1 一键跑)。 */ async function ensureServices() { const healthy = async () => { try { const response = await fetch(`${BASE}/api/health`, { signal: AbortSignal.timeout(2000) }); if (!response.ok) return false; const payload = await response.json(); return Boolean(payload.ok); } catch { return false; } }; if (await healthy()) return null; if (!BASE.includes('127.0.0.1:8787') && !BASE.includes('localhost:8787')) { console.error(`✗ 服务未就绪:${BASE}/api/health(非默认地址时不自动启动)`); process.exit(1); } console.log(' · 服务未启动,自动拉起(node scripts/start.mjs --no-open --skip-install)'); const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'start.mjs'), '--no-open', '--skip-install'], { cwd: ROOT, stdio: 'ignore', detached: false, }); for (let attempt = 0; attempt < 120; attempt += 1) { await sleep(1000); if (await healthy()) return child; } console.error('✗ 自动启动超时'); try { child.kill(); } catch { /* 忽略 */ } process.exit(1); } /** * 造一份最小演示数据:工作区 → 上传 samples/small.csv → 处理 → 提一个问题。 * 这样探针在任何机器上都能自给自足(不依赖上一次运行留下的 data/)。 */ async function seedDemoSession() { const fs = await import('node:fs'); const apiJson = async (pathname, init) => { const response = await fetch(`${BASE}${pathname}`, init); const text = await response.text(); if (!response.ok) throw new Error(`${pathname} -> ${response.status} ${text.slice(0, 200)}`); return text ? JSON.parse(text) : null; }; let workspace = (await apiJson('/api/workspaces')).items[0]; if (!workspace) { workspace = await apiJson('/api/workspaces', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: '演示工作区' }), }); } let files = (await apiJson(`/api/workspaces/${workspace.id}/files`)).items; if (!files.some((file) => file.kind === 'stat')) { const samplePath = path.join(ROOT, 'samples', 'small.csv'); if (!existsSync(samplePath)) throw new Error(`缺少样本数据 ${samplePath},请先运行 python scripts/gen_sample_data.py`); const uploaded = await apiJson(`/api/workspaces/${workspace.id}/files`, { method: 'POST', headers: { 'Content-Type': 'application/octet-stream', 'X-Filename': 'small.csv' }, body: fs.readFileSync(samplePath), }); const run = await apiJson('/api/process', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ workspace_id: workspace.id, input_object_id: uploaded.id, output_name: 'small_统计结果.xlsx' }), }); for (let attempt = 0; attempt < 300; attempt += 1) { await sleep(700); const state = await apiJson(`/api/process/${run.id}`); if (state.status === 'succeeded' || state.status === 'failed') { if (state.status !== 'succeeded') throw new Error(`处理失败:${state.error}`); break; } } } const session = await apiJson('/api/sessions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ workspace_id: workspace.id, title: '溯源演示' }), }); const response = await fetch(`${BASE}/api/sessions/${session.id}/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: '2026 年 3 月 DDR5 的进口额是多少美元?来自哪张表?' }), }); if (!response.ok) throw new Error(`对话失败 HTTP ${response.status}`); await response.text(); } async function main() { const browser = findBrowser(); if (!browser) { console.error('✗ 找不到 Chrome/Edge,可手动截图;本脚本已跳过'); process.exit(0); } const services = await ensureServices(); mkdirSync(OUT, { recursive: true }); const child = spawn( browser, [ '--headless=new', '--disable-gpu', '--hide-scrollbars', '--no-first-run', '--no-default-browser-check', `--remote-debugging-port=${PORT}`, `--user-data-dir=${path.join(OUT, 'profile')}`, '--window-size=1500,1150', 'about:blank', ], { stdio: 'ignore' }, ); let wsUrl = null; for (let attempt = 0; attempt < 40 && !wsUrl; attempt += 1) { await sleep(250); try { const targets = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json(); wsUrl = targets.find((item) => item.type === 'page')?.webSocketDebuggerUrl ?? null; } catch { /* 还没起来 */ } } if (!wsUrl) { console.error('✗ 浏览器调试端口没有就绪'); child.kill(); process.exit(1); } const socket = new WebSocket(wsUrl); await new Promise((resolve, reject) => { socket.addEventListener('open', resolve, { once: true }); socket.addEventListener('error', reject, { once: true }); }); const cdp = new Cdp(socket); await cdp.send('Page.enable'); await cdp.send('Runtime.enable'); // 带一个变化的 query 再挂 hash:保证是"整页重载",而不是同页只改 hash(后者不会重新拉数据) let navCounter = 0; const open = async (hash, waitMs = 2500) => { navCounter += 1; await cdp.send('Page.navigate', { url: `${BASE}/?ui=${navCounter}#${hash.replace(/^#/, '')}` }); await sleep(waitMs); }; const results = []; const shot = async (name) => { const file = path.join(OUT, `${name}.png`); await cdp.screenshot(file); results.push(file); console.log(` ✓ 截图 ${path.relative(ROOT, file)}`); }; console.log('1. 打开对话页'); await open('#/chat'); let chipCount = await cdp.evaluate(`document.querySelectorAll('.chip').length`); if (chipCount === 0) { console.log(' · 没有历史对话,自动造一份演示数据并问一句'); await seedDemoSession(); await open('#/chat', 4500); chipCount = await cdp.evaluate(`document.querySelectorAll('.chip').length`); } console.log(` 页面上有 ${chipCount} 个溯源 chip`); await shot('01-chat-chips'); if (chipCount > 0) { console.log('2. 点击第一个 chip,检查抽屉是否出现'); await cdp.evaluate(`document.querySelector('.chip').click()`); await sleep(1200); const drawerText = await cdp.evaluate(`document.querySelector('.drawer')?.innerText ?? ''`); if (!drawerText.includes('数字溯源')) { console.error('✗ 抽屉没有打开'); child.kill(); process.exit(1); } console.log(' 抽屉内容片段:', drawerText.replace(/\s+/g, ' ').slice(0, 120)); await shot('02-trace-drawer'); console.log('3. 点击"在结果表中查看这一行",检查跳转与高亮'); await cdp.evaluate(` (() => { const buttons = [...document.querySelectorAll('.drawer button')]; const target = buttons.find((b) => b.textContent.includes('在结果表中查看')); if (!target) return 'no-button'; target.click(); return 'clicked'; })() `); await sleep(2500); const highlighted = await cdp.evaluate(`document.querySelectorAll('.data-table tr.highlight').length`); const modalOpen = await cdp.evaluate(`Boolean(document.querySelector('.modal'))`); console.log(` 弹窗打开: ${modalOpen},高亮行数: ${highlighted}`); await shot('03-row-jump'); if (!modalOpen || highlighted < 1) { console.error('✗ 没有定位到结果行'); child.kill(); process.exit(1); } } console.log('4. 数据处理页'); await open('#/process'); await sleep(1200); await shot('04-process'); console.log('5. 文件页(含指纹列)'); await open('#/files'); await sleep(1200); await shot('05-files'); console.log('6. 系统页(两本台账)'); await open('#/system'); await sleep(1500); await shot('06-system'); socket.close(); child.kill(); try { spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }); } catch { /* 忽略 */ } if (services?.pid) { try { spawnSync('taskkill', ['/pid', String(services.pid), '/T', '/F'], { stdio: 'ignore' }); } catch { /* 忽略 */ } } console.log(`\n全部交互验证通过,截图在 ${OUT}`); return results; } main() .then(() => process.exit(0)) .catch((error) => { console.error('✗ UI 探针失败:', error.message); process.exit(1); });