#!/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); } 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'); const open = async (hash, waitMs = 2500) => { await cdp.send('Page.navigate', { url: `${BASE}/${hash}` }); 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'); const 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); });