app.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. // app.js — Main Workbench State & Console / Queue / BMC Synchronization
  2. (() => {
  3. const $ = id => document.getElementById(id);
  4. const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
  5. function redact(value) {
  6. if (Array.isArray(value)) return value.map(redact);
  7. if (!value || typeof value !== 'object') return value;
  8. return Object.fromEntries(Object.entries(value).map(([key,item]) => [key,/^(password|token|api_token|secret)$/i.test(key) ? '已隐藏' : redact(item)]));
  9. }
  10. let stationId = 'S1', stationUserChosen = false, stations = [], polling = false, repollPending = false, selectionRevision = 0, connected = false;
  11. let sysInfoCache = null, sysInfoFetchedAt = 0, dirtyPollTimer = null;
  12. const logs = new Map(), pending = new Map(), diagnostics = new Map();
  13. let queueItems = [], queuePolling = false, eventPolling = false, auditItems = [], auditPolling = false;
  14. const eventViews = new Map(), bmcPending = new Map();
  15. const fanStateByStation = new Map(), fanQueryInFlight = new Set();
  16. let diagnosticError = '';
  17. const terminalStates = new Set(['succeeded', 'failed', 'interrupted']);
  18. const queueLabels = {queued:'排队', dispatching:'分派中', running:'执行', succeeded:'成功', failed:'失败', interrupted:'中断'};
  19. const operationLabels = {
  20. WriteSol:'发送控制台',
  21. WriteDiagnosticSol:'发送 BIOS 控制台',
  22. SetDiagnosticSol:'连接管理',
  23. StationPower:'主板电源',
  24. QueryBmc:'读取 BMC 信息',
  25. ConfigureConnections:'配置设备连接',
  26. ConfigurePxe:'配置 PXE',
  27. GetN540Config:'读取 N540 串口服务器',
  28. ConfigureN540:'配置 N540 纯净透传',
  29. SaveFirmwareSettings:'保存 ICT 配置',
  30. ApplyUipParameters:'下发 ICT 参数',
  31. ContinueUip:'ICT 发送 exit 继续',
  32. SkipAmt:'退出当前 AMT 菜单',
  33. ListUefiFiles:'读取 UEFI 目录',
  34. StartMt:'启动 MT 程序',
  35. SaveBootPlan:'保存启动计划',
  36. ControlBootPlan:'启动计划控制',
  37. SaveAmtSettings:'保存 AMT 配置',
  38. ApplyAmtSettings:'应用 AMT 配置',
  39. StartAmt:'提交 AMT 测试启动',
  40. ExecuteAmtCommand:'执行 AMT 菜单命令',
  41. SaveProfile:'保存测试 Profile',
  42. DeleteProfile:'删除测试 Profile',
  43. LoadProfileToWorkspace:'加载 Profile 到工作区',
  44. SubmitTaskBatch:'提交多计划测试队列',
  45. ControlTaskBatch:'控制多计划测试队列',
  46. ConfirmDimmReplacement:'确认更换异常内存条',
  47. SetStageIntent:'预设阶段控制状态',
  48. ApplyErrorPreset:'应用零加压拉偏预设',
  49. ClearTerminalView:'锚定清空控制台窗口',
  50. };
  51. const actionLabels = {
  52. open:'连接 BIOS 控制台',
  53. close:'断开 BIOS 控制台',
  54. reconnect:'重连 BIOS 控制台',
  55. host_on:'主板开机',
  56. host_off:'主板关机',
  57. host_reset:'主板复位',
  58. host_cycle:'主板关开循环',
  59. bmc_warm_reset:'BMC 热重启(恢复默认温控)',
  60. fan_low_speed_on:'开启风扇降速模式',
  61. fan_low_speed_off:'关闭风扇降速(恢复默认温控)',
  62. };
  63. const phases = [['boot', '启动'], ['uip', 'ICT 配置'], ['training', 'Training'], ['rmt', 'RMT 执行'], ['amt', 'AMT / AMEMDIAG'], ['post', 'POST / DXE / BDS'], ['uefi', 'UEFI'], ['mt', 'MT']];
  64. const phaseNames = new Map([...phases, ['amemdiag', 'AMEMDIAG控制台']]);
  65. const labels = {
  66. powered_off:'已断电', post:'POST / DXE / BDS', amemdiag:'AMEMDIAG 控制台',
  67. idle:'空闲', rmt:'RMT', amt:'AMT / AMEMDIAG测试', uefi_ready:'UEFI', mt:'MT',
  68. online:'在线', offline:'离线', on:'开', off:'关', unknown:'未知',
  69. pending:'待判定', pass:'通过', fail:'失败', failed:'失败', skipped:'跳过',
  70. completed:'已完成', stopped:'已停止', running:'运行中', connecting:'连接中',
  71. closed:'未连接', disabled:'未启用', enabled:'已启用', error:'连接异常',
  72. valid:'有效', unavailable:'无读数',
  73. };
  74. const label = value => labels[value] || value || '未知';
  75. const diag = () => diagnostics.get(stationId) || {};
  76. function transportLabel(snapshot = diag()) {
  77. const value = snapshot.transport || '';
  78. if (value === 'local_serial') return '物理串口 · /dev/ttyUSB0';
  79. if (value.startsWith('local_serial:')) return '物理串口 · ' + value.slice('local_serial:'.length);
  80. if (value === 'tcp_serial') return 'N540 TCP Server · ' + (snapshot.session_rx_bytes ? `RX ${snapshot.session_rx_bytes}B` : 'TCP 透传');
  81. if (value.startsWith('tcp_serial:')) return 'N540 TCP · ' + value.slice('tcp_serial:'.length);
  82. if (value.startsWith('tcp_serial_server:')) return 'N540 TCPC 监听 · ' + value.slice('tcp_serial_server:'.length);
  83. if (value === 'ipmi_sol' || value.startsWith('ipmi_sol:')) return 'IPMI SOL';
  84. if (value === 'ssh_console') return 'SSH BIOS 控制台';
  85. if (value.startsWith('ssh_console:')) return `SSH BIOS · ${value.slice('ssh_console:'.length)}`;
  86. return value || '等待链路信息';
  87. }
  88. function capabilities(s = current()) {
  89. return window.stlFirmware?.capabilities(s?.station_id) || {
  90. console: !!s?.bmc_address,
  91. bmc_power: !!s?.bmc_address,
  92. bmc_query: !!s?.bmc_address,
  93. };
  94. }
  95. function consoleContext() {
  96. const d = diag();
  97. return {
  98. kind: 'diagnostic',
  99. key: d.session_id ? `diag:${stationId}:${d.session_id}` : '',
  100. session_id: d.session_id || '',
  101. exists: !!d.session_id,
  102. writable: connected && (d.state === 'online' || !!current()?.console_online),
  103. };
  104. }
  105. function runLog(key) {
  106. if (!logs.has(key)) logs.set(key, {offset:0, text:'', decoder:new TextDecoder()});
  107. return logs.get(key);
  108. }
  109. function visibleLog() {
  110. const c = consoleContext();
  111. return c.key ? runLog(c.key) : null;
  112. }
  113. function terminalText(text) {
  114. return String(text || '')
  115. .replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '')
  116. .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
  117. .replace(/\x1b[()][A-Z0-9]/g, '')
  118. .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '')
  119. .replace(/\r(?!\n)/g, '\n');
  120. }
  121. const stamp = () => new Date().toLocaleTimeString();
  122. const id = () => `web-${Date.now()}-${Math.random().toString(36).slice(2)}`;
  123. const current = () => stations.find(s => s.station_id === stationId);
  124. const decode = value => Uint8Array.from(atob(value || ''), c => c.charCodeAt(0));
  125. function encode(bytes) {
  126. let text = '';
  127. for (let i = 0; i < bytes.length; i += 8192) text += String.fromCharCode(...bytes.subarray(i, i + 8192));
  128. return btoa(text);
  129. }
  130. function status(text, error = false) {
  131. $('action-status').textContent = terminalText(text);
  132. $('action-status').classList.toggle('error', error);
  133. }
  134. function enable(button, allowed) {
  135. const el = $(button);
  136. if (el) el.disabled = !allowed || el.dataset.busy === '1';
  137. }
  138. function time(ms) { return Number(ms) > 0 ? new Date(Number(ms)).toLocaleString() : '未知'; }
  139. function formatElapsed(ms) {
  140. const n = Math.max(0, Math.floor(Number(ms || 0) / 1000));
  141. const h = Math.floor(n / 3600), m = Math.floor((n % 3600) / 60), s = n % 60;
  142. return [h, m, s].map(v => String(v).padStart(2, '0')).join(':');
  143. }
  144. function callApi(method, payload = {}, timeoutMs) {
  145. return window.stlTransport.call(method, payload, timeoutMs);
  146. }
  147. async function command(method, request, cmdLabel) {
  148. const commandStation = request.station_id || stationId;
  149. const args = {...request};
  150. delete args.station_id; delete args.command_id; delete args.operator;
  151. const commandId = id(), tracked = {label:cmdLabel, station:commandStation, state:'submitting', updated:0};
  152. pending.set(commandId, tracked);
  153. let result;
  154. try {
  155. result = await callApi('EnqueueCommand', {
  156. command_id: commandId,
  157. station_id: commandStation,
  158. method,
  159. arguments: args,
  160. operator: 'operator',
  161. });
  162. } catch (error) {
  163. if (tracked.result) result = tracked.result;
  164. else {
  165. if (['DISCONNECTED','REQUEST_TIMEOUT','SEND_FAILED'].includes(error.code)) {
  166. tracked.state = 'submission_unknown';
  167. throw Object.assign(
  168. new Error(`${cmdLabel}:提交结果待核对 · ${commandId}。重连后将按此编号查询,不会自动重复执行。${error.message}`),
  169. {code:error.code, command_id:commandId}
  170. );
  171. } else pending.delete(commandId);
  172. throw error;
  173. }
  174. }
  175. Object.assign(tracked, {state:result.state, updated:result.updated_unix_ms, result});
  176. if (method === 'QueryBmc') bmcPending.set(commandStation, result.command_id);
  177. if (!$('command-station-filter').value || $('command-station-filter').value === commandStation) {
  178. queueItems = [result, ...queueItems.filter(item => item.command_id !== result.command_id)].slice(0, 100);
  179. renderQueue();
  180. }
  181. showCommand(result, cmdLabel);
  182. receiveBmcResult(result);
  183. return result;
  184. }
  185. function showCommand(result, cmdLabel) {
  186. const meanings = {queued:'已排队', dispatching:'正在分派', running:'执行中', succeeded:'执行成功', failed:'执行失败', interrupted:'已中断'};
  187. status(`${cmdLabel}:${meanings[result.state] || result.state}${result.detail ? ' — ' + result.detail : ''}`, ['failed', 'interrupted'].includes(result.state));
  188. if (terminalStates.has(result.state)) pending.delete(result.command_id);
  189. }
  190. function operation(item) {
  191. return actionLabels[item.arguments?.action] || operationLabels[item.method] || item.method || '未知操作';
  192. }
  193. function renderQueue() {
  194. const selectedState = $('command-state-filter').value;
  195. const items = [...queueItems].sort((a,b) => Number(b.sequence) - Number(a.sequence));
  196. const counts = {queued:0, running:0, succeeded:0, failed:0, interrupted:0};
  197. for (const item of items) {
  198. const state = item.state === 'dispatching' ? 'running' : item.state;
  199. if (state in counts) counts[state]++;
  200. }
  201. $('command-queue-counts').innerHTML = Object.entries(counts).map(([state,count]) => `<span class="queue-count">${queueLabels[state]}<strong>${count}</strong></span>`).join('');
  202. $('command-queue-size').textContent = String(items.length);
  203. const open = new Set([...document.querySelectorAll('#commands-tbody details[open]')].map(node => node.dataset.command));
  204. const visible = items.filter(item => !selectedState || item.state === selectedState || (selectedState === 'running' && item.state === 'dispatching'));
  205. $('commands-tbody').innerHTML = visible.map(item => {
  206. const result = JSON.stringify(redact({arguments:item.arguments || {}, result:item.result || {}, ...(item.error_code ? {error_code:item.error_code} : {})}), null, 2);
  207. const summary = item.detail || queueLabels[item.state] || item.state;
  208. return `<tr data-command-id="${escape(item.command_id)}" data-command-state="${escape(item.state)}"><td>${time(item.created_unix_ms)}</td><td>${escape(item.station_id)}</td><td><span class="queue-operation">${escape(operation(item))}</span><span class="queue-method">${escape(item.method)}</span></td><td>${escape(item.operator || 'operator')}</td><td><span class="queue-state queue-state-${escape(item.state)}">${escape(queueLabels[item.state] || item.state)}</span></td><td><details class="queue-result" data-command="${escape(item.command_id)}" ${open.has(item.command_id) ? 'open' : ''}><summary>${escape(summary)}</summary><div class="queue-result-meta">${escape(item.command_id)} · 更新 ${time(item.updated_unix_ms)}</div><pre>${escape(result)}</pre></details></td></tr>`;
  209. }).join('') || '<tr><td colspan="6">当前筛选下没有命令记录</td></tr>';
  210. }
  211. function applyFanResultText(targetStationId, text) {
  212. try {
  213. const parsed = JSON.parse(text || '{}');
  214. if (parsed && (typeof parsed.enabled === 'boolean' || parsed.fan_mode_restored === 'auto')) {
  215. const enabled = parsed.fan_mode_restored === 'auto' ? false : !!parsed.enabled;
  216. fanStateByStation.set(targetStationId, {
  217. enabled,
  218. mode: enabled ? 'low_speed' : 'auto',
  219. raw_mode: parsed.raw_mode || (enabled ? '01' : '00'),
  220. label: parsed.label || (enabled ? '降速静音模式 (系统30% / 电源1%)' : '服务器默认自动温控 (Auto)'),
  221. fans: Array.isArray(parsed.fans) ? parsed.fans : [],
  222. });
  223. if (targetStationId === stationId) renderFanControl(current());
  224. }
  225. } catch (_) {}
  226. }
  227. function renderFanControl(s = current()) {
  228. const caps = capabilities(s), available = connected && !!s && !!caps.bmc_query && s.bmc_state === 'online';
  229. const st = s ? fanStateByStation.get(s.station_id) : null;
  230. const chk = $('chk-fan-low-speed');
  231. if (chk) {
  232. chk.disabled = !available || chk.dataset.busy === '1';
  233. if (st && chk.dataset.busy !== '1') chk.checked = !!st.enabled;
  234. }
  235. enable('btn-fan-refresh', connected && !!s && !!caps.bmc_query);
  236. enable('btn-bmc-warm-reset', connected && !!s && !!caps.bmc_query);
  237. const badge = $('fan-mode-badge'), summary = $('fan-rpm-summary');
  238. if (!badge || !summary) return;
  239. if (!s || !caps.bmc_query) {
  240. badge.textContent = 'BMC 未启用';
  241. badge.className = 'badge';
  242. summary.textContent = '';
  243. return;
  244. }
  245. if (!st) {
  246. badge.textContent = s.bmc_state === 'online' ? '待读取风扇模式' : `BMC ${label(s.bmc_state)}`;
  247. badge.className = 'badge';
  248. summary.textContent = '';
  249. return;
  250. }
  251. badge.textContent = `当前: ${st.label}`;
  252. badge.className = 'badge ' + (st.enabled ? 'error' : 'connected');
  253. summary.textContent = st.fans?.length ? st.fans.slice(0, 6).join(' · ') : (st.raw_mode ? `原始模式字节: ${st.raw_mode}` : '');
  254. }
  255. async function refreshFanMode(targetStationId = stationId, silent = true) {
  256. const s = stations.find(x => x.station_id === targetStationId);
  257. if (!connected || !s || !capabilities(s).bmc_query || fanQueryInFlight.has(targetStationId) || s.bmc_state !== 'online') return;
  258. fanQueryInFlight.add(targetStationId);
  259. try {
  260. const cmd = await command('QueryBmc', {station_id: targetStationId, query: 'fan_mode'}, '查询风扇温控模式');
  261. if (cmd?.result?.text) applyFanResultText(targetStationId, cmd.result.text);
  262. } catch (error) {
  263. if (!silent) status(`风扇状态读取失败:${error.message}`, true);
  264. } finally {
  265. fanQueryInFlight.delete(targetStationId);
  266. if (targetStationId === stationId) renderFanControl(current());
  267. }
  268. }
  269. function receiveBmcResult(item) {
  270. if (item.method === 'QueryBmc' && terminalStates.has(item.state) && item.state === 'succeeded' && item.result?.text) {
  271. if (['fan_mode','fan_low_speed_on','fan_low_speed_off','bmc_warm_reset'].includes(item.arguments?.query || item.result?.query)) {
  272. applyFanResultText(item.station_id, item.result.text);
  273. }
  274. }
  275. if (item.method !== 'QueryBmc' || bmcPending.get(item.station_id) !== item.command_id || !terminalStates.has(item.state)) return;
  276. bmcPending.delete(item.station_id);
  277. if (stationId !== item.station_id) return;
  278. $('bmc-query-output').textContent = item.state === 'succeeded' ? item.result?.text || '设备未返回文本' : `查询失败:${item.detail || item.error_code || item.state}`;
  279. $('bmc-query-time').textContent = time(item.result?.observed_unix_ms || item.updated_unix_ms);
  280. }
  281. async function pollQueue() {
  282. if (queuePolling) return;
  283. queuePolling = true;
  284. const filter = $('command-station-filter').value;
  285. try {
  286. const snapshot = await callApi('GetQueue', {station_id:filter, limit:100});
  287. const fetched = snapshot.items || [], byId = new Map(fetched.map(item => [item.command_id,item]));
  288. for (const [key, tracked] of [...pending]) {
  289. let item = byId.get(key);
  290. if (!item) {
  291. try { item = await callApi('GetQueueItem', {command_id:key}); }
  292. catch (error) {
  293. if (error.code === 'NOT_FOUND' && ['submitting','submission_unknown'].includes(tracked.state)) continue;
  294. throw error;
  295. }
  296. }
  297. tracked.result = item;
  298. if (item.state !== tracked.state || item.updated_unix_ms !== tracked.updated) {
  299. tracked.state = item.state; tracked.updated = item.updated_unix_ms;
  300. showCommand(item, `${tracked.station} ${tracked.label}`);
  301. }
  302. receiveBmcResult(item);
  303. }
  304. if (filter !== $('command-station-filter').value) return;
  305. queueItems = fetched; renderQueue();
  306. $('command-queue-updated').textContent = `已同步 ${stamp()} · 等待 ${Number(snapshot.pending_count || 0)} / 执行 ${Number(snapshot.running_count || 0)}`;
  307. $('command-queue-error').classList.add('hidden');
  308. } catch (error) {
  309. $('command-queue-error').textContent = `队列读取失败,保留上次记录:${error.message}`;
  310. $('command-queue-error').classList.remove('hidden');
  311. } finally { queuePolling = false; }
  312. }
  313. function deviceEventView() {
  314. const filter = $('device-event-station-filter').value;
  315. if (!eventViews.has(filter)) eventViews.set(filter, {events:[], cursor:0, initialized:false, hasMore:false, updated:''});
  316. return eventViews.get(filter);
  317. }
  318. function renderDeviceEvents() {
  319. const view = deviceEventView(), selectedLevel = $('device-event-level-filter').value;
  320. const open = new Set([...document.querySelectorAll('#device-events-tbody details[open]')].map(node => node.dataset.event));
  321. 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();
  322. const severity = {info:'信息', warning:'警告', warn:'警告', error:'错误', critical:'严重', fatal:'严重'};
  323. $('device-events-tbody').innerHTML = events.map(event => {
  324. const payload = event.payload || {}, phase = event.phase ? phaseNames.get(event.phase) || label(event.phase) : '—';
  325. const detail = JSON.stringify(redact({sequence:event.sequence, ...(event.command_id ? {command_id:event.command_id} : {}), payload}), null, 2);
  326. return `<tr data-event-sequence="${escape(event.sequence)}"><td>${time(event.observed_unix_ms)}</td><td>${escape(event.station_id)}</td><td><span class="event-source">现场诊断</span><span class="event-phase">${escape(phase)}</span></td><td><span class="event-level event-level-${escape(event.severity)}">${escape(severity[event.severity] || event.severity || '信息')}</span></td><td>${escape(event.kind)}</td><td><details class="queue-result" data-event="${escape(event.sequence)}" ${open.has(String(event.sequence)) ? 'open' : ''}><summary>${escape(event.message || event.kind)}</summary><pre>${escape(detail)}</pre></details></td></tr>`;
  327. }).join('') || '<tr><td colspan="6">当前筛选下没有设备事件</td></tr>';
  328. $('device-event-cursor').textContent = `本页读取位置:${view.cursor} · 保留 ${view.events.length} 条`;
  329. $('device-events-updated').textContent = view.updated ? `已同步 ${view.updated}` : '等待设备事件';
  330. }
  331. async function pollDeviceEvents() {
  332. if (eventPolling) return;
  333. eventPolling = true;
  334. const filter = $('device-event-station-filter').value, view = deviceEventView();
  335. try {
  336. const result = await callApi('ReadEventQueue', {station_id:filter, after_sequence:view.cursor, limit:100});
  337. view.initialized = true;
  338. const next = Number(result.next_after_sequence || view.cursor);
  339. const existing = new Set(view.events.map(event => String(event.sequence)));
  340. 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);
  341. view.hasMore = !!result.has_more; view.updated = stamp();
  342. view.cursor = next;
  343. if (filter === $('device-event-station-filter').value) {
  344. renderDeviceEvents(); $('device-events-error').classList.add('hidden');
  345. }
  346. } catch (error) {
  347. $('device-events-error').textContent = `设备事件读取失败,保留上次记录:${error.message}`;
  348. $('device-events-error').classList.remove('hidden');
  349. } finally { eventPolling = false; }
  350. }
  351. function renderAuditLogs() {
  352. if (!$('audit-logs-tbody')) return;
  353. const catLabels = {
  354. profile_library:'Profile 配置库',
  355. task_batch:'多计划测试队列',
  356. ict_settings:'ICT 参数保存',
  357. ict_dispatch:'ICT 固件下发',
  358. amt_settings:'AMT 参数保存',
  359. amt_dispatch:'AMT 固件下发',
  360. pxe_mt86:'PXE 与 mt86.cfg',
  361. boot_plan:'启动计划',
  362. thermal_mcu:'高温罩温控',
  363. connections:'连接设置',
  364. dimm_replacement:'停机换条确认',
  365. stage_intent:'阶段预设覆盖',
  366. error_preset:'时序拉偏预设',
  367. start_test:'测试启动',
  368. power:'电源控制',
  369. };
  370. const open = new Set([...document.querySelectorAll('#audit-logs-tbody details[open]')].map(n => n.dataset.seq));
  371. $('audit-logs-tbody').innerHTML = auditItems.map(item => {
  372. const seq = String(item.sequence || '');
  373. const detailJson = JSON.stringify(redact(item.details || {}), null, 2);
  374. return `<tr>
  375. <td><code>#${escape(seq)}</code></td>
  376. <td>${time(item.timestamp_unix_ms)}</td>
  377. <td><strong>${escape(item.station_id || '-')}</strong></td>
  378. <td>${escape(item.operator || 'operator')}</td>
  379. <td><span class="badge">${escape(catLabels[item.category] || item.category || '-')}</span></td>
  380. <td><code>${escape(item.action || '-')}</code></td>
  381. <td><details class="queue-result" data-seq="${escape(seq)}" ${open.has(seq) ? 'open' : ''}><summary>${escape(item.summary || '-')}</summary><pre>${escape(detailJson)}</pre></details></td>
  382. </tr>`;
  383. }).join('') || '<tr><td colspan="7">当前筛选条件下暂无变更审计记录</td></tr>';
  384. }
  385. async function pollAuditLogs() {
  386. if (auditPolling || !$('audit-logs-tbody')) return;
  387. auditPolling = true;
  388. const stFilter = $('audit-station-filter')?.value || '';
  389. const catFilter = $('audit-category-filter')?.value || '';
  390. try {
  391. const res = await callApi('ReadAuditLogs', {station_id: stFilter, category: catFilter, limit: 100});
  392. auditItems = res.items || [];
  393. renderAuditLogs();
  394. if ($('audit-logs-updated')) $('audit-logs-updated').textContent = `已同步 ${stamp()} · 累计序号 #${res.latest_sequence || 0}`;
  395. } catch (_) {
  396. } finally { auditPolling = false; }
  397. }
  398. async function action(button, task) {
  399. const element = $(button);
  400. if (!element || element.dataset.busy === '1') return;
  401. element.dataset.busy = '1'; element.disabled = true;
  402. try { await task(); } catch (error) { status(error.message, true); }
  403. finally { element.dataset.busy = ''; element.disabled = false; renderDetail(); await poll(); }
  404. }
  405. function bind(button, task) { if ($(button)) $(button).onclick = () => action(button, task); }
  406. function renderCards() {
  407. window.stlNavigation.updateStations(stations, stationId);
  408. $('stations-grid').innerHTML = stations.map(s => {
  409. const stage = window.stlFirmware.snapshot(s.station_id)?.firmware?.stage_progress;
  410. const state = stage?.main?.label || '阶段待观测';
  411. const caps = window.stlFirmware.capabilities(s.station_id);
  412. const unavailable = !!caps && !caps.console && !caps.bmc_query;
  413. const shortName = (s.name || s.station_id).replace(/\s*\(.+\)$/, '');
  414. const d = diagnostics.get(s.station_id);
  415. const consoleOnline = !!(s.console_online ?? (d?.state === 'online'));
  416. const nodeOnline = consoleOnline || s.bmc_state === 'online';
  417. const kind = (unavailable || !nodeOnline) ? 'offline' : 'idle';
  418. const bmcBadge = s.bmc_state === 'online' ? 'BMC 在线' : (s.bmc_address ? `BMC ${label(s.bmc_state || 'offline')}` : '仅串口模式');
  419. return `<div class="station-card ${s.station_id === stationId ? 'active' : ''}" data-id="${escape(s.station_id)}" role="button" tabindex="0" aria-pressed="${s.station_id === stationId}">
  420. <div class="station-card-header"><div><span class="station-name">${escape(s.station_id)} · ${escape(shortName)}</span><div class="station-subtitle">${escape(d?.transport ? transportLabel(d) : s.bmc_address ? 'BMC ' + s.bmc_address : '未配置连接')}</div></div><span class="station-status-tag tag-${s.awaiting_dimm_replacement ? 'error' : kind}">${escape(unavailable ? '未配置' : s.awaiting_dimm_replacement ? '待换条' : !nodeOnline ? '离线' : label(state))}</span></div>
  421. <div class="station-info-row"><span>主板电源</span><span>${escape(label(s.server_power))} · ${escape(bmcBadge)}</span></div>
  422. <div class="station-info-row"><span>测试用时</span><span>${escape(formatElapsed(s.elapsed_ms || 0))}</span></div>
  423. <div class="station-card-footer"><span><i class="status-dot ${consoleOnline ? 'online' : ''}"></i>控制台 ${escape(consoleOnline ? '在线 (活动)' : label(d?.state || 'closed'))}</span><span>${escape(s.firmware_family || '硬件工位')}</span></div>
  424. </div>`;
  425. }).join('');
  426. document.querySelectorAll('.station-card').forEach(card => {
  427. card.onclick = () => selectStation(card.dataset.id);
  428. card.onkeydown = event => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); selectStation(card.dataset.id); } };
  429. });
  430. }
  431. function renderDimms(s) { window.stlDimms?.render(window.stlFirmware.snapshot(s.station_id) || {}); }
  432. function renderBoot(s, d) {
  433. const control = window.stlFirmware.snapshot(s.station_id) || {};
  434. window.stlStages.render(control, {station:s, diagnostic:d});
  435. }
  436. function renderDiagnostic(s) {
  437. const d = diag(), caps = capabilities(s), available = connected && !!s, consoleReady = available && !!caps.console;
  438. enable('btn-diag-open', consoleReady && !['online','connecting'].includes(d.state));
  439. enable('btn-diag-reconnect', consoleReady && d.state !== 'connecting');
  440. enable('btn-diag-close', available && ['online','connecting','error'].includes(d.state));
  441. for (const act of ['on','off','reset','cycle']) {
  442. enable(`btn-host-${act}`, available && !!caps.bmc_power);
  443. if ($(`btn-host-${act}`)) $(`btn-host-${act}`).title = caps.bmc_power ? '' : '未启用 BMC IPMI';
  444. }
  445. enable('btn-refresh-station', connected);
  446. enable('btn-query-bmc', available && !!caps.bmc_query && !bmcPending.has(stationId));
  447. const consoleOnline = !!(s?.console_online ?? (d.state === 'online'));
  448. $('diagnostic-state').textContent = diagnosticError ? '读取失败' : (consoleOnline ? '控制台在线' : label(d.state || 'closed'));
  449. $('diagnostic-state').classList.toggle('connected', consoleOnline);
  450. $('diagnostic-state').classList.toggle('error', !!diagnosticError || d.state === 'error');
  451. renderBoot(s, d);
  452. }
  453. function renderDetail() {
  454. const s = current(), context = consoleContext();
  455. enable('btn-send-sol', context.writable);
  456. enable('btn-send-enter', context.writable);
  457. $('sol-input-cmd').disabled = !context.writable;
  458. document.querySelectorAll('[data-sol-key]').forEach(button => { button.disabled = !context.writable || button.dataset.busy === '1'; });
  459. enable('btn-download-sol', connected && context.exists);
  460. if (!s) { renderDiagnostic({}); renderDimms({}); return; }
  461. $('detail-station-tag').textContent = `${s.station_id} · ${s.name || '工位'}`;
  462. if ($('detail-elapsed')) {
  463. const ended = Number(s.ended_unix_ms) > 0;
  464. const activeTiming = Number(s.started_unix_ms) > 0 && !ended;
  465. $('detail-elapsed').textContent = (ended ? '本批耗时 ' : '测试用时 ') + formatElapsed(s.elapsed_ms || 0);
  466. $('detail-elapsed').classList.toggle('connected', activeTiming);
  467. }
  468. const stageProgress = window.stlFirmware.snapshot(s.station_id)?.firmware?.stage_progress;
  469. $('detail-phase-tag').textContent = (stageProgress?.live === false ? '最后观测:' : '本轮进度:') + (stageProgress?.main?.label || '等待阶段数据');
  470. const executionState = window.stlFirmware.snapshot(stationId)?.boot_execution?.state;
  471. const consoleOnline = !!(s.console_online ?? (diag().state === 'online'));
  472. $('console-lock-badge').textContent = !consoleOnline && diag().state !== 'online' ? '未连接' : executionState === 'paused' ? '计划已暂停 · 人工接管' : executionState === 'waiting_user' ? '人工节点 · 可输入' : executionState === 'running' ? '自动计划执行中' : '手动调试';
  473. $('sol-state-badge').textContent = consoleOnline ? '控制台在线' : label(diag().state || 'closed');
  474. $('sol-state-badge').classList.toggle('connected', consoleOnline);
  475. $('console-context').textContent = `现场诊断 · ${transportLabel()} · ${diag().session_id || '点击「连接串口」建立会话'}`;
  476. renderDiagnostic(s); renderFanControl(s); renderDimms(s); window.stlFirmware.render();
  477. if (connected && s && s.bmc_state === 'online' && !fanStateByStation.has(s.station_id) && !fanQueryInFlight.has(s.station_id)) {
  478. refreshFanMode(s.station_id, true);
  479. }
  480. }
  481. function renderLog() {
  482. const context = consoleContext(), state = visibleLog();
  483. if (!state?.text) {
  484. $('sol-terminal').textContent = context.exists ? '等待串口输出…' : '连接串口后在此显示主板 BIOS 实时输出。连接成功不会自动发送回车。';
  485. $('sol-terminal').dataset.renderedOffset = '0';
  486. return;
  487. }
  488. const curOff = String(state.offset || 0);
  489. if ($('sol-terminal').dataset.renderedOffset === curOff && $('sol-terminal').dataset.renderedLen === String(state.text.length)) {
  490. return;
  491. }
  492. $('sol-terminal').dataset.renderedOffset = curOff;
  493. $('sol-terminal').dataset.renderedLen = String(state.text.length);
  494. $('sol-terminal').textContent = state.text;
  495. if ($('chk-autoscroll').checked) $('sol-terminal').scrollTop = $('sol-terminal').scrollHeight;
  496. }
  497. let uartPumpActive = false;
  498. async function pumpCleanUart(waitMs = 0) {
  499. if (uartPumpActive || !connected) return;
  500. const selectedStation = stationId, revision = selectionRevision;
  501. const snapshot = diagnostics.get(selectedStation);
  502. if (!snapshot?.session_id) return;
  503. uartPumpActive = true;
  504. try {
  505. const key = `diag:${selectedStation}:${snapshot.session_id}`, state = runLog(key);
  506. const reqWait = waitMs;
  507. const chunk = await callApi('ReadCleanedUart', {
  508. station_id: selectedStation,
  509. offset: state.offset,
  510. max_bytes: 65536,
  511. wait_ms: reqWait,
  512. }, Math.max(12000, reqWait + 8000));
  513. if (selectedStation !== stationId || revision !== selectionRevision) return;
  514. const clearOff = Number(chunk.last_clear_screen_offset || 0);
  515. if (clearOff > (state.clearAnchor || 0)) {
  516. state.text = '';
  517. state.clearAnchor = clearOff;
  518. }
  519. if (chunk.text) {
  520. state.text = (chunk.jumped_to_tail ? chunk.text : state.text + chunk.text).slice(-48000);
  521. }
  522. const nextOff = Number(chunk.next_offset ?? state.offset);
  523. if (nextOff > state.offset || chunk.jumped_to_tail) state.offset = nextOff;
  524. renderLog();
  525. } catch (_) {
  526. } finally {
  527. uartPumpActive = false;
  528. }
  529. }
  530. async function startLiveTailLoop() {
  531. while (true) {
  532. if (connected && diag().session_id && !uartPumpActive) {
  533. await pumpCleanUart(1000);
  534. await new Promise(r => setTimeout(r, 40));
  535. } else {
  536. await new Promise(r => setTimeout(r, 350));
  537. }
  538. }
  539. }
  540. async function pollDiagnostic() {
  541. const selectedStation = stationId, revision = selectionRevision;
  542. try {
  543. const snapshot = await callApi('GetDiagnostic', {station_id:selectedStation});
  544. if (selectedStation !== stationId || revision !== selectionRevision) return;
  545. diagnostics.set(selectedStation, snapshot); diagnosticError = '';
  546. if (snapshot.session_id && !uartPumpActive) {
  547. await pumpCleanUart(0);
  548. }
  549. } catch (error) {
  550. if (selectedStation === stationId) diagnosticError = `诊断状态读取失败:${error.message}`;
  551. }
  552. renderDetail(); renderLog();
  553. }
  554. async function selectStation(next, byUser = true) {
  555. if (byUser) stationUserChosen = true;
  556. stationId = next; diagnosticError = ''; selectionRevision++;
  557. $('bmc-query-output').textContent = '点击查询显示 BMC 返回结果。'; $('bmc-query-time').textContent = '';
  558. renderCards(); renderDetail(); renderLog();
  559. await poll();
  560. }
  561. async function poll() {
  562. if (polling) {
  563. repollPending = true;
  564. return;
  565. }
  566. polling = true;
  567. try {
  568. const needSysInfo = !sysInfoCache || (Date.now() - sysInfoFetchedAt >= 30000);
  569. const [info, list] = await Promise.all([
  570. needSysInfo ? callApi('GetSystemInfo') : Promise.resolve(sysInfoCache),
  571. callApi('ListStations'),
  572. ]);
  573. if (needSysInfo && info) {
  574. sysInfoCache = info;
  575. sysInfoFetchedAt = Date.now();
  576. }
  577. if (!connected) status('已连接后端;选择工位操作。');
  578. connected = true;
  579. $('refresh-indicator').classList.remove('offline');
  580. $('sys-version').textContent = info.version || '未知';
  581. $('sys-commit').textContent = info.commit ? info.commit.slice(0, 7) : '未知';
  582. $('sys-mode').textContent = info.mode === 'hardware' ? '硬件实机' : (info.mode || '未知');
  583. $('sys-heartbeat').textContent = stamp();
  584. $('refresh-indicator').textContent = 'WebSocket 已连接';
  585. stations = list.stations || [];
  586. if (!current() && stations.length) stationId = stations[0].station_id;
  587. if (!stationUserChosen && stations.length) {
  588. const cur = current();
  589. const curOnline = !!(cur && (cur.console_online || cur.bmc_state === 'online'));
  590. if (!curOnline) {
  591. const live = stations.find(s => s.console_online || s.bmc_state === 'online');
  592. if (live) stationId = live.station_id;
  593. }
  594. }
  595. renderCards(); renderDetail();
  596. await Promise.all([pollQueue(), pollDeviceEvents(), pollAuditLogs(), pollDiagnostic(), window.stlFirmware.refresh()]);
  597. renderDetail();
  598. } catch (error) {
  599. connected = false;
  600. sysInfoFetchedAt = 0;
  601. $('refresh-indicator').textContent = '连接失败 · 显示上次数据';
  602. $('refresh-indicator').classList.add('offline');
  603. status(`后端连接失败:${error.message}`, true);
  604. renderDetail();
  605. } finally {
  606. polling = false;
  607. if (repollPending) {
  608. repollPending = false;
  609. setTimeout(() => void poll(), 40);
  610. }
  611. }
  612. }
  613. async function sendBytes(bytes, description = '发送控制台') {
  614. const context = consoleContext();
  615. if (!context.writable) throw new Error('当前控制台不可写:请先连接 BIOS 串口');
  616. const data = encode(new TextEncoder().encode(bytes));
  617. await command('WriteDiagnosticSol', {station_id:stationId, session_id:context.session_id, data}, description);
  618. }
  619. async function sendSol(empty = false) {
  620. const text = $('sol-input-cmd').value;
  621. if (!empty && !text) throw new Error('请输入命令;如需空回车请使用右侧按钮');
  622. await sendBytes((empty ? '' : text) + (empty || $('chk-append-enter').checked ? '\r' : ''));
  623. if (!empty) $('sol-input-cmd').value = '';
  624. }
  625. bind('btn-send-sol', () => sendSol());
  626. bind('btn-send-enter', () => sendSol(true));
  627. $('sol-input-cmd').onkeydown = event => {
  628. if (event.key === 'Enter' && !event.isComposing) {
  629. event.preventDefault();
  630. $($('sol-input-cmd').value === '' ? 'btn-send-enter' : 'btn-send-sol').click();
  631. }
  632. };
  633. 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~'};
  634. document.querySelectorAll('[data-sol-key]').forEach(button => {
  635. button.onclick = async () => {
  636. if (button.dataset.busy === '1') return;
  637. button.dataset.busy = '1'; button.disabled = true;
  638. try { await sendBytes(keys[button.dataset.solKey], `发送 ${button.textContent}`); } catch (e) { status(e.message, true); }
  639. finally { button.dataset.busy = ''; renderDetail(); await poll(); }
  640. };
  641. });
  642. $('btn-clear-sol').onclick = async () => {
  643. const log = visibleLog();
  644. if (log) {
  645. log.text = '';
  646. $('sol-terminal').dataset.renderedOffset = '';
  647. }
  648. renderLog();
  649. if (connected) {
  650. try {
  651. const res = await command('ClearTerminalView', {station_id: stationId}, '锚定清空控制台窗口');
  652. const cleanOff = Number(res?.result?.clean_offset || 0);
  653. if (log && cleanOff > 0) {
  654. log.text = '';
  655. log.offset = cleanOff;
  656. log.clearAnchor = cleanOff;
  657. $('sol-terminal').dataset.renderedOffset = '';
  658. renderLog();
  659. }
  660. } catch (e) {
  661. status(`清空锚点同步失败:${e.message}`, true);
  662. }
  663. }
  664. };
  665. bind('btn-refresh-station', async () => { await poll(); status('已刷新工位状态。'); });
  666. bind('btn-fan-refresh', async () => { await refreshFanMode(stationId, false); });
  667. $('chk-fan-low-speed').onchange = async () => {
  668. const chk = $('chk-fan-low-speed'), wantLowSpeed = chk.checked;
  669. chk.dataset.busy = '1'; chk.disabled = true;
  670. try {
  671. const q = wantLowSpeed ? 'fan_low_speed_on' : 'fan_low_speed_off';
  672. const labelText = wantLowSpeed ? '开启风扇降低转速 (30%/1%)' : '关闭风扇降低转速并恢复服务器默认温控';
  673. await command('QueryBmc', {station_id: stationId, query: q}, labelText);
  674. } catch (error) {
  675. chk.checked = !wantLowSpeed;
  676. status(error.message, true);
  677. } finally {
  678. chk.dataset.busy = '';
  679. renderFanControl(current());
  680. await poll();
  681. }
  682. };
  683. bind('btn-bmc-warm-reset', async () => {
  684. await command('QueryBmc', {station_id: stationId, query: 'bmc_warm_reset'}, 'BMC 热重启 (恢复默认温控)');
  685. });
  686. bind('btn-query-bmc', async () => {
  687. const selectedStation = stationId, query = $('bmc-query-kind').value;
  688. $('bmc-query-output').textContent = '查询已提交,等待后端返回…';
  689. $('bmc-query-time').textContent = '';
  690. try {
  691. await command('QueryBmc', {station_id:selectedStation, query}, '读取 BMC 信息');
  692. } catch (error) {
  693. if (stationId === selectedStation) $('bmc-query-output').textContent = `查询失败:${error.message}`;
  694. throw error;
  695. }
  696. });
  697. for (const [button, actionName, description] of [['btn-diag-open','open','连接 BIOS 控制台'],['btn-diag-close','close','断开 BIOS 控制台'],['btn-diag-reconnect','reconnect','重连 BIOS 控制台']]) {
  698. bind(button, async () => {
  699. await command('SetDiagnosticSol', {station_id:stationId, action:actionName}, description);
  700. });
  701. }
  702. for (const [suffix, actionName, description] of [['on','host_on','主板开机'],['off','host_off','主板关机'],['reset','host_reset','主板复位'],['cycle','host_cycle','主板关开循环']]) {
  703. bind(`btn-host-${suffix}`, async () => {
  704. await command('StationPower', {station_id:stationId, action:actionName}, description);
  705. });
  706. }
  707. bind('btn-refresh-commands', pollQueue);
  708. bind('btn-refresh-device-events', pollDeviceEvents);
  709. bind('btn-refresh-audits', pollAuditLogs);
  710. if ($('btn-web-logout')) {
  711. $('btn-web-logout').onclick = async () => {
  712. try {
  713. await fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' });
  714. } finally {
  715. window.location.reload();
  716. }
  717. };
  718. }
  719. if ($('audit-station-filter')) $('audit-station-filter').onchange = pollAuditLogs;
  720. if ($('audit-category-filter')) $('audit-category-filter').onchange = pollAuditLogs;
  721. $('command-station-filter').onchange = () => { queueItems = []; renderQueue(); pollQueue(); };
  722. $('command-state-filter').onchange = renderQueue;
  723. $('device-event-station-filter').onchange = () => { renderDeviceEvents(); pollDeviceEvents(); };
  724. $('device-event-level-filter').onchange = renderDeviceEvents;
  725. function saveFile(name, data, type = 'application/octet-stream') {
  726. const url = URL.createObjectURL(new Blob([data], {type}));
  727. const anchor = document.createElement('a'); anchor.href = url; anchor.download = name; anchor.click();
  728. setTimeout(() => URL.revokeObjectURL(url), 10000);
  729. }
  730. async function readFile(method, request) {
  731. const chunks = []; let offset = 0;
  732. while (true) {
  733. const part = await callApi(method, {...request, offset, max_bytes: 262144});
  734. chunks.push(decode(part.data));
  735. const next = Number(part.next_offset);
  736. if (part.eof) break;
  737. if (!(next > Number(offset))) throw new Error('下载未推进,请重试');
  738. offset = next;
  739. }
  740. return new Blob(chunks);
  741. }
  742. bind('btn-download-sol', async () => {
  743. const context = consoleContext();
  744. saveFile(`${context.session_id || stationId}-sol.bin`, await readFile('ReadDiagnosticSol', {station_id:stationId, session_id:context.session_id}));
  745. status('原始控制台日志已下载');
  746. });
  747. const services = {
  748. callApi, command, bind, status, time, formatElapsed, terminalText,
  749. useLiveConsole: () => { renderDetail(); },
  750. stationId: () => stationId,
  751. station: current,
  752. diagnostic: diag,
  753. consoleContext,
  754. connected: () => connected,
  755. };
  756. window.stlFirmware.init(services);
  757. window.stlBootPlan.init(services);
  758. window.stlAmt.init(services);
  759. window.stlDimms.init(services);
  760. window.stlStages.init(services);
  761. window.addEventListener('stl:station-select', event => selectStation(event.detail.stationId));
  762. window.addEventListener('stl:transport-state', event => {
  763. const transport = event.detail, ready = transport.state === 'open';
  764. const stateLabels = {idle:'等待连接',connecting:'连接中',open:'已连接',disconnected:'已断开 · 重连中',closed:'已断开'};
  765. $('transport-state').textContent = 'WebSocket · ' + (stateLabels[transport.state] || transport.state);
  766. $('transport-state').dataset.state = transport.state;
  767. $('transport-state').classList.toggle('connected', ready);
  768. $('transport-state').classList.toggle('error', ['disconnected','closed'].includes(transport.state));
  769. if (ready) {
  770. if (transport.generation > 1) {
  771. sysInfoFetchedAt = 0;
  772. poll();
  773. }
  774. } else {
  775. connected = false;
  776. $('refresh-indicator').textContent = '连接未就绪 · 显示上次数据';
  777. $('refresh-indicator').classList.add('offline');
  778. renderDetail();
  779. }
  780. });
  781. window.addEventListener('stl:server-event', event => {
  782. const ev = event.detail?.event;
  783. if (ev === 'task_complete') {
  784. if (dirtyPollTimer) { clearTimeout(dirtyPollTimer); dirtyPollTimer = null; }
  785. void poll();
  786. } else if (ev === 'station_dirty') {
  787. if (!dirtyPollTimer) {
  788. dirtyPollTimer = setTimeout(() => {
  789. dirtyPollTimer = null;
  790. void poll();
  791. }, 500);
  792. }
  793. }
  794. });
  795. window.addEventListener('load', async () => {
  796. renderDetail();
  797. await poll();
  798. setInterval(poll, 10000);
  799. void startLiveTailLoop();
  800. });
  801. })();