test_web_browser.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. // Node 22+. Uses an existing CDP endpoint or launches a disposable local browser.
  2. // Default: read-only UI checks. Device-writing checks require simulated mode.
  3. import {spawn} from 'node:child_process';
  4. import {mkdtemp, readdir, readFile, rm} from 'node:fs/promises';
  5. import {tmpdir} from 'node:os';
  6. import path from 'node:path';
  7. import assert from 'node:assert/strict';
  8. const url = process.env.STL_WEB_URL || 'http://192.168.2.79:8080/';
  9. const cdpUrl = process.env.STL_CDP_URL || 'http://127.0.0.1:9222';
  10. const writeTest = process.env.STL_BROWSER_WRITE_TEST === '1';
  11. const browserPath = process.env.STL_BROWSER_PATH || (process.platform === 'win32' ? 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe' : 'chromium');
  12. const temporary = await mkdtemp(path.join(tmpdir(), 'stl-browser-'));
  13. let browser, socket, targetId, nextId = 1;
  14. const requests = new Map();
  15. const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
  16. async function waitUntil(probe, description, timeout = 15000) {
  17. const until = Date.now() + timeout;
  18. while (Date.now() < until) { if (await probe()) return; await delay(150); }
  19. throw new Error('Timed out: ' + description);
  20. }
  21. function cdp(method, params = {}) {
  22. return new Promise((resolve, reject) => {
  23. const id = nextId++, timer = setTimeout(() => { requests.delete(id); reject(new Error('CDP timeout: ' + method)); }, 10000);
  24. requests.set(id, {resolve, reject, timer});
  25. socket.send(JSON.stringify({id, method, params}));
  26. });
  27. }
  28. async function evaluate(expression) {
  29. const result = await cdp('Runtime.evaluate', {expression, awaitPromise: true, returnByValue: true});
  30. if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
  31. return result.result?.value;
  32. }
  33. const readRpc = (method, payload = {}) => evaluate(`window.__stlSmokeRead(${JSON.stringify(method)}, ${JSON.stringify(payload)})`);
  34. try {
  35. try { await fetch(cdpUrl+'/json/version', {signal: AbortSignal.timeout(1500)}); }
  36. catch {
  37. browser = spawn(browserPath, ['--headless', '--disable-gpu', '--remote-debugging-port='+new URL(cdpUrl).port, '--user-data-dir='+temporary, 'about:blank'], {stdio:'ignore'});
  38. let launchError; browser.on('error', e => { launchError = e; });
  39. await waitUntil(async () => { if (launchError) throw launchError; try { return (await fetch(cdpUrl+'/json/version')).ok; } catch { return false; } }, 'browser CDP');
  40. }
  41. const created = await fetch(cdpUrl+'/json/new?'+encodeURIComponent(url), {method:'PUT'});
  42. if (!created.ok) throw new Error('Cannot create isolated test tab: HTTP '+created.status);
  43. const target = await created.json(); targetId = target.id;
  44. socket = new WebSocket(target.webSocketDebuggerUrl);
  45. socket.addEventListener('message', event => {
  46. const message = JSON.parse(event.data), request = requests.get(message.id);
  47. if (!request) return;
  48. clearTimeout(request.timer); requests.delete(message.id);
  49. message.error ? request.reject(new Error(JSON.stringify(message.error))) : request.resolve(message.result);
  50. });
  51. await new Promise((resolve,reject) => { socket.addEventListener('open',resolve,{once:true});socket.addEventListener('error',reject,{once:true}); });
  52. await cdp('Browser.setDownloadBehavior', {behavior:'allow', downloadPath:temporary});
  53. await waitUntil(() => evaluate(`document.querySelectorAll('.station-card').length === 4 && document.getElementById('sys-version').textContent !== '未知'`), 'four connected stations');
  54. await evaluate(`window.__stlSmokeRead = async (method, payload = {}) => {
  55. if (!['GetSystemInfo','GetStation','GetRun','ListArtifacts'].includes(method)) throw new Error('Read-only helper');
  56. const data = new TextEncoder().encode(JSON.stringify(payload)), frame = new Uint8Array(5+data.length);
  57. new DataView(frame.buffer).setUint32(1,data.length); frame.set(data,5);
  58. const response = await fetch('/stl.v1.BenchService/'+method,{method:'POST',headers:{'Content-Type':'application/grpc-web+json'},body:frame});
  59. const bytes = new Uint8Array(await response.arrayBuffer()), view = new DataView(bytes.buffer); let result, status;
  60. for(let offset=0;offset<bytes.length;) {const flags=bytes[offset],n=view.getUint32(offset+1);const text=new TextDecoder().decode(bytes.subarray(offset+5,offset+5+n));offset+=5+n;if(flags===0)result=JSON.parse(text);else status=text;}
  61. if (!status?.includes('grpc-status: 0')) throw new Error(status || 'missing trailers'); return result;
  62. }`);
  63. const info = await readRpc('GetSystemInfo');
  64. const ui = await evaluate(`(() => ({title:document.title,version:document.getElementById('sys-version').textContent,commit:document.getElementById('sys-commit').textContent,
  65. stations:[...document.querySelectorAll('.station-card')].map(card=>({id:card.dataset.id,status:card.querySelector('.station-status-tag').textContent})),
  66. cpu0:document.querySelectorAll('#cpu0-grid .dimm-slot').length,cpu1:document.querySelectorAll('#cpu1-grid .dimm-slot').length}))()`);
  67. assert.equal(ui.version, info.version); assert.equal(ui.commit, info.commit ? info.commit.slice(0,7) : '未知');
  68. assert.equal(ui.stations.length,4); assert.equal(ui.cpu0,12); assert.equal(ui.cpu1,12);
  69. await evaluate(`document.querySelector('[data-id="S2"]').click()`);
  70. await waitUntil(() => evaluate(`document.getElementById('detail-station-tag').textContent.startsWith('S2')`), 'station selection');
  71. await evaluate(`document.querySelector('[data-id="S1"]').click()`);
  72. const result = {mode: info.mode, url, ui, read_only:!writeTest};
  73. if (writeTest) {
  74. assert.equal(info.mode,'simulated','Write smoke test refuses hardware mode');
  75. await evaluate(`(() => {const original=window.fetch;window.__stlSmokeWrites=[];window.fetch=(input,options)=>{if(String(input).endsWith('/WriteSol')&&options?.body){const bytes=new Uint8Array(options.body);window.__stlSmokeWrites.push(JSON.parse(new TextDecoder().decode(bytes.subarray(5))));}return original(input,options);};})()`);
  76. const existing = await readRpc('GetStation',{station_id:'S1'}); assert.ok(!existing.run_id,'Use a fresh simulated station');
  77. await evaluate(`document.getElementById('btn-open-start').click()`);
  78. await waitUntil(() => evaluate(`!document.getElementById('modal-start-run').classList.contains('hidden')`), 'start modal');
  79. await evaluate(`document.getElementById('start-wo').value='BROWSER-WO'; document.getElementById('start-batch').value='BROWSER-BATCH'; document.getElementById('start-operator').value='browser-test'; document.getElementById('start-dimms').value='0,A,D0,BROWSER-SN-0\\n1,A,D0,BROWSER-SN-1'; document.getElementById('btn-confirm-start-run').click()`);
  80. let runId;
  81. await waitUntil(async()=> {const s=await readRpc('GetStation',{station_id:'S1'}); runId=s.run_id; return !!runId && s.phase!=='preparing';},'run enters active phase');
  82. await waitUntil(()=>evaluate(`!document.getElementById('btn-sol-mode').disabled`),'manual button');
  83. await evaluate(`document.getElementById('btn-sol-mode').click()`);
  84. await waitUntil(async()=> (await readRpc('GetStation',{station_id:'S1'})).control_mode==='manual','manual takeover');
  85. await waitUntil(()=>evaluate(`!document.getElementById('btn-send-sol').disabled`),'manual SOL input');
  86. await evaluate(`document.getElementById('sol-input-cmd').value='help'; document.getElementById('btn-send-sol').click()`);
  87. await waitUntil(()=>evaluate(`document.getElementById('action-status').textContent.includes('发送 SOL') && document.getElementById('action-status').textContent.includes('执行成功')`),'SOL command acknowledgement');
  88. assert.equal(await evaluate(`atob(window.__stlSmokeWrites.at(-1).data)`), 'help\r', 'SOL command must end in one CR');
  89. await evaluate(`document.getElementById('btn-send-enter').click()`);
  90. await waitUntil(()=>evaluate(`window.__stlSmokeWrites.length === 2`),'explicit empty CR sent');
  91. assert.equal(await evaluate(`atob(window.__stlSmokeWrites.at(-1).data)`), '\r', 'Empty return must be one CR');
  92. await evaluate(`document.getElementById('btn-open-target').click()`);
  93. await waitUntil(()=>evaluate(`!document.getElementById('modal-target-temp').classList.contains('hidden')`),'temperature dialog');
  94. await evaluate(`document.getElementById('input-new-target-c').value='78.5'; document.getElementById('btn-save-temp').click()`);
  95. await waitUntil(async()=> (await readRpc('GetStation',{station_id:'S1'})).temperature?.applied_target_c===78.5,'target readback');
  96. await evaluate(`window.confirm=()=>true; document.getElementById('btn-stop-run').click()`);
  97. await waitUntil(async()=> {const r=await readRpc('GetRun',{run_id:runId}); return r.state==='stopped'&&r.supply_state==='off';},'stop and whole-station off');
  98. await waitUntil(()=>evaluate(`!document.getElementById('btn-import-artifact').disabled`),'result import available');
  99. await evaluate(`(() => { const dt=new DataTransfer();dt.items.add(new File(['browser result evidence'],'browser-evidence.txt',{type:'text/plain'}));document.getElementById('artifact-file').files=dt.files;document.getElementById('artifact-kind').value='raw';document.getElementById('btn-import-artifact').click(); })()`);
  100. await waitUntil(async()=> (await readRpc('ListArtifacts',{run_id:runId})).artifacts?.some(a=>a.filename==='browser-evidence.txt'),'artifact imported');
  101. await evaluate(`document.getElementById('btn-download-report').click()`);
  102. let reportFile;
  103. await waitUntil(async()=> {reportFile=(await readdir(temporary)).find(n=>n.endsWith('-report.json'));return !!reportFile;},'report download');
  104. const report = JSON.parse(await readFile(path.join(temporary,reportFile),'utf8')); assert.equal(report.run.run_id,runId);
  105. result.write_checks = ['start with actual SN inputs','manual takeover','SOL send','target readback','stop and power off','result import','report download'];
  106. result.run_id = runId;
  107. }
  108. console.log('BROWSER_TEST_SUCCESS\n'+JSON.stringify(result,null,2));
  109. } catch (error) { console.error('BROWSER_TEST_FAILED:',error.stack); process.exitCode=1; }
  110. finally {
  111. for (const req of requests.values()) clearTimeout(req.timer);
  112. if (socket) socket.close();
  113. if (targetId) await fetch(cdpUrl+'/json/close/'+targetId).catch(()=>{});
  114. if (browser) { browser.kill(); await delay(500); }
  115. await rm(temporary,{recursive:true,force:true}).catch(()=>{});
  116. }