ui_probe.mjs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. async function main() {
  79. const browser = findBrowser();
  80. if (!browser) {
  81. console.error('✗ 找不到 Chrome/Edge,可手动截图;本脚本已跳过');
  82. process.exit(0);
  83. }
  84. mkdirSync(OUT, { recursive: true });
  85. const child = spawn(
  86. browser,
  87. [
  88. '--headless=new',
  89. '--disable-gpu',
  90. '--hide-scrollbars',
  91. '--no-first-run',
  92. '--no-default-browser-check',
  93. `--remote-debugging-port=${PORT}`,
  94. `--user-data-dir=${path.join(OUT, 'profile')}`,
  95. '--window-size=1500,1150',
  96. 'about:blank',
  97. ],
  98. { stdio: 'ignore' },
  99. );
  100. let wsUrl = null;
  101. for (let attempt = 0; attempt < 40 && !wsUrl; attempt += 1) {
  102. await sleep(250);
  103. try {
  104. const targets = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json();
  105. wsUrl = targets.find((item) => item.type === 'page')?.webSocketDebuggerUrl ?? null;
  106. } catch {
  107. /* 还没起来 */
  108. }
  109. }
  110. if (!wsUrl) {
  111. console.error('✗ 浏览器调试端口没有就绪');
  112. child.kill();
  113. process.exit(1);
  114. }
  115. const socket = new WebSocket(wsUrl);
  116. await new Promise((resolve, reject) => {
  117. socket.addEventListener('open', resolve, { once: true });
  118. socket.addEventListener('error', reject, { once: true });
  119. });
  120. const cdp = new Cdp(socket);
  121. await cdp.send('Page.enable');
  122. await cdp.send('Runtime.enable');
  123. const open = async (hash, waitMs = 2500) => {
  124. await cdp.send('Page.navigate', { url: `${BASE}/${hash}` });
  125. await sleep(waitMs);
  126. };
  127. const results = [];
  128. const shot = async (name) => {
  129. const file = path.join(OUT, `${name}.png`);
  130. await cdp.screenshot(file);
  131. results.push(file);
  132. console.log(` ✓ 截图 ${path.relative(ROOT, file)}`);
  133. };
  134. console.log('1. 打开对话页');
  135. await open('#/chat');
  136. const chipCount = await cdp.evaluate(`document.querySelectorAll('.chip').length`);
  137. console.log(` 页面上有 ${chipCount} 个溯源 chip`);
  138. await shot('01-chat-chips');
  139. if (chipCount > 0) {
  140. console.log('2. 点击第一个 chip,检查抽屉是否出现');
  141. await cdp.evaluate(`document.querySelector('.chip').click()`);
  142. await sleep(1200);
  143. const drawerText = await cdp.evaluate(`document.querySelector('.drawer')?.innerText ?? ''`);
  144. if (!drawerText.includes('数字溯源')) {
  145. console.error('✗ 抽屉没有打开');
  146. child.kill();
  147. process.exit(1);
  148. }
  149. console.log(' 抽屉内容片段:', drawerText.replace(/\s+/g, ' ').slice(0, 120));
  150. await shot('02-trace-drawer');
  151. console.log('3. 点击"在结果表中查看这一行",检查跳转与高亮');
  152. await cdp.evaluate(`
  153. (() => {
  154. const buttons = [...document.querySelectorAll('.drawer button')];
  155. const target = buttons.find((b) => b.textContent.includes('在结果表中查看'));
  156. if (!target) return 'no-button';
  157. target.click();
  158. return 'clicked';
  159. })()
  160. `);
  161. await sleep(2500);
  162. const highlighted = await cdp.evaluate(`document.querySelectorAll('.data-table tr.highlight').length`);
  163. const modalOpen = await cdp.evaluate(`Boolean(document.querySelector('.modal'))`);
  164. console.log(` 弹窗打开: ${modalOpen},高亮行数: ${highlighted}`);
  165. await shot('03-row-jump');
  166. if (!modalOpen || highlighted < 1) {
  167. console.error('✗ 没有定位到结果行');
  168. child.kill();
  169. process.exit(1);
  170. }
  171. }
  172. console.log('4. 数据处理页');
  173. await open('#/process');
  174. await sleep(1200);
  175. await shot('04-process');
  176. console.log('5. 文件页(含指纹列)');
  177. await open('#/files');
  178. await sleep(1200);
  179. await shot('05-files');
  180. console.log('6. 系统页(两本台账)');
  181. await open('#/system');
  182. await sleep(1500);
  183. await shot('06-system');
  184. socket.close();
  185. child.kill();
  186. try {
  187. spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
  188. } catch {
  189. /* 忽略 */
  190. }
  191. console.log(`\n全部交互验证通过,截图在 ${OUT}`);
  192. return results;
  193. }
  194. main()
  195. .then(() => process.exit(0))
  196. .catch((error) => {
  197. console.error('✗ UI 探针失败:', error.message);
  198. process.exit(1);
  199. });