ui_probe.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. #!/usr/bin/env node
  2. /**
  3. * 用 Chrome DevTools Protocol 驱动无头浏览器做"真实交互"验证(截图 + 点击)。
  4. *
  5. * node scripts/ui_probe.mjs [--url http://127.0.0.1:8787] [--out .run/ui]
  6. *
  7. * 为什么需要它:SSR 渲染测试覆盖不到"点击 chip → 抽屉 → 跳转到结果行",
  8. * 而这正是架构文档要求的交互。这里用 CDP 真点一遍并截图,产物可直接放进文档。
  9. */
  10. import { spawn, spawnSync } from 'node:child_process';
  11. import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
  12. import path from 'node:path';
  13. const ROOT = path.resolve(import.meta.dirname, '..');
  14. const args = process.argv.slice(2);
  15. const argOf = (name, fallback) => {
  16. const index = args.indexOf(name);
  17. return index >= 0 && args[index + 1] ? args[index + 1] : fallback;
  18. };
  19. const BASE = argOf('--url', 'http://127.0.0.1:8787');
  20. const OUT = path.resolve(ROOT, argOf('--out', '.run/ui'));
  21. const PORT = 9333;
  22. const CHROME_CANDIDATES = [
  23. 'C:/Program Files/Google/Chrome/Application/chrome.exe',
  24. 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
  25. 'C:/Program Files/Microsoft/Edge/Application/msedge.exe',
  26. '/usr/bin/google-chrome',
  27. '/usr/bin/chromium',
  28. ];
  29. function findBrowser() {
  30. for (const candidate of CHROME_CANDIDATES) {
  31. if (existsSync(candidate)) return candidate;
  32. }
  33. return null;
  34. }
  35. const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
  36. class Cdp {
  37. constructor(ws) {
  38. this.ws = ws;
  39. this.id = 0;
  40. this.pending = new Map();
  41. ws.addEventListener('message', (event) => {
  42. const payload = JSON.parse(event.data);
  43. if (payload.id && this.pending.has(payload.id)) {
  44. const { resolve, reject } = this.pending.get(payload.id);
  45. this.pending.delete(payload.id);
  46. payload.error ? reject(new Error(JSON.stringify(payload.error))) : resolve(payload.result);
  47. }
  48. });
  49. }
  50. send(method, params = {}) {
  51. const id = ++this.id;
  52. return new Promise((resolve, reject) => {
  53. this.pending.set(id, { resolve, reject });
  54. this.ws.send(JSON.stringify({ id, method, params }));
  55. setTimeout(() => {
  56. if (this.pending.has(id)) {
  57. this.pending.delete(id);
  58. reject(new Error(`CDP 超时: ${method}`));
  59. }
  60. }, 30000);
  61. });
  62. }
  63. async evaluate(expression) {
  64. const result = await this.send('Runtime.evaluate', {
  65. expression,
  66. awaitPromise: true,
  67. returnByValue: true,
  68. });
  69. if (result.exceptionDetails) throw new Error(result.exceptionDetails.text ?? '页面内异常');
  70. return result.result?.value;
  71. }
  72. async screenshot(file) {
  73. const { data } = await this.send('Page.captureScreenshot', { format: 'png' });
  74. writeFileSync(file, Buffer.from(data, 'base64'));
  75. return file;
  76. }
  77. }
  78. /** 如果服务没起,就自己拉起来(方便 run_tests.ps1 一键跑)。 */
  79. async function ensureServices() {
  80. const healthy = async () => {
  81. try {
  82. const response = await fetch(`${BASE}/api/health`, { signal: AbortSignal.timeout(2000) });
  83. if (!response.ok) return false;
  84. const payload = await response.json();
  85. return Boolean(payload.ok);
  86. } catch {
  87. return false;
  88. }
  89. };
  90. if (await healthy()) return null;
  91. if (!BASE.includes('127.0.0.1:8787') && !BASE.includes('localhost:8787')) {
  92. console.error(`✗ 服务未就绪:${BASE}/api/health(非默认地址时不自动启动)`);
  93. process.exit(1);
  94. }
  95. console.log(' · 服务未启动,自动拉起(node scripts/start.mjs --no-open --skip-install)');
  96. const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'start.mjs'), '--no-open', '--skip-install'], {
  97. cwd: ROOT,
  98. stdio: 'ignore',
  99. detached: false,
  100. });
  101. for (let attempt = 0; attempt < 120; attempt += 1) {
  102. await sleep(1000);
  103. if (await healthy()) return child;
  104. }
  105. console.error('✗ 自动启动超时');
  106. try {
  107. child.kill();
  108. } catch {
  109. /* 忽略 */
  110. }
  111. process.exit(1);
  112. }
  113. /**
  114. * 造一份最小演示数据:工作区 → 上传 samples/small.csv → 处理 → 提一个问题。
  115. * 这样探针在任何机器上都能自给自足(不依赖上一次运行留下的 data/)。
  116. */
  117. async function seedDemoSession() {
  118. const fs = await import('node:fs');
  119. const apiJson = async (pathname, init) => {
  120. const response = await fetch(`${BASE}${pathname}`, init);
  121. const text = await response.text();
  122. if (!response.ok) throw new Error(`${pathname} -> ${response.status} ${text.slice(0, 200)}`);
  123. return text ? JSON.parse(text) : null;
  124. };
  125. let workspace = (await apiJson('/api/workspaces')).items[0];
  126. if (!workspace) {
  127. workspace = await apiJson('/api/workspaces', {
  128. method: 'POST',
  129. headers: { 'Content-Type': 'application/json' },
  130. body: JSON.stringify({ name: '演示工作区' }),
  131. });
  132. }
  133. let files = (await apiJson(`/api/workspaces/${workspace.id}/files`)).items;
  134. if (!files.some((file) => file.kind === 'stat')) {
  135. const samplePath = path.join(ROOT, 'samples', 'small.csv');
  136. if (!existsSync(samplePath)) throw new Error(`缺少样本数据 ${samplePath},请先运行 python scripts/gen_sample_data.py`);
  137. const uploaded = await apiJson(`/api/workspaces/${workspace.id}/files`, {
  138. method: 'POST',
  139. headers: { 'Content-Type': 'application/octet-stream', 'X-Filename': 'small.csv' },
  140. body: fs.readFileSync(samplePath),
  141. });
  142. const run = await apiJson('/api/process', {
  143. method: 'POST',
  144. headers: { 'Content-Type': 'application/json' },
  145. body: JSON.stringify({ workspace_id: workspace.id, input_object_id: uploaded.id, output_name: 'small_统计结果.xlsx' }),
  146. });
  147. for (let attempt = 0; attempt < 300; attempt += 1) {
  148. await sleep(700);
  149. const state = await apiJson(`/api/process/${run.id}`);
  150. if (state.status === 'succeeded' || state.status === 'failed') {
  151. if (state.status !== 'succeeded') throw new Error(`处理失败:${state.error}`);
  152. break;
  153. }
  154. }
  155. }
  156. const session = await apiJson('/api/sessions', {
  157. method: 'POST',
  158. headers: { 'Content-Type': 'application/json' },
  159. body: JSON.stringify({ workspace_id: workspace.id, title: '溯源演示' }),
  160. });
  161. const response = await fetch(`${BASE}/api/sessions/${session.id}/chat`, {
  162. method: 'POST',
  163. headers: { 'Content-Type': 'application/json' },
  164. body: JSON.stringify({ message: '2026 年 3 月 DDR5 的进口额是多少美元?来自哪张表?' }),
  165. });
  166. if (!response.ok) throw new Error(`对话失败 HTTP ${response.status}`);
  167. await response.text();
  168. }
  169. async function main() {
  170. const browser = findBrowser();
  171. if (!browser) {
  172. console.error('✗ 找不到 Chrome/Edge,可手动截图;本脚本已跳过');
  173. process.exit(0);
  174. }
  175. const services = await ensureServices();
  176. mkdirSync(OUT, { recursive: true });
  177. const child = spawn(
  178. browser,
  179. [
  180. '--headless=new',
  181. '--disable-gpu',
  182. '--hide-scrollbars',
  183. '--no-first-run',
  184. '--no-default-browser-check',
  185. `--remote-debugging-port=${PORT}`,
  186. `--user-data-dir=${path.join(OUT, 'profile')}`,
  187. '--window-size=1500,1150',
  188. 'about:blank',
  189. ],
  190. { stdio: 'ignore' },
  191. );
  192. let wsUrl = null;
  193. for (let attempt = 0; attempt < 40 && !wsUrl; attempt += 1) {
  194. await sleep(250);
  195. try {
  196. const targets = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json();
  197. wsUrl = targets.find((item) => item.type === 'page')?.webSocketDebuggerUrl ?? null;
  198. } catch {
  199. /* 还没起来 */
  200. }
  201. }
  202. if (!wsUrl) {
  203. console.error('✗ 浏览器调试端口没有就绪');
  204. child.kill();
  205. process.exit(1);
  206. }
  207. const socket = new WebSocket(wsUrl);
  208. await new Promise((resolve, reject) => {
  209. socket.addEventListener('open', resolve, { once: true });
  210. socket.addEventListener('error', reject, { once: true });
  211. });
  212. const cdp = new Cdp(socket);
  213. await cdp.send('Page.enable');
  214. await cdp.send('Runtime.enable');
  215. // 带一个变化的 query 再挂 hash:保证是"整页重载",而不是同页只改 hash(后者不会重新拉数据)
  216. let navCounter = 0;
  217. const open = async (hash, waitMs = 2500) => {
  218. navCounter += 1;
  219. await cdp.send('Page.navigate', { url: `${BASE}/?ui=${navCounter}#${hash.replace(/^#/, '')}` });
  220. await sleep(waitMs);
  221. };
  222. const results = [];
  223. const shot = async (name) => {
  224. const file = path.join(OUT, `${name}.png`);
  225. await cdp.screenshot(file);
  226. results.push(file);
  227. console.log(` ✓ 截图 ${path.relative(ROOT, file)}`);
  228. };
  229. console.log('1. 打开对话页');
  230. await open('#/chat');
  231. let chipCount = await cdp.evaluate(`document.querySelectorAll('.chip').length`);
  232. if (chipCount === 0) {
  233. console.log(' · 没有历史对话,自动造一份演示数据并问一句');
  234. await seedDemoSession();
  235. await open('#/chat', 4500);
  236. chipCount = await cdp.evaluate(`document.querySelectorAll('.chip').length`);
  237. }
  238. console.log(` 页面上有 ${chipCount} 个溯源 chip`);
  239. await shot('01-chat-chips');
  240. if (chipCount > 0) {
  241. console.log('2. 点击第一个 chip,检查抽屉是否出现');
  242. await cdp.evaluate(`document.querySelector('.chip').click()`);
  243. await sleep(1200);
  244. const drawerText = await cdp.evaluate(`document.querySelector('.drawer')?.innerText ?? ''`);
  245. if (!drawerText.includes('数字溯源')) {
  246. console.error('✗ 抽屉没有打开');
  247. child.kill();
  248. process.exit(1);
  249. }
  250. console.log(' 抽屉内容片段:', drawerText.replace(/\s+/g, ' ').slice(0, 120));
  251. await shot('02-trace-drawer');
  252. console.log('3. 点击"在结果表中查看这一行",检查跳转与高亮');
  253. await cdp.evaluate(`
  254. (() => {
  255. const buttons = [...document.querySelectorAll('.drawer button')];
  256. const target = buttons.find((b) => b.textContent.includes('在结果表中查看'));
  257. if (!target) return 'no-button';
  258. target.click();
  259. return 'clicked';
  260. })()
  261. `);
  262. await sleep(2500);
  263. const highlighted = await cdp.evaluate(`document.querySelectorAll('.data-table tr.highlight').length`);
  264. const modalOpen = await cdp.evaluate(`Boolean(document.querySelector('.modal'))`);
  265. console.log(` 弹窗打开: ${modalOpen},高亮行数: ${highlighted}`);
  266. await shot('03-row-jump');
  267. if (!modalOpen || highlighted < 1) {
  268. console.error('✗ 没有定位到结果行');
  269. child.kill();
  270. process.exit(1);
  271. }
  272. }
  273. console.log('4. 数据处理页');
  274. await open('#/process');
  275. await sleep(1200);
  276. await shot('04-process');
  277. console.log('5. 文件页(含指纹列)');
  278. await open('#/files');
  279. await sleep(1200);
  280. await shot('05-files');
  281. console.log('6. 系统页(两本台账)');
  282. await open('#/system');
  283. await sleep(1500);
  284. await shot('06-system');
  285. socket.close();
  286. child.kill();
  287. try {
  288. spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
  289. } catch {
  290. /* 忽略 */
  291. }
  292. if (services?.pid) {
  293. try {
  294. spawnSync('taskkill', ['/pid', String(services.pid), '/T', '/F'], { stdio: 'ignore' });
  295. } catch {
  296. /* 忽略 */
  297. }
  298. }
  299. console.log(`\n全部交互验证通过,截图在 ${OUT}`);
  300. return results;
  301. }
  302. main()
  303. .then(() => process.exit(0))
  304. .catch((error) => {
  305. console.error('✗ UI 探针失败:', error.message);
  306. process.exit(1);
  307. });