| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180 |
- // Node 22+. Uses an existing CDP endpoint or launches a disposable local browser.
- // Default: read-only UI checks. Device-writing checks require simulated mode.
- import {spawn} from 'node:child_process';
- import {mkdtemp, readdir, readFile, rm, mkdir, writeFile} from 'node:fs/promises';
- import {tmpdir} from 'node:os';
- import path from 'node:path';
- import assert from 'node:assert/strict';
- const url = process.env.STL_WEB_URL || 'http://192.168.2.79:8080/';
- let cdpUrl = process.env.STL_CDP_URL || '';
- const writeTest = process.env.STL_BROWSER_WRITE_TEST === '1';
- const evidenceDir = process.env.STL_BROWSER_EVIDENCE_DIR;
- const browserPath = process.env.STL_BROWSER_PATH || (process.platform === 'win32' ? 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe' : 'chromium');
- const temporary = await mkdtemp(path.join(tmpdir(), 'stl-browser-'));
- let browser, socket, targetId, nextId = 1;
- let launchError, childExit, browserStderr = '';
- const requests = new Map();
- const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
- async function waitUntil(probe, description, timeout = 15000) {
- console.log('[browser] Waiting: '+description);
- const until = Date.now() + timeout;
- while (Date.now() < until) { if (await probe()) { console.log('[browser] Passed: '+description); return; } await delay(150); }
- throw new Error('Timed out: ' + description);
- }
- async function cdpVersion() {
- const response = await fetch(cdpUrl+'/json/version', {signal: AbortSignal.timeout(1500)});
- if (!response.ok) throw new Error('CDP version HTTP '+response.status);
- const version = await response.json();
- if (typeof version.Browser !== 'string' || typeof version.webSocketDebuggerUrl !== 'string' || !/^wss?:\/\//.test(version.webSocketDebuggerUrl)) {
- throw new Error('Port did not return a valid browser CDP version response');
- }
- return version;
- }
- async function launchBrowser(port) {
- console.log('[browser] Launching a disposable browser with '+(port === 0 ? 'an automatically assigned' : 'the configured')+' debugging port');
- browser = spawn(browserPath, ['--headless', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
- '--remote-debugging-port='+port, '--user-data-dir='+temporary, 'about:blank'], {stdio:['ignore','ignore','pipe']});
- browser.on('error', error => { launchError = error; });
- browser.on('exit', (code, signal) => { childExit = {code, signal}; });
- browser.stderr.on('data', data => { browserStderr = (browserStderr + data.toString()).slice(-8192); });
- if (port === 0) {
- await waitUntil(async () => {
- if (launchError) throw launchError;
- try {
- const text = await readFile(path.join(temporary, 'DevToolsActivePort'), 'utf8');
- const actualPort = Number(text.split(/\r?\n/)[0]);
- if (!Number.isInteger(actualPort) || actualPort < 1 || actualPort > 65535) return false;
- cdpUrl = 'http://127.0.0.1:'+actualPort;
- return true;
- } catch (error) { if (error.code === 'ENOENT') return false; throw error; }
- }, 'browser-assigned port file');
- }
- await waitUntil(async () => {
- if (launchError) throw launchError;
- try { await cdpVersion(); return true; } catch { return false; }
- }, 'valid browser CDP JSON');
- }
- function cdp(method, params = {}) {
- return new Promise((resolve, reject) => {
- const id = nextId++, timer = setTimeout(() => { requests.delete(id); reject(new Error('CDP timeout: ' + method)); }, 10000);
- requests.set(id, {resolve, reject, timer});
- socket.send(JSON.stringify({id, method, params}));
- });
- }
- async function evaluate(expression) {
- const result = await cdp('Runtime.evaluate', {expression, awaitPromise: true, returnByValue: true});
- if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
- return result.result?.value;
- }
- const readRpc = (method, payload = {}) => evaluate(`window.__stlSmokeRead(${JSON.stringify(method)}, ${JSON.stringify(payload)})`);
- async function saveEvidence(label, result) {
- if (!evidenceDir || socket?.readyState !== WebSocket.OPEN) return;
- await mkdir(evidenceDir, {recursive:true});
- const screenshot = await cdp('Page.captureScreenshot', {format:'png', fromSurface:true, captureBeyondViewport:true});
- const filename = path.join(evidenceDir, 'browser-'+label+'.png');
- await writeFile(filename, Buffer.from(screenshot.data, 'base64'));
- await writeFile(path.join(evidenceDir, 'browser-'+label+'.json'), JSON.stringify(result, null, 2));
- console.log('[browser] Evidence: '+filename);
- }
- try {
- // Do not print local debugging URLs: editors can auto-forward and occupy them.
- console.log('[browser] Starting '+(writeTest ? 'simulated interaction' : 'read-only')+' checks');
- if (cdpUrl) {
- try { const version = await cdpVersion(); console.log('[browser] Reusing '+version.Browser); }
- catch { await launchBrowser(Number(new URL(cdpUrl).port || 80)); }
- } else {
- await launchBrowser(0);
- }
- console.log('[browser] Creating isolated test tab');
- const created = await fetch(cdpUrl+'/json/new?'+encodeURIComponent(url), {method:'PUT', signal:AbortSignal.timeout(5000)});
- if (!created.ok) throw new Error('Cannot create isolated test tab: HTTP '+created.status);
- const target = await created.json(); targetId = target.id;
- socket = new WebSocket(target.webSocketDebuggerUrl);
- socket.addEventListener('message', event => {
- const message = JSON.parse(event.data), request = requests.get(message.id);
- if (!request) return;
- clearTimeout(request.timer); requests.delete(message.id);
- message.error ? request.reject(new Error(JSON.stringify(message.error))) : request.resolve(message.result);
- });
- await new Promise((resolve,reject) => {
- const timer = setTimeout(()=>reject(new Error('CDP WebSocket open timeout')),5000);
- socket.addEventListener('open',()=>{clearTimeout(timer);resolve();},{once:true});
- socket.addEventListener('error',()=>{clearTimeout(timer);reject(new Error('CDP WebSocket connection failed'));},{once:true});
- });
- console.log('[browser] CDP WebSocket ready');
- await cdp('Browser.setDownloadBehavior', {behavior:'allow', downloadPath:temporary});
- await waitUntil(() => evaluate(`document.querySelectorAll('.station-card').length === 4 && document.getElementById('sys-version').textContent !== '未知'`), 'four connected stations');
- await evaluate(`window.__stlSmokeRead = async (method, payload = {}) => {
- if (!['GetSystemInfo','GetStation','GetRun','ListArtifacts'].includes(method)) throw new Error('Read-only helper');
- const data = new TextEncoder().encode(JSON.stringify(payload)), frame = new Uint8Array(5+data.length);
- new DataView(frame.buffer).setUint32(1,data.length); frame.set(data,5);
- const response = await fetch('/stl.v1.BenchService/'+method,{method:'POST',headers:{'Content-Type':'application/grpc-web+json'},body:frame,signal:AbortSignal.timeout(5000)});
- const bytes = new Uint8Array(await response.arrayBuffer()), view = new DataView(bytes.buffer); let result, status;
- 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;}
- if (!status?.includes('grpc-status: 0')) throw new Error(status || 'missing trailers'); return result;
- }`);
- const info = await readRpc('GetSystemInfo');
- const ui = await evaluate(`(() => ({title:document.title,version:document.getElementById('sys-version').textContent,commit:document.getElementById('sys-commit').textContent,
- stations:[...document.querySelectorAll('.station-card')].map(card=>({id:card.dataset.id,status:card.querySelector('.station-status-tag').textContent})),
- cpu0:document.querySelectorAll('#cpu0-grid .dimm-slot').length,cpu1:document.querySelectorAll('#cpu1-grid .dimm-slot').length}))()`);
- assert.equal(ui.version, info.version); assert.equal(ui.commit, info.commit ? info.commit.slice(0,7) : '未知');
- assert.equal(ui.stations.length,4); assert.equal(ui.cpu0,12); assert.equal(ui.cpu1,12);
- await evaluate(`document.querySelector('[data-id="S2"]').click()`);
- await waitUntil(() => evaluate(`document.getElementById('detail-station-tag').textContent.startsWith('S2')`), 'station selection');
- await evaluate(`document.querySelector('[data-id="S1"]').click()`);
- const result = {mode: info.mode, url, ui, read_only:!writeTest};
- if (writeTest) {
- assert.equal(info.mode,'simulated','Write smoke test refuses hardware mode');
- 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);};})()`);
- const existing = await readRpc('GetStation',{station_id:'S1'}); assert.ok(!existing.run_id,'Use a fresh simulated station');
- await evaluate(`document.getElementById('btn-open-start').click()`);
- await waitUntil(() => evaluate(`!document.getElementById('modal-start-run').classList.contains('hidden')`), 'start modal');
- 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()`);
- let runId;
- 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');
- await waitUntil(()=>evaluate(`!document.getElementById('btn-sol-mode').disabled`),'manual button');
- await evaluate(`document.getElementById('btn-sol-mode').click()`);
- await waitUntil(async()=> (await readRpc('GetStation',{station_id:'S1'})).control_mode==='manual','manual takeover');
- await waitUntil(()=>evaluate(`!document.getElementById('btn-send-sol').disabled`),'manual SOL input');
- await evaluate(`document.getElementById('sol-input-cmd').value='help'; document.getElementById('btn-send-sol').click()`);
- await waitUntil(()=>evaluate(`document.getElementById('action-status').textContent.includes('发送 SOL') && document.getElementById('action-status').textContent.includes('执行成功')`),'SOL command acknowledgement');
- assert.equal(await evaluate(`atob(window.__stlSmokeWrites.at(-1).data)`), 'help\r', 'SOL command must end in one CR');
- await evaluate(`document.getElementById('btn-send-enter').click()`);
- await waitUntil(()=>evaluate(`window.__stlSmokeWrites.length === 2`),'explicit empty CR sent');
- assert.equal(await evaluate(`atob(window.__stlSmokeWrites.at(-1).data)`), '\r', 'Empty return must be one CR');
- await evaluate(`document.getElementById('btn-open-target').click()`);
- await waitUntil(()=>evaluate(`!document.getElementById('modal-target-temp').classList.contains('hidden')`),'temperature dialog');
- await evaluate(`document.getElementById('input-new-target-c').value='78.5'; document.getElementById('btn-save-temp').click()`);
- await waitUntil(async()=> (await readRpc('GetStation',{station_id:'S1'})).temperature?.applied_target_c===78.5,'target readback');
- await evaluate(`window.confirm=()=>true; document.getElementById('btn-stop-run').click()`);
- await waitUntil(async()=> {const r=await readRpc('GetRun',{run_id:runId}); return r.state==='stopped'&&r.supply_state==='off';},'stop and whole-station off');
- await waitUntil(()=>evaluate(`!document.getElementById('btn-import-artifact').disabled`),'result import available');
- 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(); })()`);
- await waitUntil(async()=> (await readRpc('ListArtifacts',{run_id:runId})).artifacts?.some(a=>a.filename==='browser-evidence.txt'),'artifact imported');
- await evaluate(`document.getElementById('btn-download-report').click()`);
- let reportFile;
- await waitUntil(async()=> {reportFile=(await readdir(temporary)).find(n=>n.endsWith('-report.json'));return !!reportFile;},'report download');
- const report = JSON.parse(await readFile(path.join(temporary,reportFile),'utf8')); assert.equal(report.run.run_id,runId);
- result.write_checks = ['start with actual SN inputs','manual takeover','SOL send','target readback','stop and power off','result import','report download'];
- result.run_id = runId;
- }
- await saveEvidence('success', result);
- console.log('BROWSER_TEST_SUCCESS\n'+JSON.stringify(result,null,2));
- } catch (error) {
- console.error('BROWSER_TEST_FAILED:',error.stack); process.exitCode=1;
- if (browser) {
- console.error('[browser] Child status:', JSON.stringify(childExit || {state:'running', pid:browser.pid}));
- const tail = browserStderr.slice(-4096).replace(/wss?:\/\/[^\s]+/g, '[debugging endpoint]');
- if (tail) console.error('[browser] Browser stderr tail:\n'+tail);
- }
- await saveEvidence('failure', {url, error:error.stack}).catch(e=>console.error('[browser] Evidence unavailable:',e.message));
- }
- finally {
- console.log('[browser] Closing test tab and temporary browser');
- for (const req of requests.values()) clearTimeout(req.timer);
- if (socket) socket.close();
- if (targetId) await fetch(cdpUrl+'/json/close/'+targetId, {signal:AbortSignal.timeout(2000)}).catch(()=>{});
- if (browser) { browser.kill(); await delay(500); }
- await rm(temporary,{recursive:true,force:true}).catch(()=>{});
- }
|