| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- // 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} 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/';
- const cdpUrl = process.env.STL_CDP_URL || 'http://127.0.0.1:9222';
- const writeTest = process.env.STL_BROWSER_WRITE_TEST === '1';
- 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;
- const requests = new Map();
- const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
- async function waitUntil(probe, description, timeout = 15000) {
- const until = Date.now() + timeout;
- while (Date.now() < until) { if (await probe()) return; await delay(150); }
- throw new Error('Timed out: ' + description);
- }
- 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)})`);
- try {
- try { await fetch(cdpUrl+'/json/version', {signal: AbortSignal.timeout(1500)}); }
- catch {
- browser = spawn(browserPath, ['--headless', '--disable-gpu', '--remote-debugging-port='+new URL(cdpUrl).port, '--user-data-dir='+temporary, 'about:blank'], {stdio:'ignore'});
- let launchError; browser.on('error', e => { launchError = e; });
- await waitUntil(async () => { if (launchError) throw launchError; try { return (await fetch(cdpUrl+'/json/version')).ok; } catch { return false; } }, 'browser CDP');
- }
- const created = await fetch(cdpUrl+'/json/new?'+encodeURIComponent(url), {method:'PUT'});
- 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) => { socket.addEventListener('open',resolve,{once:true});socket.addEventListener('error',reject,{once:true}); });
- 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});
- 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.phase!=='preparing';},'run enters active phase');
- 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;
- }
- console.log('BROWSER_TEST_SUCCESS\n'+JSON.stringify(result,null,2));
- } catch (error) { console.error('BROWSER_TEST_FAILED:',error.stack); process.exitCode=1; }
- finally {
- for (const req of requests.values()) clearTimeout(req.timer);
- if (socket) socket.close();
- if (targetId) await fetch(cdpUrl+'/json/close/'+targetId).catch(()=>{});
- if (browser) { browser.kill(); await delay(500); }
- await rm(temporary,{recursive:true,force:true}).catch(()=>{});
- }
|