test_web_browser.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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, mkdir, writeFile} 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. let cdpUrl = process.env.STL_CDP_URL || '';
  10. const writeTest = process.env.STL_BROWSER_WRITE_TEST === '1';
  11. const evidenceDir = process.env.STL_BROWSER_EVIDENCE_DIR;
  12. const browserPath = process.env.STL_BROWSER_PATH || (process.platform === 'win32' ? 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe' : 'chromium');
  13. const temporary = await mkdtemp(path.join(tmpdir(), 'stl-browser-'));
  14. let browser, socket, targetId, nextId = 1;
  15. let launchError, childExit, browserStderr = '';
  16. const requests = new Map();
  17. const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
  18. async function waitUntil(probe, description, timeout = 15000) {
  19. console.log('[browser] Waiting: '+description);
  20. const until = Date.now() + timeout;
  21. while (Date.now() < until) { if (await probe()) { console.log('[browser] Passed: '+description); return; } await delay(150); }
  22. throw new Error('Timed out: ' + description);
  23. }
  24. async function cdpVersion() {
  25. const response = await fetch(cdpUrl+'/json/version', {signal: AbortSignal.timeout(1500)});
  26. if (!response.ok) throw new Error('CDP version HTTP '+response.status);
  27. const version = await response.json();
  28. if (typeof version.Browser !== 'string' || typeof version.webSocketDebuggerUrl !== 'string' || !/^wss?:\/\//.test(version.webSocketDebuggerUrl)) {
  29. throw new Error('Port did not return a valid browser CDP version response');
  30. }
  31. return version;
  32. }
  33. async function launchBrowser(port) {
  34. console.log('[browser] Launching a disposable browser with '+(port === 0 ? 'an automatically assigned' : 'the configured')+' debugging port');
  35. browser = spawn(browserPath, ['--headless', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
  36. '--remote-debugging-port='+port, '--user-data-dir='+temporary, 'about:blank'], {stdio:['ignore','ignore','pipe']});
  37. browser.on('error', error => { launchError = error; });
  38. browser.on('exit', (code, signal) => { childExit = {code, signal}; });
  39. browser.stderr.on('data', data => { browserStderr = (browserStderr + data.toString()).slice(-8192); });
  40. if (port === 0) {
  41. await waitUntil(async () => {
  42. if (launchError) throw launchError;
  43. try {
  44. const text = await readFile(path.join(temporary, 'DevToolsActivePort'), 'utf8');
  45. const actualPort = Number(text.split(/\r?\n/)[0]);
  46. if (!Number.isInteger(actualPort) || actualPort < 1 || actualPort > 65535) return false;
  47. cdpUrl = 'http://127.0.0.1:'+actualPort;
  48. return true;
  49. } catch (error) { if (error.code === 'ENOENT') return false; throw error; }
  50. }, 'browser-assigned port file');
  51. }
  52. await waitUntil(async () => {
  53. if (launchError) throw launchError;
  54. try { await cdpVersion(); return true; } catch { return false; }
  55. }, 'valid browser CDP JSON');
  56. }
  57. function cdp(method, params = {}) {
  58. return new Promise((resolve, reject) => {
  59. const id = nextId++, timer = setTimeout(() => { requests.delete(id); reject(new Error('CDP timeout: ' + method)); }, 10000);
  60. requests.set(id, {resolve, reject, timer});
  61. socket.send(JSON.stringify({id, method, params}));
  62. });
  63. }
  64. async function evaluate(expression) {
  65. const result = await cdp('Runtime.evaluate', {expression, awaitPromise: true, returnByValue: true});
  66. if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
  67. return result.result?.value;
  68. }
  69. const readRpc = (method, payload = {}) => evaluate(`window.__stlSmokeRead(${JSON.stringify(method)}, ${JSON.stringify(payload)})`);
  70. async function saveEvidence(label, result) {
  71. if (!evidenceDir || socket?.readyState !== WebSocket.OPEN) return;
  72. await mkdir(evidenceDir, {recursive:true});
  73. const screenshot = await cdp('Page.captureScreenshot', {format:'png', fromSurface:true, captureBeyondViewport:true});
  74. const filename = path.join(evidenceDir, 'browser-'+label+'.png');
  75. await writeFile(filename, Buffer.from(screenshot.data, 'base64'));
  76. await writeFile(path.join(evidenceDir, 'browser-'+label+'.json'), JSON.stringify(result, null, 2));
  77. console.log('[browser] Evidence: '+filename);
  78. }
  79. try {
  80. // Do not print local debugging URLs: editors can auto-forward and occupy them.
  81. console.log('[browser] Starting '+(writeTest ? 'simulated interaction' : 'read-only')+' checks');
  82. if (cdpUrl) {
  83. try { const version = await cdpVersion(); console.log('[browser] Reusing '+version.Browser); }
  84. catch { await launchBrowser(Number(new URL(cdpUrl).port || 80)); }
  85. } else {
  86. await launchBrowser(0);
  87. }
  88. console.log('[browser] Creating isolated test tab');
  89. const created = await fetch(cdpUrl+'/json/new?'+encodeURIComponent(url), {method:'PUT', signal:AbortSignal.timeout(5000)});
  90. if (!created.ok) throw new Error('Cannot create isolated test tab: HTTP '+created.status);
  91. const target = await created.json(); targetId = target.id;
  92. socket = new WebSocket(target.webSocketDebuggerUrl);
  93. socket.addEventListener('message', event => {
  94. const message = JSON.parse(event.data), request = requests.get(message.id);
  95. if (!request) return;
  96. clearTimeout(request.timer); requests.delete(message.id);
  97. message.error ? request.reject(new Error(JSON.stringify(message.error))) : request.resolve(message.result);
  98. });
  99. await new Promise((resolve,reject) => {
  100. const timer = setTimeout(()=>reject(new Error('CDP WebSocket open timeout')),5000);
  101. socket.addEventListener('open',()=>{clearTimeout(timer);resolve();},{once:true});
  102. socket.addEventListener('error',()=>{clearTimeout(timer);reject(new Error('CDP WebSocket connection failed'));},{once:true});
  103. });
  104. console.log('[browser] CDP WebSocket ready');
  105. await cdp('Browser.setDownloadBehavior', {behavior:'allow', downloadPath:temporary});
  106. await waitUntil(() => evaluate(`document.querySelectorAll('.station-card').length === 4 && document.getElementById('sys-version').textContent !== '未知'`), 'four connected stations');
  107. await evaluate(`window.__stlSmokeRead = async (method, payload = {}) => {
  108. if (!['GetSystemInfo','GetStation','GetRun','ListArtifacts'].includes(method)) throw new Error('Read-only helper');
  109. const data = new TextEncoder().encode(JSON.stringify(payload)), frame = new Uint8Array(5+data.length);
  110. new DataView(frame.buffer).setUint32(1,data.length); frame.set(data,5);
  111. const response = await fetch('/stl.v1.BenchService/'+method,{method:'POST',headers:{'Content-Type':'application/grpc-web+json'},body:frame,signal:AbortSignal.timeout(5000)});
  112. const bytes = new Uint8Array(await response.arrayBuffer()), view = new DataView(bytes.buffer); let result, status;
  113. 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;}
  114. if (!status?.includes('grpc-status: 0')) throw new Error(status || 'missing trailers'); return result;
  115. }`);
  116. const info = await readRpc('GetSystemInfo');
  117. const ui = await evaluate(`(() => ({title:document.title,version:document.getElementById('sys-version').textContent,commit:document.getElementById('sys-commit').textContent,
  118. stations:[...document.querySelectorAll('.station-card')].map(card=>({id:card.dataset.id,status:card.querySelector('.station-status-tag').textContent})),
  119. cpu0:document.querySelectorAll('#cpu0-grid .dimm-slot').length,cpu1:document.querySelectorAll('#cpu1-grid .dimm-slot').length}))()`);
  120. assert.equal(ui.version, info.version); assert.equal(ui.commit, info.commit ? info.commit.slice(0,7) : '未知');
  121. assert.equal(ui.stations.length,4); assert.equal(ui.cpu0,12); assert.equal(ui.cpu1,12);
  122. await evaluate(`document.querySelector('[data-id="S2"]').click()`);
  123. await waitUntil(() => evaluate(`document.getElementById('detail-station-tag').textContent.startsWith('S2')`), 'station selection');
  124. await evaluate(`document.querySelector('[data-id="S1"]').click()`);
  125. const result = {mode: info.mode, url, ui, read_only:!writeTest};
  126. if (writeTest) {
  127. assert.equal(info.mode,'simulated','Write smoke test refuses hardware mode');
  128. 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);};})()`);
  129. const existing = await readRpc('GetStation',{station_id:'S1'}); assert.ok(!existing.run_id,'Use a fresh simulated station');
  130. await evaluate(`document.getElementById('btn-open-start').click()`);
  131. await waitUntil(() => evaluate(`!document.getElementById('modal-start-run').classList.contains('hidden')`), 'start modal');
  132. 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()`);
  133. let runId;
  134. await waitUntil(async()=> {const s=await readRpc('GetStation',{station_id:'S1'}); runId=s.run_id; return !!runId && s.sol_state==='online';},'active run with SOL online');
  135. await waitUntil(()=>evaluate(`!document.getElementById('btn-sol-mode').disabled`),'manual button');
  136. await evaluate(`document.getElementById('btn-sol-mode').click()`);
  137. await waitUntil(async()=> (await readRpc('GetStation',{station_id:'S1'})).control_mode==='manual','manual takeover');
  138. await waitUntil(()=>evaluate(`!document.getElementById('btn-send-sol').disabled`),'manual SOL input');
  139. await evaluate(`document.getElementById('sol-input-cmd').value='help'; document.getElementById('btn-send-sol').click()`);
  140. await waitUntil(()=>evaluate(`document.getElementById('action-status').textContent.includes('发送 SOL') && document.getElementById('action-status').textContent.includes('执行成功')`),'SOL command acknowledgement');
  141. assert.equal(await evaluate(`atob(window.__stlSmokeWrites.at(-1).data)`), 'help\r', 'SOL command must end in one CR');
  142. await evaluate(`document.getElementById('btn-send-enter').click()`);
  143. await waitUntil(()=>evaluate(`window.__stlSmokeWrites.length === 2`),'explicit empty CR sent');
  144. assert.equal(await evaluate(`atob(window.__stlSmokeWrites.at(-1).data)`), '\r', 'Empty return must be one CR');
  145. await evaluate(`document.getElementById('btn-open-target').click()`);
  146. await waitUntil(()=>evaluate(`!document.getElementById('modal-target-temp').classList.contains('hidden')`),'temperature dialog');
  147. await evaluate(`document.getElementById('input-new-target-c').value='78.5'; document.getElementById('btn-save-temp').click()`);
  148. await waitUntil(async()=> (await readRpc('GetStation',{station_id:'S1'})).temperature?.applied_target_c===78.5,'target readback');
  149. await evaluate(`window.confirm=()=>true; document.getElementById('btn-stop-run').click()`);
  150. await waitUntil(async()=> {const r=await readRpc('GetRun',{run_id:runId}); return r.state==='stopped'&&r.supply_state==='off';},'stop and whole-station off');
  151. await waitUntil(()=>evaluate(`!document.getElementById('btn-import-artifact').disabled`),'result import available');
  152. 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(); })()`);
  153. await waitUntil(async()=> (await readRpc('ListArtifacts',{run_id:runId})).artifacts?.some(a=>a.filename==='browser-evidence.txt'),'artifact imported');
  154. await evaluate(`document.getElementById('btn-download-report').click()`);
  155. let reportFile;
  156. await waitUntil(async()=> {reportFile=(await readdir(temporary)).find(n=>n.endsWith('-report.json'));return !!reportFile;},'report download');
  157. const report = JSON.parse(await readFile(path.join(temporary,reportFile),'utf8')); assert.equal(report.run.run_id,runId);
  158. result.write_checks = ['start with actual SN inputs','manual takeover','SOL send','target readback','stop and power off','result import','report download'];
  159. result.run_id = runId;
  160. }
  161. await saveEvidence('success', result);
  162. console.log('BROWSER_TEST_SUCCESS\n'+JSON.stringify(result,null,2));
  163. } catch (error) {
  164. console.error('BROWSER_TEST_FAILED:',error.stack); process.exitCode=1;
  165. if (browser) {
  166. console.error('[browser] Child status:', JSON.stringify(childExit || {state:'running', pid:browser.pid}));
  167. const tail = browserStderr.slice(-4096).replace(/wss?:\/\/[^\s]+/g, '[debugging endpoint]');
  168. if (tail) console.error('[browser] Browser stderr tail:\n'+tail);
  169. }
  170. await saveEvidence('failure', {url, error:error.stack}).catch(e=>console.error('[browser] Evidence unavailable:',e.message));
  171. }
  172. finally {
  173. console.log('[browser] Closing test tab and temporary browser');
  174. for (const req of requests.values()) clearTimeout(req.timer);
  175. if (socket) socket.close();
  176. if (targetId) await fetch(cdpUrl+'/json/close/'+targetId, {signal:AbortSignal.timeout(2000)}).catch(()=>{});
  177. if (browser) { browser.kill(); await delay(500); }
  178. await rm(temporary,{recursive:true,force:true}).catch(()=>{});
  179. }