| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846 |
- // Node 22+. Uses an existing CDP endpoint or launches a disposable local browser.
- // Default: read-only UI checks. Full writes require simulated mode.
- // STL_BROWSER_HARDWARE_CONSOLE_TEST=1 permits only a guarded S1 UIP list query, BMC read, and reload.
- 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 firmwareTest = process.env.STL_BROWSER_FIRMWARE_TEST === '1';
- const planTest = process.env.STL_BROWSER_PLAN_TEST === '1';
- const hardwareConsoleTest = process.env.STL_BROWSER_HARDWARE_CONSOLE_TEST === '1';
- const manualRecipeId = process.env.STL_BROWSER_MANUAL_RECIPE_ID || '';
- 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 observedWrites = [];
- const wsRequests = [], httpRpcRequests = [], wsConnections = new Map();
- const writeMethods = new Set(['EnqueueCommand','PutRecipe','BeginArtifact','UploadArtifactChunk','FinishArtifact','WriteSol','WriteDiagnosticSol','SetDiagnosticSol','StationPower','StartRun','StopRun','SetTargetTemperature','ConfirmStage','ConfirmPower','SetSolMode','QueryBmc']);
- 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}));
- });
- }
- function receiveCdpMessage(event) {
- const message=JSON.parse(event.data), request=requests.get(message.id);
- if(message.method==='Network.requestWillBeSent') {
- const requestUrl=message.params.request.url, method=requestUrl.split('/').at(-1);
- if(requestUrl.includes('/stl.v1.BenchService/')) httpRpcRequests.push(method);
- if(writeMethods.has(method)) observedWrites.push(method);
- }
- if(message.method==='Network.webSocketCreated' && /\/ws(?:\?|$)/.test(message.params.url)) {
- wsConnections.set(message.params.requestId,message.params.url);
- }
- if(message.method==='Network.webSocketFrameSent' && message.params.response.opcode===1) {
- try {
- const frame=JSON.parse(message.params.response.payloadData);
- if(frame.v===1 && typeof frame.id==='string' && typeof frame.method==='string') {
- // Capture method/IDs only: API authorization never enters evidence files.
- wsRequests.push({id:frame.id,method:frame.method,command_id:frame.params?.command_id});
- if(writeMethods.has(frame.method)) observedWrites.push(frame.method);
- }
- } catch {}
- }
- if(!request)return;
- clearTimeout(request.timer);requests.delete(message.id);
- message.error ? request.reject(new Error(JSON.stringify(message.error))) : request.resolve(message.result);
- }
- async function socketReady(connection) {
- await new Promise((resolve,reject)=>{
- const timer=setTimeout(()=>reject(new Error('CDP WebSocket open timeout')),5000);
- connection.addEventListener('open',()=>{clearTimeout(timer);resolve();},{once:true});
- connection.addEventListener('error',()=>{clearTimeout(timer);reject(new Error('CDP WebSocket connection failed'));},{once:true});
- });
- }
- 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;
- }
- async function waitForButton(id) {
- // Backend state can lead the page's next poll. A disabled DOM click is a no-op.
- await waitUntil(() => evaluate(`(() => {
- const button=document.getElementById(${JSON.stringify(id)});
- return !!button && !button.matches(':disabled') && button.dataset.busy !== '1';
- })()`), 'UI button enabled: '+id);
- }
- async function clickButton(id) {
- await evaluate(`(() => {const button=document.getElementById(${JSON.stringify(id)}), pane=button?.closest('[data-pages]'); if(pane && pane.hidden) window.stlNavigation.show(pane.dataset.pages.split(' ')[0]);})()`);
- await waitForButton(id);
- await evaluate(`document.getElementById(${JSON.stringify(id)}).click()`);
- }
- const readRpc = (method, payload = {}) => evaluate(`window.__stlSmokeRead(${JSON.stringify(method)}, ${JSON.stringify(payload)})`);
- async function installReadHelper() {
- await evaluate(`window.__stlSmokeRead = async (method, payload = {}) => {
- if (!['GetSystemInfo','GetStation','GetRun','ListRuns','ListArtifacts','ListEvents','QueryTemperatures','GetRecipe','ListRecipes','GetDiagnostic','ReadDiagnosticSol','GetQueue','GetQueueItem','ReadEventQueue','GetStationControl','GetFirmwareCatalog'].includes(method)) throw new Error('Read-only helper');
- return window.stlTransport.call(method,payload);
- }`);
- }
- async function installQueueCapture() {
- await evaluate(`(() => {
- const original=window.stlTransport.call.bind(window.stlTransport);window.__stlQueueSubmissions=[];window.__stlRecipeSaves=[];
- window.stlTransport.call=(method,params)=>{
- if(method==='EnqueueCommand')window.__stlQueueSubmissions.push(structuredClone(params));
- if(method==='PutRecipe')window.__stlRecipeSaves.push(structuredClone(params));
- return original(method,params);
- };
- })()`);
- }
- const submitted = method => evaluate(`window.__stlQueueSubmissions.filter(item=>item.method===${JSON.stringify(method)})`);
- async function completedQueueItem(commandId, description, expectedState = 'succeeded') {
- let item;
- await waitUntil(async()=> {
- // The client observer records submission before EnqueueCommand has persisted
- // it. A concurrent queue read can reach the backend first.
- try { item=await readRpc('GetQueueItem',{command_id:commandId}); }
- catch (error) { if (error.message.includes('NOT_FOUND')) return false; throw error; }
- return ['succeeded','failed','interrupted'].includes(item.state);
- },description,30000);
- assert.equal(item.state,expectedState,description+': '+(item.detail || item.error_code || ''));
- return item;
- }
- async function checkSecondUi(commandId) {
- const response=await fetch(cdpUrl+'/json/new?'+encodeURIComponent(url),{method:'PUT',signal:AbortSignal.timeout(5000)});
- if(!response.ok)throw new Error('Cannot create independent observer UI');
- const observer=await response.json(), original=socket, connection=new WebSocket(observer.webSocketDebuggerUrl);
- connection.addEventListener('message',receiveCdpMessage);
- try {
- await socketReady(connection);socket=connection;
- await cdp('Network.enable');
- await waitUntil(()=>evaluate(`document.querySelector('[data-command-id="${commandId}"]')?.dataset.commandState==='succeeded' && document.querySelectorAll('#device-events-tbody [data-event-sequence]').length>0`),'second UI sees first UI command results and device events',30000);
- } finally {
- socket=original;connection.close();
- await fetch(cdpUrl+'/json/close/'+observer.id,{signal:AbortSignal.timeout(2000)}).catch(()=>{});
- }
- }
- 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:false});
- const filename = path.join(evidenceDir, 'browser-'+label+'.png');
- await writeFile(filename, Buffer.from(screenshot.data, 'base64'));
- const full = await cdp('Page.captureScreenshot', {format:'png', fromSurface:true, captureBeyondViewport:true});
- await writeFile(path.join(evidenceDir, 'browser-'+label+'-full.png'), Buffer.from(full.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.
- assert.ok([writeTest,firmwareTest,hardwareConsoleTest,planTest].filter(Boolean).length <= 1,'Select one write/firmware/hardware validation mode');
- console.log('[browser] Starting '+(planTest ? 'simulated boot plan' : firmwareTest ? 'simulated firmware interaction' : writeTest ? 'simulated interaction' : hardwareConsoleTest ? 'restricted hardware console' : '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',receiveCdpMessage);
- await socketReady(socket);
- console.log('[browser] CDP WebSocket ready');
- await cdp('Emulation.setDeviceMetricsOverride', {width:1920, height:1080, deviceScaleFactor:1, mobile:false});
- await cdp('Browser.setDownloadBehavior', {behavior:'allow', downloadPath:temporary});
- await cdp('Network.enable');
- await waitUntil(() => evaluate(`document.querySelectorAll('.station-card').length === 4 && document.getElementById('sys-version').textContent !== '未知'`), 'four connected stations');
- await waitUntil(() => evaluate(`window.stlTransport?.snapshot().state==='open' && document.getElementById('transport-state')?.dataset.state==='open'`), 'application JSON v1 WebSocket connected');
- await installReadHelper();
- await installQueueCapture();
- const info = await readRpc('GetSystemInfo');
- await waitUntil(()=>evaluate(`document.querySelectorAll('#cpu0-grid .dimm-slot[data-slot-id]').length===12 && document.querySelectorAll('#cpu1-grid .dimm-slot[data-slot-id]').length===12`),'backend-owned 24-slot snapshot rendered');
- 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,
- layout:(()=>{const r=document.querySelector('.app-container').getBoundingClientRect();return {viewport:innerWidth,height:innerHeight,contentWidth:r.width,left:r.left,right:document.documentElement.clientWidth-r.right,scrollWidth:document.documentElement.scrollWidth,background:getComputedStyle(document.body).backgroundColor};})(),
- bootStages:[...document.querySelectorAll('.boot-stage')].map(node=>node.dataset.phase), diagnosticControls:['btn-diag-open','btn-diag-reconnect','btn-host-on','btn-host-reset','btn-host-cycle','btn-host-off'].every(id=>!!document.getElementById(id)), queuePanels:['commands-tbody','device-events-tbody','command-station-filter','device-event-station-filter'].every(id=>!!document.getElementById(id)), progressFields:!!document.getElementById('detail-progress') && document.querySelectorAll('.station-progress').length===4, archiveControls:['history-batch-filter','history-sn-filter','history-state-filter','temperature-history','recipe-editor'].every(id=>!!document.getElementById(id))}))()`);
- 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);
- assert.equal(ui.layout.viewport,1920); assert.equal(ui.layout.height,1080);
- assert.ok(ui.layout.contentWidth>=1800 && ui.layout.left>=18 && ui.layout.left<=32 && ui.layout.right>=18 && ui.layout.right<=32,'1080p view uses the available width with compact side margins');
- assert.ok(ui.layout.scrollWidth<=ui.layout.viewport,'Page must not overflow horizontally');
- assert.ok(ui.bootStages.indexOf('uip') < ui.bootStages.indexOf('training'),'UIP configuration is displayed before Training');
- for (const phase of ['boot','uip','training','rmt','amt','post','uefi','mt']) assert.ok(ui.bootStages.includes(phase),'Missing standard phase '+phase);
- assert.ok(ui.diagnosticControls,'Diagnostic controls are available');
- assert.ok(ui.queuePanels,'Command queue and independent device events are available');
- assert.ok(ui.progressFields,'Actual progress fields are present for each station');
- assert.ok(ui.archiveControls,'History filters, temperature samples and recipe editor are present');
- 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()`);
- await waitUntil(() => evaluate(`document.getElementById('detail-station-tag').textContent.startsWith('S1')`), 'S1 selected for subsequent checks');
- const result = {mode: info.mode, url, ui, read_only:!writeTest && !firmwareTest && !hardwareConsoleTest && !planTest};
- const beforeReconnect=await evaluate('window.stlTransport.snapshot()'), writesBeforeReconnect=observedWrites.length;
- await evaluate('window.stlTransport.reconnect()');
- await waitUntil(()=>evaluate(`window.stlTransport.snapshot().state==='open' && window.stlTransport.snapshot().generation>${beforeReconnect.generation} && document.getElementById('refresh-indicator').textContent.includes('已连接')`),'UI reconnect restores snapshot and command/event queue reads');
- await readRpc('GetSystemInfo');
- await waitUntil(()=>Promise.resolve(wsRequests.some(x=>x.method==='GetStationControl')&&wsRequests.some(x=>x.method==='GetQueue')&&wsRequests.some(x=>x.method==='ReadEventQueue')),'control snapshot and both queues travel over WebSocket');
- assert.equal(observedWrites.length,writesBeforeReconnect,'Reconnection does not submit or replay a device command');
- assert.equal(httpRpcRequests.length,0,'HTML UI makes no HTTP RPC calls');
- const unknownMethod=await evaluate(`window.stlTransport.call('SmokeUnknownMethod').then(()=>({ok:true}),error=>({ok:false,code:error.code}))`);
- assert.deepEqual(unknownMethod,{ok:false,code:'UNIMPLEMENTED'},'WebSocket errors preserve structured API codes');
- assert.equal((await readRpc('GetSystemInfo')).version,info.version,'The same connection continues after an RPC error');
- result.transport={...(await evaluate('window.stlTransport.snapshot()')),reconnect_checked:true,no_write_replay:true,error_code_checked:true,http_rpc_fetches:httpRpcRequests.length};
- await waitUntil(()=>evaluate(`document.getElementById('uip-catalog-count').textContent.includes('目录') && !document.getElementById('capability-summary').textContent.includes('读取')`),'firmware catalog and connection capabilities loaded');
- const catalog=await readRpc('GetFirmwareCatalog',{station_id:'S1'});
- assert.ok(Array.isArray(catalog.items) && catalog.items.length>0,'Backend exposes a firmware catalog');
- const control=await readRpc('GetStationControl',{station_id:'S1'});
- assert.ok(control.connections && control.capabilities && control.firmware,'Connection settings, capabilities and firmware observations are separate');
- assert.equal(control.dimms.length,24,'Every control snapshot returns all physical slots');
- assert.equal(new Set(control.dimms.map(x=>x.slot_id)).size,24,'Slot IDs are stable and unique');
- assert.ok(catalog.amt?.items?.length>0,'AMT directory is provided by backend');
- await waitUntil(()=>evaluate(`!!document.getElementById('boot-plan-preset') && document.getElementById('amt-catalog-count').textContent.includes('目录')`),'plan and AMT configuration loaded');
- const dimmUi=await evaluate(`([...document.querySelectorAll('.dimm-slot[data-slot-id]')].map(n=>({id:n.dataset.slotId,quality:n.dataset.temperatureQuality,text:n.querySelector('.slot-temp').textContent})))`);
- for(const row of control.dimms){const shown=dimmUi.find(x=>x.id===row.slot_id);assert.ok(shown,'All backend slots are displayed');if(typeof row.temperature?.value_c==='number' && row.temperature.quality==='reported')assert.match(shown.text,/\d/,'BMC reported temperatures are not hidden as unverified');}
- result.dimm_snapshot={count:control.dimms.length,slots:dimmUi};
- result.page_checks=[];
- for(const [page,panel] of [['overview','stations-grid'],['connections','connection-fields'],['plan','plan-title'],['uip','uip-title'],['amt','amt-title'],['testing','mt-title'],['records','archive-title'],['queue','command-queue-title']]) {
- await evaluate(`document.querySelector('.workspace-tab[data-page="${page}"]').click()`);
- const shown=await evaluate(`(() => {const p=document.getElementById('${panel}');return {page:document.body.dataset.currentPage,visible:!!p && p.getClientRects().length>0,overflow:document.documentElement.scrollWidth>innerWidth};})()`);
- assert.equal(shown.page,page);assert.equal(shown.visible,true);assert.equal(shown.overflow,false);
- result.page_checks.push(shown);
- if(evidenceDir) await saveEvidence('page-'+page,{page,...shown});
- }
- await evaluate("window.stlNavigation.show('amt')");
- const amtActions=await evaluate(`({visible:['btn-save-amt-settings','btn-apply-amt-settings','btn-start-amt','btn-amt-exit'].every(id=>document.getElementById(id).getClientRects().length>0),uip_hidden:document.getElementById('uip-rmt').getClientRects().length===0,owner:document.getElementById('amt-control-owner').textContent,uses_uip_explanation:document.querySelector('.amt-panel').textContent.includes('UIP 的 admt')})`);
- assert.ok(amtActions.visible&&amtActions.uip_hidden&&!amtActions.uses_uip_explanation,'AMT has independent save/apply/start/exit actions and no UIP setting duplication');
- result.amt_actions=amtActions;
- await evaluate("window.stlNavigation.show('testing')");
- await waitUntil(()=>evaluate(`!!window.stlFirmware.snapshot('S1').firmware?.stage_progress && document.getElementById('stage-detail-panel').getClientRects().length>0`),'backend stage detail projection available');
- const stageDisplay = await evaluate(`(() => {
- const p=window.stlFirmware.snapshot('S1').firmware.stage_progress;
- return {boot_id:p.boot_id,shown_boot:document.getElementById('stage-detail-panel').dataset.bootId,
- main:p.main?.id || 'unknown',shown_main:document.getElementById('boot-stages').dataset.mainPhase,
- backend_stages:(p.stages||[]).map(x=>x.id),shown_stages:[...document.querySelectorAll('#boot-stages [data-phase]')].map(x=>x.dataset.phase),
- backend_cpus:(p.per_cpu||[]).map(x=>String(x.cpu)),shown_cpus:[...document.querySelectorAll('#stage-cpu-cards [data-cpu]')].map(x=>x.dataset.cpu),
- step_count:(p.steps||[]).length,shown_steps:document.querySelectorAll('#stage-steps-body tr[data-step-id]').length,
- summary:document.getElementById('boot-current').textContent,detail:document.getElementById('stage-detail-live').textContent,
- overflow:document.documentElement.scrollWidth>innerWidth};
- })()`);
- assert.equal(stageDisplay.shown_boot,stageDisplay.boot_id || '');
- assert.equal(stageDisplay.shown_main,stageDisplay.main,'Major phase comes from backend projection');
- assert.deepEqual(stageDisplay.shown_stages,stageDisplay.backend_stages);
- assert.deepEqual(stageDisplay.shown_cpus,stageDisplay.backend_cpus);
- assert.equal(stageDisplay.shown_steps,Math.min(80,stageDisplay.step_count));
- assert.equal(stageDisplay.overflow,false);
- const filterCheck=await evaluate(`(() => {
- const p=window.stlFirmware.snapshot('S1').firmware.stage_progress,step=(p.steps||[]).find(x=>x.cpu!==null && x.cpu!==undefined);
- if(!step)return {available:false};
- const phase=document.getElementById('stage-filter-phase'),cpu=document.getElementById('stage-filter-cpu');
- phase.value=step.stage;cpu.value=String(step.cpu);phase.dispatchEvent(new Event('change'));
- const shown=[...document.querySelectorAll('#stage-steps-body tr[data-step-id]')].map(x=>({stage:x.dataset.stage,cpu:x.dataset.cpu}));
- document.getElementById('btn-stage-filter-reset').click();
- return {available:true,expected:{stage:step.stage,cpu:String(step.cpu)},shown};
- })()`);
- if(filterCheck.available){assert.ok(filterCheck.shown.length>0);for(const row of filterCheck.shown)assert.deepEqual(row,filterCheck.expected);}
- await evaluate("window.stlNavigation.show('overview')");
- const stageOverview=await evaluate(`({summary:document.getElementById('boot-stages').getClientRects().length>0,details:document.getElementById('stage-detail-panel').getClientRects().length>0,algorithms:document.getElementById('algorithm-progress').getClientRects().length>0,link:document.getElementById('btn-stage-details').getClientRects().length>0})`);
- assert.deepEqual(stageOverview,{summary:true,details:false,algorithms:false,link:true},'Overview keeps the main progress; detail panels stay on later pages');
- result.stage_display={...stageDisplay,filters_checked:filterCheck.available,overview:stageOverview};
- await evaluate(`window.stlNavigation.show('uip');document.getElementById('uip-search').value='errhandle';document.getElementById('uip-search').dispatchEvent(new Event('input'))`);
- assert.ok(await evaluate(`document.getElementById('uip-parameters').textContent.includes('errhandle')`),'UIP catalog search shows errhandle');
- await evaluate(`document.getElementById('uip-search').value='';document.getElementById('uip-search').dispatchEvent(new Event('input'));window.stlNavigation.show('overview')`);
- assert.ok(await evaluate("!!document.getElementById('rmt-results-panel')"),'RMT evidence panel exists');
- if(control.firmware.rmt_measurements?.length) {
- const expectedCpus=[...new Set(control.firmware.rmt_results.map(row=>Number(row.cpu)))].sort();
- await evaluate("window.stlNavigation.show('testing');document.getElementById('rmt-results-panel').open=true");
- await waitUntil(()=>evaluate(`document.querySelectorAll('#rmt-cpu-results [data-rmt-cpu]').length===${expectedCpus.length}`),'real RMT CPU evidence rendered');
- const rmt=await evaluate(`({cpus:[...document.querySelectorAll('#rmt-cpu-results [data-rmt-cpu]')].map(n=>({cpu:Number(n.dataset.rmtCpu),supported:n.dataset.rmtExecutionSupported==='true',text:n.textContent})),rows:document.querySelectorAll('#rmt-measurements tr').length,text:document.getElementById('rmt-measurements').textContent,overflow:document.documentElement.scrollWidth>innerWidth})`);
- assert.deepEqual(rmt.cpus.map(x=>x.cpu).sort(),expectedCpus);
- assert.equal(rmt.rows,Math.min(32,control.firmware.rmt_measurements.length));
- assert.equal(rmt.overflow,false);
- for(const row of control.firmware.rmt_results)assert.equal(rmt.cpus.find(x=>x.cpu===Number(row.cpu)).supported,row.execution_supported===true);
- result.rmt_display={cpus:rmt.cpus,rows:rmt.rows,overflow:rmt.overflow};
- await saveEvidence('rmt-evidence',result.rmt_display);
- await evaluate("document.getElementById('rmt-results-panel').open=false;window.stlNavigation.show('overview')");
- }
- result.firmware_catalog_count=catalog.items.length;
- result.capabilities=control.capabilities;
- if(!control.capabilities.bmc_power) assert.equal(await evaluate(`document.getElementById('btn-host-on').disabled`),true,'Unavailable BMC power action is disabled');
- if (process.env.STL_BROWSER_ALGORITHM_REPLAY_TEST === '1') {
- assert.equal(info.mode,'simulated','Algorithm replay check uses an isolated simulated bench');
- await waitUntil(()=>evaluate(`document.querySelectorAll('#algorithm-progress .algorithm-cpu').length===2`),'both CPU algorithm rows');
- const readAlgorithms=()=>evaluate(`(() => ({rows:[...document.querySelectorAll('#algorithm-progress .algorithm-cpu')].map(n=>({cpu:n.dataset.cpu,index:n.dataset.index,total:n.dataset.total,completed:n.dataset.completed,state:n.dataset.state,text:n.textContent})),percent:document.getElementById('detail-progress').dataset.percent,progress:document.getElementById('detail-progress').textContent}))()`);
- const first=await readAlgorithms();
- assert.deepEqual(first.rows.map(({cpu,index,total,completed,state})=>({cpu,index,total,completed,state})),[
- {cpu:'0',index:'9',total:'19',completed:'8',state:'running'},
- {cpu:'1',index:'9',total:'19',completed:'8',state:'running'}]);
- for(const row of first.rows){assert.match(row.text,/AMEMDIAG/);assert.match(row.text,/A-MD1/);}
- assert.equal(first.percent,'');assert.ok(!first.progress.includes('%'));
- await cdp('Page.reload',{ignoreCache:true});
- await waitUntil(()=>evaluate(`document.querySelectorAll('#algorithm-progress .algorithm-cpu').length===2`),'algorithm rows restored after reload');
- const after=await readAlgorithms();
- assert.deepEqual(after.rows.map(({text,...row})=>row),first.rows.map(({text,...row})=>row));
- result.algorithm_replay={source:'captured current-sol.raw',rows:first.rows,reload_restored:true,no_fabricated_percent:true};
- }
- if (writeTest) {
- assert.equal(info.mode,'simulated','Write smoke test refuses hardware mode');
- const existing = await readRpc('GetStation',{station_id:'S1'}); assert.ok(!existing.run_id,'Use a fresh simulated station');
- await clickButton('btn-open-start');
- await waitUntil(() => evaluate(`!document.getElementById('modal-start-run').classList.contains('hidden')`), 'start modal');
- await waitForButton('btn-confirm-start-run');
- 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-recipe').value='DEMO-80'; document.getElementById('start-recipe').dispatchEvent(new Event('change')); 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('boot-stages').dataset.source==='run' && document.getElementById('boot-stages').dataset.runId===${JSON.stringify(runId)} && document.querySelector('.boot-stage[data-phase="uip"]').classList.contains('observed')`),'active run UIP stage shown from parser events');
- const runEvidence=await readRpc('ListEvents',{run_id:runId,after_event_id:0,limit:1000});
- assert.ok(runEvidence.events.some(event=>event.phase==='uip' && ['stage','prompt'].includes(event.kind) && event.raw_line && event.details?.parser_version && !event.artifact_id),'Run stage has live parser evidence');
- await waitUntil(()=>evaluate(`!document.getElementById('btn-sol-mode').disabled`),'manual button');
- await clickButton('btn-sol-mode');
- 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 waitForButton('btn-send-sol');
- await evaluate(`document.getElementById('sol-input-cmd').value='help'; document.getElementById('btn-send-sol').click()`);
- await waitUntil(()=>evaluate(`document.getElementById('action-status').textContent.includes('发送控制台') && document.getElementById('action-status').textContent.includes('执行成功')`),'SOL command acknowledgement');
- assert.equal(Buffer.from((await submitted('WriteSol')).at(-1).arguments.data,'base64').toString(), 'help\r', 'SOL command must end in one CR');
- await clickButton('btn-send-enter');
- await waitUntil(async()=> (await submitted('WriteSol')).length === 2,'explicit empty CR enqueued');
- assert.equal(Buffer.from((await submitted('WriteSol')).at(-1).arguments.data,'base64').toString(), '\r', 'Empty return must be one CR');
- await clickButton('btn-open-target');
- await waitUntil(()=>evaluate(`!document.getElementById('modal-target-temp').classList.contains('hidden')`),'temperature dialog');
- await waitForButton('btn-save-temp');
- 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 waitForButton('btn-stop-run');
- 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 waitForButton('btn-import-artifact');
- 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 clickButton('btn-download-report');
- 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 waitForButton('btn-refresh-history');
- await evaluate(`document.getElementById('history-batch-filter').value='BROWSER-BATCH';document.getElementById('history-sn-filter').value='BROWSER-SN-1';document.getElementById('history-state-filter').value='stopped';document.getElementById('btn-refresh-history').click()`);
- await waitUntil(()=>evaluate(`document.getElementById('history-match-count').textContent.includes('匹配') && [...document.getElementById('history-run').options].some(option=>option.value===${JSON.stringify(runId)}) && !document.getElementById('btn-refresh-history').disabled`),'batch, SN and state history filtering');
- const matchedRuns=await readRpc('ListRuns',{station_id:'S1',batch_no:'BROWSER-BATCH',sn:'BROWSER-SN-1',state:'stopped',limit:50});
- const visibleRunIds=await evaluate(`[...document.getElementById('history-run').options].map(option=>option.value).filter(Boolean)`);
- assert.deepEqual(visibleRunIds,matchedRuns.runs.map(run=>run.run_id),'History dropdown reflects backend filters');
- await waitForButton('btn-refresh-history');
- await evaluate(`document.getElementById('history-batch-filter').value='BROWSER-NO-MATCH-${Date.now()}';document.getElementById('btn-refresh-history').click()`);
- await waitUntil(()=>evaluate(`document.getElementById('history-match-count').textContent.includes('匹配 0 条') && document.getElementById('run-summary').textContent==='尚无测试记录'`),'empty history result does not show an unrelated recent run');
- await clickButton('btn-reset-history');
- await waitUntil(()=>evaluate(`!document.getElementById('history-batch-filter').value && document.getElementById('history-match-count').textContent.includes('最近') && !document.getElementById('btn-reset-history').disabled`),'history filter reset');
- result.history_filter_checks=['exact station/batch/SN/state match','dropdown matches ListRuns results','empty matches remain empty','reset restores current/recent selection'];
- // A separate automatic run keeps the manual-input smoke test from advancing
- // BIOS prompts that the automatic profile still needs to configure.
- await waitUntil(()=>evaluate(`!document.getElementById('btn-open-start').disabled`),'automatic progress run available');
- await clickButton('btn-open-start');
- await waitUntil(()=>evaluate(`!document.getElementById('modal-start-run').classList.contains('hidden')`),'automatic progress run dialog');
- await waitForButton('btn-confirm-start-run');
- await evaluate(`document.getElementById('start-wo').value='BROWSER-AUTO-WO';document.getElementById('start-batch').value='BROWSER-AUTO-BATCH';document.getElementById('start-recipe').value='DEMO-80';document.getElementById('start-recipe').dispatchEvent(new Event('change'));document.getElementById('btn-confirm-start-run').click()`);
- let progressRunId;
- await waitUntil(async()=> {const station=await readRpc('GetStation',{station_id:'S1'});progressRunId=station.run_id;return !!progressRunId && progressRunId!==runId;},'automatic progress run started');
- await waitUntil(()=>evaluate(`document.getElementById('boot-stages').dataset.runId===${JSON.stringify(progressRunId)} && document.querySelector('.boot-stage[data-phase="mt"]').classList.contains('observed')`),'automatic run MT start promptly observed',15000);
- let progressSnapshot;
- await waitUntil(async()=> {progressSnapshot=await readRpc('GetStation',{station_id:'S1'});return progressSnapshot.run_id===progressRunId && typeof progressSnapshot.progress_percent==='number' && progressSnapshot.progress_phase==='mt' && Number(progressSnapshot.progress_observed_unix_ms)>0;},'actual first MT progress report (separate from startup)',35000);
- await waitUntil(()=>evaluate(`document.getElementById('detail-progress').dataset.phase==='mt' && Number(document.getElementById('detail-progress').dataset.percent)===${progressSnapshot.progress_percent} && document.getElementById('detail-progress').dataset.observedMs===${JSON.stringify(String(progressSnapshot.progress_observed_unix_ms))} && document.getElementById('detail-progress').textContent.includes('最近报告进度')`),'actual progress, source phase and report time displayed');
- const progressEvents=await readRpc('ListEvents',{run_id:progressRunId,after_event_id:0,limit:1000});
- const progressEvent=progressEvents.events.find(event=>event.kind==='progress' && event.phase==='mt' && event.details?.percent===progressSnapshot.progress_percent && event.details?.parser_version && event.raw_line && !event.artifact_id);
- assert.ok(progressEvent,'Displayed percentage is backed by this run actual parser progress');
- for(const phase of ['uip','rmt','amt','uefi','mt']) {
- assert.equal(await evaluate(`document.querySelector('.boot-stage[data-phase="${phase}"]').classList.contains('observed')`),true,'Actual run observed '+phase);
- assert.ok(progressEvents.events.some(event=>event.phase===phase && ['stage','prompt','training','progress','rmt_margin'].includes(event.kind) && event.raw_line && event.details?.parser_version && !event.artifact_id),'Observed '+phase+' has this run live parser evidence');
- }
- result.run_observation_checks=['active run timeline uses its own live parser events','configuration/workflow events do not fabricate boot stages','MT startup visible within 15 seconds','percentage retains actual phase and report time'];
- result.progress_evidence={run_id:progressRunId,percent:progressSnapshot.progress_percent,phase:progressSnapshot.progress_phase,observed_unix_ms:progressSnapshot.progress_observed_unix_ms,event_id:progressEvent.event_id};
- const originalRecipe=await readRpc('GetRecipe',{recipe_id:'DEMO-80'});
- await evaluate(`document.getElementById('recipe-editor').open=true`);
- await waitUntil(()=>evaluate(`[...document.getElementById('recipe-edit-select').options].some(option=>option.value==='DEMO-80')`),'recipe editor options loaded');
- await evaluate(`document.getElementById('recipe-edit-select').value='DEMO-80';document.getElementById('recipe-edit-select').dispatchEvent(new Event('change'))`);
- await waitUntil(()=>evaluate(`document.getElementById('recipe-edit-id').value==='DEMO-80' && !document.getElementById('recipe-edit-fields').disabled && !document.getElementById('btn-save-recipe').disabled`),'existing recipe loaded for editing');
- let renamedRecipe;
- const temporaryName=originalRecipe.name+' · 浏览器模拟验收';
- try {
- await waitForButton('btn-save-recipe');
- await evaluate(`document.getElementById('recipe-edit-name').value=${JSON.stringify(temporaryName)};document.getElementById('btn-save-recipe').click()`);
- await waitUntil(async()=> {renamedRecipe=await readRpc('GetRecipe',{recipe_id:'DEMO-80'});return renamedRecipe.name===temporaryName && renamedRecipe.revision===originalRecipe.revision+1;},'recipe saved using expected revision');
- assert.equal(renamedRecipe.profile_id,originalRecipe.profile_id,'Saving retains the existing firmware profile');
- const runningSnapshot=await readRpc('GetRun',{run_id:progressRunId});
- assert.equal(runningSnapshot.recipe.name,originalRecipe.name,'Running test retains its recipe name snapshot');
- assert.equal(runningSnapshot.recipe.revision,originalRecipe.revision,'Running test retains its recipe revision snapshot');
- } finally {
- const latest=await readRpc('GetRecipe',{recipe_id:'DEMO-80'});
- if(latest.name!==originalRecipe.name) {
- await waitUntil(()=>evaluate(`!document.getElementById('btn-load-recipe').disabled && !document.getElementById('btn-save-recipe').disabled`),'recipe editor ready to restore');
- await clickButton('btn-load-recipe');
- await waitUntil(()=>evaluate(`Number(document.getElementById('recipe-edit-revision').value)===${latest.revision} && !document.getElementById('btn-load-recipe').disabled`),'latest recipe revision reloaded for restoration');
- await waitForButton('btn-save-recipe');
- await evaluate(`document.getElementById('recipe-edit-name').value=${JSON.stringify(originalRecipe.name)};document.getElementById('btn-save-recipe').click()`);
- await waitUntil(async()=> (await readRpc('GetRecipe',{recipe_id:'DEMO-80'})).name===originalRecipe.name,'original recipe name restored');
- }
- }
- const restoredRecipe=await readRpc('GetRecipe',{recipe_id:'DEMO-80'});
- assert.deepEqual(restoredRecipe,{...originalRecipe,revision:originalRecipe.revision+2},'Only the intended name round trip and revision increments occur');
- const recipeWrites=await evaluate('window.__stlRecipeSaves');
- assert.deepEqual(recipeWrites.map(request=>request.expected_revision),[originalRecipe.revision,originalRecipe.revision+1]);
- result.recipe_checks={recipe_id:'DEMO-80',original_revision:originalRecipe.revision,restored_revision:restoredRecipe.revision,original_name_restored:true,profile_preserved:true,running_snapshot_unchanged:true};
- await evaluate(`document.getElementById('recipe-editor').open=false;document.getElementById('temperature-history').open=true`);
- await waitUntil(()=>evaluate(`document.getElementById('temperature-history').dataset.runId===${JSON.stringify(progressRunId)} && document.querySelectorAll('#temperature-history-tbody [data-sample-id]').length>0 && !document.getElementById('btn-temperature-more').disabled`),'actual temperature samples rendered');
- const temperatures=await readRpc('QueryTemperatures',{run_id:progressRunId,after_sample_id:0,limit:100});
- assert.ok(temperatures.samples.length>0);
- const environmentSample=temperatures.samples.find(sample=>typeof sample.temperature?.hood_air?.value_c==='number');
- assert.ok(environmentSample,'Actual environment temperature exists in recorded samples');
- assert.ok(await evaluate(`document.querySelector('[data-sample-id="${environmentSample.sample_id}"]')?.dataset.sampleRun===${JSON.stringify(progressRunId)} && document.querySelector('[data-sample-id="${environmentSample.sample_id}"]').textContent.includes(${JSON.stringify(environmentSample.temperature.hood_air.value_c.toFixed(1)+'°C')})`),'Temperature row retains the actual value and selected run');
- assert.ok(await evaluate(`document.querySelector('[data-sample-id="${environmentSample.sample_id}"]').textContent.includes(${JSON.stringify(environmentSample.temperature.hood_air.quality)})`),'Temperature quality is visible');
- const laterTemperatures=await readRpc('QueryTemperatures',{run_id:progressRunId,after_sample_id:temperatures.next_after_sample_id,limit:100});
- if(laterTemperatures.samples.length) {
- await clickButton('btn-temperature-more');
- await waitUntil(()=>evaluate(`!!document.querySelector('[data-sample-id="${laterTemperatures.samples[0].sample_id}"]')`),'next temperature page loaded by sample cursor');
- }
- result.temperature_history_checks={run_id:progressRunId,first_page_samples:temperatures.samples.length,next_page_samples:laterTemperatures.samples.length,sample_id:environmentSample.sample_id,environment_c:environmentSample.temperature.hood_air.value_c,quality:environmentSample.temperature.hood_air.quality};
- await evaluate(`document.getElementById('temperature-history').open=false`);
- await clickButton('btn-stop-run');
- await waitUntil(async()=> {const run=await readRpc('GetRun',{run_id:progressRunId});return run.state==='stopped' && run.supply_state==='off';},'automatic progress run stopped and powered off');
- // Exercise the separate diagnostic session after the high-temperature run.
- // These commands remain simulation-only; the default hardware check is read-only.
- await clickButton('btn-sim-supply-on');
- await waitUntil(async()=> (await readRpc('GetStation',{station_id:'S1'})).supply_state==='on','diagnostic simulated supply on');
- await clickButton('btn-diag-open');
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).state==='online','standalone diagnostic SOL online');
- const diagnostic = await readRpc('GetDiagnostic',{station_id:'S1'});
- assert.ok(diagnostic.session_id);
- assert.ok(!(await readRpc('GetStation',{station_id:'S1'})).run_id,'Diagnostic must not create a high-temperature run');
- await clickButton('btn-host-on');
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).phase==='uip','real simulated UIP output detected');
- await waitUntil(()=>evaluate(`!document.getElementById('btn-send-sol').disabled`),'diagnostic command input enabled');
- assert.equal(await evaluate(`document.getElementById('btn-open-start').disabled`),true,'Test start must wait for diagnostic session to close');
- await waitForButton('btn-send-sol');
- await evaluate(`document.getElementById('sol-input-cmd').value='help';document.getElementById('btn-send-sol').click()`);
- await waitUntil(async()=> (await submitted('WriteDiagnosticSol')).length===1,'diagnostic command enqueued');
- const diagWrite = (await submitted('WriteDiagnosticSol'))[0];
- assert.equal(diagWrite.arguments.session_id,diagnostic.session_id);assert.equal(Buffer.from(diagWrite.arguments.data,'base64').toString(),'help\r');
- await completedQueueItem(diagWrite.command_id,'diagnostic console queue item completed');
- await waitUntil(()=>evaluate(`!document.getElementById('btn-send-enter').disabled`),'first diagnostic return available');
- await clickButton('btn-send-enter');
- await waitUntil(async()=> (await submitted('WriteDiagnosticSol')).length===2 && await evaluate(`!document.getElementById('btn-send-enter').disabled`),'first UIP return accepted');
- await clickButton('btn-send-enter');
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).phase==='uefi','diagnostic UEFI entered');
- const afterUefi=await readRpc('GetDiagnostic',{station_id:'S1'});
- for(const phase of ['uip','rmt','amt','uefi']) assert.ok(afterUefi.observations.some(o=>o.phase===phase),'Missing observed phase '+phase);
- await waitForButton('btn-send-sol');
- await evaluate(`document.getElementById('sol-input-cmd').value='memtest.efi';document.getElementById('btn-send-sol').click()`);
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).observations.some(o=>o.phase==='mt'),'diagnostic MT output observed');
- await clickButton('btn-host-reset');
- await waitUntil(async()=> {const d=await readRpc('GetDiagnostic',{station_id:'S1'});return d.phase==='uip'&&d.observations.some(o=>o.kind==='power_command');},'host reset and new UIP observation');
- await clickButton('btn-host-cycle');
- await waitUntil(async()=> {const d=await readRpc('GetDiagnostic',{station_id:'S1'});return d.phase==='uip'&&d.observations.filter(o=>o.kind==='power_command').length>=3;},'host cycle and new UIP observation');
- await waitForButton('btn-query-bmc');
- await evaluate(`document.getElementById('bmc-query-kind').value='info';document.getElementById('btn-query-bmc').click()`);
- await waitUntil(()=>evaluate(`document.getElementById('bmc-query-output').textContent.includes('SIMULATED BMC')`),'BMC query output visible');
- await clickButton('btn-download-sol');
- await waitUntil(async()=> (await readdir(temporary)).some(n=>n===diagnostic.session_id+'-sol.bin'),'diagnostic raw log download');
- await clickButton('btn-host-off');
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).phase==='off','diagnostic host off observed');
- await clickButton('btn-diag-close');
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).state==='closed','diagnostic closed');
- await clickButton('btn-sim-supply-off');
- await waitUntil(async()=> (await readRpc('GetStation',{station_id:'S1'})).supply_state==='off','diagnostic simulated supply off');
- const submissions=await evaluate('window.__stlQueueSubmissions');
- assert.ok(submissions.some(item=>item.method==='StartRun') && submissions.some(item=>item.method==='QueryBmc'),'Run and BMC operations are submitted to the queue');
- for(const request of submissions) await completedQueueItem(request.command_id,'queue result for '+request.method);
- assert.ok(observedWrites.length && observedWrites.every(method=>['EnqueueCommand','PutRecipe','BeginArtifact','UploadArtifactChunk','FinishArtifact'].includes(method)),'Device/run controls use EnqueueCommand; recipe edits and file chunks use their typed APIs');
- const queue=await readRpc('GetQueue',{station_id:'S1',limit:100});
- for(const request of submissions) assert.ok(queue.items.some(item=>item.command_id===request.command_id && item.state==='succeeded'),'Shared queue retains '+request.method);
- const firstEvents=await readRpc('ReadEventQueue',{station_id:'S1',after_sequence:0,limit:100});
- const otherReader=await readRpc('ReadEventQueue',{station_id:'S1',after_sequence:0,limit:100});
- assert.ok(firstEvents.events.length>0,'Device event queue has actual dispatched operation events');
- assert.deepEqual(firstEvents.events.map(event=>event.sequence),otherReader.events.slice(0,firstEvents.events.length).map(event=>event.sequence),'Reading does not consume another UI event cursor');
- await waitUntil(()=>evaluate(`document.querySelectorAll('#commands-tbody [data-command-id]').length>0 && document.querySelectorAll('#device-events-tbody [data-event-sequence]').length>0`),'shared command and device-event rows rendered');
- // A read against the powered-off simulator must fail visibly, without changing power.
- const previousQueries=(await submitted('QueryBmc')).length;
- await waitUntil(()=>evaluate(`!document.getElementById('btn-query-bmc').disabled`),'offline simulated BMC query available');
- await waitForButton('btn-query-bmc');
- await evaluate(`document.getElementById('bmc-query-kind').value='info';document.getElementById('btn-query-bmc').click()`);
- await waitUntil(async()=> (await submitted('QueryBmc')).length===previousQueries+1,'offline simulated query enqueued');
- const failedRequest=(await submitted('QueryBmc')).at(-1);
- const failedResult = await completedQueueItem(failedRequest.command_id, 'offline simulated query result', 'failed');
- assert.equal(failedResult.state,'failed');assert.ok(failedResult.detail,'Failed queue item includes the device error');
- await waitUntil(()=>evaluate(`document.getElementById('bmc-query-output').textContent.includes('查询失败') && document.querySelector('[data-command-id="${failedRequest.command_id}"]')?.dataset.commandState==='failed'`),'device failure visible in BMC panel and shared queue');
- if (manualRecipeId) {
- await waitUntil(()=>evaluate(`!document.getElementById('btn-open-start').disabled`),'manual confirmation test available');
- await clickButton('btn-open-start');
- await waitUntil(()=>evaluate(`!document.getElementById('modal-start-run').classList.contains('hidden')`),'manual confirmation run dialog');
- assert.ok(await evaluate(`[...document.getElementById('start-recipe').options].some(option=>option.value===${JSON.stringify(manualRecipeId)})`),'Configured manual validation recipe must exist');
- await waitForButton('btn-confirm-start-run');
- await evaluate(`document.getElementById('start-wo').value='BROWSER-MANUAL-WO';document.getElementById('start-batch').value='BROWSER-MANUAL-BATCH';document.getElementById('start-recipe').value=${JSON.stringify(manualRecipeId)};document.getElementById('start-recipe').dispatchEvent(new Event('change'));document.getElementById('btn-confirm-start-run').click()`);
- let manualStation;
- await waitUntil(async()=> {manualStation=await readRpc('GetStation',{station_id:'S1'});return !!manualStation.run_id && !!manualStation.pending_step_id && !['power_on','power_off'].includes(manualStation.pending_step_id);},'actual manual stage waiting for operator',30000);
- await waitUntil(()=>evaluate(`!document.getElementById('manual-confirm-bar').classList.contains('hidden') && !document.getElementById('btn-fail-stage').classList.contains('hidden') && !document.getElementById('btn-fail-stage').disabled`),'manual failure action visible and enabled');
- const manualEvidence='浏览器模拟验收:人工拒绝当前配置步骤,验证失败收尾。';
- await waitForButton('btn-fail-stage');
- await evaluate(`document.getElementById('confirm-evidence').value=${JSON.stringify(manualEvidence)};document.getElementById('btn-fail-stage').click()`);
- await waitUntil(async()=> (await submitted('ConfirmStage')).some(item=>item.arguments.run_id===manualStation.run_id),'manual failure queued');
- const rejectedStage=(await submitted('ConfirmStage')).find(item=>item.arguments.run_id===manualStation.run_id);
- assert.equal(rejectedStage.arguments.succeeded,false);assert.equal(rejectedStage.arguments.evidence,manualEvidence);
- await completedQueueItem(rejectedStage.command_id,'manual rejection accepted by backend');
- let manualRun;
- await waitUntil(async()=> {manualRun=await readRpc('GetRun',{run_id:manualStation.run_id});return manualRun.state==='failed' && manualRun.supply_state==='off';},'manual rejection finishes run and powers whole station off',30000);
- const manualEvents=await readRpc('ListEvents',{run_id:manualStation.run_id,after_event_id:0,limit:1000});
- assert.ok(manualEvents.events.some(event=>event.kind==='manual_confirmation' && event.details?.succeeded===false && event.message===manualEvidence),'Manual failure evidence recorded with succeeded=false');
- result.manual_failure_check={run_id:manualRun.run_id,command_id:rejectedStage.command_id,state:manualRun.state,supply_state:manualRun.supply_state,verdict:manualRun.verdict,evidence:manualEvidence};
- } else result.manual_failure_check={executed:false,reason:'Set STL_BROWSER_MANUAL_RECIPE_ID to an actual manual simulated profile to exercise failure confirmation'};
- await checkSecondUi(submissions.at(-1).command_id);
- result.queue_checks=['all device/run actions submitted through EnqueueCommand','successful actions reached terminal queue states','GetQueue retains actual operation results','device-event readers have independent cursors','powered-off BMC query failure visible in shared queue and BMC panel','independent second UI displays first UI operations'];
- result.queue_commands=submissions.map(item=>({command_id:item.command_id,method:item.method,station_id:item.station_id}));
- result.queue_expected_failure={command_id:failedResult.command_id,state:failedResult.state,detail:failedResult.detail,error_code:failedResult.error_code};
- result.diagnostic_session_id=diagnostic.session_id;
- result.diagnostic_checks=['independent SOL session without test run','single CR command routing','UIP/RMT/AMT/UEFI/MT observations','host reset','host cycle','BMC query','raw log download','host off and close'];
- }
- if (planTest) {
- assert.equal(info.mode,'simulated','Boot-plan write check refuses hardware mode');
- await evaluate(`window.confirm=()=>true`);
- const initial=await readRpc('GetStationControl',{station_id:'S1'}),station=await readRpc('GetStation',{station_id:'S1'}),diagnostic=await readRpc('GetDiagnostic',{station_id:'S1'});
- assert.ok(!station.run_id && !['online','connecting'].includes(diagnostic.state),'Use an idle simulated station with a closed console');
- assert.equal(station.supply_state,'off','Use a simulated bench with whole-station supply off');
- assert.equal((initial.firmware_settings.uip_overrides||[]).length,0,'Use an isolated default UIP settings fixture');
- assert.equal((initial.firmware_settings.uip_raw_commands||[]).length,0,'Use an isolated default raw-command fixture');
- assert.ok(!initial.firmware_settings.mt_selection?.efi_path,'Use a fixture without a saved MT selection');
- assert.equal((initial.amt_settings.overrides||[]).length,0,'Use an isolated default AMT settings fixture');
- assert.equal((initial.amt_settings.raw_commands||[]).length,0,'Use a fixture without custom AMT raw commands');
- const field=async(id,value)=>evaluate(`(() => {const f=document.getElementById(${JSON.stringify(id)});if(!f)throw Error('Missing field '+${JSON.stringify(id)});if(f.type==='checkbox')f.checked=${JSON.stringify(value)};else f.value=${JSON.stringify(value)};f.dispatchEvent(new Event(f.tagName==='SELECT'||f.type==='checkbox'?'change':'input',{bubbles:true}));})()`);
- const uiCommand=async(button,method,description)=>{const before=(await submitted(method)).length;await clickButton(button);await waitUntil(async()=> (await submitted(method)).length>before,description+' enqueued');return completedQueueItem((await submitted(method)).at(-1).command_id,description);};
- const choosePlan=async(plan)=>{await evaluate(`window.stlNavigation.show('plan')`);await field('boot-plan-preset',plan.preset);for(const [key,value]of Object.entries(plan.stages||{}))await evaluate(`(() => {const s=document.querySelector('[data-plan-stage="${key}"]');s.value=${JSON.stringify(value)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`);await field('boot-plan-mt-enabled',!!plan.mt_enabled);await field('boot-plan-use-in-runs',!!plan.use_in_runs);return uiCommand('btn-save-boot-plan','SaveBootPlan','save boot plan '+plan.preset);};
- const allStages=mode=>Object.fromEntries(['uip1','amt','uip2','uefi','mt'].map(stage=>[stage,mode]));
- const automatic={preset:'auto',stages:allStages('auto'),mt_enabled:false,use_in_runs:false};
- const originalPlan=JSON.parse(JSON.stringify(initial.boot_plan));
- let planError;
- try {
- await clickButton('btn-uip-defaults');
- await field('uip-raw-commands','errhandle disable');
- await field('uip-rmt','enable');
- await uiCommand('btn-save-firmware-settings','SaveFirmwareSettings','save UIP settings including raw commands');
- const fw=(await readRpc('GetStationControl',{station_id:'S1'})).firmware_settings;
- assert.deepEqual(fw.uip_raw_commands,['errhandle disable']);assert.ok(fw.uip_overrides.some(x=>x.id==='rmt'&&x.value==='enable'));
- await evaluate(`window.stlNavigation.show('amt')`);
- await field('amt-action','skip');await field('amt-test-command','amemdiag 1');
- await field('amt-search','algomask');
- await waitUntil(()=>evaluate(`!!document.querySelector('.amt-include[data-name="algomask"]')`),'AMT algomask configuration is exposed');
- await evaluate(`(() => {const value=document.querySelector('.amt-parameter-value[data-name="algomask"]');value.value='0x1';value.dispatchEvent(new Event('input',{bubbles:true}));const include=document.querySelector('.amt-include[data-name="algomask"]');include.checked=true;include.dispatchEvent(new Event('change',{bubbles:true}));})()`);
- await uiCommand('btn-save-amt-settings','SaveAmtSettings','save explicit AMT setting without executing it');
- const amt=(await readRpc('GetStationControl',{station_id:'S1'})).amt_settings;
- assert.equal(amt.action,'skip');assert.ok(amt.overrides.some(x=>x.name==='algomask'&&x.value==='0x1'));
- await choosePlan(automatic);
- const saved=(await readRpc('GetStationControl',{station_id:'S1'})).boot_plan;assert.equal(saved.preset,'auto');assert.equal(saved.mt_enabled,false);assert.equal(saved.use_in_runs,false);
- const savedWrites=observedWrites.length,origin=await evaluate('performance.timeOrigin');
- await cdp('Page.reload',{ignoreCache:true});
- await waitUntil(async()=>{try{return await evaluate(`performance.timeOrigin!==${origin} && document.getElementById('boot-plan-save-state')?.textContent==='已保存配置' && document.getElementById('amt-catalog-count')?.textContent.includes('目录')`);}catch{return false;}},'saved plan reloads without execution');
- await installReadHelper();await installQueueCapture();
- await evaluate("window.confirm=()=>true");
- assert.equal(observedWrites.length,savedWrites,'Page reload only reads state');
- assert.equal((await readRpc('GetDiagnostic',{station_id:'S1'})).state,diagnostic.state,'Saving/reloading does not open console');
- assert.equal(await evaluate(`document.getElementById('boot-plan-preset').value`),'auto');
- assert.equal(await evaluate(`document.getElementById('uip-raw-commands').value`),'errhandle disable');
- assert.equal(await evaluate(`document.getElementById('amt-test-command').value`),'amemdiag 1');
- await uiCommand('btn-sim-supply-on','StationPower','supply on for plan check');
- await uiCommand('btn-diag-open','SetDiagnosticSol','open simulated console');
- await uiCommand('btn-host-on','StationPower','start fixture before controlled restart');
- await waitUntil(async()=> (await readRpc('GetStationControl',{station_id:'S1'})).phase_actions.continue_uip.available,'fixture waits in UIP before restart');
- const beforeBoot=(await readRpc('GetStationControl',{station_id:'S1'})).firmware;
- await uiCommand('btn-restart-boot-plan','ControlBootPlan','restart and execute saved automatic plan');
- let autoResult;
- await waitUntil(async()=>{autoResult=await readRpc('GetStationControl',{station_id:'S1'});if(['failed','blocked'].includes(autoResult.boot_execution.state))throw new Error(JSON.stringify(autoResult.boot_execution));return autoResult.boot_execution.state==='completed';},'automatic UIP / AMT skip / UEFI plan completed',60000);
- assert.equal(autoResult.firmware.observed_phase,'uefi');assert.notEqual(autoResult.firmware.boot_id,beforeBoot.boot_id,'Real fixture restart starts a new observed boot');
- assert.ok(Number(autoResult.firmware.boot_sequence)>Number(beforeBoot.boot_sequence));
- assert.equal((await submitted('StartMt')).length,0,'No external MT is submitted when disabled');
- await waitUntil(()=>evaluate(`document.getElementById('boot-execution-state').textContent==='计划已完成'`),'automatic completion shown in UI');
- await saveEvidence('plan-automatic',{execution:autoResult.boot_execution,firmware:autoResult.firmware});
- const custom={...automatic,preset:'custom',stages:{...automatic.stages,uip1:'manual'}};
- await choosePlan(custom);
- await uiCommand('btn-restart-boot-plan','ControlBootPlan','restart custom plan with manual UIP');
- await waitUntil(async()=>{const c=await readRpc('GetStationControl',{station_id:'S1'});return c.boot_execution.state==='waiting_user' && c.firmware.console_prompt?.cpu===0 && c.phase_actions.continue_uip.available;},'custom plan waits for CPU0 UIP user input',30000);
- await waitUntil(()=>evaluate(`document.getElementById('boot-execution-reason').textContent.length>0`),'manual wait reason shown');
- await uiCommand('btn-pause-boot-plan','ControlBootPlan','explicitly pause and take over');
- await waitUntil(async()=> (await readRpc('GetStationControl',{station_id:'S1'})).boot_execution.state==='paused','plan paused');
- const apply0=await uiCommand('btn-apply-uip','ApplyUipParameters','manually apply CPU0 UIP while paused');
- assert.ok(apply0.result.commands.includes('rmt enable')&&apply0.result.commands.includes('errhandle disable'));
- const cr0=await uiCommand('btn-continue-uip','ContinueUip','manual CPU0 continue');assert.equal(cr0.result.bytes_hex,'0d');
- await waitUntil(async()=>{const c=await readRpc('GetStationControl',{station_id:'S1'});return c.firmware.console_prompt?.cpu===1&&c.phase_actions.continue_uip.available;},'CPU1 input remains available while plan paused');
- await uiCommand('btn-resume-boot-plan','ControlBootPlan','resume observing after manual takeover');
- await waitUntil(async()=> (await readRpc('GetStationControl',{station_id:'S1'})).boot_execution.state==='waiting_user','custom CPU1 remains a user-owned node');
- await uiCommand('btn-apply-uip','ApplyUipParameters','manual CPU1 UIP settings');
- const cr1=await uiCommand('btn-continue-uip','ContinueUip','manual CPU1 continue');assert.equal(cr1.result.bytes_hex,'0d');
- let customResult;
- await waitUntil(async()=>{customResult=await readRpc('GetStationControl',{station_id:'S1'});if(['failed','blocked'].includes(customResult.boot_execution.state))throw new Error(JSON.stringify(customResult.boot_execution));return customResult.boot_execution.state==='completed';},'manual nodes hand off to automatic later stages',60000);
- assert.equal(customResult.firmware.observed_phase,'uefi');
- const manual={...automatic,preset:'manual',stages:allStages('manual')};await choosePlan(manual);
- assert.deepEqual((await readRpc('GetStationControl',{station_id:'S1'})).boot_plan.stages,manual.stages);
- result.plan_checks={save_does_not_execute:true,reload_preserves_settings:true,raw_uip_saved:fw.uip_raw_commands,amt_saved:amt,automatic_boot:autoResult.firmware.boot_id,automatic_state:autoResult.boot_execution.state,custom_boot:customResult.firmware.boot_id,custom_state:customResult.boot_execution.state,manual_uip_bytes:[cr0.result.bytes_hex,cr1.result.bytes_hex],pause_resume:true,manual_preset_saved:true,mt_disabled:true};
- assert.ok(observedWrites.every(method=>method==='EnqueueCommand'),'Plan and AMT operations use the shared command queue');
- } catch(error) {planError=error;throw error;}
- finally {
- const problems=[];
- const attempt=async(description,fn)=>{try{await fn();}catch(error){problems.push(description+': '+error.message);}};
- await attempt('stop active plan',async()=>{const c=await readRpc('GetStationControl',{station_id:'S1'});if(['running','waiting_user','waiting_boot','paused','amt_preparing','amt_running'].includes(c.boot_execution.state))await uiCommand('btn-stop-boot-plan','ControlBootPlan','cleanup active plan');});
- await attempt('restore UIP defaults',async()=>{await clickButton('btn-uip-defaults');await uiCommand('btn-save-firmware-settings','SaveFirmwareSettings','restore UIP defaults');});
- await attempt('restore AMT defaults',async()=>{await evaluate(`window.stlNavigation.show('amt')`);await field('amt-search','algomask');await evaluate(`(() => {const f=document.querySelector('.amt-include[data-name="algomask"]');if(f){f.checked=false;f.dispatchEvent(new Event('change',{bubbles:true}));}})()`);await field('amt-action',initial.amt_settings.action);await field('amt-test-command',initial.amt_settings.test_command);await field('amt-exit-after',initial.amt_settings.exit_after!==false);await field('amt-raw-commands','');await uiCommand('btn-save-amt-settings','SaveAmtSettings','restore AMT settings');});
- await attempt('restore boot plan',()=>choosePlan(originalPlan));
- await attempt('power off and close diagnostic',async()=>{const st=await readRpc('GetStation',{station_id:'S1'});if(st.server_power==='on')await uiCommand('btn-host-off','StationPower','cleanup simulated host power');const d=await readRpc('GetDiagnostic',{station_id:'S1'});if(['online','connecting','error'].includes(d.state))await uiCommand('btn-diag-close','SetDiagnosticSol','cleanup simulated diagnostic');await uiCommand('btn-sim-supply-off','StationPower','cleanup simulated whole supply');});
- result.plan_cleanup={restored:problems.length===0,problems};
- if(problems.length){console.error('[browser] Plan cleanup:',problems.join('\n'));if(!planError)throw new Error('Plan cleanup incomplete: '+problems.join('; '));}
- }
- }
- if (firmwareTest) {
- assert.equal(info.mode,'simulated','Firmware interaction test uses a simulated bench only');
- await evaluate(`window.confirm=()=>true`);
- const before=await readRpc('GetStation',{station_id:'S1'});
- const oldDiagnostic=await readRpc('GetDiagnostic',{station_id:'S1'});
- assert.ok(!before.run_id && !['online','connecting'].includes(oldDiagnostic.state),'Use an idle simulated S1 with a closed console');
- assert.ok(control.capabilities.bmc_power,'Initial fixture must permit simulated host power');
- await clickButton('btn-uip-defaults');
- assert.equal((await evaluate('window.__stlQueueSubmissions')).length,0,'Keeping UIP defaults sends no device operation');
- await clickButton('btn-save-firmware-settings');
- let request=(await submitted('SaveFirmwareSettings')).at(-1);
- await completedQueueItem(request.command_id,'save unchanged firmware defaults');
- assert.deepEqual((await readRpc('GetStationControl',{station_id:'S1'})).firmware_settings.uip_overrides,[]);
- await clickButton('btn-sim-supply-on');
- await waitUntil(async()=> (await readRpc('GetStation',{station_id:'S1'})).supply_state==='on','simulated station supply on');
- await clickButton('btn-diag-open');
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).state==='online','firmware console opened');
- await clickButton('btn-host-on');
- await waitUntil(async()=> (await readRpc('GetStationControl',{station_id:'S1'})).firmware.observed_phase==='uip','UIP is observed before training');
- await evaluate(`window.stlNavigation.show('uip');for(const [id,value] of [['uip-rmt','enable'],['uip-errhandle','disable']]){const f=document.getElementById(id);f.value=value;f.dispatchEvent(new Event('change'));}`);
- assert.ok(await evaluate(`document.getElementById('uip-command-preview').textContent.includes('rmt enable') && document.getElementById('uip-command-preview').textContent.includes('errhandle disable')`),'UIP preview contains only explicit overrides');
- await clickButton('btn-apply-uip');
- request=(await submitted('ApplyUipParameters')).at(-1);
- const applied=await completedQueueItem(request.command_id,'explicit UIP parameters queued and sent');
- assert.ok(applied.result.commands.includes('rmt enable') && applied.result.commands.includes('errhandle disable'),'Backend records actual submitted commands');
- await clickButton('btn-save-firmware-settings');
- await completedQueueItem((await submitted('SaveFirmwareSettings')).at(-1).command_id,'save UIP overrides');
- const saved=(await readRpc('GetStationControl',{station_id:'S1'})).firmware_settings.uip_overrides;
- assert.ok(saved.some(x=>x.id==='rmt'&&x.value==='enable') && saved.some(x=>x.id==='errhandle'&&x.value==='disable'));
- const applyCountBeforeContinue=(await submitted('ApplyUipParameters')).length;
- await clickButton('btn-continue-uip');
- const continueCpu0=await completedQueueItem((await submitted('ContinueUip')).at(-1).command_id,'first CPU continues with empty CR');
- assert.equal(continueCpu0.result.action,'ContinueUip');
- assert.equal(continueCpu0.result.bytes_hex,'0d');
- assert.equal(continueCpu0.result.before.cpu,0);
- await waitUntil(async()=> {const state=await readRpc('GetStationControl',{station_id:'S1'});return state.phase_actions.continue_uip.available && state.firmware.console_prompt.cpu===1;},'CPU1 UIP prompt available');
- await clickButton('btn-continue-uip');
- const continueCpu1=await completedQueueItem((await submitted('ContinueUip')).at(-1).command_id,'second CPU continues with empty CR');
- assert.equal(continueCpu1.result.action,'ContinueUip');
- assert.equal(continueCpu1.result.bytes_hex,'0d');
- assert.equal(continueCpu1.result.before.cpu,1);
- assert.equal((await submitted('ApplyUipParameters')).length,applyCountBeforeContinue,'Continue does not silently apply the saved or edited UIP settings');
- await waitUntil(()=>evaluate(`document.getElementById('phase-action-last-summary').textContent.includes('UIP 空回车')`),'phase action result shown separately from test verdict');
- const skippedAmt=[];
- for (const cpu of [0,1]) {
- await waitUntil(async()=> {const state=await readRpc('GetStationControl',{station_id:'S1'});return state.phase_actions.skip_amt.available && state.firmware.console_prompt.cpu===cpu;},`CPU${cpu} AMEMDIAG menu ready (requires simulation.amt_menu=true)`,15000);
- await waitUntil(()=>evaluate(`!document.getElementById('btn-start-amt').disabled`),'manual AMT start remains independent of automatic-plan skip choice');
- await clickButton('btn-amt-exit');
- const skipped=await completedQueueItem((await submitted('SkipAmt')).at(-1).command_id,`CPU${cpu} AMT exits without a test`);
- assert.equal(skipped.result.action,'SkipAmt');assert.equal(skipped.result.before.cpu,cpu);
- assert.equal(skipped.result.bytes_hex,'657869740d');assert.equal(skipped.result.no_new_test_started,true);
- skippedAmt.push(skipped.result);
- }
- await waitUntil(()=>evaluate(`document.getElementById('phase-action-last-summary').textContent.includes('退出 AMT')`),'AMT exit result shown');
- await waitUntil(async()=> (await readRpc('GetStationControl',{station_id:'S1'})).firmware.observed_phase==='uefi','training and skipped AMT menus lead to UEFI');
- await evaluate(`window.stlNavigation.show('testing');document.getElementById('uefi-directory').value='fs0:\\\\EFI';document.getElementById('uefi-refresh-map').checked=true;`);
- await clickButton('btn-list-uefi');
- const listResult=await completedQueueItem((await submitted('ListUefiFiles')).at(-1).command_id,'UEFI file list returned');
- assert.ok(listResult.result.entries.length>0,'Directory result contains real parsed fixture entries');
- const writesBeforeEmptyEnter=(await submitted('WriteDiagnosticSol')).length;
- await evaluate(`document.getElementById('sol-input-cmd').value='';document.getElementById('sol-input-cmd').dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',bubbles:true}));`);
- await waitUntil(async()=> (await submitted('WriteDiagnosticSol')).length===writesBeforeEmptyEnter+1,'blank command input accepts keyboard Enter');
- const emptyEnter=(await submitted('WriteDiagnosticSol')).at(-1);
- assert.equal(Buffer.from(emptyEnter.arguments.data,'base64').toString(),'\r','Keyboard blank Enter sends only CR');
- await completedQueueItem(emptyEnter.command_id,'blank Enter reaches the current console');
- await waitUntil(()=>evaluate(`document.querySelectorAll('.uefi-file').length>0 && [...document.querySelectorAll('.uefi-file')].some(n=>/memtest.*\.efi/i.test(n.dataset.path))`),'EFI files appear in page');
- const chosen=await evaluate(`(() => {const nodes=[...document.querySelectorAll('.uefi-file')],efi=nodes.find(n=>/memtest.*\.efi/i.test(n.dataset.path)),config=nodes.find(n=>/\.(cfg|ini)$/i.test(n.dataset.path));if(!efi||!config)throw Error('Fixture needs EFI and config');efi.click();config.click();document.getElementById('mt-command-template').value='{efi_path} -c {config_path} {arguments}';document.getElementById('mt-command-template').dispatchEvent(new Event('input'));return {efi:efi.dataset.path,config:config.dataset.path,preview:document.getElementById('mt-command-preview').textContent};})()`);
- // -c is explicitly selected for this simulator check; no production syntax is assumed.
- assert.ok(chosen.preview.includes(chosen.efi) && chosen.preview.includes(chosen.config));
- await clickButton('btn-save-mt-selection');
- await completedQueueItem((await submitted('SaveFirmwareSettings')).at(-1).command_id,'save selected MT files');
- await clickButton('btn-start-mt');
- const mtRequest=(await submitted('StartMt')).at(-1);
- const mtResult=await completedQueueItem(mtRequest.command_id,'selected MT program command submitted');
- assert.equal(mtRequest.arguments.selection.efi_path,chosen.efi);assert.equal(mtRequest.arguments.selection.config_path,chosen.config);
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).observations.some(x=>x.phase==='mt'),'MT output observed');
- await clickButton('btn-host-off');
- await completedQueueItem((await submitted('StationPower')).at(-1).command_id,'host off after firmware validation');
- await clickButton('btn-diag-close');
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).state==='closed','close console before editing connections');
- await evaluate(`window.stlNavigation.show('connections');document.getElementById('connection-bmc-enabled').checked=false;document.getElementById('connection-bmc-enabled').dispatchEvent(new Event('input'));`);
- await clickButton('btn-save-connections');
- const connectionsRequest=(await submitted('ConfigureConnections')).at(-1);
- await completedQueueItem(connectionsRequest.command_id,'disable optional BMC networking');
- await waitUntil(()=>evaluate(`document.getElementById('btn-host-on').disabled && document.getElementById('btn-query-bmc').disabled && !document.getElementById('btn-diag-open').disabled`),'BMC actions disabled while console remains available');
- const disabled=await readRpc('GetStationControl',{station_id:'S1'});
- assert.equal(disabled.capabilities.bmc_power,false);assert.equal(disabled.capabilities.bmc_query,false);assert.equal(disabled.capabilities.console,true);
- await clickButton('btn-sim-supply-on');
- await completedQueueItem((await submitted('StationPower')).at(-1).command_id,'supply on without BMC networking');
- await clickButton('btn-diag-open');
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).state==='online','console opens with BMC networking disabled');
- await clickButton('btn-diag-close');
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).state==='closed','close optional-BMC console');
- await evaluate(`document.getElementById('connection-bmc-enabled').checked=true;document.getElementById('connection-bmc-enabled').dispatchEvent(new Event('input'));`);
- await clickButton('btn-save-connections');
- await completedQueueItem((await submitted('ConfigureConnections')).at(-1).command_id,'restore simulated BMC option');
- await clickButton('btn-uip-defaults');
- await evaluate(`for(const id of ['mt-efi-path','mt-config-path','mt-arguments']){const field=document.getElementById(id);field.value='';field.dispatchEvent(new Event('input'));}document.getElementById('mt-command-template').value='{efi_path} {arguments}';document.getElementById('mt-command-template').dispatchEvent(new Event('input'));`);
- await clickButton('btn-save-firmware-settings');
- await completedQueueItem((await submitted('SaveFirmwareSettings')).at(-1).command_id,'restore default firmware settings after simulated validation');
- await clickButton('btn-sim-supply-off');
- await completedQueueItem((await submitted('StationPower')).at(-1).command_id,'finish simulated firmware check');
- const all=await evaluate('window.__stlQueueSubmissions');
- assert.ok(observedWrites.every(method=>method==='EnqueueCommand'),'All firmware and connection writes use queue');
- result.firmware_checks={defaults_send_nothing:true,explicit_uip_commands:applied.result.commands,saved_uip_overrides:saved,uip_continue:[continueCpu0.result,continueCpu1.result],amt_skip:skippedAmt,continue_does_not_apply_overrides:true,blank_keyboard_enter:true,uefi_entries:listResult.result.entries.length,mt_selection:mtRequest.arguments.selection,mt_command:mtResult.result.command,bmc_optional:true,console_available_without_bmc:true,queue_commands:all.map(x=>({command_id:x.command_id,method:x.method}))};
- await evaluate(`window.stlNavigation.show('testing')`);
- }
- if (hardwareConsoleTest) {
- assert.equal(info.mode,'hardware','Restricted console check requires hardware mode');
- const station = await readRpc('GetStation',{station_id:'S1'});
- assert.equal(station.station_id,'S1');
- assert.equal(station.bmc_address,'192.168.0.100','Restricted check is only for the authorized S1 BMC');
- assert.ok(!station.run_id,'Hardware test must not be active');
- await waitUntil(()=>evaluate(`document.getElementById('detail-station-tag').textContent.startsWith('S1')`),'hardware S1 selected');
- const beforeConnect=await readRpc('GetDiagnostic',{station_id:'S1'});
- if (beforeConnect.state !== 'online') {
- assert.ok(beforeConnect.state !== 'connecting','An existing connection is still being established');
- await waitUntil(()=>evaluate(`!document.getElementById('btn-diag-open').disabled`),'hardware console connect button');
- await clickButton('btn-diag-open');
- }
- await waitUntil(async()=> (await readRpc('GetDiagnostic',{station_id:'S1'})).state==='online','hardware BIOS console online',30000);
- const before=await readRpc('GetDiagnostic',{station_id:'S1'});
- assert.ok(before.session_id);
- assert.equal(before.phase,'uip','The list command is only verified for a stationary UIP prompt; this check will not send it in AMEMDIAG or another phase');
- assert.ok(!(await readRpc('GetStation',{station_id:'S1'})).run_id,'No active run before the console query');
- await evaluate(`(() => {
- const source=document.getElementById('console-source');source.value='diagnostic';source.dispatchEvent(new Event('change'));
- document.getElementById('chk-append-enter').checked=true;
- })()`);
- await waitUntil(()=>evaluate(`!document.getElementById('btn-send-sol').disabled`),'hardware manual console input');
- await waitForButton('btn-send-sol');
- await evaluate(`document.getElementById('sol-input-cmd').value='list';document.getElementById('btn-send-sol').click()`);
- await waitUntil(async()=> (await submitted('WriteDiagnosticSol')).length===1,'hardware list request enqueued');
- const request=(await submitted('WriteDiagnosticSol'))[0];
- assert.equal(request.station_id,'S1');assert.equal(request.arguments.session_id,before.session_id);
- assert.equal(Buffer.from(request.arguments.data,'base64').toString(),'list\r','Only list plus exactly one CR is sent');
- await completedQueueItem(request.command_id,'hardware list command dispatched and completed');
- let raw='',offset=Number(before.bytes_received || 0);
- await waitUntil(async()=> {
- const part=await readRpc('ReadDiagnosticSol',{station_id:'S1',session_id:before.session_id,offset,max_bytes:65536});
- if(part.data)raw+=Buffer.from(part.data,'base64').toString('utf8');
- offset=Number(part.next_offset || offset);
- return raw.includes('CxmtDdrTest') && /Please input/i.test(raw);
- },'fresh UIP response and command prompt',30000);
- await waitForButton('btn-query-bmc');
- await evaluate(`document.getElementById('bmc-query-kind').value='info';document.getElementById('btn-query-bmc').click()`);
- await waitUntil(()=>evaluate(`document.getElementById('bmc-query-time').textContent && !document.getElementById('btn-query-bmc').disabled && document.getElementById('bmc-query-output').textContent.includes('Firmware Revision')`),'hardware BMC information displayed',30000);
- const bmcRequest=(await submitted('QueryBmc')).at(-1);
- assert.equal(bmcRequest.arguments.query,'info');
- const bmcQueueItem=await completedQueueItem(bmcRequest.command_id,'hardware BMC query dispatched and completed');
- assert.ok(bmcQueueItem.result?.text?.includes('Firmware Revision'),'BMC result is retained in the shared queue');
- const bmcInfo=await evaluate(`document.getElementById('bmc-query-output').textContent`);
- await clickButton('btn-download-sol');
- const downloaded=before.session_id+'-sol.bin';
- await waitUntil(async()=> (await readdir(temporary)).includes(downloaded),'hardware raw console log downloaded',30000);
- const log=await readFile(path.join(temporary,downloaded));
- assert.ok(log.length>Number(before.bytes_received || 0),'Downloaded log contains the new console response');
- assert.ok(log.includes(Buffer.from('CxmtDdrTest')));
- if(evidenceDir){await mkdir(evidenceDir,{recursive:true});await writeFile(path.join(evidenceDir,downloaded),log);await writeFile(path.join(evidenceDir,'hardware-uip-response.txt'),raw);await writeFile(path.join(evidenceDir,'hardware-bmc-info.txt'),bmcInfo);}
- const beforeReload=await readRpc('GetDiagnostic',{station_id:'S1'});
- assert.equal(beforeReload.session_id,before.session_id);assert.equal(beforeReload.state,'online');
- const queuedRequests=await evaluate('window.__stlQueueSubmissions');
- const writeCount=queuedRequests.filter(item=>item.method==='WriteDiagnosticSol').length;
- assert.equal(writeCount,1,'Exactly one diagnostic console command was sent');
- assert.ok(queuedRequests.every(item=>item.station_id==='S1' && (item.method==='WriteDiagnosticSol' || item.method==='QueryBmc' && item.arguments.query==='info' || item.method==='SetDiagnosticSol' && item.arguments.action==='open')),'Only the explicitly allowed console/read operations were enqueued');
- assert.ok(observedWrites.every(method=>method==='EnqueueCommand'),'No legacy device control RPC bypasses the queue');
- const mutationCount=observedWrites.length;
- const previousPageOrigin=await evaluate('performance.timeOrigin');
- await cdp('Page.reload',{ignoreCache:true});
- await waitUntil(async()=> {try {return await evaluate(`performance.timeOrigin!==${previousPageOrigin} && document.querySelectorAll('.station-card').length===4 && !!document.getElementById('sys-version') && document.getElementById('sys-version').textContent!=='未知'`);} catch {return false;}},'hardware page reloaded');
- await installReadHelper();
- await waitUntil(()=>evaluate(`document.getElementById('console-context').textContent.includes(${JSON.stringify(before.session_id)}) && document.getElementById('sol-terminal').textContent.length>20 && !document.getElementById('sol-terminal').textContent.startsWith('等待')`),'existing hardware session restored in UI',30000);
- const afterReload=await readRpc('GetDiagnostic',{station_id:'S1'});
- assert.equal(afterReload.session_id,before.session_id,'Reload must retain the backend session');
- assert.equal(afterReload.state,'online','Backend session remains online after reload');
- assert.equal(observedWrites.length,mutationCount,'Reload must not send another console/power command');
- await waitUntil(()=>evaluate(`document.querySelector('[data-command-id="${request.command_id}"]')?.dataset.commandState==='succeeded' && document.querySelectorAll('#device-events-tbody [data-event-sequence]').length>0`),'shared queue results visible after local UI state is discarded');
- result.hardware_console={station_id:'S1',bmc_address:station.bmc_address,session_id:before.session_id,transport:afterReload.transport,phase_before:before.phase,phase_after:afterReload.phase,command:'list\r',command_count:writeCount,raw_response_bytes:Buffer.byteLength(raw),download_bytes:log.length,backend_session_retained:true,backend_session_left_open:true,requests:queuedRequests.map(item=>({command_id:item.command_id,method:item.method,station_id:item.station_id}))};
- result.hardware_console_checks=['authorized S1 hardware identity','no active high-temperature run','existing or UI-opened console connection','stationary UIP list plus one CR','queue dispatch and retained result','fresh firmware prompt response','BMC info displayed','raw console log download','browser reload preserves backend session and shared queue display'];
- }
- if (!writeTest && !firmwareTest && !hardwareConsoleTest && !planTest) assert.equal(observedWrites.length,0,'Default browser check must remain read-only');
- assert.equal(httpRpcRequests.length,0,'Every tested HTML page uses WebSocket only');
- assert.ok(wsConnections.size>0 && wsRequests.length>0,'CDP observed actual application WebSocket connections and JSON requests');
- assert.equal(new Set(wsRequests.map(x=>x.id)).size,wsRequests.length,'No WebSocket request ID is resent');
- result.transport={...result.transport,observed_connections:wsConnections.size,observed_requests:wsRequests.length,http_rpc_fetches:httpRpcRequests.length};
- 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, hardware_console_test:hardwareConsoleTest, simulated_write_test:writeTest, simulated_plan_test:planTest, observed_writes:observedWrites, 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(()=>{});
- }
|