ui_probe.mjs 8.2 KB

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