// app.js — Main Workbench State & Console / Queue / BMC Synchronization
(() => {
const $ = id => document.getElementById(id);
const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
function redact(value) {
if (Array.isArray(value)) return value.map(redact);
if (!value || typeof value !== 'object') return value;
return Object.fromEntries(Object.entries(value).map(([key,item]) => [key,/^(password|token|api_token|secret)$/i.test(key) ? '已隐藏' : redact(item)]));
}
let stationId = 'S1', stationUserChosen = false, stations = [], polling = false, repollPending = false, selectionRevision = 0, connected = false;
let sysInfoCache = null, sysInfoFetchedAt = 0, dirtyPollTimer = null;
const logs = new Map(), pending = new Map(), diagnostics = new Map();
let queueItems = [], queuePolling = false, eventPolling = false, auditItems = [], auditPolling = false;
let alarmOffset = 0, alarmTotal = 0, alarmLimit = 50, alarmPolling = false;
const eventViews = new Map(), bmcPending = new Map();
const fanStateByStation = new Map(), fanQueryInFlight = new Set();
let diagnosticError = '';
const terminalStates = new Set(['succeeded', 'failed', 'interrupted']);
const queueLabels = {queued:'排队', dispatching:'分派中', running:'执行', succeeded:'成功', failed:'失败', interrupted:'中断'};
const operationLabels = {
WriteSol:'发送控制台',
WriteDiagnosticSol:'发送 BIOS 控制台',
SetDiagnosticSol:'连接管理',
StationPower:'主板电源',
QueryBmc:'读取 BMC 信息',
ConfigureConnections:'配置设备连接',
ConfigurePxe:'配置 PXE',
GetN540Config:'读取 N540 串口服务器',
ConfigureN540:'配置 N540 纯净透传',
SaveFirmwareSettings:'保存 ICT 配置',
ApplyUipParameters:'下发 ICT 参数',
ContinueUip:'ICT 发送 exit 继续',
SkipAmt:'退出当前 AMT 菜单',
ListUefiFiles:'读取 UEFI 目录',
StartMt:'启动 MT 程序',
SaveBootPlan:'保存启动计划',
ControlBootPlan:'启动计划控制',
SaveAmtSettings:'保存 AMT 配置',
ApplyAmtSettings:'应用 AMT 配置',
StartAmt:'提交 AMT 测试启动',
ExecuteAmtCommand:'执行 AMT 菜单命令',
SaveProfile:'保存测试 Profile',
DeleteProfile:'删除测试 Profile',
LoadProfileToWorkspace:'加载 Profile 到工作区',
SubmitTaskBatch:'提交多计划测试队列',
ControlTaskBatch:'控制多计划测试队列',
ConfirmDimmReplacement:'确认更换异常内存条',
SetStageIntent:'预设阶段控制状态',
ApplyErrorPreset:'应用零加压拉偏预设',
ClearTerminalView:'锚定清空控制台窗口',
ConfigureWatchdog:'配置防卡死与断联保护',
ConfigureThermalPolicy:'配置高温罩闭环联动策略',
AddStation:'新增工位',
RemoveStation:'移除工位',
};
const actionLabels = {
open:'连接 BIOS 控制台',
close:'断开 BIOS 控制台',
reconnect:'重连 BIOS 控制台',
host_on:'主板开机',
host_off:'主板关机',
host_reset:'主板复位',
host_cycle:'主板关开循环',
bmc_warm_reset:'BMC 热重启(恢复默认温控)',
fan_low_speed_on:'开启风扇降速模式',
fan_low_speed_off:'关闭风扇降速(恢复默认温控)',
};
const phases = [['boot', '启动'], ['uip', 'ICT 配置'], ['training', 'Training'], ['rmt', 'RMT 执行'], ['amt', 'AMT / AMEMDIAG'], ['post', 'POST / DXE / BDS'], ['uefi', 'UEFI'], ['mt', 'MT']];
const phaseNames = new Map([...phases, ['amemdiag', 'AMEMDIAG控制台']]);
const labels = {
powered_off:'已断电', post:'POST / DXE / BDS', amemdiag:'AMEMDIAG 控制台',
idle:'空闲', rmt:'RMT', amt:'AMT / AMEMDIAG测试', uefi_ready:'UEFI', mt:'MT',
online:'在线', offline:'离线', on:'开', off:'关', unknown:'未知',
pending:'待判定', pass:'通过', fail:'失败', failed:'失败', skipped:'跳过',
completed:'已完成', stopped:'已停止', running:'运行中', connecting:'连接中',
closed:'未连接', disabled:'未启用', enabled:'已启用', error:'连接异常',
valid:'有效', unavailable:'无读数',
};
const label = value => labels[value] || value || '未知';
const diag = () => diagnostics.get(stationId) || {};
function transportLabel(snapshot = diag()) {
const value = snapshot.transport || '';
if (value === 'local_serial') return '物理串口 · /dev/ttyUSB0';
if (value.startsWith('local_serial:')) return '物理串口 · ' + value.slice('local_serial:'.length);
if (value === 'tcp_serial') return 'N540 TCP Server · ' + (snapshot.session_rx_bytes ? `RX ${snapshot.session_rx_bytes}B` : 'TCP 透传');
if (value.startsWith('tcp_serial:')) return 'N540 TCP · ' + value.slice('tcp_serial:'.length);
if (value.startsWith('tcp_serial_server:')) return 'N540 TCPC 监听 · ' + value.slice('tcp_serial_server:'.length);
if (value === 'ipmi_sol' || value.startsWith('ipmi_sol:')) return 'IPMI SOL';
if (value === 'ssh_console') return 'SSH BIOS 控制台';
if (value.startsWith('ssh_console:')) return `SSH BIOS · ${value.slice('ssh_console:'.length)}`;
return value || '等待链路信息';
}
function capabilities(s = current()) {
return window.stlFirmware?.capabilities(s?.station_id) || {
console: !!s?.bmc_address,
bmc_power: !!s?.bmc_address,
bmc_query: !!s?.bmc_address,
};
}
function consoleContext() {
const d = diag();
return {
kind: 'diagnostic',
key: d.session_id ? `diag:${stationId}:${d.session_id}` : '',
session_id: d.session_id || '',
exists: !!d.session_id,
writable: connected && (d.state === 'online' || !!current()?.console_online),
};
}
function runLog(key) {
if (!logs.has(key)) logs.set(key, {offset:0, text:'', decoder:new TextDecoder()});
return logs.get(key);
}
function visibleLog() {
const c = consoleContext();
return c.key ? runLog(c.key) : null;
}
function terminalText(text) {
return String(text || '')
.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '')
.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
.replace(/\x1b[()][A-Z0-9]/g, '')
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '')
.replace(/\r(?!\n)/g, '\n');
}
const stamp = () => new Date().toLocaleTimeString();
const id = () => `web-${Date.now()}-${Math.random().toString(36).slice(2)}`;
const current = () => stations.find(s => s.station_id === stationId);
const decode = value => Uint8Array.from(atob(value || ''), c => c.charCodeAt(0));
function encode(bytes) {
let text = '';
for (let i = 0; i < bytes.length; i += 8192) text += String.fromCharCode(...bytes.subarray(i, i + 8192));
return btoa(text);
}
function status(text, error = false) {
$('action-status').textContent = terminalText(text);
$('action-status').classList.toggle('error', error);
}
function enable(button, allowed) {
const el = $(button);
if (el) el.disabled = !allowed || el.dataset.busy === '1';
}
function time(ms) { return Number(ms) > 0 ? new Date(Number(ms)).toLocaleString() : '未知'; }
function formatElapsed(ms) {
const n = Math.max(0, Math.floor(Number(ms || 0) / 1000));
const h = Math.floor(n / 3600), m = Math.floor((n % 3600) / 60), s = n % 60;
return [h, m, s].map(v => String(v).padStart(2, '0')).join(':');
}
function callApi(method, payload = {}, timeoutMs) {
return window.stlTransport.call(method, payload, timeoutMs);
}
async function command(method, request, cmdLabel) {
const commandStation = request.station_id || stationId;
const args = {...request};
delete args.station_id; delete args.command_id; delete args.operator;
const commandId = id(), tracked = {label:cmdLabel, station:commandStation, state:'submitting', updated:0};
pending.set(commandId, tracked);
let result;
try {
result = await callApi('EnqueueCommand', {
command_id: commandId,
station_id: commandStation,
method,
arguments: args,
operator: 'operator',
});
} catch (error) {
if (tracked.result) result = tracked.result;
else {
if (['DISCONNECTED','REQUEST_TIMEOUT','SEND_FAILED'].includes(error.code)) {
tracked.state = 'submission_unknown';
throw Object.assign(
new Error(`${cmdLabel}:提交结果待核对 · ${commandId}。重连后将按此编号查询,不会自动重复执行。${error.message}`),
{code:error.code, command_id:commandId}
);
} else pending.delete(commandId);
throw error;
}
}
Object.assign(tracked, {state:result.state, updated:result.updated_unix_ms, result});
if (method === 'QueryBmc') bmcPending.set(commandStation, result.command_id);
if (!$('command-station-filter').value || $('command-station-filter').value === commandStation) {
queueItems = [result, ...queueItems.filter(item => item.command_id !== result.command_id)].slice(0, 100);
renderQueue();
}
showCommand(result, cmdLabel);
receiveBmcResult(result);
return result;
}
function showCommand(result, cmdLabel) {
const meanings = {queued:'已排队', dispatching:'正在分派', running:'执行中', succeeded:'执行成功', failed:'执行失败', interrupted:'已中断'};
status(`${cmdLabel}:${meanings[result.state] || result.state}${result.detail ? ' — ' + result.detail : ''}`, ['failed', 'interrupted'].includes(result.state));
if (terminalStates.has(result.state)) pending.delete(result.command_id);
}
function operation(item) {
return actionLabels[item.arguments?.action] || operationLabels[item.method] || item.method || '未知操作';
}
function renderQueue() {
const selectedState = $('command-state-filter').value;
const items = [...queueItems].sort((a,b) => Number(b.sequence) - Number(a.sequence));
const counts = {queued:0, running:0, succeeded:0, failed:0, interrupted:0};
for (const item of items) {
const state = item.state === 'dispatching' ? 'running' : item.state;
if (state in counts) counts[state]++;
}
$('command-queue-counts').innerHTML = Object.entries(counts).map(([state,count]) => `${queueLabels[state]}${count}`).join('');
$('command-queue-size').textContent = String(items.length);
const open = new Set([...document.querySelectorAll('#commands-tbody details[open]')].map(node => node.dataset.command));
const visible = items.filter(item => !selectedState || item.state === selectedState || (selectedState === 'running' && item.state === 'dispatching'));
$('commands-tbody').innerHTML = visible.map(item => {
const result = JSON.stringify(redact({arguments:item.arguments || {}, result:item.result || {}, ...(item.error_code ? {error_code:item.error_code} : {})}), null, 2);
const summary = item.detail || queueLabels[item.state] || item.state;
return `
| ${time(item.created_unix_ms)} | ${escape(item.station_id)} | ${escape(operation(item))}${escape(item.method)} | ${escape(item.operator || 'operator')} | ${escape(queueLabels[item.state] || item.state)} | ${escape(summary)}${escape(item.command_id)} · 更新 ${time(item.updated_unix_ms)} ${escape(result)} |
`;
}).join('') || '| 当前筛选下没有命令记录 |
';
}
function applyFanResultText(targetStationId, text) {
try {
const parsed = JSON.parse(text || '{}');
if (parsed && (typeof parsed.enabled === 'boolean' || parsed.fan_mode_restored === 'auto')) {
const enabled = parsed.fan_mode_restored === 'auto' ? false : !!parsed.enabled;
fanStateByStation.set(targetStationId, {
enabled,
mode: enabled ? 'low_speed' : 'auto',
raw_mode: parsed.raw_mode || (enabled ? '01' : '00'),
label: parsed.label || (enabled ? '降速静音模式 (系统30% / 电源1%)' : '服务器默认自动温控 (Auto)'),
fans: Array.isArray(parsed.fans) ? parsed.fans : [],
});
if (targetStationId === stationId) renderFanControl(current());
}
} catch (_) {}
}
function renderFanControl(s = current()) {
const caps = capabilities(s), available = connected && !!s && !!caps.bmc_query && s.bmc_state === 'online';
const st = s ? fanStateByStation.get(s.station_id) : null;
const chk = $('chk-fan-low-speed');
if (chk) {
chk.disabled = !available || chk.dataset.busy === '1';
if (st && chk.dataset.busy !== '1') chk.checked = !!st.enabled;
}
enable('btn-fan-refresh', connected && !!s && !!caps.bmc_query);
enable('btn-bmc-warm-reset', connected && !!s && !!caps.bmc_query);
const badge = $('fan-mode-badge'), summary = $('fan-rpm-summary');
if (!badge || !summary) return;
if (!s || !caps.bmc_query) {
badge.textContent = 'BMC 未启用';
badge.className = 'badge';
summary.textContent = '';
return;
}
if (!st) {
badge.textContent = s.bmc_state === 'online' ? '待读取风扇模式' : `BMC ${label(s.bmc_state)}`;
badge.className = 'badge';
summary.textContent = '';
return;
}
badge.textContent = `当前: ${st.label}`;
badge.className = 'badge ' + (st.enabled ? 'error' : 'connected');
summary.textContent = st.fans?.length ? st.fans.slice(0, 6).join(' · ') : (st.raw_mode ? `原始模式字节: ${st.raw_mode}` : '');
}
async function refreshFanMode(targetStationId = stationId, silent = true) {
const s = stations.find(x => x.station_id === targetStationId);
if (!connected || !s || !capabilities(s).bmc_query || fanQueryInFlight.has(targetStationId) || s.bmc_state !== 'online') return;
fanQueryInFlight.add(targetStationId);
try {
const cmd = await command('QueryBmc', {station_id: targetStationId, query: 'fan_mode'}, '查询风扇温控模式');
if (cmd?.result?.text) applyFanResultText(targetStationId, cmd.result.text);
} catch (error) {
if (!silent) status(`风扇状态读取失败:${error.message}`, true);
} finally {
fanQueryInFlight.delete(targetStationId);
if (targetStationId === stationId) renderFanControl(current());
}
}
function receiveBmcResult(item) {
if (item.method === 'QueryBmc' && terminalStates.has(item.state) && item.state === 'succeeded' && item.result?.text) {
if (['fan_mode','fan_low_speed_on','fan_low_speed_off','bmc_warm_reset'].includes(item.arguments?.query || item.result?.query)) {
applyFanResultText(item.station_id, item.result.text);
}
}
if (item.method !== 'QueryBmc' || bmcPending.get(item.station_id) !== item.command_id || !terminalStates.has(item.state)) return;
bmcPending.delete(item.station_id);
if (stationId !== item.station_id) return;
$('bmc-query-output').textContent = item.state === 'succeeded' ? item.result?.text || '设备未返回文本' : `查询失败:${item.detail || item.error_code || item.state}`;
$('bmc-query-time').textContent = time(item.result?.observed_unix_ms || item.updated_unix_ms);
}
async function pollQueue() {
if (queuePolling) return;
queuePolling = true;
const filter = $('command-station-filter').value;
try {
const snapshot = await callApi('GetQueue', {station_id:filter, limit:100});
const fetched = snapshot.items || [], byId = new Map(fetched.map(item => [item.command_id,item]));
for (const [key, tracked] of [...pending]) {
let item = byId.get(key);
if (!item) {
try { item = await callApi('GetQueueItem', {command_id:key}); }
catch (error) {
if (error.code === 'NOT_FOUND' && ['submitting','submission_unknown'].includes(tracked.state)) continue;
throw error;
}
}
tracked.result = item;
if (item.state !== tracked.state || item.updated_unix_ms !== tracked.updated) {
tracked.state = item.state; tracked.updated = item.updated_unix_ms;
showCommand(item, `${tracked.station} ${tracked.label}`);
}
receiveBmcResult(item);
}
if (filter !== $('command-station-filter').value) return;
queueItems = fetched; renderQueue();
$('command-queue-updated').textContent = `已同步 ${stamp()} · 等待 ${Number(snapshot.pending_count || 0)} / 执行 ${Number(snapshot.running_count || 0)}`;
$('command-queue-error').classList.add('hidden');
} catch (error) {
$('command-queue-error').textContent = `队列读取失败,保留上次记录:${error.message}`;
$('command-queue-error').classList.remove('hidden');
} finally { queuePolling = false; }
}
function deviceEventView() {
const filter = $('device-event-station-filter').value;
if (!eventViews.has(filter)) eventViews.set(filter, {events:[], cursor:0, initialized:false, hasMore:false, updated:''});
return eventViews.get(filter);
}
function renderDeviceEvents() {
const view = deviceEventView(), selectedLevel = $('device-event-level-filter').value;
const open = new Set([...document.querySelectorAll('#device-events-tbody details[open]')].map(node => node.dataset.event));
const events = view.events.filter(event => !selectedLevel || (selectedLevel === 'warning' ? ['warning','warn'].includes(event.severity) : selectedLevel === 'error' ? ['error','critical','fatal'].includes(event.severity) : event.severity === selectedLevel)).slice().reverse();
const severity = {info:'信息', warning:'警告', warn:'警告', error:'错误', critical:'严重', fatal:'严重'};
$('device-events-tbody').innerHTML = events.map(event => {
const payload = event.payload || {}, phase = event.phase ? phaseNames.get(event.phase) || label(event.phase) : '—';
const detail = JSON.stringify(redact({sequence:event.sequence, ...(event.command_id ? {command_id:event.command_id} : {}), payload}), null, 2);
return `| ${time(event.observed_unix_ms)} | ${escape(event.station_id)} | 现场诊断${escape(phase)} | ${escape(severity[event.severity] || event.severity || '信息')} | ${escape(event.kind)} | ${escape(event.message || event.kind)}${escape(detail)} |
`;
}).join('') || '| 当前筛选下没有设备事件 |
';
$('device-event-cursor').textContent = `本页读取位置:${view.cursor} · 保留 ${view.events.length} 条`;
$('device-events-updated').textContent = view.updated ? `已同步 ${view.updated}` : '等待设备事件';
}
async function pollDeviceEvents() {
if (eventPolling) return;
eventPolling = true;
const filter = $('device-event-station-filter').value, view = deviceEventView();
try {
const result = await callApi('ReadEventQueue', {station_id:filter, after_sequence:view.cursor, limit:100});
view.initialized = true;
const next = Number(result.next_after_sequence || view.cursor);
const existing = new Set(view.events.map(event => String(event.sequence)));
view.events = view.events.concat((result.events || []).filter(event => !existing.has(String(event.sequence)))).sort((a,b) => Number(a.sequence) - Number(b.sequence)).slice(-200);
view.hasMore = !!result.has_more; view.updated = stamp();
view.cursor = next;
if (filter === $('device-event-station-filter').value) {
renderDeviceEvents(); $('device-events-error').classList.add('hidden');
}
} catch (error) {
$('device-events-error').textContent = `设备事件读取失败,保留上次记录:${error.message}`;
$('device-events-error').classList.remove('hidden');
} finally { eventPolling = false; }
}
function renderAuditLogs() {
if (!$('audit-logs-tbody')) return;
const catLabels = {
profile_library:'Profile 配置库',
task_batch:'多计划测试队列',
ict_settings:'ICT 参数保存',
ict_dispatch:'ICT 固件下发',
amt_settings:'AMT 参数保存',
amt_dispatch:'AMT 固件下发',
pxe_mt86:'PXE 与 mt86.cfg',
boot_plan:'启动计划',
thermal_mcu:'高温罩温控',
connections:'连接设置',
dimm_replacement:'停机换条确认',
stage_intent:'阶段预设覆盖',
error_preset:'时序拉偏预设',
start_test:'测试启动',
power:'电源控制',
};
const open = new Set([...document.querySelectorAll('#audit-logs-tbody details[open]')].map(n => n.dataset.seq));
$('audit-logs-tbody').innerHTML = auditItems.map(item => {
const seq = String(item.sequence || '');
const detailJson = JSON.stringify(redact(item.details || {}), null, 2);
return `
#${escape(seq)} |
${time(item.timestamp_unix_ms)} |
${escape(item.station_id || '-')} |
${escape(item.operator || 'operator')} |
${escape(catLabels[item.category] || item.category || '-')} |
${escape(item.action || '-')} |
${escape(item.summary || '-')}${escape(detailJson)} |
`;
}).join('') || '| 当前筛选条件下暂无变更审计记录 |
';
}
async function pollAuditLogs() {
if (auditPolling || !$('audit-logs-tbody')) return;
auditPolling = true;
const stFilter = $('audit-station-filter')?.value || '';
const catFilter = $('audit-category-filter')?.value || '';
try {
const res = await callApi('ReadAuditLogs', {station_id: stFilter, category: catFilter, limit: 100});
auditItems = res.items || [];
renderAuditLogs();
if ($('audit-logs-updated')) $('audit-logs-updated').textContent = `已同步 ${stamp()} · 累计序号 #${res.latest_sequence || 0}`;
} catch (_) {
} finally { auditPolling = false; }
}
async function action(button, task) {
const element = $(button);
if (!element || element.dataset.busy === '1') return;
element.dataset.busy = '1'; element.disabled = true;
try { await task(); } catch (error) { status(error.message, true); }
finally { element.dataset.busy = ''; element.disabled = false; renderDetail(); await poll(); }
}
function bind(button, task) { if ($(button)) $(button).onclick = () => action(button, task); }
function renderCards() {
window.stlNavigation.updateStations(stations, stationId);
$('stations-grid').innerHTML = stations.map(s => {
const stage = window.stlFirmware.snapshot(s.station_id)?.firmware?.stage_progress;
const state = stage?.main?.label || '阶段待观测';
const caps = window.stlFirmware.capabilities(s.station_id);
const unavailable = !!caps && !caps.console && !caps.bmc_query;
const shortName = (s.name || s.station_id).replace(/\s*\(.+\)$/, '');
const d = diagnostics.get(s.station_id);
const consoleOnline = !!(s.console_online ?? (d?.state === 'online'));
const nodeOnline = consoleOnline || s.bmc_state === 'online';
const isLinkWaiting = s.observed_detail === 'link_offline_waiting';
const faultCode = s.fault_code || '';
const hasFail = s.awaiting_dimm_replacement || s.task_status === 'failed' || s.verdict === 'fail' || !!faultCode;
const kind = unavailable ? 'offline' : hasFail ? 'error' : isLinkWaiting ? 'warn' : !nodeOnline ? 'offline' : 'idle';
const statusTagText = unavailable ? '未配置'
: faultCode === 'stage_hang_timeout' || faultCode === 'mt_duration_timeout' || faultCode === 'amt_duration_timeout' ? '卡死超时'
: faultCode === 'link_lost_timeout' ? '失联超时'
: faultCode === 'reconnect_power_off' ? '异常掉电'
: faultCode === 'consecutive_hang_limit_exceeded' ? '死机熔断'
: s.awaiting_dimm_replacement ? '待换条'
: hasFail ? '测试失败'
: isLinkWaiting ? '双断等待恢复'
: !nodeOnline ? '离线'
: label(state) + (s.serial_gap_detected ? ' · 曾丢字' : '');
const bmcBadge = s.bmc_state === 'online' ? 'BMC 在线' : (s.bmc_address ? `BMC ${label(s.bmc_state || 'offline')}` : '仅串口模式');
return `
主板电源${escape(label(s.server_power))} · ${escape(bmcBadge)}
测试用时${escape(formatElapsed(s.elapsed_ms || 0))}
`;
}).join('');
document.querySelectorAll('.station-card').forEach(card => {
card.onclick = () => selectStation(card.dataset.id);
card.onkeydown = event => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); selectStation(card.dataset.id); } };
});
renderStationRoster();
window.stlUi?.renderProductionDashboard?.(stations);
}
function renderStationRoster() {
const tbody = $('station-roster-tbody');
if (!tbody) return;
tbody.innerHTML = stations.map(s => {
const online = s.console_online || s.bmc_state === 'online';
return `
| ${escape(s.station_id)} |
${escape(s.name || s.station_id)} |
${escape(s.bmc_address || '未配置')} |
${online ? '在线' : '离线'} |
|
`;
}).join('') || '| 暂无工位 |
';
tbody.querySelectorAll('[data-remove-station]').forEach(btn => {
btn.onclick = async () => {
const sid = btn.dataset.removeStation;
const ok = window.stlUi ? await window.stlUi.confirm('移除工位', `确认永久移除工位 ${sid} 吗?该工位串口和温控会话将被停止并从工位清单移除。`, '确认移除', true) : true;
if (!ok) return;
btn.disabled = true;
try {
await callApi('RemoveStation', { station_id: sid });
status(`已移除工位 ${sid}`);
if ($('station-roster-status')) $('station-roster-status').textContent = `已移除 ${sid}`;
await poll();
} catch (err) {
status(`移除工位失败:${err.message}`, true);
btn.disabled = false;
}
};
});
}
async function pollAlarms() {
const tbody = $('station-alarms-tbody');
if (!tbody || alarmPolling || !connected) return;
const sid = stationId;
alarmPolling = true;
try {
const res = await callApi('GetStationErrors', { station_id: sid, offset: alarmOffset, limit: alarmLimit });
if (sid !== stationId) return;
alarmTotal = Number(res.total || 0);
const items = Array.isArray(res.items) ? res.items : [];
window.stlStore?.setStationMap?.('alarmsByStation', sid, { total: alarmTotal, items }, 'alarms_poll');
if ($('station-alarm-count-badge')) {
$('station-alarm-count-badge').textContent = `${alarmTotal} 条`;
$('station-alarm-count-badge').classList.toggle('error', alarmTotal > 0);
}
if ($('btn-export-alarms-xlsx')) {
$('btn-export-alarms-xlsx').href = `/api/stations/${encodeURIComponent(sid)}/alarms.xlsx`;
}
if ($('station-alarms-page-info')) {
const start = alarmTotal === 0 ? 0 : alarmOffset + 1;
const end = Math.min(alarmTotal, alarmOffset + items.length);
$('station-alarms-page-info').textContent = `共 ${alarmTotal} 条 · 当前显示第 ${start}–${end} 条`;
}
if ($('btn-alarms-prev')) $('btn-alarms-prev').disabled = alarmOffset <= 0;
if ($('btn-alarms-next')) $('btn-alarms-next').disabled = !res.has_more;
tbody.innerHTML = items.map(e => {
const loc = [e.slot || '', e.address ? `Addr=${e.address}` : ''].filter(Boolean).join(' · ') || '全局';
return `| ${time(e.ts_ms || e.observed_unix_ms)} | ${escape(e.stage || 'system')} | ${escape(loc)} | ${escape(e.message || e.code || '-')} |
`;
}).join('') || '| 当前工位暂无异常记录 |
';
} catch (_) {
} finally {
alarmPolling = false;
}
}
function renderBmcSensors(s) {
const tbody = $('bmc-sensors-tbody');
if (!tbody) return;
const ctrl = window.stlFirmware.snapshot(s?.station_id || stationId) || {};
const sensors = Array.isArray(ctrl.bmc_sensors) ? ctrl.bmc_sensors : [];
const cnt = $('bmc-sensors-count');
if (cnt) cnt.textContent = `${sensors.length} 项`;
const sig = JSON.stringify(sensors);
if (tbody.dataset.sig === sig) return;
tbody.dataset.sig = sig;
const catMap = { temp: '温度', temperature: '温度', voltage: '电压', fan: '风扇', current: '电流', power: '功率', discrete: '离散状态', other: '其他' };
tbody.innerHTML = sensors.map(item => {
const valTxt = typeof item.value === 'number' && Number.isFinite(item.value)
? `${Number.isInteger(item.value) ? item.value : item.value.toFixed(2)} ${item.unit || ''}`.trim()
: (item.status || item.raw_hex || '-');
const stLower = String(item.status || '').toLowerCase();
const isOk = !stLower || stLower === 'ok' || stLower === 'nominal' || stLower.includes('ok');
const isBad = stLower.includes('crit') || stLower.includes('fail') || stLower.includes('warn') || stLower.includes('non-rec');
const stCls = isBad ? 'error' : isOk ? 'connected' : '';
return `${escape(item.name || '-')} | ${escape(catMap[item.category] || item.sensor_type || item.category || '-')} | ${escape(valTxt)} | ${escape(item.status || 'OK')} |
`;
}).join('') || '| 等待 BMC SDR 全量采集数据... |
';
}
function renderDimms(s) {
window.stlDimms?.render(window.stlFirmware.snapshot(s.station_id) || {});
renderBmcSensors(s);
}
function renderBoot(s, d) {
const control = window.stlFirmware.snapshot(s.station_id) || {};
window.stlStages.render(control, {station:s, diagnostic:d});
}
function renderDiagnostic(s) {
const d = diag(), caps = capabilities(s), available = connected && !!s, consoleReady = available && !!caps.console;
enable('btn-diag-open', consoleReady && !['online','connecting'].includes(d.state));
enable('btn-diag-reconnect', consoleReady && d.state !== 'connecting');
enable('btn-diag-close', available && ['online','connecting','error'].includes(d.state));
for (const act of ['on','off','reset','cycle']) {
enable(`btn-host-${act}`, available && !!caps.bmc_power);
if ($(`btn-host-${act}`)) $(`btn-host-${act}`).title = caps.bmc_power ? '' : '未启用 BMC IPMI';
}
enable('btn-refresh-station', connected);
enable('btn-query-bmc', available && !!caps.bmc_query && !bmcPending.has(stationId));
const consoleOnline = !!(s?.console_online ?? (d.state === 'online'));
$('diagnostic-state').textContent = diagnosticError ? '读取失败' : (consoleOnline ? '控制台在线' : label(d.state || 'closed'));
$('diagnostic-state').classList.toggle('connected', consoleOnline);
$('diagnostic-state').classList.toggle('error', !!diagnosticError || d.state === 'error');
renderBoot(s, d);
}
function renderDetail() {
const s = current(), context = consoleContext();
enable('btn-send-sol', context.writable);
enable('btn-send-enter', context.writable);
$('sol-input-cmd').disabled = !context.writable;
document.querySelectorAll('[data-sol-key]').forEach(button => { button.disabled = !context.writable || button.dataset.busy === '1'; });
enable('btn-download-sol', connected && context.exists);
if (!s) { renderDiagnostic({}); renderDimms({}); return; }
$('detail-station-tag').textContent = `${s.station_id} · ${s.name || '工位'}`;
if ($('detail-elapsed')) {
const ended = Number(s.ended_unix_ms) > 0;
const activeTiming = Number(s.started_unix_ms) > 0 && !ended;
$('detail-elapsed').textContent = (ended ? '本批耗时 ' : '测试用时 ') + formatElapsed(s.elapsed_ms || 0);
$('detail-elapsed').classList.toggle('connected', activeTiming);
}
const stageProgress = window.stlFirmware.snapshot(s.station_id)?.firmware?.stage_progress;
$('detail-phase-tag').textContent = (stageProgress?.live === false ? '最后观测:' : '本轮进度:') + (stageProgress?.main?.label || '等待阶段数据');
const executionState = window.stlFirmware.snapshot(stationId)?.boot_execution?.state;
const consoleOnline = !!(s.console_online ?? (diag().state === 'online'));
$('console-lock-badge').textContent = !consoleOnline && diag().state !== 'online' ? '未连接' : executionState === 'paused' ? '计划已暂停 · 人工接管' : executionState === 'waiting_user' ? '人工节点 · 可输入' : executionState === 'running' ? '自动计划执行中' : '手动调试';
$('sol-state-badge').textContent = consoleOnline ? '控制台在线' : label(diag().state || 'closed');
$('sol-state-badge').classList.toggle('connected', consoleOnline);
$('console-context').textContent = `现场诊断 · ${transportLabel()} · ${diag().session_id || '点击「连接串口」建立会话'}`;
renderDiagnostic(s); renderFanControl(s); renderDimms(s); window.stlFirmware.render();
if (connected && s && s.bmc_state === 'online' && !fanStateByStation.has(s.station_id) && !fanQueryInFlight.has(s.station_id)) {
refreshFanMode(s.station_id, true);
}
}
function renderLog() {
const context = consoleContext(), state = visibleLog();
if (!state?.text) {
$('sol-terminal').textContent = context.exists ? '等待串口输出…' : '连接串口后在此显示主板 BIOS 实时输出。连接成功不会自动发送回车。';
$('sol-terminal').dataset.renderedOffset = '0';
return;
}
const curOff = String(state.offset || 0);
if ($('sol-terminal').dataset.renderedOffset === curOff && $('sol-terminal').dataset.renderedLen === String(state.text.length)) {
return;
}
$('sol-terminal').dataset.renderedOffset = curOff;
$('sol-terminal').dataset.renderedLen = String(state.text.length);
$('sol-terminal').textContent = state.text;
if ($('chk-autoscroll').checked) $('sol-terminal').scrollTop = $('sol-terminal').scrollHeight;
}
let uartPumpActive = false;
async function pumpCleanUart(waitMs = 0) {
if (uartPumpActive || !connected) return;
const selectedStation = stationId, revision = selectionRevision;
const snapshot = diagnostics.get(selectedStation);
if (!snapshot?.session_id) return;
uartPumpActive = true;
try {
const key = `diag:${selectedStation}:${snapshot.session_id}`, state = runLog(key);
const reqWait = waitMs;
const chunk = await callApi('ReadCleanedUart', {
station_id: selectedStation,
offset: state.offset,
max_bytes: 65536,
wait_ms: reqWait,
}, Math.max(12000, reqWait + 8000));
if (selectedStation !== stationId || revision !== selectionRevision) return;
const clearOff = Number(chunk.last_clear_screen_offset || 0);
if (clearOff > (state.clearAnchor || 0)) {
state.text = '';
state.clearAnchor = clearOff;
}
if (chunk.text) {
state.text = (chunk.jumped_to_tail ? chunk.text : state.text + chunk.text).slice(-512000);
}
const nextOff = Number(chunk.next_offset ?? state.offset);
if (nextOff > state.offset || chunk.jumped_to_tail) state.offset = nextOff;
renderLog();
} catch (_) {
} finally {
uartPumpActive = false;
}
}
async function startLiveTailLoop() {
while (true) {
if (connected && diag().session_id && !uartPumpActive) {
await pumpCleanUart(1000);
await new Promise(r => setTimeout(r, 40));
} else {
await new Promise(r => setTimeout(r, 350));
}
}
}
async function pollDiagnostic() {
const selectedStation = stationId, revision = selectionRevision;
try {
const snapshot = await callApi('GetDiagnostic', {station_id:selectedStation});
if (selectedStation !== stationId || revision !== selectionRevision) return;
diagnostics.set(selectedStation, snapshot); diagnosticError = '';
window.stlStore?.setStationMap?.('diagnosticsByStation', selectedStation, snapshot, 'diag_poll');
if (snapshot.session_id && !uartPumpActive) {
await pumpCleanUart(0);
}
} catch (error) {
if (selectedStation === stationId) diagnosticError = `诊断状态读取失败:${error.message}`;
}
renderDetail(); renderLog();
}
async function selectStation(next, byUser = true) {
if (byUser) stationUserChosen = true;
stationId = next; diagnosticError = ''; selectionRevision++; alarmOffset = 0;
window.stlStore?.set?.('stationId', stationId, byUser ? 'user_select' : 'auto_select');
$('bmc-query-output').textContent = '点击查询显示 BMC 返回结果。'; $('bmc-query-time').textContent = '';
if ($('btn-export-alarms-xlsx')) $('btn-export-alarms-xlsx').href = `/api/stations/${encodeURIComponent(stationId)}/alarms.xlsx`;
renderCards(); renderDetail(); renderLog();
await poll();
}
async function poll(lightweight = false) {
if (polling) {
repollPending = true;
return;
}
polling = true;
try {
const needSysInfo = !sysInfoCache || (Date.now() - sysInfoFetchedAt >= 30000);
const reads = [
needSysInfo ? callApi('GetSystemInfo') : Promise.resolve(sysInfoCache),
lightweight && stations.length ? Promise.resolve({ stations }) : callApi('ListStations'),
];
const [info, list] = await Promise.all(reads);
if (needSysInfo && info) {
sysInfoCache = info;
sysInfoFetchedAt = Date.now();
window.stlStore?.set?.('sysInfo', info, 'poll');
}
if (!connected) status('已连接后端;选择工位操作。');
connected = true;
window.stlStore?.set?.('connected', true, 'poll');
$('refresh-indicator').classList.remove('offline');
$('sys-version').textContent = info.version || '未知';
$('sys-commit').textContent = info.commit ? info.commit.slice(0, 7) : '未知';
$('sys-mode').textContent = info.mode === 'hardware' ? '硬件实机' : (info.mode || '未知');
$('sys-heartbeat').textContent = stamp();
$('refresh-indicator').textContent = 'WebSocket 已连接';
const authOn = info.web_auth_enabled !== false;
$('btn-change-password')?.classList.toggle('hidden', !authOn);
$('btn-web-logout')?.classList.toggle('hidden', !authOn);
if (!lightweight || !stations.length) {
stations = list.stations || [];
window.stlStore?.set?.('stations', stations, 'poll');
}
if (!current() && stations.length) stationId = stations[0].station_id;
if (!stationUserChosen && stations.length) {
const cur = current();
const curOnline = !!(cur && (cur.console_online || cur.bmc_state === 'online'));
const curActiveOrAlert = !!(cur && (
cur.task_status === 'running' ||
cur.observed_detail === 'link_offline_waiting' ||
cur.awaiting_dimm_replacement ||
cur.task_status === 'failed' ||
cur.verdict === 'fail' ||
cur.fault_code ||
cur.serial_gap_detected
));
if (!curOnline && !curActiveOrAlert) {
const live = stations.find(s => s.console_online || s.bmc_state === 'online');
if (live) stationId = live.station_id;
}
}
window.stlStore?.set?.('stationId', stationId, 'sync');
const curPage = window.stlNavigation?.current?.() || 'overview';
const tasks = [pollDiagnostic(), window.stlFirmware.refresh(), pollAlarms()];
if (curPage === 'records' || curPage === 'queue' || pending.size > 0) {
tasks.push(pollQueue());
}
if (curPage === 'records' || curPage === 'queue') {
tasks.push(pollDeviceEvents(), pollAuditLogs());
}
await Promise.all(tasks);
renderCards();
renderDetail();
} catch (error) {
connected = false;
window.stlStore?.set?.('connected', false, 'poll_error');
sysInfoFetchedAt = 0;
$('refresh-indicator').textContent = '连接失败 · 显示上次数据';
$('refresh-indicator').classList.add('offline');
status(`后端连接失败:${error.message}`, true);
renderDetail();
} finally {
polling = false;
if (repollPending) {
repollPending = false;
setTimeout(() => void poll(), 40);
}
}
}
async function sendBytes(bytes, description = '发送控制台') {
const context = consoleContext();
if (!context.writable) throw new Error('当前控制台不可写:请先连接 BIOS 串口');
const data = encode(new TextEncoder().encode(bytes));
await command('WriteDiagnosticSol', {station_id:stationId, session_id:context.session_id, data}, description);
}
async function sendSol(empty = false) {
const text = $('sol-input-cmd').value;
if (!empty && !text) throw new Error('请输入命令;如需空回车请使用右侧按钮');
await sendBytes((empty ? '' : text) + (empty || $('chk-append-enter').checked ? '\r' : ''));
if (!empty) $('sol-input-cmd').value = '';
}
bind('btn-send-sol', () => sendSol());
bind('btn-send-enter', () => sendSol(true));
$('sol-input-cmd').onkeydown = event => {
if (event.key === 'Enter' && !event.isComposing) {
event.preventDefault();
$($('sol-input-cmd').value === '' ? 'btn-send-enter' : 'btn-send-sol').click();
}
};
const keys = {space:' ', escape:'\x1b', tab:'\t', up:'\x1b[A', down:'\x1b[B', right:'\x1b[C', left:'\x1b[D', ctrlc:'\x03', backspace:'\x08', f2:'\x1bOQ', f11:'\x1b[23~', delete:'\x1b[3~'};
document.querySelectorAll('[data-sol-key]').forEach(button => {
button.onclick = async () => {
if (button.dataset.busy === '1') return;
button.dataset.busy = '1'; button.disabled = true;
try { await sendBytes(keys[button.dataset.solKey], `发送 ${button.textContent}`); } catch (e) { status(e.message, true); }
finally { button.dataset.busy = ''; renderDetail(); await poll(); }
};
});
$('btn-clear-sol').onclick = async () => {
const log = visibleLog();
if (log) {
log.text = '';
$('sol-terminal').dataset.renderedOffset = '';
}
renderLog();
if (connected) {
try {
const res = await command('ClearTerminalView', {station_id: stationId}, '锚定清空控制台窗口');
const cleanOff = Number(res?.result?.clean_offset || 0);
if (log && cleanOff > 0) {
log.text = '';
log.offset = cleanOff;
log.clearAnchor = cleanOff;
$('sol-terminal').dataset.renderedOffset = '';
renderLog();
}
} catch (e) {
status(`清空锚点同步失败:${e.message}`, true);
}
}
};
bind('btn-refresh-station', async () => { await poll(); status('已刷新工位状态。'); });
bind('btn-fan-refresh', async () => { await refreshFanMode(stationId, false); });
$('chk-fan-low-speed').onchange = async () => {
const chk = $('chk-fan-low-speed'), wantLowSpeed = chk.checked;
chk.dataset.busy = '1'; chk.disabled = true;
try {
const q = wantLowSpeed ? 'fan_low_speed_on' : 'fan_low_speed_off';
const labelText = wantLowSpeed ? '开启风扇降低转速 (30%/1%)' : '关闭风扇降低转速并恢复服务器默认温控';
await command('QueryBmc', {station_id: stationId, query: q}, labelText);
} catch (error) {
chk.checked = !wantLowSpeed;
status(error.message, true);
} finally {
chk.dataset.busy = '';
renderFanControl(current());
await poll();
}
};
bind('btn-bmc-warm-reset', async () => {
await command('QueryBmc', {station_id: stationId, query: 'bmc_warm_reset'}, 'BMC 热重启 (恢复默认温控)');
});
bind('btn-query-bmc', async () => {
const selectedStation = stationId, query = $('bmc-query-kind').value;
$('bmc-query-output').textContent = '查询已提交,等待后端返回…';
$('bmc-query-time').textContent = '';
try {
await command('QueryBmc', {station_id:selectedStation, query}, '读取 BMC 信息');
} catch (error) {
if (stationId === selectedStation) $('bmc-query-output').textContent = `查询失败:${error.message}`;
throw error;
}
});
for (const [button, actionName, description] of [['btn-diag-open','open','连接 BIOS 控制台'],['btn-diag-close','close','断开 BIOS 控制台'],['btn-diag-reconnect','reconnect','重连 BIOS 控制台']]) {
bind(button, async () => {
await command('SetDiagnosticSol', {station_id:stationId, action:actionName}, description);
});
}
for (const [suffix, actionName, description, needConfirm] of [
['on','host_on','主板开机',false],
['off','host_off','主板关机',true],
['reset','host_reset','主板复位',true],
['cycle','host_cycle','主板关开循环',true],
]) {
bind(`btn-host-${suffix}`, async () => {
if (needConfirm && window.stlUi) {
const ok = await window.stlUi.confirm(`确认${description}`, `确定要对工位 ${stationId} 执行「${description}」操作吗?若当前正在运行测试,该操作会中断当前轮次。`, `确认${description}`, true);
if (!ok) return;
}
await command('StationPower', {station_id:stationId, action:actionName}, description);
});
}
bind('btn-add-station', async () => {
const sid = ($('add-station-id')?.value || '').trim().toUpperCase();
const name = ($('add-station-name')?.value || '').trim() || sid;
const bmcHost = ($('add-station-bmc')?.value || '').trim();
const cpuCount = Math.max(1, Number($('add-station-cpus')?.value || 2));
if (!sid) throw new Error('请输入新工位 ID(例如 S5)');
await callApi('AddStation', { station_id: sid, name, bmc_host: bmcHost, cpu_count: cpuCount });
if ($('add-station-id')) $('add-station-id').value = '';
if ($('add-station-name')) $('add-station-name').value = '';
if ($('add-station-bmc')) $('add-station-bmc').value = '';
if ($('station-roster-status')) $('station-roster-status').textContent = `已新增工位 ${sid}`;
status(`已新增工位 ${sid} (${name})`);
await poll();
});
bind('btn-alarms-refresh', async () => { await pollAlarms(); });
if ($('btn-alarms-prev')) $('btn-alarms-prev').onclick = () => { alarmOffset = Math.max(0, alarmOffset - alarmLimit); void pollAlarms(); };
if ($('btn-alarms-next')) $('btn-alarms-next').onclick = () => { if (alarmOffset + alarmLimit < alarmTotal) { alarmOffset += alarmLimit; void pollAlarms(); } };
bind('btn-refresh-commands', pollQueue);
bind('btn-refresh-device-events', pollDeviceEvents);
bind('btn-refresh-audits', pollAuditLogs);
if ($('btn-web-logout')) {
$('btn-web-logout').onclick = async () => {
try {
await fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' });
} finally {
window.location.reload();
}
};
}
if ($('audit-station-filter')) $('audit-station-filter').onchange = pollAuditLogs;
if ($('audit-category-filter')) $('audit-category-filter').onchange = pollAuditLogs;
$('command-station-filter').onchange = () => { queueItems = []; renderQueue(); pollQueue(); };
$('command-state-filter').onchange = renderQueue;
$('device-event-station-filter').onchange = () => { renderDeviceEvents(); pollDeviceEvents(); };
$('device-event-level-filter').onchange = renderDeviceEvents;
function saveFile(name, data, type = 'application/octet-stream') {
const url = URL.createObjectURL(new Blob([data], {type}));
const anchor = document.createElement('a'); anchor.href = url; anchor.download = name; anchor.click();
setTimeout(() => URL.revokeObjectURL(url), 10000);
}
async function readFile(method, request) {
const chunks = []; let offset = 0;
while (true) {
const part = await callApi(method, {...request, offset, max_bytes: 262144});
chunks.push(decode(part.data));
const next = Number(part.next_offset);
if (part.eof) break;
if (!(next > Number(offset))) throw new Error('下载未推进,请重试');
offset = next;
}
return new Blob(chunks);
}
bind('btn-download-sol', async () => {
const context = consoleContext();
saveFile(`${context.session_id || stationId}-sol.bin`, await readFile('ReadDiagnosticSol', {station_id:stationId, session_id:context.session_id}));
status('原始控制台日志已下载');
});
const services = {
callApi, command, bind, status, time, formatElapsed, terminalText,
useLiveConsole: () => { renderDetail(); },
stationId: () => stationId,
station: current,
diagnostic: diag,
consoleContext,
connected: () => connected,
};
window.stlFirmware.init(services);
window.stlBootPlan.init(services);
window.stlAmt.init(services);
window.stlDimms.init(services);
window.stlStages.init(services);
window.stlUi?.init?.({
onSelectStation: sid => void selectStation(sid, true),
onStartStation: async (sid, { targetTemp, profileId }) => {
try {
let chosenProfile = null;
if (profileId && profileId !== '__current__') {
const ctrl = window.stlFirmware.snapshot(sid) || {};
const list = Array.isArray(ctrl.saved_profiles) ? ctrl.saved_profiles : [];
chosenProfile = list.find(p => (p.profile_id || p.name) === profileId) || null;
await window.stlBootPlan.awaitCommand('LoadProfileToWorkspace', { station_id: sid, profile_id: profileId }, `加载 ${sid} 配置`);
}
const useTemp = Number.isFinite(Number(targetTemp)) ? Math.max(0, Math.min(254, Number(targetTemp))) : 0;
await window.stlBootPlan.awaitCommand('ConfigureThermalPolicy', {
station_id: sid,
thermal_policy: { auto_enabled: useTemp > 0, target_temp_c: useTemp, require_online: useTemp > 0 },
}, useTemp > 0 ? `设置 ${sid} 目标温度 ${useTemp}℃` : `关闭 ${sid} 自动温控`);
if (chosenProfile && (Number(chosenProfile.repeat) === 0 || Number(chosenProfile.repeat) > 1)) {
const runProf = {
...JSON.parse(JSON.stringify(chosenProfile)),
target_temp_c: useTemp,
thermal_auto_enabled: useTemp > 0,
require_thermal_online: useTemp > 0,
};
await window.stlBootPlan.awaitCommand('SubmitTaskBatch', {
station_id: sid,
profiles: [runProf],
stop_on_fail: true,
auto_start: true,
skip_thermal_check: false,
}, `产线启动工位 ${sid} 多轮队列`);
} else {
await window.stlBootPlan.awaitCommand('ControlBootPlan', { station_id: sid, action: 'restart', skip_thermal_check: false }, `产线启动工位 ${sid}`);
}
status(useTemp > 0 ? `工位 ${sid} 已启动高温测试(目标 ${useTemp}℃)。` : `工位 ${sid} 已启动常温测试(不控温)。`);
await poll();
} catch (err) {
status(`工位 ${sid} 启动被拦截或失败:${err.message}`, true);
if (window.stlUi) {
await window.stlUi.confirm(`工位 ${sid} 无法启动`, err.message, '我知道了', false);
}
}
},
onStopStation: async sid => {
try {
await command('ControlTaskBatch', { station_id: sid, action: 'stop' }, `停止工位 ${sid} 测试队列`);
await command('ControlBootPlan', { station_id: sid, action: 'stop' }, `停止工位 ${sid} 启动计划`);
status(`已停止工位 ${sid},后端已自动联动高温罩降温。`);
await poll();
} catch (err) {
status(`停止工位 ${sid} 失败:${err.message}`, true);
}
},
});
window.addEventListener('stl:page-change', ev => {
const pg = ev.detail?.page;
if (pg === 'records' || pg === 'queue') {
void Promise.all([pollQueue(), pollDeviceEvents(), pollAuditLogs(), pollAlarms()]);
}
});
window.addEventListener('stl:station-select', event => selectStation(event.detail.stationId));
window.addEventListener('stl:transport-state', event => {
const transport = event.detail, ready = transport.state === 'open';
const stateLabels = {idle:'等待连接',connecting:'连接中',open:'已连接',disconnected:'已断开 · 重连中',closed:'已断开'};
$('transport-state').textContent = 'WebSocket · ' + (stateLabels[transport.state] || transport.state);
$('transport-state').dataset.state = transport.state;
$('transport-state').classList.toggle('connected', ready);
$('transport-state').classList.toggle('error', ['disconnected','closed'].includes(transport.state));
if (ready) {
if (transport.generation > 1) {
sysInfoFetchedAt = 0;
poll();
}
} else {
connected = false;
window.stlStore?.set?.('connected', false, 'transport_close');
$('refresh-indicator').textContent = '连接未就绪 · 显示上次数据';
$('refresh-indicator').classList.add('offline');
renderDetail();
}
});
window.addEventListener('stl:server-event', event => {
const detail = event.detail || {};
const ev = detail.event;
if (ev === 'task_complete') {
if (dirtyPollTimer) { clearTimeout(dirtyPollTimer); dirtyPollTimer = null; }
void poll(false);
} else if (ev === 'station_dirty') {
const payload = detail.result || detail;
const stArr = Array.isArray(payload.stations) ? payload.stations : [];
if (stArr.length) {
stations = stArr;
window.stlStore?.set?.('stations', stations, 'ws_dirty');
renderCards();
}
const dirtyList = Array.isArray(payload.dirty_stations) ? payload.dirty_stations : [];
const curDirty = !dirtyList.length || dirtyList.includes(stationId);
if (curDirty && !dirtyPollTimer) {
dirtyPollTimer = setTimeout(() => {
dirtyPollTimer = null;
void poll(stArr.length > 0);
}, 350);
}
}
});
window.addEventListener('load', async () => {
renderDetail();
await poll();
setInterval(poll, 10000);
void startLiveTailLoop();
});
})();