Przeglądaj źródła

Release 0.8.1.22: strip backend thermal_mcu, single 118.efi, ICT unsupported skip, disconnect reset, 108_VD012 amt 1 & Qt-Clean delivery

XJKJ STL 2 tygodni temu
rodzic
commit
06526ad51b
46 zmienionych plików z 5498 dodań i 8290 usunięć
  1. 2 2
      Dockerfile
  2. 3 3
      README.md
  3. 1 1
      VERSION
  4. 1 1
      contracts/firmware-vd012.json
  5. 3 2
      docker-compose.yml
  6. BIN
      docs/6400高温罩快速使用说明书.docx
  7. 0 1696
      docs/MCU_24CH_THERMAL_PROTOCOL_V1.1.md
  8. 48 0
      docs/QT_CLIENT_API_ZH.md
  9. 49 32
      docs/WEBSOCKET_API_ZH.md
  10. 2 2
      native/stl_accel/build.sh
  11. 1384 165
      native/stl_accel/c_bridge.c
  12. 214 42
      native/stl_accel/parser_re2c.re
  13. 5 5
      native/stl_accel/scan_asm.S
  14. 247 81
      native/stl_accel/src/actors.rs
  15. 122 192
      native/stl_accel/src/api.rs
  16. 165 35
      native/stl_accel/src/commands.rs
  17. 232 204
      native/stl_accel/src/devices.rs
  18. 187 9
      native/stl_accel/src/lib.rs
  19. 840 275
      native/stl_accel/src/main.rs
  20. 606 210
      native/stl_accel/src/pxe.rs
  21. 709 55
      native/stl_accel/src/results.rs
  22. 15 13
      native/stl_accel/src/storage.rs
  23. 0 3730
      native/stl_accel/src/thermal_mcu.rs
  24. 192 71
      native/stl_accel/src/workflow.rs
  25. 82 0
      native/stl_accel/stl_accel.h
  26. 67 15
      src/backendlink.cpp
  27. 3 1
      src/backendlink.h
  28. 1 1
      src/createtaskdialog.cpp
  29. 27 2
      src/detailview.cpp
  30. 1 1
      src/main.cpp
  31. 43 37
      src/mainwindow.cpp
  32. 4 4
      src/mainwindow.h
  33. 3 3
      src/overviewview.cpp
  34. 9 14
      src/powerbutton.cpp
  35. 3 4
      src/powerbutton.h
  36. 85 46
      src/stationdata.cpp
  37. 13 11
      src/stationdata.h
  38. 3 3
      src/uiformat.h
  39. 35 12
      web/amt-controls.js
  40. 49 21
      web/app.js
  41. 5 4
      web/boot-plan-controls.js
  42. 12 31
      web/firmware-controls.js
  43. 19 279
      web/index.html
  44. 3 2
      web/stage-progress.js
  45. 4 3
      web/style.css
  46. 0 970
      web/thermal-console.js

+ 2 - 2
Dockerfile

@@ -4,7 +4,7 @@ ENV DEBIAN_FRONTEND=noninteractive
 WORKDIR /app
 
 RUN apt-get update && \
-    apt-get install -y --no-install-recommends ipmitool freeipmi-tools openssh-client sshpass ca-certificates && \
+    apt-get install -y --no-install-recommends libfreeipmi17 libipmiconsole2 libssh-4 ca-certificates && \
     rm -rf /var/lib/apt/lists/*
 
 COPY VERSION README.md ./
@@ -14,7 +14,7 @@ COPY config/ ./config/
 COPY build/native/stl_native_server /usr/local/bin/stl_native_server
 
 ARG STL_BUILD_COMMIT=vd012-native
-ARG STL_VERSION=0.8.1.21
+ARG STL_VERSION=0.8.1.22
 ENV STL_BUILD_COMMIT=${STL_BUILD_COMMIT} \
     STL_VERSION=${STL_VERSION}
 

+ 3 - 3
README.md

@@ -1,12 +1,12 @@
 # XJKJ-STL 高温内存测试工作台
 
-当前版本:`0.8.1.21`(分支:`dev`)。
+当前版本:`0.8.1.22`(分支:`dev`)。
 
 本仓库为 `XJKJ-STL` DDR5 内存高温测试与 BIOS 串口诊断工作台全栈源码(含原生高性能控制后端 `stl_native_server`、现代 Web 多页前端 `web/`、以及 Windows/Linux Qt 客户端 `src/`),仅提供 Web 前端完整 WebSocket(`/ws`)及面向 Qt 的精简纯净 WebSocket 接口(`/ws?view=qt-clean`),并内建非阻塞 UDP `:69` TFTP PXE 文件服务与 MemTest86 HTML 报告解析归档(已移除旧版 gRPC 服务)。
 
 ## 目录结构
 
-- `contracts/firmware-vd012.json`:双机固件参数契约(224 项 ICT 参数、`showmain` 0~101 步骤表、`showtrain` 0~84 步骤表、30 项 AMT 参数及默认测试计划定义,兼容 `.166` `107_VD012` 与 `.165` `CxmtDdrTest`)。
+- `contracts/firmware-vd012.json`:双机固件参数契约(224 项 ICT 参数、`showmain` 0~101 步骤表、`showtrain` 0~84 步骤表、30 项 AMT 参数及默认测试计划定义,兼容 `108_VD012` 与 `101_VD013`)。
 - `native/stl_accel/`:纯 SSE2 基线 + CPUID 动态分派(`SSE2` / `SSE4.2+POPCNT` / `AVX2+BMI1/2`)原生后端与构建脚本 `build.sh`:
   - `scan_asm.S`:手写向量化 Base64 编码及单遍零分配 UEFI 光标重定位/ANSI 控制码清洗、切行与标签预分类热核;
   - `parser_re2c.re` / `parser_re2c.c`:确定性 `re2c` DFA 固件阶段与报错状态机;
@@ -14,7 +14,7 @@
   - `c_bridge.c`:CPUID/XGETBV 分派、64 位单调递增环形缓冲大页/保护页封装、持久非阻塞 IPMI 连接池、POSIX PTY/物理串口 `/dev/ttyUSB0`/TCP 透传/SOL 桥接、`writev` 帧合并及可选 Gen7.5~Gen9.5 OpenCL 批处理;
   - `src/`:按工位无锁分片 Actor 服务模块(`main.rs`、`actors.rs`、`api.rs`、`commands.rs`、`workflow.rs`、`firmware.rs`、`results.rs`、`devices.rs`、`pxe.rs`、`storage.rs`、`config.rs`、`json.rs`、`lib.rs`)。
 - `web/`:静态多页 Web 前端(ICT 显示统一、全量 224 项 ICT + 30 项 AMT、7 阶段独立完成徽章、双队列编排、阻塞伪推送清洗终端)。
-- `src/` + `DDR5_SLT_Monitor.pro`:Qt 客户端源码(`0.8.1.21`),对接 `/ws?view=qt-clean`。
+- `src/` + `DDR5_SLT_Monitor.pro`:Qt 客户端源码(`0.8.1.22`),对接 `/ws?view=qt-clean`。
 - `docs/`:`QT_CLIENT_API_ZH.md`(Qt 纯净接口规范)与 `WEBSOCKET_API_ZH.md`(完整 WebSocket 接口手册)。
 - `config/`:`backend.example.json` 与 `dimms.example.json` 配置示例(现场 `config/station0-live.json` 原位保留并由 `.gitignore` 忽略)。
 - `deploy/`:`systemd` 服务文件与环境变量示例。

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.8.1.21
+0.8.1.22

Plik diff jest za duży
+ 1 - 1
contracts/firmware-vd012.json


+ 3 - 2
docker-compose.yml

@@ -3,9 +3,9 @@ services:
     build:
       context: .
       args:
-        STL_VERSION: ${STL_VERSION:-0.8.1.21}
+        STL_VERSION: ${STL_VERSION:-0.8.1.22}
         STL_BUILD_COMMIT: ${STL_BUILD_COMMIT:-vd012-native}
-    image: xjkj-stl:0.8.1.21
+    image: xjkj-stl:0.8.1.22
     container_name: xjkj-stl-backend
     restart: unless-stopped
     stop_grace_period: 30s
@@ -24,6 +24,7 @@ services:
     environment:
       STL_BMC_S1_PASSWORD: ${STL_BMC_S1_PASSWORD:-Admin123@pl}
       STL_BMC_S2_PASSWORD: ${STL_BMC_S2_PASSWORD:-Admin123@pl}
+      STL_BMC_S3_PASSWORD: ${STL_BMC_S3_PASSWORD:-Admin123@pl}
     command:
       - /usr/local/bin/stl_native_server
       - --config

BIN
docs/6400高温罩快速使用说明书.docx


Plik diff jest za duży
+ 0 - 1696
docs/MCU_24CH_THERMAL_PROTOCOL_V1.1.md


+ 48 - 0
docs/QT_CLIENT_API_ZH.md

@@ -648,3 +648,51 @@ void BackendLink::applyBiosUart(const QJsonObject &result)
    - 严禁将服务器 BMC 侧 DIMM 温度混入工位高温罩腔体温度;无本地高温罩串口接入时 `temperature.current_c` 严格返回 `null`。
 4. **单文件 Windows Qt 客户端运行期升级**:
    - `DDR5_SLT_Monitor.exe`(`0.8.1.21`,纯 `x86-64 SSE2` 基线校验通过)首次启动自解压释放至 `%LOCALAPPDATA%\XJKJ-STL\runtime-0.8.1.21`,继续保持 `STL_QT_CONFIG_DIR` 外置同级目录读写。
+
+### 11.1 补充修订(运行中重测按钮、1~254°C 曲线缩放、PXE/XML 报告闭环与 SSE2 基线对齐)
+
+1. **客户端控制交互与温控曲线自适应**:
+   - Qt 主界面测试进行中主圆钮文案由【执行中】改为绿色【重新开始】(`PowerButton` 取消 `hitButton` 锁死),支持运行过程中随时点击重新开始发起新一轮测试并重置状态,不再锁定防误触。
+   - 「创建任务」页及后端目标温度 `target_temp` 范围放宽至 `1~254°C`(`0xFF` 为串口协议保留无效值,默认仍为 `70°C`);设备详情页【温控曲线】默认保持 `20~90°C` 观感,若有效采样温度超出该区间则按 `5°C` 步长动态扩展纵轴范围(最高 `260°C`),避免曲线裁剪。
+   - `/ws` 完整版与 `/ws?view=qt-clean` 均保持稳定事件推送:`/ws?view=qt-clean` 推送 `state`、`bios_uart` 与 `task_complete`;`/ws` 另推送 `station_dirty`(含 `dirty_bitmap`、`unix_ms`)触发前端增量刷新;`GetTaskStatus` 在未启动任何轮次时返回 `task_status: "not_started"`。
+2. **串口切行、Stage-1 PXE 完成判据与 HTML/XML 双报告解析**:
+   - Qt 与后端串口行切割同时兼容 `\r`、`\n`、`\r\n`(并自动吞掉跨 TCP 分包边界拆开的配对 `\n`),避免双路 AMT 菜单仅回显 `\r` 导致的粘行。
+   - Stage-1 PXE 引导日志(`NBP file downloaded successfully` / `LoadImage Status = Success` / `StartImage Status = Success`)同步作为独立 PXE 分支标志置位 `uefi_complete = true`。
+   - MT 结果判定与远端 `192.168.2.63` 拉取同时支持 `MemTest86-Report-*.html`(含 UTF-16LE/BE 解码及 `<style>` 剥离)与 `Clients/*.TestResult.xml`(解析 `Result` / `INCOMPLETE PASS`、`NumEccCorr` / `NumEccUncorr`、`<DimmErr>` 与 `<LogEntry>` 通道坐标),写入 `stage_errors.mt` 与对应 DIMM `fail` 状态。
+3. **零加压安全时序拉偏与运行期 CPUID 分派基线**:
+   - `ApplyErrorPreset` 默认 `preset_id` 为 `"safe_trcd_trp_pull"`(保留兼容别名 `"safe_timing_pull_light"` → `"safe_trcd_trp_pull"`、`"safe_refresh_pull"` → `"safe_trfc_pull"`),按参数 `id` 幂等覆盖 `uip_overrides`(保留既有 `rmt` 等设置)。
+   - 服务端、C/汇编内核与 Windows Qt 客户端统一采用纯 `x86-64 SSE2` 安全编译基线,运行期按 `CPUID` 动态分派 `SSE2` / `SSE4.2+POPCNT` / `AVX2+BMI1/2`,避免无 AVX/POPCNT 处理器(如部分 Intel 2~8 代赛扬/奔腾)触发 `SIGILL`。
+
+### 11.2 权威后端计时同步规范(上电起表、阶段不重置、全部完成冻结与队列连续计时)
+
+1. **后端单一权威计时字段**:
+   - `state` 推送、`GetState`、`GetTaskStatus`、`StartTest` 与 `task_complete` 推送中,每个工位对象均由后端按实时钟动态填充:
+     - `started_unix_ms`(字符串毫秒时间戳,未开始或空闲为 `"0"`);
+     - `ended_unix_ms`(字符串毫秒时间戳,空闲或测试进行中为 `"0"`,全部测试到达终态后冻结为结束时间戳);
+     - `elapsed_ms`(非负整数毫秒:进行中等于当前时刻与 `started_unix_ms` 差值,终态后恒等于 `ended_unix_ms - started_unix_ms`);
+     - `server_unix_ms`(整数毫秒:服务端当前参考时间)。
+2. **禁止过阶段重置与被动串口误起表**:
+   - 仅当测试命令明确触发上电/重启时记录 `started_unix_ms`,此后跨 `ICT1`、`Training`、`RMT`、`AMT`、`ICT2`、`UEFI`、`MT` 全部阶段及主机内热复位期间 `started_unix_ms` 严格保持不变;仅接入串口旁路观察日志(未发启动命令)时 `started_unix_ms = "0"`、`ended_unix_ms = "0"`、`elapsed_ms = 0`。
+   - 只有所有测试完成、阶段 FAIL 阻塞(`awaiting_dimm_replacement = true`)、手动停机(`SkipMt` / `stop` / 运行中 `StationPower("host_off")`)时才冻结 `ended_unix_ms`。
+3. **多任务队列连续计时(`continue_timer`)与 Qt 前端消费规则**:
+   - 后端托管批次队列(`SubmitTaskBatch`)在多组 Profile 与多次重复之间自动保持同一 `started_unix_ms`,直至全批完成后冻结 `ended_unix_ms`。
+   - Qt 前端多任务串行从第 2 轮起调用 `StartTest(..., continue_timer: true)`(`SubmitTaskBatch` 同理),通知后端沿用本批 `started_unix_ms` 连续累计总耗时。
+   - Qt(`StationStore::applyBackendTiming` / `runtimeMs`)与 Web 前端直接消费后端返回的 `started_unix_ms`、`ended_unix_ms` 与 `elapsed_ms`(Qt 仅在收到 `ended_unix_ms == "0"` 的 1s 心跳间隙内做有上限平滑递增并立即由下一帧后端 `elapsed_ms` 对齐),绝不依据本地墙钟或 `boot_id` / `phase` 切换私自清零重启。
+
+
+## 12. 0.8.1.22 变更与补充规范(STM32 温控剥离、唯一 `118.efi`、ICT 不支持命令跳过、失联实时清空及双固件 `108_VD012` / `101_VD013` 对齐)
+
+本章节在完整保留第 0~8 章原始基础接口定义(第 1~507 行一字不改)以及第 9~11 章规范的前提下,记录 `0.8.1.22` 版本的核心架构收口与实机兼容修正:
+
+1. **STM32 高温罩温控职责边界彻底隔离**:
+   - 高温罩 STM32 温控完全由 Qt Clean 上位机通过本地串口直接控制与采集,Rust 后端不再内嵌 `thermal_mcu` 控制线程,且不再向工位写入任何虚拟或服务侧腔体温度(`temperature.current_c` 与 `temperature.target_c` 保持 `null`、`state: "unconfigured"`)。
+   - Rust 后端仅负责解析服务器 BMC SDR 24 通道 DIMM 温度传感器并准确映射至 `channels[i].temperature_c`;当 BMC 离线、主机关机或某槽位 SDR 不再上报有效读数时,立即清空对应通道过期温度(返回 `null`)。
+2. **唯一 `118.efi` 标准化与旧变体清理**:
+   - 彻底废除 `118_orig.efi`、`118_serial.efi`、`118_uip_stage1.efi`、`118_mod.efi`、`118.efi.orig` 等多版本切换与覆盖逻辑,PXE TFTP 与 UEFI Shell 均固定使用源码编译的唯一 `118.efi`,配置下发仅同步渲染全部候选 `mt86.cfg`。
+3. **ICT 阶段不支持命令容错收集与继续执行**:
+   - ICT Stage 1 / Stage 2 下发命令若收到 `Invalid or not support command, please check it`(如 `ap enable`)并正常返回 `Please input your command:` 提示符,后端将其收集记入 `unsupported_commands` 与归档 `summary.json`,自动跳过该命令并继续执行后续配置命令及 `exit\r`,严禁直接判整轮 FAIL。
+4. **测试机失联 / 离线 / 空闲工位状态实时清空重置**:
+   - 当测试机控制台与 BMC 均处于失联/未连接状态时,后端自动清空 `channels[0..23]` 的在位 (`present=false`)、PASS/FAIL (`state="idle"`) 与温度 (`temperature_c=null`),并将 `boot_id`、`phase`、`run_state`、`task_status` (`"not_started"`)、计时 (`started_unix_ms="0"`、`elapsed_ms=0`) 与 `stage_errors` 重置为干净初始态,前端无需额外推测或缓存清理。
+5. **`108_VD012` / `101_VD013` 双固件日志与运行期对齐**:
+   - 对齐 `108_VD012` 的 `[HS_BIOS]Version:`、`[HS_BIOS][Training]` 前缀、`MRC_STATUS_RESET_REQUIRED` 内部热复位,并排除早期 KTI/SNC 拓扑检查中的 `Pipe Sync SBSP Status -- FAILED` 误报,保障双路服务器(如 `192.168.2.168`)稳定通过 Training/RMT/AMT/ICT2/UEFI/MT 全流程。
+   - Windows Qt 客户端升级至 `0.8.1.22`(纯 `x86-64 SSE2` 基线单文件自解压 `DDR5_SLT_Monitor.exe`,首次释放目录 `%LOCALAPPDATA%\XJKJ-STL\runtime-0.8.1.22`)。

Plik diff jest za duży
+ 49 - 32
docs/WEBSOCKET_API_ZH.md


+ 2 - 2
native/stl_accel/build.sh

@@ -20,7 +20,7 @@ ar rcs "${BUILD_DIR}/libstl_kernels.a" \
     "${BUILD_DIR}/c_bridge.o"
 
 rustc -O -C target-cpu=x86-64 -C lto=thin -C codegen-units=1 -C strip=debuginfo src/main.rs \
-    -L "${BUILD_DIR}" -l static=stl_kernels -l util -l dl -o "${BUILD_DIR}/stl_native_server"
+    -L "${BUILD_DIR}" -l static=stl_kernels -l freeipmi -l ipmiconsole -l ssh -l util -l dl -l pthread -o "${BUILD_DIR}/stl_native_server"
 rustc --test -O -C target-cpu=x86-64 src/main.rs \
-    -L "${BUILD_DIR}" -l static=stl_kernels -l util -l dl -o "${BUILD_DIR}/stl_native_tests"
+    -L "${BUILD_DIR}" -l static=stl_kernels -l freeipmi -l ipmiconsole -l ssh -l util -l dl -l pthread -o "${BUILD_DIR}/stl_native_tests"
 (cd "${ROOT_DIR}" && "${BUILD_DIR}/stl_native_tests")

Plik diff jest za duży
+ 1384 - 165
native/stl_accel/c_bridge.c


+ 214 - 42
native/stl_accel/parser_re2c.re

@@ -80,7 +80,8 @@ static void extract_leading_bracket_cpu(const uint8_t *s, const uint8_t *end, St
 }
 
 /* Extract N<cpu>.C<ch>[.D<dimm>][.SC<sub>][.R<rank>] topology token & RMT margins */
-static int extract_ncd_token(const uint8_t *s, const uint8_t *end, StlRe2cEvent *ev) {
+static int extract_ncd_token_cols(const uint8_t *s, const uint8_t *end, StlRe2cEvent *ev, int *out_cols) {
+    if (out_cols) *out_cols = 0;
     for (const uint8_t *p = s; p + 5 <= end; p++) {
         if ((p[0] == 'N' || p[0] == 'n') &&
             (p[1] >= '0' && p[1] <= '3') && p[2] == '.' &&
@@ -109,6 +110,9 @@ static int extract_ncd_token(const uint8_t *s, const uint8_t *end, StlRe2cEvent
                     } else if (q + 3 <= end && (q[1] == 'L' || q[1] == 'l') && q[2] >= '0' && q[2] <= '9') {
                         q += 3;
                         while (q < end && *q >= '0' && *q <= '9') q++;
+                    } else if (q + 4 <= end && (q[1] == ' ' || q[1] == '\t') && (q[2] == 'A' || q[2] == 'a') && q[3] >= '0' && q[3] <= '9') {
+                        q += 4;
+                        while (q < end && *q >= '0' && *q <= '9') q++;
                     } else if (q + 3 <= end && (q[1] == 'B' || q[1] == 'b') && q[2] >= '0' && q[2] <= '9') {
                         int bk = 0;
                         const uint8_t *bp = q + 2;
@@ -124,6 +128,7 @@ static int extract_ncd_token(const uint8_t *s, const uint8_t *end, StlRe2cEvent
                         break;
                     }
                 }
+                while (q < end && (*q == ' ' || *q == '\t')) q++;
                 if (q < end && *q == ':') {
                     q++;
                     int32_t vals[4] = {0, 0, 0, 0};
@@ -143,6 +148,7 @@ static int extract_ncd_token(const uint8_t *s, const uint8_t *end, StlRe2cEvent
                             }
                         }
                     }
+                    if (out_cols) *out_cols = got;
                     if (got >= 4) {
                         ev->val0 = vals[0];
                         ev->val1 = vals[1];
@@ -157,6 +163,10 @@ static int extract_ncd_token(const uint8_t *s, const uint8_t *end, StlRe2cEvent
     return 0;
 }
 
+static int extract_ncd_token(const uint8_t *s, const uint8_t *end, StlRe2cEvent *ev) {
+    return extract_ncd_token_cols(s, end, ev, NULL);
+}
+
 static int match_ci_kw(const uint8_t *p, const uint8_t *end, const char *kw, const uint8_t **after) {
     size_t klen = strlen(kw);
     if ((size_t)(end - p) < klen) return 0;
@@ -185,8 +195,26 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
     extract_leading_bracket_cpu(s, end, ev);
     extract_ncd_token(s, end, ev);
 
-    /* Check MemTest86 "(P0,C3,S0,R0)" or "Channel/Slot: N0-3-0" or "(Chan,Slot,Rank,Bank,Row,Col): (3,0,0,12,...)" */
+    /* Check MemTest86 "CPU<0|1>_DIMM_<A..L>", "(P0,C3,S0,R0)", "Channel/Slot: N0-3-0", or "(Chan,Slot,Rank,Bank,Row,Col): (3,0,0,12,...)" */
     for (const uint8_t *p = s; p + 6 <= end; p++) {
+        if (p + 11 <= end &&
+            (p == s || (!((p[-1] >= 'a' && p[-1] <= 'z') || (p[-1] >= 'A' && p[-1] <= 'Z') ||
+                          (p[-1] >= '0' && p[-1] <= '9') || p[-1] == '_'))) &&
+            ascii_lower(p[0]) == 'c' && ascii_lower(p[1]) == 'p' && ascii_lower(p[2]) == 'u' &&
+            (p[3] == '0' || p[3] == '1') && p[4] == '_' &&
+            ascii_lower(p[5]) == 'd' && ascii_lower(p[6]) == 'i' && ascii_lower(p[7]) == 'm' && ascii_lower(p[8]) == 'm' &&
+            p[9] == '_') {
+            uint8_t ltr = p[10];
+            uint8_t ul = (ltr >= 'a' && ltr <= 'z') ? (uint8_t)(ltr - 32) : ltr;
+            int ok_after = (p + 11 == end) ||
+                (!((p[11] >= 'a' && p[11] <= 'z') || (p[11] >= 'A' && p[11] <= 'Z') ||
+                   (p[11] >= '0' && p[11] <= '9') || p[11] == '_'));
+            if (ok_after && ul >= 'A' && ul <= 'L') {
+                ev->cpu = (int8_t)(p[3] - '0');
+                ev->channel = (int8_t)(ul - 'A');
+                if (ev->dimm < 0) ev->dimm = 0;
+            }
+        }
         if ((p[0] == 'N' || p[0] == 'n') && (p[1] == '0' || p[1] == '1') &&
             p[2] == '-' && p[3] >= '0' && p[3] <= '9') {
             int32_t ch = -1, sl = -1;
@@ -216,20 +244,53 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
                 }
             }
         }
-        if (p + 25 <= end && memcmp(p, "(Chan,Slot,Rank,Bank,Row,", 25) == 0) {
-            const uint8_t *lp = memchr(p + 25, '(', (size_t)(end - (p + 25)));
-            if (lp) {
-                int32_t c_ch = -1, c_sl = -1, c_rk = -1, c_bk = -1;
-                const uint8_t *nx = lp + 1;
-                if (parse_i32_at(nx, end, &c_ch, &nx) && nx < end && *nx == ',' &&
-                    parse_i32_at(nx + 1, end, &c_sl, &nx) && nx < end && *nx == ',' &&
-                    parse_i32_at(nx + 1, end, &c_rk, &nx) && nx < end && *nx == ',' &&
-                    parse_i32_at(nx + 1, end, &c_bk, &nx)) {
-                    if (c_ch >= 0 && c_ch <= 11) ev->channel = (int8_t)c_ch;
-                    if (c_sl >= 0 && c_sl <= 1) ev->dimm = (int8_t)c_sl;
-                    if (c_rk >= 0 && c_rk <= 3) ev->rank = (int8_t)c_rk;
-                    if (c_bk >= 0 && c_bk < 32) ev->bank = (int8_t)c_bk;
-                    ev->subkind = 5; /* 2nd-line MT ECC coordinate continuation */
+        size_t tup_skip = 0;
+        if (p + 28 <= end && memcmp(p, "(Channel,Slot,Rank,Bank,Row,", 28) == 0) {
+            tup_skip = 28;
+        } else if (p + 25 <= end && memcmp(p, "(Chan,Slot,Rank,Bank,Row,", 25) == 0) {
+            tup_skip = 25;
+        } else if (p + 16 <= end && memcmp(p, "(Ch,Sl,Rk,Bk,Rw,", 16) == 0) {
+            tup_skip = 16;
+        }
+        if (tup_skip > 0) {
+            const uint8_t *rp = memchr(p + tup_skip, ')', (size_t)(end - (p + tup_skip)));
+            const uint8_t *nx = rp ? (rp + 1) : (p + tup_skip);
+            while (nx < end && (*nx == ':' || *nx == '=' || *nx == ' ' || *nx == '\t' || *nx == '(')) {
+                nx++;
+            }
+            int32_t c_ch = -1, c_sl = -1, c_rk = -1, c_bk = -1;
+            if (parse_i32_at(nx, end, &c_ch, &nx) && nx < end && *nx == ',' &&
+                parse_i32_at(nx + 1, end, &c_sl, &nx) && nx < end && *nx == ',' &&
+                parse_i32_at(nx + 1, end, &c_rk, &nx) && nx < end && *nx == ',' &&
+                parse_i32_at(nx + 1, end, &c_bk, &nx)) {
+                if (c_ch >= 12 && c_ch <= 23 && ev->cpu < 0) {
+                    ev->cpu = 1;
+                    ev->channel = (int8_t)(c_ch - 12);
+                } else if (c_ch >= 0 && c_ch <= 11) {
+                    ev->channel = (int8_t)c_ch;
+                }
+                if (c_sl >= 0 && c_sl <= 1) ev->dimm = (int8_t)c_sl;
+                if (c_rk >= 0 && c_rk <= 3) ev->rank = (int8_t)c_rk;
+                if (c_bk >= 0 && c_bk < 32) ev->bank = (int8_t)c_bk;
+            }
+        }
+        if ((p + 6 <= end && (p[0] == 'C' || p[0] == 'c') && (p[1] == 'h' || p[1] == 'H') &&
+             p[2] == '/' && (p[3] == 'S' || p[3] == 's') && (p[4] == 'l' || p[4] == 'L') && p[5] == ':')) {
+            const uint8_t *nx = p + 6;
+            while (nx < end && (*nx == ' ' || *nx == '\t')) nx++;
+            if (nx < end && *nx >= '0' && *nx <= '9') {
+                int32_t c_ch = -1, c_sl = -1;
+                if (parse_i32_at(nx, end, &c_ch, &nx) && c_ch >= 0 && c_ch <= 23) {
+                    if (c_ch >= 12 && ev->cpu < 0) {
+                        ev->cpu = 1;
+                        ev->channel = (int8_t)(c_ch - 12);
+                    } else if (c_ch <= 11) {
+                        ev->channel = (int8_t)c_ch;
+                    }
+                    if (nx < end && (*nx == '/' || *nx == '-' || *nx == ',') &&
+                        parse_i32_at(nx + 1, end, &c_sl, &nx) && c_sl >= 0 && c_sl <= 1) {
+                        ev->dimm = (int8_t)c_sl;
+                    }
                 }
             }
         }
@@ -255,7 +316,8 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
                 ev->cpu = (int8_t)v;
             }
         } else if (match_ci_kw(p, end, "channel", &after) || match_ci_kw(p, end, "ch", &after) ||
-                   match_ci_kw(p, end, "chan", &after)) {
+                   match_ci_kw(p, end, "chan", &after) ||
+                   (ev->channel < 0 && match_ci_kw(p, end, "chid", &after))) {
             if (parse_i32_at(after, end, &v, NULL) && v >= 0 && v <= 23) {
                 if (v >= 12 && ev->cpu < 0) {
                     ev->cpu = 1;
@@ -264,7 +326,8 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
                     ev->channel = (int8_t)v;
                 }
             }
-        } else if (match_ci_kw(p, end, "dimm", &after) || match_ci_kw(p, end, "slot", &after)) {
+        } else if (match_ci_kw(p, end, "dimm", &after) || match_ci_kw(p, end, "dimmslot", &after) ||
+                   match_ci_kw(p, end, "slot", &after) || match_ci_kw(p, end, "sl", &after)) {
             if (parse_i32_at(after, end, &v, NULL) && v >= 0 && v <= 23) {
                 if (v <= 1) {
                     ev->dimm = (int8_t)v;
@@ -274,7 +337,7 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
                     ev->dimm = 0;
                 }
             }
-        } else if (match_ci_kw(p, end, "rank", &after)) {
+        } else if (match_ci_kw(p, end, "rank", &after) || match_ci_kw(p, end, "dimmrank", &after)) {
             if (parse_i32_at(after, end, &v, NULL) && v >= 0 && v <= 3) {
                 ev->rank = (int8_t)v;
             }
@@ -284,7 +347,7 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
             }
         } else if (match_ci_kw(p, end, "bank", &after) || match_ci_kw(p, end, "ba", &after)) {
             if (parse_i32_at(after, end, &v, NULL)) {
-                if (ascii_lower(p[1]) == 'a' && v >= 0 && v <= 3) {
+                if ((after - p) == 2 && v >= 0 && v <= 3) {
                     ba = (int)v;
                 } else if (v >= 0 && v < 32) {
                     direct_bank = (int)v;
@@ -328,9 +391,9 @@ static void trim_ws(const uint8_t **ps, const uint8_t **pe) {
 */
 
 static uint32_t re2c_scan_token(const uint8_t *s, const uint8_t *end, StlRe2cEvent *ev) {
-    uint8_t buf[520];
+    uint8_t buf[1025];
     size_t n = (size_t)(end - s);
-    if (n > 512) n = 512;
+    if (n > 1024) n = 1024;
     memcpy(buf, s, n);
     buf[n] = 0;
 
@@ -397,9 +460,13 @@ scan_anywhere:
     while (YYCURSOR < lim) {
         const uint8_t *tok = YYCURSOR;
         /*!re2c
-            "[SYS_BIOS]Version:" {
+            "[" ("SYS_" | "HS_") "BIOS]Version:" {
+                if (tok[1] == 'H') ev->fw_family = 1;
                 return STL_LK_BIOS_BOOT;
             }
+            "[BIOS][Vref]" | "[CHIPID]" | "[SPD_MR]" | "[SPD_CRC]" {
+                return STL_LK_NONE;
+            }
             "Welcome to Hovsee" | "Hovsee inc. IMC Config Tool" {
                 ev->fw_family = 1;
                 return STL_LK_ICT_BANNER_HOVSEE;
@@ -443,6 +510,7 @@ scan_anywhere:
                 continue;
             }
             "[Hovsee]Exit UIP" | "[CxmtDdrTest]Exit UIP" |
+            "[Hovsee]Exit Uip ddr test" | "[CxmtDdrTest]Exit Uip ddr test" |
             "[Hovsee]Exit Hovsee UIP" | "[CxmtDdrTest]Exit CxmtDdrTest UIP" |
             "[Hovsee]Exit ICT ddr test" | "[CxmtDdrTest]Exit ICT ddr test" |
             "No command input or timeout, so go on training" |
@@ -466,14 +534,12 @@ scan_anywhere:
             "[HS_StartMemTrain]" | "[HD_StartMemTrain]" |
             "[Hovsee]Socket " [01] " RcdQcaTraining" {
                 if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'S') ev->fw_family = 1;
-                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'D') ev->fw_family = 2;
                 if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'o') ev->fw_family = 1;
                 return STL_LK_MRC_START;
             }
             "STOP_MRC_RUN" | "MRC Done" | "Memory Training Complete" |
             "[HS_EndMemTrain]" | "[HD_EndMemTrain]" {
                 if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'S') ev->fw_family = 1;
-                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'D') ev->fw_family = 2;
                 return STL_LK_MRC_DONE;
             }
             "0x4F : DXE IPL Start" | "0x60 : DXE Core Started" |
@@ -486,14 +552,22 @@ scan_anywhere:
                 ev->subkind = 3; /* AMT start */
                 return STL_LK_AMT_PROGRESS;
             }
-            "[BIOS][Training][ScktId:" WS [01] "]" {
+            "[" ("HS_" | "") "BIOS][Training][ScktId:" WS [01] "]" {
+                if (tok[1] == 'H') ev->fw_family = 1;
                 extract_coords_and_addr(s, end, ev);
-                /* Check if Rank Margin Tool or MemTest or FAILED */
+                int is_pipe_sync_sbsp = 0;
+                for (const uint8_t *p = YYCURSOR; p + 20 <= lim; p++) {
+                    if (memcmp(p, "Pipe Sync SBSP Status", 21) == 0) {
+                        is_pipe_sync_sbsp = 1;
+                        break;
+                    }
+                }
+                /* Check if Rank Margin Tool or MemTest or FAILED (excluding benign SNC/Pipe Sync SBSP Status reset notice) */
                 for (const uint8_t *p = YYCURSOR; p + 6 <= lim; p++) {
                     if (p + 16 <= lim && memcmp(p, "Rank Margin Tool", 16) == 0) {
                         return STL_LK_RMT_STOP;
                     }
-                    if (memcmp(p, "FAILED", 6) == 0) {
+                    if (!is_pipe_sync_sbsp && memcmp(p, "FAILED", 6) == 0) {
                         ev->subkind = 2;
                         return STL_LK_TRAINING_ERROR;
                     }
@@ -507,7 +581,6 @@ scan_anywhere:
             "START_RMT" | "Starting RMT test v" | "Rank Margin Tool -- Started" |
             "[HS_StartRmt]" | "[HD_StartRmt]" {
                 if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'S') ev->fw_family = 1;
-                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'D') ev->fw_family = 2;
                 extract_coords_and_addr(s, end, ev);
                 return STL_LK_RMT_START;
             }
@@ -521,7 +594,6 @@ scan_anywhere:
                     return STL_LK_RMT_STOP;
                 }
                 if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'D') {
-                    ev->fw_family = 2;
                     return STL_LK_RMT_STOP;
                 }
                 for (const uint8_t *p = tok; p + 8 <= lim; p++) {
@@ -533,7 +605,7 @@ scan_anywhere:
                 continue;
             }
             "[" ("HS" | "HD") "_" ("RMTSensor" | "Sensor") "]" {
-                ev->fw_family = (tok[2] == 'S') ? 1 : 2;
+                if (tok[2] == 'S') ev->fw_family = 1;
                 extract_ncd_token(s, end, ev);
                 const uint8_t *cl = memchr(YYCURSOR, ':', (size_t)(lim - YYCURSOR));
                 if (cl) {
@@ -550,7 +622,7 @@ scan_anywhere:
                 return STL_LK_INLINE_TEMP;
             }
             "[" ("HS" | "HD") "_DRAM]" {
-                ev->fw_family = (tok[2] == 'S') ? 1 : 2;
+                if (tok[2] == 'S') ev->fw_family = 1;
                 extract_coords_and_addr(s, end, ev);
                 /* Check Size:0 -> absent, else present */
                 ev->subkind = 4;
@@ -656,13 +728,17 @@ scan_anywhere:
                 extract_coords_and_addr(s, end, ev);
                 return STL_LK_AMT_ERROR;
             }
+            ("[Parity Error]" | "[Parity]") WS "Test:" {
+                ev->subkind = 2;
+                extract_coords_and_addr(s, end, ev);
+                return STL_LK_MT_ERROR;
+            }
             "Failing DIMM" | "[BIOS][FailMode]" |
             "Training Fail" | "BIST Error" | "BIST FAIL" | "Uncorrectable" |
             "Correctable error threshold exceeded" | "Critical Margin Error" |
-            "Pipe Sync SBSP Status -- FAILED" |
             "FatalError:" | "No Eye width" |
             "No eye found" | "smaller than minimum critical margin" | "RxPerBitDeskew Failure" |
-            "Parity Error" | "Parity error" | "PEC Error" | "PEC error" {
+            "Parity Error" | "Parity error" | "[Parity]" | "[Parity Error]" | "PEC Error" | "PEC error" {
                 ev->subkind = 2;
                 extract_coords_and_addr(s, end, ev);
                 return STL_LK_TRAINING_ERROR;
@@ -671,9 +747,15 @@ scan_anywhere:
                 return STL_LK_UEFI_BANNER;
             }
             "Start PXE over IPv4" | "Downloading NBP file" | "NBP filename is" {
+                ev->subkind = 0;
+                return STL_LK_PXE_BOOT;
+            }
+            "NBP file downloaded successfully" | "LoadImage Status = Success" | "StartImage Status = Success" {
+                ev->subkind = 1;
                 return STL_LK_PXE_BOOT;
             }
             "PassMark MemTest86" | "MemTest86 V" | "MemTest86 v" |
+            "Hovsee V" | "Hovsee v" |
             "Found configuration file:" | "*** TEST SESSION -" | "Launching 118.efi" |
             "STL_SIM TEST_START MT" {
                 return STL_LK_MT_BANNER;
@@ -689,16 +771,42 @@ scan_anywhere:
                 ev->subkind = 1;
                 return STL_LK_MT_PASS_COMPLETE;
             }
-            "[MEM ERROR" | "[ECC Errors]" | "[Data Error]" | "ECC Error:" {
+            "[MEM ERROR" | "[Mem Error]" | "[ECC Errors]" | "[ECC Error]" |
+            "[IBECC Errors]" | "[Scrub ECC Errors]" | "[Data Error]" | "ECC Error:" {
                 ev->subkind = 2;
                 extract_coords_and_addr(s, end, ev);
                 return STL_LK_MT_ERROR;
             }
-            "Channel/Slot:" | "Channel-Slot:" | "(Chan,Slot,Rank,Bank,Row," {
+            "DIMM err count=" {
+                int32_t cnt = 0;
+                if (parse_i32_at(YYCURSOR, lim, &cnt, NULL) && cnt > 0) {
+                    ev->subkind = 2;
+                    extract_coords_and_addr(s, end, ev);
+                    return STL_LK_MT_ERROR;
+                }
+                continue;
+            }
+            "Channel/Slot:" | "Channel-Slot:" |
+            "(Chan,Slot,Rank,Bank,Row," | "(Channel,Slot,Rank,Bank,Row," | "(Ch,Sl,Rk,Bk,Rw," {
                 ev->subkind = 5; /* 2nd-line MT ECC/Data Error coordinate continuation */
                 extract_coords_and_addr(s, end, ev);
                 return STL_LK_MT_ERROR;
             }
+            "(" WS "Test" WS DIG WS "cumulative error count:" WS DIG {
+                int32_t tid = 0, cnt = 0;
+                const uint8_t *nx = NULL;
+                const uint8_t *tpos = memchr(tok, 'T', (size_t)(YYCURSOR - tok));
+                if (tpos && parse_i32_at(tpos + 4, YYCURSOR, &tid, &nx)) {
+                    const uint8_t *cl = memchr(nx ? nx : tok, ':', (size_t)(YYCURSOR - (nx ? nx : tok)));
+                    if (cl && parse_i32_at(cl + 1, lim, &cnt, NULL) && cnt > 0) {
+                        ev->subkind = 6; /* MemTest86 per-test cumulative error count */
+                        ev->val1 = tid;
+                        ev->val0 = cnt;
+                        return STL_LK_MT_ERROR;
+                    }
+                }
+                continue;
+            }
             "Finished pass #" DIG WS "(of" WS DIG ")" {
                 int32_t pno = 0, ptot = 0;
                 const uint8_t *nx = NULL;
@@ -722,11 +830,64 @@ scan_anywhere:
                 ev->val2 = (ptot > 0) ? ((pno * 100) / ptot) : 50;
                 return STL_LK_MT_PROGRESS;
             }
+            ("#" WS)? "Tests Passed" WS ":" WS DIG "/" DIG {
+                int32_t passed = 0, total = 0;
+                const uint8_t *cl = memchr(tok, ':', (size_t)(YYCURSOR - tok));
+                const uint8_t *nx = NULL;
+                if (cl && parse_i32_at(cl + 1, YYCURSOR, &passed, &nx)
+                    && nx && nx < YYCURSOR && *nx == '/'
+                    && parse_i32_at(nx + 1, YYCURSOR, &total, NULL) && total > 0) {
+                    if (passed == total) {
+                        ev->subkind = 1;
+                        ev->val0 = 0;
+                        return STL_LK_MT_PASS_COMPLETE;
+                    }
+                    ev->val0 = passed;
+                    ev->val1 = total;
+                    ev->val2 = (passed * 100) / total;
+                    return STL_LK_MT_PROGRESS;
+                }
+                continue;
+            }
+            ("#" WS)? "Tests Completed" WS ":" WS DIG "/" DIG {
+                int32_t done = 0, total = 0;
+                const uint8_t *cl = memchr(tok, ':', (size_t)(YYCURSOR - tok));
+                const uint8_t *nx = NULL;
+                if (cl && parse_i32_at(cl + 1, YYCURSOR, &done, &nx)
+                    && nx && nx < YYCURSOR && *nx == '/'
+                    && parse_i32_at(nx + 1, YYCURSOR, &total, NULL) && total > 0) {
+                    ev->val0 = done;
+                    ev->val1 = total;
+                    ev->val2 = (done * 100) / total;
+                    return STL_LK_MT_PROGRESS;
+                }
+                continue;
+            }
+            ("#" WS)? "Bits in Error" WS ":" WS "Total" WS ":" WS DIG {
+                int32_t cnt = 0;
+                const uint8_t *tpos = NULL;
+                for (const uint8_t *p = tok; p + 5 <= YYCURSOR; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_kw(p, YYCURSOR, "total", &af)) {
+                        tpos = af;
+                        break;
+                    }
+                }
+                if (tpos) {
+                    const uint8_t *cl = memchr(tpos, ':', (size_t)(YYCURSOR - tpos));
+                    if (cl && parse_i32_at(cl + 1, YYCURSOR, &cnt, NULL) && cnt > 0) {
+                        ev->subkind = 6;
+                        ev->val0 = cnt;
+                        ev->val1 = 99;
+                        return STL_LK_MT_ERROR;
+                    }
+                }
+                continue;
+            }
             ("Test Result" | "Test result" | "Result") WS ":" WS (("INCOMPLETE" | "Incomplete" | "incomplete") WS)? ("PASS" | "Pass" | "pass" | "FAIL" | "Fail" | "fail" | "FAILED" | "Failed" | "failed") {
                 for (const uint8_t *p = tok; p + 4 <= lim; p++) {
                     const uint8_t *af = NULL;
-                    if (match_ci_kw(p, lim, "incomplete", &af) ||
-                        match_ci_kw(p, lim, "fail", &af) ||
+                    if (match_ci_kw(p, lim, "fail", &af) ||
                         match_ci_kw(p, lim, "failed", &af)) {
                         ev->subkind = 2;
                         return STL_LK_MT_FAIL_COMPLETE;
@@ -768,8 +929,9 @@ scan_anywhere:
                 }
                 return STL_LK_MT_PROGRESS;
             }
-            "N" [01] ".C" DIG (".D" [01])? (".SC" [01])? ".R" DIG (".L" DIG)? (".B" DIG)? WS ":" {
-                extract_ncd_token(s, end, ev);
+            "N" [01] ".C" DIG (".D" [01])? (".SC" [01])? ".R" DIG (".L" DIG | "." WS "A" DIG)? (".B" DIG)? WS ":" {
+                int mcols = 0;
+                extract_ncd_token_cols(s, end, ev, &mcols);
                 for (const uint8_t *q = YYCURSOR; q + 4 <= lim; q++) {
                     const uint8_t *af = NULL;
                     if (match_ci_word(YYCURSOR, q, lim, "advanced memtest", &af) ||
@@ -787,7 +949,10 @@ scan_anywhere:
                         return STL_LK_TRAINING_ERROR;
                     }
                 }
-                return STL_LK_RMT_ROW;
+                if (mcols >= 4) {
+                    return STL_LK_RMT_ROW;
+                }
+                continue;
             }
             "N" [01] ".C" DIG ".D" [01] {
                 extract_ncd_token(s, end, ev);
@@ -841,10 +1006,17 @@ scan_anywhere:
                 }
                 continue;
             }
+            ("Test" DIG | "Test:" WS DIG) WS "Addr:" WS {
+                ev->subkind = 2;
+                extract_coords_and_addr(s, end, ev);
+                return STL_LK_MT_ERROR;
+            }
             "Test:" WS DIG {
                 for (const uint8_t *p = YYCURSOR; p + 4 <= lim; p++) {
                     const uint8_t *af = NULL;
-                    if (match_ci_kw(p, lim, "expected", &af) || match_ci_kw(p, lim, "actual", &af)) {
+                    if (match_ci_kw(p, lim, "expected", &af) ||
+                        match_ci_kw(p, lim, "actual", &af) ||
+                        match_ci_kw(p, lim, "addr", &af)) {
                         ev->subkind = 2;
                         extract_coords_and_addr(s, end, ev);
                         return STL_LK_MT_ERROR;

+ 5 - 5
native/stl_accel/scan_asm.S

@@ -1040,12 +1040,12 @@ asm_clean_split_classify_avx2:
     cmpl    %eax, %edx
     jbe     .Lcup_col_done
 
-    /* Forward column gap on same row: pad spaces (clamped to <= 32 spaces & <= 1000 half_len) */
+    /* Forward column gap on same row: pad spaces (clamped to <= 160 spaces & <= 1000 half_len) */
     movl    %edx, %ecx
     subl    %eax, %ecx              /* gap = col0 - cur_col */
-    cmpl    $32, %ecx
+    cmpl    $160, %ecx
     jbe     1f
-    movl    $32, %ecx
+    movl    $160, %ecx
 1:  movl    28(%r12), %eax          /* half_len */
 2:  cmpl    $1000, %eax
     jae     3f
@@ -1066,9 +1066,9 @@ asm_clean_split_classify_avx2:
     testl   %ecx, %ecx
     jnz     1f
     movl    $1, %ecx
-1:  cmpl    $32, %ecx
+1:  cmpl    $160, %ecx
     jbe     2f
-    movl    $32, %ecx
+    movl    $160, %ecx
 2:  addl    %ecx, 20(%r12)
     movl    28(%r12), %eax
 3:  cmpl    $1000, %eax

+ 247 - 81
native/stl_accel/src/actors.rs

@@ -13,9 +13,12 @@ use crate::devices::{
 use crate::firmware::FirmwareContract;
 use crate::json::JsonVal;
 use crate::lib;
-use crate::results::{now_ms, StationState};
+use crate::results::{now_ms, patch_timing_fields, StationState};
 use crate::storage::{strip_private_keys_recursive};
-use crate::workflow::{apply_profile_to_station, control_boot_plan, step_boot_plan, step_task_batch, submit_task_batch};
+use crate::workflow::{
+    apply_profile_to_station, control_boot_plan_impl, step_boot_plan, step_task_batch,
+    submit_task_batch,
+};
 use std::path::PathBuf;
 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
 use std::sync::{mpsc, Arc, Condvar, Mutex, RwLock};
@@ -42,6 +45,8 @@ pub struct StationPublishedView {
     pub console_online: bool,
     pub server_power: String,
     pub boot_id: String,
+    pub run_started_unix_ms: i64,
+    pub run_ended_unix_ms: i64,
     pub diag_session_id: String,
     pub last_clear_screen_offset: u64,
     pub raw_base_offset: u64,
@@ -167,12 +172,6 @@ pub enum StationMsg {
     MtReportSyncDone {
         fetched: bool,
     },
-    UpdateChamberTelemetry {
-        serial_path: String,
-        current_c: Option<f64>,
-        target_c: Option<f64>,
-        state: String,
-    },
 }
 
 pub enum IpmiJob {
@@ -277,6 +276,20 @@ impl PushBroadcaster {
             list.retain(|tx| tx.send(Arc::clone(&bytes)).is_ok());
         }
     }
+
+    pub fn broadcast_web_dirty(&self, bitmap: u64) {
+        let mut res = JsonVal::obj();
+        res.set("dirty_bitmap", JsonVal::Num(bitmap as f64));
+        res.set("unix_ms", JsonVal::Num(now_ms() as f64));
+        let mut ev = JsonVal::obj();
+        ev.set("v", JsonVal::Num(1.0));
+        ev.set("event", JsonVal::Str("station_dirty".to_string()));
+        ev.set("result", res);
+        let bytes: Arc<[u8]> = Arc::from(ev.to_json().into_bytes().into_boxed_slice());
+        if let Ok(mut list) = self.full_ws_senders.lock() {
+            list.retain(|tx| tx.send(Arc::clone(&bytes)).is_ok());
+        }
+    }
 }
 
 pub fn build_published_view(st: &StationState) -> StationPublishedView {
@@ -303,6 +316,8 @@ pub fn build_published_view(st: &StationState) -> StationPublishedView {
         console_online: st.console_online,
         server_power: st.server_power.clone(),
         boot_id: st.boot_id.clone(),
+        run_started_unix_ms: st.run_started_unix_ms,
+        run_ended_unix_ms: st.run_ended_unix_ms,
         diag_session_id: st.diag_session_id.clone(),
         last_clear_screen_offset: st.last_clear_screen_offset,
         raw_base_offset: st.raw_ring.base_offset(),
@@ -350,7 +365,9 @@ fn build_station_list_entry(st: &StationState) -> JsonVal {
         JsonVal::Str(st.boot_plan.get_str_or("preset", "manual")),
     );
     s.set("verdict", JsonVal::Str(verdict.to_string()));
-    s.set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
+    let now = now_ms();
+    patch_timing_fields(&mut s, st.run_started_unix_ms, st.run_ended_unix_ms, now);
+    s.set("updated_unix_ms", JsonVal::Num(now as f64));
     s
 }
 
@@ -582,8 +599,10 @@ fn build_station_control_base(st: &StationState) -> JsonVal {
             o.set("cpu", JsonVal::Num(r.cpu as f64));
             o.set("state", JsonVal::Str(r.state.clone()));
             o.set("measurement_rows", JsonVal::Num(r.measurement_rows as f64));
-            o.set("min_dq_width", JsonVal::Num(r.min_dq_width as f64));
-            o.set("min_vref_width", JsonVal::Num(r.min_vref_width as f64));
+            let dq_w = if r.min_dq_width == i32::MAX { 0 } else { r.min_dq_width };
+            let vref_w = if r.min_vref_width == i32::MAX { 0 } else { r.min_vref_width };
+            o.set("min_dq_width", JsonVal::Num(dq_w as f64));
+            o.set("min_vref_width", JsonVal::Num(vref_w as f64));
             o.set(
                 "execution_supported",
                 JsonVal::Bool(r.execution_supported),
@@ -643,9 +662,57 @@ fn build_station_control_base(st: &StationState) -> JsonVal {
     fw_obs.set("amt_results", JsonVal::Arr(amt_arr));
     fw_obs.set("active_amt_cpus", JsonVal::Arr(active_amt));
     fw_obs.set("mt_result", st.mt_result.clone());
+    let mut training_dimms_arr = Vec::new();
+    for (idx, d) in st.dimms.iter().enumerate() {
+        if d.presence == "present" || d.enabled == "disabled" || d.stage_training != "idle" {
+            let cpu = idx / 12;
+            let ch_char = (b'A' + (idx % 12) as u8) as char;
+            let slot_name = format!("CPU{}_{}", cpu, ch_char);
+            let tr_state = if d.enabled == "disabled" {
+                "disabled"
+            } else if d.presence == "present" || d.stage_training == "pass" {
+                "enabled"
+            } else {
+                "unknown"
+            };
+            let ev_text = if d.sn.is_empty() {
+                format!("{} · Presence={} · Training={}", slot_name, d.presence, d.stage_training)
+            } else {
+                format!(
+                    "{} · Presence={} · Training={} · S/N: {}",
+                    slot_name, d.presence, d.stage_training, d.sn
+                )
+            };
+            let mut o = JsonVal::obj();
+            o.set("slot", JsonVal::Str(slot_name));
+            o.set("cpu", JsonVal::Num(cpu as f64));
+            o.set("channel", JsonVal::Str(ch_char.to_string()));
+            o.set("dimm", JsonVal::Num(0.0));
+            o.set("state", JsonVal::Str(tr_state.to_string()));
+            o.set("training_state", JsonVal::Str(tr_state.to_string()));
+            if !d.sn.is_empty() {
+                o.set("sn", JsonVal::Str(d.sn.clone()));
+            }
+            o.set("evidence", JsonVal::Str(ev_text));
+            training_dimms_arr.push(o);
+        }
+    }
+    let uefi_fs_arr: Vec<JsonVal> = st
+        .uefi_fs_candidates
+        .iter()
+        .map(|fs| {
+            let mut o = JsonVal::obj();
+            o.set("name", JsonVal::Str(fs.clone()));
+            o
+        })
+        .collect();
     fw_obs.set("stage_errors", stg_errs.clone());
-    fw_obs.set("training_dimms", JsonVal::Arr(Vec::new()));
-    fw_obs.set("uefi_filesystems", JsonVal::Arr(Vec::new()));
+    fw_obs.set(
+        "unsupported_commands",
+        JsonVal::Arr(st.unsupported_commands.clone()),
+    );
+    fw_obs.set("training_dimms", JsonVal::Arr(training_dimms_arr));
+    fw_obs.set("uefi_filesystems", JsonVal::Arr(uefi_fs_arr));
 
     let mut phase_actions = JsonVal::obj();
     let mut cont_uip = JsonVal::obj();
@@ -703,10 +770,11 @@ fn build_station_control_base(st: &StationState) -> JsonVal {
     if let Some(ref p) = st.last_phase_action {
         out.set("last_phase_action", p.clone());
     }
+    patch_timing_fields(&mut out, st.run_started_unix_ms, st.run_ended_unix_ms, now_ms());
     out
 }
 
-fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
+pub(crate) fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
     let mut s = JsonVal::obj();
     s.set("station_id", JsonVal::Str(st.station_id.clone()));
     s.set("firmware_family", JsonVal::Str(st.fw_family_name().to_string()));
@@ -742,22 +810,22 @@ fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
     };
     s.set("phase", JsonVal::Str(phase_str.to_string()));
 
-    let run_state = if st.awaiting_dimm_replacement {
+    let bp_state = st.boot_execution.get_str_or("state", "idle");
+    let is_terminal = matches!(
+        bp_state.as_str(),
+        "completed" | "failed" | "stopped" | "interrupted"
+    );
+    let run_state = if st.awaiting_dimm_replacement || bp_state == "blocked" {
         "blocked".to_string()
+    } else if is_terminal {
+        bp_state.clone()
     } else if st.prompt_ready {
         "waiting_input".to_string()
     } else {
-        st.boot_execution.get_str_or("state", "idle")
+        bp_state.clone()
     };
     s.set("run_state", JsonVal::Str(run_state));
-    let started_ms = if st.run_started_unix_ms > 0 {
-        st.run_started_unix_ms
-    } else if st.single_run_started_ms > 0 {
-        st.single_run_started_ms
-    } else {
-        st.observed_unix_ms
-    };
-    s.set("started_unix_ms", JsonVal::Str(started_ms.to_string()));
+    patch_timing_fields(&mut s, st.run_started_unix_ms, st.run_ended_unix_ms, now_ms());
     s.set("boot_id", JsonVal::Str(st.boot_id.clone()));
 
     let has_any_err =
@@ -820,11 +888,20 @@ fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
         .get(&cpu_idx)
         .map(|r| r.status == "pass" && r.algorithm_count > 0)
         .unwrap_or(false);
+    let input_ready =
+        st.prompt_ready && !st.awaiting_dimm_replacement && bp_state != "blocked" && !is_terminal;
     let mut input_obj = JsonVal::obj();
-    input_obj.set("id", JsonVal::Str(st.current_input_id()));
+    input_obj.set(
+        "id",
+        JsonVal::Str(if input_ready {
+            st.current_input_id()
+        } else {
+            String::new()
+        }),
+    );
     input_obj.set("stage", JsonVal::Str(stage_str.to_string()));
     input_obj.set("cpu", JsonVal::Num(cpu_idx as f64));
-    input_obj.set("ready", JsonVal::Bool(st.prompt_ready));
+    input_obj.set("ready", JsonVal::Bool(input_ready));
     input_obj.set("actions", JsonVal::Arr(actions_vec));
     input_obj.set("test_complete", JsonVal::Bool(test_done));
     s.set("input", input_obj);
@@ -893,6 +970,32 @@ fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
     s
 }
 
+#[inline]
+fn mark_station_dirty(
+    dirty_bitmap: &AtomicU64,
+    dirty_cond: &(Mutex<()>, Condvar),
+    bit_index: u32,
+) {
+    dirty_bitmap.fetch_or(1u64 << bit_index, Ordering::Release);
+    if let Ok(_g) = dirty_cond.0.lock() {
+        dirty_cond.1.notify_one();
+    }
+}
+
+#[inline]
+fn dispatch_pending_bmc_power(st: &mut StationState, ipmi_tx: &mpsc::Sender<IpmiJob>) {
+    if let Some(act) = st.pending_bmc_power_action.take() {
+        if act == "smart_restart" && st.bmc_enabled && !st.bmc_host.is_empty() {
+            let _ = ipmi_tx.send(IpmiJob::SmartRestart {
+                host: st.bmc_host.clone(),
+                user: st.bmc_user.clone(),
+                pass: st.bmc_password.clone(),
+                hint_off: st.server_power == "off",
+            });
+        }
+    }
+}
+
 #[allow(clippy::too_many_arguments)]
 pub fn spawn_station_actor(
     actor_idx: usize,
@@ -901,9 +1004,13 @@ pub fn spawn_station_actor(
     data_dir: PathBuf,
     pxe_tftp_dir: PathBuf,
     dirty_bitmap: Arc<AtomicU64>,
+    dirty_cond: Arc<(Mutex<()>, Condvar)>,
     push_hub: Arc<PushBroadcaster>,
     enable_hw_bg_probes: bool,
 ) -> StationHandle {
+    if enable_hw_bg_probes && st.has_stale_station_state() {
+        st.reset_on_disconnect();
+    }
     let sid = st.station_id.clone();
     let bit_index = (actor_idx.min(62)) as u32;
     let initial_view = build_published_view(&st);
@@ -981,9 +1088,13 @@ pub fn spawn_station_actor(
                         }
                     }
                     IpmiJob::PollTelemetry { host, user, pass } => {
-                        if host.is_empty() || !probe_tcp_port(&host, 22, 220) {
+                        let host_reachable = !host.is_empty()
+                            && (probe_tcp_port(&host, 22, 180) || probe_tcp_port(&host, 2200, 150));
+                        if !host_reachable {
                             let alt = resolve_reachable_bmc_host(&host, 22);
-                            if alt == host || !probe_tcp_port(&alt, 22, 220) {
+                            let alt_reachable = alt != host
+                                && (probe_tcp_port(&alt, 22, 180) || probe_tcp_port(&alt, 2200, 150));
+                            if !alt_reachable {
                                 if !host.is_empty() {
                                     let _ = actor_tx_for_ipmi.send(StationMsg::IpmiTelemetry {
                                         resolved_host: None,
@@ -1260,6 +1371,7 @@ pub fn spawn_station_actor(
             let mut registered_pty_fd: i32 = -1;
             let mut cached_pxe_state = crate::storage::load_pxe_state(&data_dir);
             let mut next_ipmi_poll_ms = now_ms() + 6000;
+            let mut offline_since_ms: Option<i64> = None;
             let mut ev_tokens = [0u64; 8];
             let mut ev_masks = [0u32; 8];
 
@@ -1329,6 +1441,9 @@ pub fn spawn_station_actor(
                         state_dirty = true;
                     } else if n_read < 0 {
                         st.next_reconnect_probe_ms = now_ms() + 800;
+                        if st.bmc_enabled && !st.bmc_host.is_empty() {
+                            next_ipmi_poll_ms = 0;
+                        }
                         state_dirty = true;
                     }
                 }
@@ -1359,28 +1474,28 @@ pub fn spawn_station_actor(
                                 &args,
                                 &operator,
                             );
-                            let pxe_changed = if method == "ConfigurePxe" {
+                            let pxe_changed = if matches!(
+                                method.as_str(),
+                                "ConfigurePxe"
+                                    | "ApplyBootPlan"
+                                    | "ApplyStationProfile"
+                                    | "SubmitTaskBatch"
+                                    | "ControlTaskBatch"
+                            ) {
                                 cached_pxe_state = pxe_mut.clone();
                                 Some(pxe_mut)
                             } else {
                                 None
                             };
-                            if let Some(act) = st.pending_bmc_power_action.take() {
-                                if act == "smart_restart" && st.bmc_enabled && !st.bmc_host.is_empty()
-                                {
-                                    let _ = ipmi_tx_for_actor.send(IpmiJob::SmartRestart {
-                                        host: st.bmc_host.clone(),
-                                        user: st.bmc_user.clone(),
-                                        pass: st.bmc_password.clone(),
-                                        hint_off: st.server_power == "off",
-                                    });
-                                }
+                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor);
+                            if method == "ConfigureConnections" {
+                                next_ipmi_poll_ms = 0;
                             }
                             uart_clone.publish(&st, false);
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
                             }
-                            dirty_bitmap.fetch_or(1u64 << bit_index, Ordering::Release);
+                            mark_station_dirty(&dirty_bitmap, &dirty_cond, bit_index);
                             if let Some(sig) = st.pending_complete_signal.take() {
                                 push_hub.broadcast_task_complete(&sig);
                             }
@@ -1408,7 +1523,7 @@ pub fn spawn_station_actor(
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
                             }
-                            dirty_bitmap.fetch_or(1u64 << bit_index, Ordering::Release);
+                            mark_station_dirty(&dirty_bitmap, &dirty_cond, bit_index);
                             if let Some(sig) = st.pending_complete_signal.take() {
                                 push_hub.broadcast_task_complete(&sig);
                             }
@@ -1481,6 +1596,10 @@ pub fn spawn_station_actor(
                             bmc_state,
                         } => {
                             if let Some(bs) = bmc_state {
+                                if bs == "offline" {
+                                    st.clear_bmc_sdr_temps();
+                                    state_dirty = true;
+                                }
                                 if st.bmc_state != bs {
                                     st.bmc_state = bs;
                                     state_dirty = true;
@@ -1500,8 +1619,25 @@ pub fn spawn_station_actor(
                                 }
                             }
                             if let Some(pwr) = power {
+                                if pwr == "off" || pwr == "unknown" {
+                                    st.clear_bmc_sdr_temps();
+                                }
                                 if st.server_power != pwr {
-                                    st.server_power = pwr;
+                                    st.server_power = pwr.clone();
+                                    state_dirty = true;
+                                }
+                                if pwr == "off"
+                                    && !st.is_run_active()
+                                    && st.observed_phase != "powered_off"
+                                {
+                                    st.observed_phase = "powered_off".to_string();
+                                    st.observed_detail = "power_off".to_string();
+                                    st.prompt_ready = false;
+                                    st.hot.prompt_ready = false;
+                                    state_dirty = true;
+                                } else if pwr == "on" && st.observed_phase == "powered_off" {
+                                    st.observed_phase = "boot".to_string();
+                                    st.observed_detail = "power_on".to_string();
                                     state_dirty = true;
                                 }
                             }
@@ -1544,7 +1680,7 @@ pub fn spawn_station_actor(
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
                             }
-                            dirty_bitmap.fetch_or(1u64 << bit_index, Ordering::Release);
+                            mark_station_dirty(&dirty_bitmap, &dirty_cond, bit_index);
                             if let Some(sig) = st.pending_complete_signal.take() {
                                 push_hub.broadcast_task_complete(&sig);
                             }
@@ -1563,11 +1699,12 @@ pub fn spawn_station_actor(
                                 &data_dir,
                                 &pxe_tftp_dir,
                             );
+                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor);
                             state_dirty = true;
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
                             }
-                            dirty_bitmap.fetch_or(1u64 << bit_index, Ordering::Release);
+                            mark_station_dirty(&dirty_bitmap, &dirty_cond, bit_index);
                             if let Some(sig) = st.pending_complete_signal.take() {
                                 push_hub.broadcast_task_complete(&sig);
                             }
@@ -1587,12 +1724,13 @@ pub fn spawn_station_actor(
                                 &data_dir,
                                 &pxe_tftp_dir,
                             );
+                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor);
                             state_dirty = true;
                             uart_clone.publish(&st, false);
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
                             }
-                            dirty_bitmap.fetch_or(1u64 << bit_index, Ordering::Release);
+                            mark_station_dirty(&dirty_bitmap, &dirty_cond, bit_index);
                             if let Some(sig) = st.pending_complete_signal.take() {
                                 push_hub.broadcast_task_complete(&sig);
                             }
@@ -1609,34 +1747,17 @@ pub fn spawn_station_actor(
                                 &data_dir,
                                 &pxe_tftp_dir,
                             );
+                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor);
                             state_dirty = true;
                             uart_clone.publish(&st, false);
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
                             }
-                            dirty_bitmap.fetch_or(1u64 << bit_index, Ordering::Release);
+                            mark_station_dirty(&dirty_bitmap, &dirty_cond, bit_index);
                             if let Some(sig) = st.pending_complete_signal.take() {
                                 push_hub.broadcast_task_complete(&sig);
                             }
                         }
-                        StationMsg::UpdateChamberTelemetry {
-                            serial_path,
-                            current_c,
-                            target_c,
-                            state,
-                        } => {
-                            if st.chamber_serial_path != serial_path
-                                || st.chamber_current_c != current_c
-                                || st.chamber_target_c != target_c
-                                || st.chamber_state != state
-                            {
-                                st.chamber_serial_path = serial_path;
-                                st.chamber_current_c = current_c;
-                                st.chamber_target_c = target_c;
-                                st.chamber_state = state;
-                                state_dirty = true;
-                            }
-                        }
                     }
                 }
 
@@ -1657,12 +1778,13 @@ pub fn spawn_station_actor(
                             .is_ok()
                     {
                         st.mt_report_sync_pending = true;
-                        st.mt_waiting_report_until_ms = now + 4500;
+                        st.mt_waiting_report_until_ms = now + 12_500;
                         let min_ms = st.mt_started_unix_ms.max(st.run_started_unix_ms);
                         crate::pxe::sync_remote_pxe_report_async(
                             pxe_host,
                             pxe_tftp_dir.clone(),
                             min_ms,
+                            st.expected_mt_report_name.clone(),
                             st.station_id.clone(),
                             actor_tx_for_pxe.clone(),
                             ev_fd,
@@ -1676,6 +1798,8 @@ pub fn spawn_station_actor(
                 let prev_bp_state = st.boot_execution.get_str_or("state", "idle");
                 let prev_tb_state = st.task_batch.get_str_or("state", "idle");
                 let prev_task_status = st.task_status.clone();
+                let prev_run_started = st.run_started_unix_ms;
+                let prev_run_ended = st.run_ended_unix_ms;
                 step_boot_plan(&mut st, &contract);
                 step_task_batch(
                     &mut st,
@@ -1684,19 +1808,12 @@ pub fn spawn_station_actor(
                     &data_dir,
                     &pxe_tftp_dir,
                 );
-                if let Some(act) = st.pending_bmc_power_action.take() {
-                    if act == "smart_restart" && st.bmc_enabled && !st.bmc_host.is_empty() {
-                        let _ = ipmi_tx_for_actor.send(IpmiJob::SmartRestart {
-                            host: st.bmc_host.clone(),
-                            user: st.bmc_user.clone(),
-                            pass: st.bmc_password.clone(),
-                            hint_off: st.server_power == "off",
-                        });
-                    }
-                }
+                dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor);
                 if st.boot_execution.get_str_or("state", "idle") != prev_bp_state
                     || st.task_batch.get_str_or("state", "idle") != prev_tb_state
                     || st.task_status != prev_task_status
+                    || st.run_started_unix_ms != prev_run_started
+                    || st.run_ended_unix_ms != prev_run_ended
                 {
                     state_dirty = true;
                 }
@@ -1738,6 +1855,31 @@ pub fn spawn_station_actor(
                     }
                 }
 
+                // 6b. Real-time disconnect/idle reset: once BOTH console and BMC are offline
+                // (or station is unconfigured idle), clear stale channel PASS/FAIL, presence,
+                // temperatures, and run state so frontends never display phantom legacy states.
+                if enable_hw_bg_probes {
+                    let bmc_disconnected = !st.bmc_enabled
+                        || st.bmc_host.is_empty()
+                        || st.bmc_state == "offline"
+                        || st.bmc_state == "disabled";
+                    let serial_disconnected = !st.console_online && st.pty_master_fd < 0;
+                    if bmc_disconnected && serial_disconnected {
+                        if st.has_stale_station_state() {
+                            let since = *offline_since_ms.get_or_insert(now);
+                            if now.saturating_sub(since) >= 1500 {
+                                st.reset_on_disconnect();
+                                offline_since_ms = None;
+                                state_dirty = true;
+                            }
+                        } else {
+                            offline_since_ms = None;
+                        }
+                    } else {
+                        offline_since_ms = None;
+                    }
+                }
+
                 // 7. Publish updated ring offsets & station snapshot + emit active `task_complete` push
                 if rx_bytes_arrived || state_dirty {
                     uart_clone.publish(&st, rx_bytes_arrived);
@@ -1746,7 +1888,7 @@ pub fn spawn_station_actor(
                     if let Ok(mut guard) = view_clone.write() {
                         *guard = build_published_view(&st);
                     }
-                    dirty_bitmap.fetch_or(1u64 << bit_index, Ordering::Release);
+                    mark_station_dirty(&dirty_bitmap, &dirty_cond, bit_index);
                 }
                 if let Some(sig) = st.pending_complete_signal.take() {
                     push_hub.broadcast_task_complete(&sig);
@@ -1805,8 +1947,20 @@ fn handle_actor_start_test(
         "host_reset".to_string()
     };
 
+    let continue_timer =
+        params.get_bool("continue_timer") == Some(true) && st.run_started_unix_ms > 0;
+    let preserved_started = if continue_timer {
+        st.run_started_unix_ms
+    } else {
+        0
+    };
+
     // Forced preemption clears any previous awaiting_dimm_replacement block on new StartTest
     st.confirm_dimm_replacement();
+    if continue_timer {
+        st.run_started_unix_ms = preserved_started;
+        st.run_ended_unix_ms = 0;
+    }
     st.next_reconnect_probe_ms = 0;
 
     if params.get("profiles").is_some() || params.get("tasks").is_some() {
@@ -1839,11 +1993,15 @@ fn handle_actor_start_test(
                         power_action,
                         prev_boot_id,
                         boot_id: st.boot_id.clone(),
-                        started_ms: now,
+                        started_ms: if st.run_started_unix_ms > 0 {
+                            st.run_started_unix_ms
+                        } else {
+                            now
+                        },
                         task_batch: Some(tb),
                         audit: Some(audit),
                     },
-                    None,
+                    Some(pxe_state.clone()),
                 ));
             }
             Err(e) => return Err(("INVALID_ARGUMENT".to_string(), e)),
@@ -1882,7 +2040,7 @@ fn handle_actor_start_test(
         }
     }
 
-    if let Err(e) = control_boot_plan(st, "restart", data_dir) {
+    if let Err(e) = control_boot_plan_impl(st, "restart", data_dir, continue_timer) {
         return Err(("FAILED_PRECONDITION".to_string(), e));
     }
 
@@ -1915,10 +2073,18 @@ fn handle_actor_start_test(
             power_action,
             prev_boot_id,
             boot_id: st.boot_id.clone(),
-            started_ms: now,
+            started_ms: if st.run_started_unix_ms > 0 {
+                st.run_started_unix_ms
+            } else {
+                now
+            },
             task_batch: None,
             audit,
         },
-        None,
+        if has_task_params {
+            Some(pxe_state.clone())
+        } else {
+            None
+        },
     ))
 }

+ 122 - 192
native/stl_accel/src/api.rs

@@ -13,7 +13,7 @@ use crate::firmware::FirmwareContract;
 use crate::json::{parse_json, JsonVal};
 use crate::lib;
 use crate::pxe::build_pxe_snapshot;
-use crate::results::{now_ms, StationState};
+use crate::results::{now_ms, patch_timing_fields, StationState};
 use crate::storage::{
     load_audit_logs, load_pxe_state, load_station_settings, record_audit_log,
     strip_private_keys_recursive,
@@ -26,9 +26,9 @@ use std::net::TcpStream;
 use std::os::unix::io::AsRawFd;
 use std::path::PathBuf;
 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
-use std::sync::{mpsc, Arc, Mutex, RwLock};
+use std::sync::{mpsc, Arc, Condvar, Mutex, RwLock};
 use std::thread;
-use std::time::Duration;
+use std::time::{Duration, Instant};
 
 pub struct QueueBook {
     pub items: Vec<JsonVal>,
@@ -54,11 +54,11 @@ pub struct AppHub {
     pub stations: BTreeMap<String, StationHandle>,
     pub contract: Arc<FirmwareContract>,
     pub dirty_bitmap: Arc<AtomicU64>,
+    pub dirty_cond: Arc<(Mutex<()>, Condvar)>,
     pub push_hub: Arc<PushBroadcaster>,
     pub queue_book: RwLock<QueueBook>,
     pub audit_book: Mutex<AuditEventBook>,
     pub pxe_state: RwLock<JsonVal>,
-    pub thermal_hub: Arc<crate::thermal_mcu::ThermalMcuHub>,
 }
 
 pub type ServerContext = AppHub;
@@ -121,7 +121,7 @@ impl AppHub {
                             entry.bmc_host = h.clone();
                             entry.bmc_enabled = bmc.get_bool("enabled").unwrap_or(true);
                             entry.bmc_state = if entry.bmc_enabled {
-                                "online".to_string()
+                                "offline".to_string()
                             } else {
                                 "disabled".to_string()
                             };
@@ -147,13 +147,6 @@ impl AppHub {
                         entry.write_gap_ms =
                             con.get_f64("write_gap_ms").unwrap_or(entry.write_gap_ms);
                     }
-                    if let Some(ch_cfg) = st_j.get("chamber") {
-                        let cport = ch_cfg.get_str_or("serial_port", "");
-                        if !cport.is_empty() && cport != "/dev/ttyUSB1" {
-                            entry.chamber_serial_path = cport;
-                            entry.chamber_state = "configured".to_string();
-                        }
-                    }
                 }
             }
         }
@@ -191,6 +184,7 @@ impl AppHub {
         let started_ms = now_ms();
         let server_id = format!("stl-{}", started_ms);
         let dirty_bitmap = Arc::new(AtomicU64::new(0));
+        let dirty_cond = Arc::new((Mutex::new(()), Condvar::new()));
         let push_hub = Arc::new(PushBroadcaster::new(b"{}".to_vec()));
 
         let mut stations = BTreeMap::new();
@@ -202,15 +196,13 @@ impl AppHub {
                 args.data_dir.clone(),
                 pxe_tftp_dir.clone(),
                 Arc::clone(&dirty_bitmap),
+                Arc::clone(&dirty_cond),
                 Arc::clone(&push_hub),
                 enable_hw_bg_probes,
             );
             stations.insert(sid, handle);
         }
 
-        let thermal_hub =
-            crate::thermal_mcu::ThermalMcuHub::spawn(args.data_dir.clone(), stations.clone());
-
         let hub = Arc::new(Self {
             version: args.version.clone(),
             commit: args.commit.clone(),
@@ -222,6 +214,7 @@ impl AppHub {
             stations,
             contract,
             dirty_bitmap,
+            dirty_cond,
             push_hub,
             queue_book: RwLock::new(QueueBook {
                 items: Vec::new(),
@@ -235,7 +228,6 @@ impl AppHub {
                 client_sessions: BTreeMap::new(),
             }),
             pxe_state: RwLock::new(pxe_state),
-            thermal_hub,
         });
 
         // Prime initial zero-copy QtClean state snapshot immediately
@@ -246,15 +238,55 @@ impl AppHub {
             thread::Builder::new()
                 .name("stl-state-pub".to_string())
                 .spawn(move || {
-                    let mut ticks: u64 = 0;
+                    let mut last_pub = Instant::now() - Duration::from_secs(2);
                     loop {
-                        thread::sleep(Duration::from_millis(200));
-                        ticks = ticks.wrapping_add(1);
-                        let dirty = bg_hub.dirty_bitmap.swap(0, Ordering::AcqRel);
-                        // Broadcast immediately when any station actor sets its dirty bit,
-                        // and keep a steady 1Hz (5 * 200ms) zero-copy heartbeat for QtClean clients.
-                        if dirty != 0 || ticks % 5 == 0 {
-                            bg_hub.refresh_and_broadcast_qt_state();
+                        let dirty = {
+                            let mut guard = bg_hub
+                                .dirty_cond
+                                .0
+                                .lock()
+                                .unwrap_or_else(|e| e.into_inner());
+                            loop {
+                                let cur = bg_hub.dirty_bitmap.load(Ordering::Acquire);
+                                if cur != 0 {
+                                    let elapsed = last_pub.elapsed();
+                                    if elapsed < Duration::from_millis(25) {
+                                        let rem = Duration::from_millis(25) - elapsed;
+                                        let (g, _) = bg_hub
+                                            .dirty_cond
+                                            .1
+                                            .wait_timeout(guard, rem)
+                                            .unwrap_or_else(|e| e.into_inner());
+                                        guard = g;
+                                        if last_pub.elapsed() >= Duration::from_millis(25) {
+                                            break bg_hub.dirty_bitmap.swap(0, Ordering::AcqRel);
+                                        }
+                                        continue;
+                                    }
+                                    break bg_hub.dirty_bitmap.swap(0, Ordering::AcqRel);
+                                }
+                                let elapsed_hb = last_pub.elapsed();
+                                let hb_wait = Duration::from_millis(1000).saturating_sub(elapsed_hb);
+                                if hb_wait.is_zero() {
+                                    break 0;
+                                }
+                                let (g, res) = bg_hub
+                                    .dirty_cond
+                                    .1
+                                    .wait_timeout(guard, hb_wait)
+                                    .unwrap_or_else(|e| e.into_inner());
+                                guard = g;
+                                if res.timed_out() {
+                                    break bg_hub.dirty_bitmap.swap(0, Ordering::AcqRel);
+                                }
+                            }
+                        };
+                        last_pub = Instant::now();
+                        bg_hub.refresh_and_broadcast_qt_state();
+                        let active_mask = bg_hub.active_station_mask();
+                        let notify_mask = dirty | active_mask;
+                        if notify_mask != 0 {
+                            bg_hub.push_hub.broadcast_web_dirty(notify_mask);
                         }
                     }
                 })
@@ -264,6 +296,25 @@ impl AppHub {
         hub
     }
 
+    pub fn active_station_mask(&self) -> u64 {
+        let mut mask = 0u64;
+        for handle in self.stations.values() {
+            if let Ok(guard) = handle.view.read() {
+                if guard.run_started_unix_ms > 0 && guard.run_ended_unix_ms == 0 {
+                    mask |= 1u64 << handle.bit_index;
+                }
+            }
+        }
+        mask
+    }
+
+    pub fn notify_state_dirty(&self, mask: u64) {
+        self.dirty_bitmap.fetch_or(mask, Ordering::Release);
+        if let Ok(_g) = self.dirty_cond.0.lock() {
+            self.dirty_cond.1.notify_one();
+        }
+    }
+
     pub fn refresh_and_broadcast_qt_state(&self) {
         let mut ev = JsonVal::obj();
         ev.set("v", JsonVal::Num(1.0));
@@ -345,20 +396,30 @@ impl AppHub {
         };
         out.set("pxe_control", pxe_snap);
         out.set("native_engine", lib::hardware_status_json());
+        patch_timing_fields(&mut out, view.run_started_unix_ms, view.run_ended_unix_ms, now_ms());
         Ok(out)
     }
 
     pub fn build_qt_clean_state(&self) -> JsonVal {
+        let now = now_ms();
         let mut st_arr = Vec::with_capacity(self.stations.len());
         for handle in self.stations.values() {
             if let Ok(guard) = handle.view.read() {
-                st_arr.push(guard.qt_clean_station.clone());
+                let mut entry = guard.qt_clean_station.clone();
+                patch_timing_fields(
+                    &mut entry,
+                    guard.run_started_unix_ms,
+                    guard.run_ended_unix_ms,
+                    now,
+                );
+                st_arr.push(entry);
             }
         }
         let mut out = JsonVal::obj();
         out.set("version", JsonVal::Str(self.version.clone()));
         out.set("mode", JsonVal::Str("hardware".to_string()));
         out.set("server_id", JsonVal::Str(self.server_id.clone()));
+        out.set("server_unix_ms", JsonVal::Num(now as f64));
         out.set("stations", JsonVal::Arr(st_arr));
         out
     }
@@ -478,89 +539,6 @@ impl AppHub {
         }
     }
 
-    fn execute_thermal_action(
-        &self,
-        params: &JsonVal,
-        default_operator: &str,
-    ) -> Result<JsonVal, String> {
-        let action = params.get_str_or("action", "");
-        if action.is_empty() {
-            return Err("缺少 action 字段".to_string());
-        }
-        let operator = params.get_str_or("operator", default_operator);
-        let sid = params.get_str_or("station_id", "S1");
-        let res = self.thermal_hub.execute_action(&action, params, &operator)?;
-        let should_audit = matches!(
-            action.as_str(),
-            "connect"
-                | "disconnect"
-                | "set_temp"
-                | "stop_preheat"
-                | "skip_preheat"
-                | "start_pid"
-                | "finish_control"
-                | "stop_heaters"
-                | "stop_fans"
-                | "emergency_stop"
-                | "pid_calibrate"
-                | "manual_duty"
-                | "start_record"
-                | "stop_record"
-        );
-        if should_audit {
-            let summary = match action.as_str() {
-                "connect" => format!(
-                    "连接 MCU 高温罩 ({})",
-                    params.get_str_or("mode", "serial")
-                ),
-                "disconnect" => "断开 MCU 高温罩连接".to_string(),
-                "set_temp" => format!(
-                    "MCU 开启设温控温: {}℃",
-                    params
-                        .get_i64("target_c")
-                        .or_else(|| params.get_i64("temp_c"))
-                        .unwrap_or(0)
-                ),
-                "stop_preheat" => "MCU 停止预加热/退出控温 (0x05)".to_string(),
-                "skip_preheat" => "MCU 跳过预热直接进入 PID (0x06)".to_string(),
-                "start_pid" => "MCU 直接启动 PID 闭环控温 (0x07)".to_string(),
-                "finish_control" => {
-                    let purge = params.get_bool("cooling_purge").unwrap_or(true);
-                    if purge {
-                        "MCU 控温结束并开启风扇吹扫散热 (0x08 00)".to_string()
-                    } else {
-                        "MCU 控温结束不吹扫 (0x08 01)".to_string()
-                    }
-                }
-                "stop_heaters" => "MCU 紧急停止并锁存全部加热块 (0x0A)".to_string(),
-                "stop_fans" => "MCU 停止并锁存全部风扇 (0x0B)".to_string(),
-                "emergency_stop" => "MCU 一键紧急全停(35路归零 + 停控温 + 锁死全部加热块)".to_string(),
-                "pid_calibrate" => format!(
-                    "MCU PID 参数标定: {}",
-                    params.get_str_or("expr", "(回读)")
-                ),
-                "manual_duty" => "MCU 35路全通道手动点火调试 (0x46)".to_string(),
-                "start_record" => format!(
-                    "开始本地高温测试全量记录: {}",
-                    res.get_str_or("csv_filename", "")
-                ),
-                "stop_record" => "停止本地高温测试全量记录".to_string(),
-                _ => format!("执行 MCU 温控动作: {}", action),
-            };
-            self.commit_audit(
-                &sid,
-                &operator,
-                AuditRecordDraft {
-                    category: "thermal_mcu".to_string(),
-                    action: action.clone(),
-                    summary,
-                    details: res.clone(),
-                },
-            );
-        }
-        Ok(res)
-    }
-
     fn execute_actor_command(
         &self,
         sid: &str,
@@ -795,10 +773,18 @@ impl AppHub {
                 Ok(info)
             }
             "ListStations" => {
+                let now = now_ms();
                 let mut arr = Vec::with_capacity(self.stations.len());
                 for handle in self.stations.values() {
                     if let Ok(guard) = handle.view.read() {
-                        arr.push(guard.list_summary.clone());
+                        let mut s = guard.list_summary.clone();
+                        patch_timing_fields(
+                            &mut s,
+                            guard.run_started_unix_ms,
+                            guard.run_ended_unix_ms,
+                            now,
+                        );
+                        arr.push(s);
                     }
                 }
                 let mut out = JsonVal::obj();
@@ -807,7 +793,13 @@ impl AppHub {
             }
             "GetStation" => {
                 let sid = params.get_str_or("station_id", "S1");
-                let view = self.read_station_view(&sid)?;
+                let mut view = self.read_station_view(&sid)?;
+                patch_timing_fields(
+                    &mut view.list_summary,
+                    view.run_started_unix_ms,
+                    view.run_ended_unix_ms,
+                    now_ms(),
+                );
                 Ok(view.list_summary)
             }
             "GetStationControl" => {
@@ -848,7 +840,8 @@ impl AppHub {
                     .get_i64("max_bytes")
                     .unwrap_or(65536)
                     .clamp(1, 262144) as usize;
-                let chunk = self.read_ring_chunk(&sid, false, offset, max_b, false)?;
+                let want_clean = method == "ReadBiosUart";
+                let chunk = self.read_ring_chunk(&sid, want_clean, offset, max_b, false)?;
                 let b64 = lib::b64_encode(&chunk.data);
                 let mut res = JsonVal::obj();
                 if method == "ReadBiosUart" {
@@ -1035,10 +1028,7 @@ impl AppHub {
                         res_obj.set("previous_boot_id", JsonVal::Str(actor_rep.prev_boot_id));
                         res_obj.set("boot_id", JsonVal::Str(actor_rep.boot_id));
                         res_obj.set("boot_observed", JsonVal::Bool(true));
-                        res_obj.set(
-                            "started_unix_ms",
-                            JsonVal::Str(actor_rep.started_ms.to_string()),
-                        );
+                        patch_timing_fields(&mut res_obj, actor_rep.started_ms, 0, now_ms());
                         if let Some(tb) = actor_rep.task_batch {
                             res_obj.set("task_batch", strip_private_keys_recursive(&tb));
                         }
@@ -1237,6 +1227,12 @@ impl AppHub {
                 if let Some(last) = view.task_history.last() {
                     out.set("latest_run", strip_private_keys_recursive(last));
                 }
+                patch_timing_fields(
+                    &mut out,
+                    view.run_started_unix_ms,
+                    view.run_ended_unix_ms,
+                    now_ms(),
+                );
                 Ok(out)
             }
             "EnqueueCommand" => {
@@ -1262,11 +1258,8 @@ impl AppHub {
                     return Ok(pending_item);
                 }
 
-                let exec_res = if sub_method == "ThermalAction" {
-                    self.execute_thermal_action(&sub_args, &operator)
-                } else {
-                    self.execute_actor_command(&sid, &sub_method, &sub_args, &operator)
-                };
+                let exec_res =
+                    self.execute_actor_command(&sid, &sub_method, &sub_args, &operator);
                 let completed_item = match exec_res {
                     Ok(res_val) => self.finalize_command(&cmd_id, |item| {
                         item.set("state", JsonVal::Str("succeeded".to_string()));
@@ -1376,14 +1369,6 @@ impl AppHub {
                 out.set("has_more", JsonVal::Bool(false));
                 Ok(out)
             }
-            "GetThermalConsole" => self.thermal_hub.get_snapshot(params),
-            "ThermalAction" => match self.execute_thermal_action(params, "web") {
-                Ok(res) => {
-                    self.refresh_and_broadcast_qt_state();
-                    Ok(res)
-                }
-                Err(msg) => Err(("FAILED_PRECONDITION".to_string(), msg)),
-            },
             other => Err((
                 "UNIMPLEMENTED".to_string(),
                 format!("不支持的 RPC 方法: {}", other),
@@ -1525,26 +1510,26 @@ fn handle_ws_loop(
                 break;
             }
 
-            // 4 stations * up to 8 chunks * 64KB monotonic `bios_uart` backfill & live push
+            // 4 stations * up to 8 chunks * 64KB monotonic `bios_uart` backfill & live push (cleaned ANSI-free text)
             if is_qt_clean {
                 for (sid, handle) in &push_hub_ref.stations {
-                    let (raw_base, raw_write) = if let Ok(g) = handle.uart_notify.state.lock() {
-                        (g.raw_base, g.raw_write)
+                    let (clean_base, clean_write) = if let Ok(g) = handle.uart_notify.state.lock() {
+                        (g.clean_base, g.clean_write)
                     } else {
                         continue;
                     };
-                    let default_start = raw_write.saturating_sub(8 * 65536).max(raw_base);
-                    let mut cur_off = (*uart_offsets.get(sid).unwrap_or(&default_start)).max(raw_base);
-                    if raw_write <= cur_off {
-                        uart_offsets.entry(sid.clone()).or_insert(raw_write);
+                    let default_start = clean_write.saturating_sub(8 * 65536).max(clean_base);
+                    let mut cur_off = (*uart_offsets.get(sid).unwrap_or(&default_start)).max(clean_base);
+                    if clean_write <= cur_off {
+                        uart_offsets.entry(sid.clone()).or_insert(clean_write);
                         continue;
                     }
                     for _ in 0..8 {
-                        if cur_off >= raw_write {
+                        if cur_off >= clean_write {
                             break;
                         }
                         let Ok(chunk) =
-                            push_hub_ref.read_ring_chunk(sid, false, cur_off, 65536, false)
+                            push_hub_ref.read_ring_chunk(sid, true, cur_off, 65536, false)
                         else {
                             break;
                         };
@@ -1758,61 +1743,6 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
         return;
     }
 
-    if let Some(fname) = path_only.strip_prefix("/api/thermal/logs/") {
-        let safe = !fname.is_empty()
-            && !fname.contains("..")
-            && !fname.contains('/')
-            && !fname.contains('\\')
-            && fname
-                .bytes()
-                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'));
-        if !safe {
-            let resp = "HTTP/1.1 400 Bad Request\r\nContent-Length: 11\r\nConnection: close\r\n\r\nBad Request";
-            let _ = stream.write_all(resp.as_bytes());
-            return;
-        }
-        let log_path = hub.thermal_hub.logs_dir.join(fname);
-        let Ok(mut f) = fs::File::open(&log_path) else {
-            let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\nConnection: close\r\n\r\nNot Found";
-            let _ = stream.write_all(resp.as_bytes());
-            return;
-        };
-        let Ok(meta) = f.metadata() else {
-            let resp = "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 21\r\nConnection: close\r\n\r\nInternal Server Error";
-            let _ = stream.write_all(resp.as_bytes());
-            return;
-        };
-        let ctype = if fname.ends_with(".csv") {
-            "text/csv; charset=utf-8"
-        } else if fname.ends_with(".jsonl") {
-            "application/x-ndjson; charset=utf-8"
-        } else {
-            "application/octet-stream"
-        };
-        let hdr = format!(
-            "HTTP/1.1 200 OK\r\nContent-Type: {}\r\nContent-Length: {}\r\nContent-Disposition: attachment; filename=\"{}\"\r\nCache-Control: no-cache\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n",
-            ctype,
-            meta.len(),
-            fname
-        );
-        if stream.write_all(hdr.as_bytes()).is_ok() && method == "GET" {
-            let mut chunk = vec![0u8; 65536];
-            loop {
-                match f.read(&mut chunk) {
-                    Ok(0) => break,
-                    Ok(n) => {
-                        if stream.write_all(&chunk[..n]).is_err() {
-                            break;
-                        }
-                    }
-                    Err(_) => break,
-                }
-            }
-        }
-        let _ = stream.flush();
-        return;
-    }
-
     let rel_path = path_only.trim_start_matches('/');
     let rel_clean = if rel_path.is_empty() {
         "index.html"

+ 165 - 35
native/stl_accel/src/commands.rs

@@ -13,7 +13,8 @@ use crate::results::{now_ms, AsyncScriptStep, StationState};
 use crate::storage::save_station_settings;
 use crate::workflow::{
     apply_profile_to_station, build_uefi_efi_probe_steps, build_uefi_mt_steps, control_boot_plan,
-    needs_uefi_efi_probe, normalize_boot_plan, start_async_script, submit_task_batch,
+    control_boot_plan_impl, needs_uefi_efi_probe, normalize_boot_plan, start_async_script,
+    submit_task_batch,
 };
 use std::path::Path;
 use std::sync::mpsc;
@@ -327,8 +328,7 @@ pub fn handle_station_command_nonblocking(
                         let pxe_server_ip = pxe_state.get_str_or("pxe_server_ip", "192.168.0.10");
                         let cfg_text = render_mt86_cfg_text(&st.mt_selection, &pxe_server_ip);
                         let pxe_host = pxe_state.get_str_or("pxe_host", "192.168.2.63");
-                        let variant = pxe_state.get_str_or("active_variant", "118_serial.efi");
-                        sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text, &variant);
+                        sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text);
                     } else if let Some(JsonVal::Obj(map)) =
                         args.get("mt").or_else(|| args.get("selection"))
                     {
@@ -362,7 +362,12 @@ pub fn handle_station_command_nonblocking(
             StationCmdExec::Immediate(Ok(res), Some(audit))
         }
         "ApplyErrorPreset" => {
-            let preset_id = args.get_str_or("preset_id", "safe_timing_pull_light");
+            let raw_preset = args.get_str_or("preset_id", "safe_trcd_trp_pull");
+            let preset_id = match raw_preset.as_str() {
+                "safe_timing_pull_light" | "" => "safe_trcd_trp_pull".to_string(),
+                "safe_refresh_pull" => "safe_trfc_pull".to_string(),
+                _ => raw_preset,
+            };
             let presets = FirmwareContract::safe_timing_pull_presets(fw_fam);
             let Some(found) = presets
                 .get_arr("presets")
@@ -378,15 +383,25 @@ pub fn handle_station_command_nonblocking(
                 );
             };
             if let Some(ovs) = found.get_arr("uip_overrides") {
-                st.uip_overrides = ovs.clone();
+                for ov in ovs {
+                    let id = ov.get_str_or("id", "");
+                    if !id.is_empty() {
+                        st.uip_overrides.retain(|x| x.get_str_or("id", "") != id);
+                        st.uip_overrides.push(ov.clone());
+                    }
+                }
             }
             save_station_settings(data_dir, st);
+            let preset_label = found
+                .get_str("label")
+                .or_else(|| found.get_str("name"))
+                .unwrap_or(&preset_id);
             let audit = AuditRecordDraft {
                 category: "ict_settings".to_string(),
                 action: "apply_error_preset".to_string(),
                 summary: format!(
                     "应用零加压安全时序拉偏预设 '{}' ({})",
-                    found.get_str_or("name", &preset_id),
+                    preset_label,
                     fw_fam
                 ),
                 details: found.clone(),
@@ -555,8 +570,7 @@ pub fn handle_station_command_nonblocking(
                 let pxe_server_ip = pxe_state.get_str_or("pxe_server_ip", "192.168.0.10");
                 let cfg_text = render_mt86_cfg_text(mt, &pxe_server_ip);
                 let pxe_host = pxe_state.get_str_or("pxe_host", "192.168.2.63");
-                let variant = pxe_state.get_str_or("active_variant", "118_serial.efi");
-                sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text, &variant);
+                sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text);
             }
             save_station_settings(data_dir, st);
             let mut details = JsonVal::obj();
@@ -651,7 +665,7 @@ pub fn handle_station_command_nonblocking(
                 );
                 return StationCmdExec::Immediate(Ok(res), None);
             }
-            let allow_partial = args.get_bool("allow_partial").unwrap_or(false);
+            let allow_partial = args.get_bool("allow_partial").unwrap_or(true);
             let mut steps: Vec<AsyncScriptStep> = lines
                 .iter()
                 .map(|ln| AsyncScriptStep {
@@ -716,7 +730,7 @@ pub fn handle_station_command_nonblocking(
                 action: "save_amt_settings".to_string(),
                 summary: format!(
                     "保存 AMT 配置:action={} · 覆盖命令 {} 条 ({})",
-                    settings.get_str_or("action", "skip"),
+                    settings.get_str_or("action", "run"),
                     cmds_preview.len(),
                     cmds_preview.join("; ")
                 ),
@@ -892,11 +906,12 @@ pub fn handle_station_command_nonblocking(
                 st.last_amt_start = Some(res.clone());
                 return StationCmdExec::Immediate(Ok(res), None);
             }
-            let test_cmd = effective_settings
+            let raw_test_cmd = effective_settings
                 .get_str("test_command")
                 .filter(|s| !s.trim().is_empty())
                 .map(|s| s.to_string())
                 .unwrap_or_else(|| st.amt_settings.get_str_or("test_command", "amemdiag 1"));
+            let test_cmd = st.resolve_amt_test_command(&raw_test_cmd);
             let mut steps: Vec<AsyncScriptStep> = setup_cmds
                 .iter()
                 .map(|ln| AsyncScriptStep {
@@ -949,6 +964,9 @@ pub fn handle_station_command_nonblocking(
                 return StationCmdExec::Immediate(Ok(res), None);
             }
             st.task_status = "completed".to_string();
+            if st.task_batch.get_str_or("state", "idle") != "running" {
+                st.freeze_run_timing(now_ms());
+            }
             st.boot_execution
                 .set("state", JsonVal::Str("completed".to_string()));
             st.boot_execution.set(
@@ -976,8 +994,7 @@ pub fn handle_station_command_nonblocking(
             let pxe_server_ip = pxe_state.get_str_or("pxe_server_ip", "192.168.0.10");
             let cfg_text = render_mt86_cfg_text(&sel, &pxe_server_ip);
             let pxe_host = pxe_state.get_str_or("pxe_host", "192.168.2.63");
-            let variant = pxe_state.get_str_or("active_variant", "118_serial.efi");
-            sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text, &variant);
+            sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text);
 
             st.mt_selection = sel.clone();
             st.boot_plan.set("mt_enabled", JsonVal::Bool(true));
@@ -1194,8 +1211,11 @@ pub fn handle_station_command_nonblocking(
             let pid = args.get_str_or("profile_id", "");
             let pname = args.get_str_or("name", "");
             st.saved_profiles.retain(|x| {
-                (!pid.is_empty() && x.get_str_or("profile_id", "") != pid)
-                    || (pid.is_empty() && x.get_str_or("name", "") != pname)
+                let x_pid = x.get_str_or("profile_id", "");
+                let x_name = x.get_str_or("name", "");
+                let match_pid = !pid.is_empty() && (x_pid == pid || x_name == pid);
+                let match_name = !pname.is_empty() && x_name == pname;
+                !match_pid && !match_name
             });
             save_station_settings(data_dir, st);
             let saved_list = st.saved_profiles.clone();
@@ -1287,15 +1307,105 @@ pub fn handle_station_command_nonblocking(
                         .set("state", JsonVal::Str("paused".to_string()));
                     let _ = control_boot_plan(st, "pause", data_dir);
                 }
-                "resume" | "confirm_dimm_replacement" => {
+                "resume" | "start" | "confirm_dimm_replacement" => {
+                    let prev_tb_state = st.task_batch.get_str_or("state", "idle");
                     st.confirm_dimm_replacement();
-                    st.task_batch
-                        .set("state", JsonVal::Str("running".to_string()));
-                    let _ = control_boot_plan(st, "resume", data_dir);
+                    if prev_tb_state == "queued" {
+                        let profiles = st
+                            .task_batch
+                            .get_arr("profiles")
+                            .cloned()
+                            .unwrap_or_default();
+                        let cur_p_idx = st
+                            .task_batch
+                            .get_i64("current_profile_index")
+                            .unwrap_or(0)
+                            .max(0) as usize;
+                        if let Some(first_profile) = profiles.get(cur_p_idx) {
+                            if let Err(e) = apply_profile_to_station(
+                                st,
+                                first_profile,
+                                contract,
+                                pxe_state,
+                                data_dir,
+                                pxe_tftp_dir,
+                            ) {
+                                return StationCmdExec::Immediate(Err(e), None);
+                            }
+                            st.single_run_active = false;
+                            st.task_batch
+                                .set("state", JsonVal::Str("running".to_string()));
+                            if let Err(e) = control_boot_plan_impl(st, "restart", data_dir, false) {
+                                return StationCmdExec::Immediate(Err(e), None);
+                            }
+                            let now = now_ms();
+                            let batch_id = st.task_batch.get_str_or("batch_id", "TB");
+                            let p_name = first_profile
+                                .get_str_or("name", &format!("Profile-{}", cur_p_idx + 1));
+                            let p_rep_total =
+                                first_profile.get_i64("repeat").unwrap_or(1).max(1);
+                            let mut r0 = JsonVal::obj();
+                            r0.set(
+                                "run_id",
+                                JsonVal::Str(format!("{}-P{}-R1", batch_id, cur_p_idx + 1)),
+                            );
+                            r0.set("profile_index", JsonVal::Num(cur_p_idx as f64));
+                            r0.set("profile_name", JsonVal::Str(p_name.clone()));
+                            r0.set("repeat_index", JsonVal::Num(1.0));
+                            r0.set("repeat_total", JsonVal::Num(p_rep_total as f64));
+                            r0.set("state", JsonVal::Str("running".to_string()));
+                            r0.set("verdict", JsonVal::Str("running".to_string()));
+                            r0.set("boot_id", JsonVal::Str(st.boot_id.clone()));
+                            r0.set("started_unix_ms", JsonVal::Str(now.to_string()));
+                            r0.set("ended_unix_ms", JsonVal::Str("0".to_string()));
+                            r0.set("log_path", JsonVal::Str(String::new()));
+                            r0.set("summary_path", JsonVal::Str(String::new()));
+                            let mut runs = st
+                                .task_batch
+                                .get_arr("runs")
+                                .cloned()
+                                .unwrap_or_default();
+                            runs.push(r0);
+                            st.task_batch.set("runs", JsonVal::Arr(runs));
+                            st.task_batch.set("current_repeat", JsonVal::Num(1.0));
+                            st.task_batch
+                                .set("current_profile_name", JsonVal::Str(p_name));
+                            st.task_batch
+                                .set("current_profile_repeats", JsonVal::Num(p_rep_total as f64));
+                            st.task_batch
+                                .set("updated_unix_ms", JsonVal::Str(now.to_string()));
+                            st.task_status = "running".to_string();
+                        } else {
+                            return StationCmdExec::Immediate(
+                                Err("任务队列中没有可启动的 Profile".to_string()),
+                                None,
+                            );
+                        }
+                    } else {
+                        st.task_batch
+                            .set("state", JsonVal::Str("running".to_string()));
+                        let _ = control_boot_plan(st, "resume", data_dir);
+                    }
                 }
                 "clear" => {
                     st.confirm_dimm_replacement();
+                    st.single_run_active = false;
+                    let now = now_ms();
+                    st.task_batch.set("batch_id", JsonVal::Str(String::new()));
                     st.task_batch.set("state", JsonVal::Str("idle".to_string()));
+                    st.task_batch.set("current_profile_index", JsonVal::Num(0.0));
+                    st.task_batch
+                        .set("current_profile_name", JsonVal::Str(String::new()));
+                    st.task_batch.set("current_repeat", JsonVal::Num(0.0));
+                    st.task_batch
+                        .set("current_profile_repeats", JsonVal::Num(0.0));
+                    st.task_batch.set("total_runs_completed", JsonVal::Num(0.0));
+                    st.task_batch.set("total_runs_planned", JsonVal::Num(0.0));
+                    st.task_batch.set("stop_on_fail", JsonVal::Bool(true));
+                    st.task_batch
+                        .set("created_unix_ms", JsonVal::Str("0".to_string()));
+                    st.task_batch
+                        .set("updated_unix_ms", JsonVal::Str(now.to_string()));
                     st.task_batch.set("profiles", JsonVal::Arr(Vec::new()));
                     st.task_batch.set("runs", JsonVal::Arr(Vec::new()));
                 }
@@ -1316,6 +1426,7 @@ pub fn handle_station_command_nonblocking(
             StationCmdExec::Immediate(Ok(st.task_batch.clone()), Some(audit))
         }
         "ConfigureConnections" => {
+            let prev_bmc_host = st.bmc_host.clone();
             if let Some(conns) = args.get("connections") {
                 if let Some(b) = conns.get("bmc") {
                     st.bmc_enabled = b.get_bool("enabled").unwrap_or(true);
@@ -1330,11 +1441,14 @@ pub fn handle_station_command_nonblocking(
                         }
                     }
                     st.ssh_alt_password = false;
-                    st.bmc_state = if st.bmc_enabled && !st.bmc_host.is_empty() {
-                        "online".to_string()
-                    } else {
-                        "disabled".to_string()
-                    };
+                    if st.bmc_host != prev_bmc_host || !st.bmc_enabled || st.bmc_host.is_empty() {
+                        st.server_power = "unknown".to_string();
+                        st.bmc_state = if st.bmc_enabled && !st.bmc_host.is_empty() {
+                            "offline".to_string()
+                        } else {
+                            "disabled".to_string()
+                        };
+                    }
                 }
                 if let Some(c) = conns.get("console") {
                     st.console_enabled = c.get_bool("enabled").unwrap_or(true);
@@ -1352,21 +1466,18 @@ pub fn handle_station_command_nonblocking(
                     let wgm = c.get_f64("write_gap_ms").unwrap_or(20.0);
                     st.write_gap_ms = if wgm > 0.0 { wgm } else { 20.0 };
                 }
-                if let Some(ch_cfg) = conns.get("chamber") {
-                    let sp = ch_cfg.get_str_or("serial_path", "");
-                    if !sp.contains("ttyUSB1") {
-                        st.chamber_serial_path = sp;
-                    }
-                    if let Some(tc) = ch_cfg.get_f64("target_c") {
-                        st.chamber_target_c = Some(tc);
-                    }
-                }
+            }
+            if st.bmc_host != prev_bmc_host {
+                st.reset_on_disconnect();
             }
             if st.bmc_host == "192.168.2.165" || st.console_host == "192.168.2.165" {
                 st.hot.fw_family = 2;
             } else if st.bmc_host == "192.168.2.166" || st.console_host == "192.168.2.166" {
                 st.hot.fw_family = 1;
+            } else if st.bmc_host != prev_bmc_host {
+                st.hot.fw_family = 0;
             }
+            st.next_reconnect_probe_ms = 0;
             let claimed = if st.bmc_enabled && !st.bmc_host.is_empty() {
                 st.bmc_host.as_str()
             } else if st.console_enabled && !st.console_host.is_empty() {
@@ -1421,8 +1532,8 @@ pub fn handle_station_command_nonblocking(
                     category: "pxe_mt86".to_string(),
                     action: "configure_pxe".to_string(),
                     summary: format!(
-                        "更新 PXE 与 mt86.cfg 多候选配置:版本 {} · Stage1 PXE={} · TSTLIST={}",
-                        pxe_snap.get_str_or("active_variant", "118_orig.efi"),
+                        "更新 PXE 与 mt86.cfg 多候选配置:{} · Stage1 PXE={} · TSTLIST={}",
+                        pxe_snap.get_str_or("active_efi", "118.efi"),
                         pxe_snap.get_bool("stage1_pxe_enabled").unwrap_or(false),
                         pxe_snap
                             .get("mt86_cfg")
@@ -1480,6 +1591,25 @@ pub fn handle_station_command_nonblocking(
                     None,
                 );
             }
+            if act == "host_off" && st.is_run_active() {
+                let now = now_ms();
+                st.freeze_run_timing(now);
+                st.single_run_active = false;
+                st.plan_paused = false;
+                st.async_script.clear();
+                st.task_status = "interrupted".to_string();
+                st.boot_execution.set("state", JsonVal::Str("stopped".to_string()));
+                st.boot_execution.set(
+                    "waiting_reason",
+                    JsonVal::Str("已发送主板关机指令,停止当前测试".to_string()),
+                );
+                st.boot_execution
+                    .set("updated_unix_ms", JsonVal::Num(now as f64));
+                if st.task_batch.get_str_or("state", "idle") == "running" {
+                    st.task_batch
+                        .set("state", JsonVal::Str("stopped".to_string()));
+                }
+            }
             StationCmdExec::DelegateIpmi {
                 kind: "power".to_string(),
                 sub_action: act,

+ 232 - 204
native/stl_accel/src/devices.rs

@@ -1,15 +1,14 @@
-// devices.rs — Non-blocking POSIX PTY / Serial (/dev/ttyUSB0, TCP, SSH, SOL),
-//              8B/20ms TX pacer, persistent IPMI shell worker, 24-ch BMC SDR parser,
-//              and local thermal chamber serial telemetry.
+// devices.rs — Non-blocking in-process libssh/libfreeipmi/libipmiconsole PTY & IPMI
+//              (/dev/ttyUSB0, TCP, SSH, IPMI SOL), 8B/20ms TX pacer, persistent libfreeipmi
+//              session worker, 24-ch BMC SDR parser, and local thermal chamber serial telemetry.
 
 use crate::lib;
 use crate::results::{now_ms, StationState};
 use std::collections::BTreeMap;
 use std::net::{SocketAddr, TcpStream};
 use std::path::Path;
-use std::process::Command;
 use std::sync::{Mutex, OnceLock};
-use std::time::{Duration, Instant};
+use std::time::Duration;
 
 static STATION_CLAIMED_HOSTS: OnceLock<Mutex<BTreeMap<String, String>>> = OnceLock::new();
 
@@ -80,6 +79,7 @@ pub fn resolve_reachable_bmc_host(preferred: &str, port: u16) -> String {
 
 pub fn open_station_pty(st: &mut StationState, data_dir: &Path) -> Result<(), String> {
     close_station_pty(st);
+    st.diag_last_error.clear();
     if !st.console_enabled {
         return Err("控制台未启用".to_string());
     }
@@ -186,6 +186,10 @@ pub fn open_station_pty(st: &mut StationState, data_dir: &Path) -> Result<(), St
         };
         if rc != 0 {
             mfd = -1;
+            if rc == -2 {
+                st.ssh_alt_password = !st.ssh_alt_password;
+                st.diag_last_error = "SSH/SOL 认证失败,已自动切换兼容密码".to_string();
+            }
         }
     }
 
@@ -193,7 +197,9 @@ pub fn open_station_pty(st: &mut StationState, data_dir: &Path) -> Result<(), St
         st.diag_state = "error".to_string();
         st.console_online = false;
         st.hot.console_online = false;
-        st.diag_last_error = "无法建立串口会话".to_string();
+        if st.diag_last_error.is_empty() {
+            st.diag_last_error = "无法建立串口会话".to_string();
+        }
         return Err(st.diag_last_error.clone());
     }
     let now = now_ms();
@@ -249,7 +255,7 @@ pub fn poll_station_pty(st: &mut StationState) -> isize {
             st.console_online = true;
             st.hot.console_online = true;
             st.observe_serial_chunk(&buf[..n as usize]);
-        } else if n < 0 || (st.pty_child_pid > 0 && unsafe { lib::c_pty_is_alive(st.pty_child_pid) } == 0) {
+        } else if n < 0 || (st.pty_child_pid <= -100 && unsafe { lib::c_pty_is_alive(st.pty_child_pid) } == 0) {
             let elapsed = now_ms().saturating_sub(st.pty_opened_ms);
             if auth_failed
                 || st.diag_last_error.starts_with("SSH 认证失败")
@@ -323,14 +329,12 @@ pub fn flush_tx_pacer(st: &mut StationState, now: i64) -> Result<(), String> {
     Ok(())
 }
 
-/// Persistent non-blocking `ipmitool shell` session managed by the dedicated per-station IPMI worker.
+/// Persistent non-blocking in-process `libfreeipmi` RMCP+ session managed by the per-station IPMI worker.
 pub struct PersistentIpmiSession {
     pub host: String,
     pub user: String,
     pub pass: String,
-    pub stdin_fd: i32,
-    pub stdout_fd: i32,
-    pub child_pid: i32,
+    pub handle: i32,
 }
 
 impl Default for PersistentIpmiSession {
@@ -339,184 +343,207 @@ impl Default for PersistentIpmiSession {
             host: String::new(),
             user: String::new(),
             pass: String::new(),
-            stdin_fd: -1,
-            stdout_fd: -1,
-            child_pid: -1,
+            handle: -1,
         }
     }
 }
 
 impl PersistentIpmiSession {
     pub fn close(&mut self) {
-        if self.stdin_fd >= 0 {
-            lib::close_fd(self.stdin_fd);
-        }
-        if self.stdout_fd >= 0 || self.child_pid > 0 {
+        if self.handle > 0 {
             unsafe {
-                lib::c_pty_close(self.stdout_fd, self.child_pid);
+                lib::c_ipmi_close(self.handle);
             }
         }
-        self.stdin_fd = -1;
-        self.stdout_fd = -1;
-        self.child_pid = -1;
+        self.handle = -1;
     }
 
     pub fn ensure_connected(&mut self, host: &str, user: &str, pass: &str) -> bool {
-        if self.stdin_fd >= 0
-            && self.stdout_fd >= 0
-            && self.child_pid > 0
+        if self.handle > 0
             && self.host == host
             && self.user == user
             && self.pass == pass
-            && unsafe { lib::c_pty_is_alive(self.child_pid) } != 0
+            && unsafe { lib::c_ipmi_is_alive(self.handle) } != 0
         {
             return true;
         }
         self.close();
-        let host_c = format!("{}\0", host);
+        let host_c = format!("{}\0", host.trim());
         let user_c = format!("{}\0", user);
         let pass_c = format!("{}\0", pass);
-        let mut in_fd = -1;
-        let mut out_fd = -1;
-        let mut pid = -1;
-        let rc = unsafe {
-            lib::c_spawn_persistent_ipmi_shell(
+        let h = unsafe {
+            lib::c_ipmi_open(
                 host_c.as_ptr(),
                 user_c.as_ptr(),
                 pass_c.as_ptr(),
                 17,
-                &mut in_fd,
-                &mut out_fd,
-                &mut pid,
+                3000,
             )
         };
-        if rc == 0 && in_fd >= 0 && out_fd >= 0 {
+        if h > 0 {
             self.host = host.to_string();
             self.user = user.to_string();
             self.pass = pass.to_string();
-            self.stdin_fd = in_fd;
-            self.stdout_fd = out_fd;
-            self.child_pid = pid;
-            // Wait up to 2000ms for the initial `ipmitool>` prompt so startup output
-            // never leaks into the first `exec_shell_cmd` call.
-            let epfd = unsafe { lib::stl_epoll_create() };
-            if epfd >= 0 {
-                unsafe {
-                    lib::stl_epoll_ctl_fd(epfd, lib::EPOLL_CTL_ADD, self.stdout_fd, lib::EPOLLIN, 1);
-                }
-            }
-            let mut acc = Vec::with_capacity(512);
-            let mut buf = [0u8; 1024];
-            let mut toks = [0u64; 4];
-            let mut evs = [0u32; 4];
-            let deadline = Instant::now() + Duration::from_millis(2000);
-            let mut ready = false;
-            while Instant::now() < deadline {
-                if epfd >= 0 {
-                    let rem = deadline.saturating_duration_since(Instant::now()).as_millis() as i32;
-                    let wait_ms = rem.clamp(1, 50);
-                    unsafe {
-                        lib::stl_epoll_wait_tokens(epfd, toks.as_mut_ptr(), evs.as_mut_ptr(), 4, wait_ms);
-                    }
-                }
-                let n = unsafe { lib::c_pty_read_nonblock(self.stdout_fd, buf.as_mut_ptr(), buf.len()) };
-                if n > 0 {
-                    acc.extend_from_slice(&buf[..n as usize]);
-                    if let Ok(s) = std::str::from_utf8(&acc) {
-                        if s.contains("ipmitool>") {
-                            ready = true;
-                            break;
-                        }
-                        if s.contains("Error:") || s.contains("Unable to establish") {
-                            break;
-                        }
-                    }
-                } else if n < 0 {
-                    break;
-                }
-            }
-            lib::close_fd(epfd);
-            if ready {
-                while unsafe { lib::c_pty_read_nonblock(self.stdout_fd, buf.as_mut_ptr(), buf.len()) } > 0 {}
-                true
-            } else {
-                self.close();
-                false
-            }
+            self.handle = h;
+            true
         } else {
             false
         }
     }
+}
 
-    /// Execute an interactive subcommand (e.g. `chassis power status`, `sdr list`) on the persistent `ipmitool shell`
-    /// using an epoll timeout on `stdout_fd` (no process fork per poll!).
-    pub fn exec_shell_cmd(&mut self, cmd_line: &str, timeout_ms: u64) -> Option<String> {
-        if self.stdin_fd < 0 || self.stdout_fd < 0 {
-            return None;
-        }
-        let mut tmp = [0u8; 4096];
-        while unsafe { lib::c_pty_read_nonblock(self.stdout_fd, tmp.as_mut_ptr(), tmp.len()) } > 0 {}
+impl Drop for PersistentIpmiSession {
+    fn drop(&mut self) {
+        self.close();
+    }
+}
 
-        let payload = format!("{}\n", cmd_line.trim());
-        if unsafe { lib::c_pty_write_bytes(self.stdin_fd, payload.as_ptr(), payload.len()) } < 0 {
-            self.close();
-            return None;
+pub fn parse_ipmi_raw_args(args: &[&str]) -> Result<(u8, u8, Vec<u8>), String> {
+    if args.len() < 3 || !args[0].eq_ignore_ascii_case("raw") {
+        return Err(format!("无效的 IPMI raw 指令: {}", args.join(" ")));
+    }
+    let parse_hex_byte = |tok: &str| -> Result<u8, String> {
+        let t = tok.trim();
+        let hex = t
+            .strip_prefix("0x")
+            .or_else(|| t.strip_prefix("0X"))
+            .unwrap_or(t);
+        if hex.is_empty() {
+            return Err(format!("无效的 IPMI 十六进制字节: {}", tok));
         }
-        let epfd = unsafe { lib::stl_epoll_create() };
-        if epfd >= 0 {
-            unsafe {
-                lib::stl_epoll_ctl_fd(epfd, lib::EPOLL_CTL_ADD, self.stdout_fd, lib::EPOLLIN, 1);
+        u8::from_str_radix(hex, 16)
+            .map_err(|_| format!("无效的 IPMI 十六进制字节: {}", tok))
+    };
+    let net_fn = parse_hex_byte(args[1])?;
+    let cmd = parse_hex_byte(args[2])?;
+    let mut payload = Vec::with_capacity(args.len().saturating_sub(3));
+    for tok in &args[3..] {
+        payload.push(parse_hex_byte(tok)?);
+    }
+    Ok((net_fn, cmd, payload))
+}
+
+fn exec_freeipmi_op(handle: i32, args: &[&str]) -> Result<String, (bool, String)> {
+    if handle <= 0 {
+        return Err((true, "IPMI 会话句柄无效".to_string()));
+    }
+    match args {
+        ["chassis", "power", "status"] | ["chassis", "status"] => {
+            let mut power_on: i32 = -1;
+            let mut buf = vec![0u8; 4096];
+            let rc = unsafe {
+                lib::c_ipmi_chassis_status(handle, &mut power_on, buf.as_mut_ptr(), buf.len())
+            };
+            if rc != 0 {
+                return Err((true, "读取 BMC chassis status 失败".to_string()));
             }
+            let nul = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
+            Ok(String::from_utf8_lossy(&buf[..nul]).into_owned())
         }
-        let deadline = Instant::now() + Duration::from_millis(timeout_ms);
-        let mut acc = Vec::with_capacity(4096);
-        let mut toks = [0u64; 4];
-        let mut evs = [0u32; 4];
-        while Instant::now() < deadline {
-            if epfd >= 0 {
-                let rem = deadline.saturating_duration_since(Instant::now()).as_millis() as i32;
-                let wait_ms = rem.clamp(1, 80);
-                unsafe {
-                    lib::stl_epoll_wait_tokens(epfd, toks.as_mut_ptr(), evs.as_mut_ptr(), 4, wait_ms);
+        ["chassis", "power", act] => {
+            let op = match *act {
+                "off" => lib::IPMI_CHASSIS_CONTROL_POWER_DOWN,
+                "on" => lib::IPMI_CHASSIS_CONTROL_POWER_UP,
+                "cycle" => lib::IPMI_CHASSIS_CONTROL_POWER_CYCLE,
+                "reset" => lib::IPMI_CHASSIS_CONTROL_HARD_RESET,
+                "soft" => lib::IPMI_CHASSIS_CONTROL_SOFT_SHUTDOWN,
+                other => {
+                    return Err((false, format!("不支持的电源动作: {}", other)));
                 }
+            };
+            let rc = unsafe { lib::c_ipmi_chassis_control(handle, op) };
+            if rc == 0 {
+                Ok(format!("Chassis Power Control: {}", act))
+            } else {
+                Err((true, format!("执行电源控制 {} 失败", act)))
             }
-            loop {
-                let n = unsafe { lib::c_pty_read_nonblock(self.stdout_fd, tmp.as_mut_ptr(), tmp.len()) };
-                if n > 0 {
-                    acc.extend_from_slice(&tmp[..n as usize]);
-                } else if n < 0 {
-                    lib::close_fd(epfd);
-                    self.close();
-                    return None;
-                } else {
-                    break;
-                }
+        }
+        ["sdr", "list"] | ["sdr", "elist"] | ["sensor", "list"] => {
+            let mut buf = vec![0u8; 131_072];
+            let mut out_len: usize = 0;
+            let rc = unsafe {
+                lib::c_ipmi_sdr_temp_list(handle, buf.as_mut_ptr(), buf.len(), &mut out_len)
+            };
+            if rc != 0 {
+                return Err((true, "读取 BMC SDR 传感器温度列表失败".to_string()));
             }
-            if let Ok(s) = std::str::from_utf8(&acc) {
-                if let Some(pos) = s.find("ipmitool>") {
-                    lib::close_fd(epfd);
-                    let cleaned = s[..pos].trim().to_string();
-                    if !cleaned.is_empty() && !cleaned.contains("Error:") && !cleaned.contains("Unable to establish") {
-                        return Some(cleaned);
-                    }
-                    return None;
-                }
+            let len = out_len.min(buf.len());
+            Ok(String::from_utf8_lossy(&buf[..len]).into_owned())
+        }
+        ["mc", "reset", "warm"] => {
+            let rc = unsafe { lib::c_ipmi_warm_reset(handle) };
+            if rc == 0 {
+                Ok("Sent warm reset command to MC".to_string())
+            } else {
+                Err((true, "BMC warm reset 指令失败".to_string()))
             }
         }
-        lib::close_fd(epfd);
-        // Never leave a timed-out in-flight command open; its delayed output would corrupt the next command.
-        self.close();
-        None
-    }
-}
-
-impl Drop for PersistentIpmiSession {
-    fn drop(&mut self) {
-        self.close();
+        ["mc", "info"] | ["lan", "print"] | ["sel", "elist"] | ["fru", "print"] => {
+            let kind = match args[0] {
+                "mc" => "mc\0",
+                "lan" => "lan\0",
+                "sel" => "sel\0",
+                "fru" => "fru\0",
+                _ => "mc\0",
+            };
+            let mut buf = vec![0u8; 131_072];
+            let mut out_len: usize = 0;
+            let rc = unsafe {
+                lib::c_ipmi_device_info(
+                    handle,
+                    kind.as_ptr(),
+                    buf.as_mut_ptr(),
+                    buf.len(),
+                    &mut out_len,
+                )
+            };
+            if rc != 0 {
+                return Err((true, format!("读取 BMC {} 信息失败", args.join(" "))));
+            }
+            let len = out_len.min(buf.len());
+            Ok(String::from_utf8_lossy(&buf[..len]).into_owned())
+        }
+        [first, ..] if first.eq_ignore_ascii_case("raw") => {
+            let (net_fn, cmd, payload) =
+                parse_ipmi_raw_args(args).map_err(|e| (false, e))?;
+            let mut rs_buf = [0u8; 260];
+            let mut out_len: usize = 0;
+            let rc = unsafe {
+                lib::c_ipmi_raw(
+                    handle,
+                    net_fn,
+                    cmd,
+                    if payload.is_empty() {
+                        std::ptr::null()
+                    } else {
+                        payload.as_ptr()
+                    },
+                    payload.len(),
+                    rs_buf.as_mut_ptr(),
+                    rs_buf.len(),
+                    &mut out_len,
+                )
+            };
+            if rc != 0 {
+                return Err((
+                    true,
+                    format!("IPMI raw 0x{:02X} 0x{:02X} 执行失败", net_fn, cmd),
+                ));
+            }
+            let len = out_len.min(rs_buf.len());
+            let hex_str = rs_buf[..len]
+                .iter()
+                .map(|b| format!("{:02x}", b))
+                .collect::<Vec<_>>()
+                .join(" ");
+            Ok(hex_str)
+        }
+        _ => Err((false, format!("不支持的 IPMI 指令: {}", args.join(" ")))),
     }
 }
 
-/// Execute BMC IPMI command via persistent shell first, falling back to dual-password (`Admin123@pl` / `ADMIN`) CLI.
+/// Execute BMC IPMI command via persistent in-process `libfreeipmi` session with dual-password
+/// (`Admin123@pl` / `ADMIN`) auto-fallback and transparent reconnect on stale session.
 /// Always runs on the dedicated per-station IPMI worker thread, NEVER blocking any Station Actor!
 pub fn run_ipmi_with_session(
     sess: Option<&mut PersistentIpmiSession>,
@@ -534,73 +561,60 @@ pub fn run_ipmi_with_session(
     } else {
         pass
     };
-    let joined = args.join(" ");
-    // Try persistent ipmitool shell for standard commands (no raw hex quotes issues)
-    if let Some(s) = sess {
-        if !args.iter().any(|a| a.contains(' ')) && s.ensure_connected(&resolved_host, user, primary_pass) {
-            let cmd_timeout_ms = if joined.starts_with("sdr") || joined.starts_with("sensor") {
-                14_000
-            } else {
-                2_500
-            };
-            if let Some(out) = s.exec_shell_cmd(&joined, cmd_timeout_ms) {
-                return Ok((resolved_host, out));
-            }
-        }
-    }
-    let out = Command::new("ipmitool")
-        .env("IPMI_PASSWORD", primary_pass)
-        .args([
-            "-I",
-            "lanplus",
-            "-N",
-            "1",
-            "-R",
-            "1",
-            "-H",
-            &resolved_host,
-            "-U",
-            user,
-            "-E",
-            "-C",
-            "17",
-        ])
-        .args(args)
-        .output()
-        .map_err(|e| format!("无法执行 ipmitool: {}", e))?;
-    if out.status.success() {
-        return Ok((resolved_host, String::from_utf8_lossy(&out.stdout).to_string()));
-    }
     let alt_pass = if primary_pass == "Admin123@pl" {
         "ADMIN"
     } else {
         "Admin123@pl"
     };
-    let out2 = Command::new("ipmitool")
-        .env("IPMI_PASSWORD", alt_pass)
-        .args([
-            "-I",
-            "lanplus",
-            "-N",
-            "1",
-            "-R",
-            "1",
-            "-H",
-            &resolved_host,
-            "-U",
-            user,
-            "-E",
-            "-C",
-            "17",
-        ])
-        .args(args)
-        .output()
-        .map_err(|e| format!("无法执行 ipmitool: {}", e))?;
-    if out2.status.success() {
-        return Ok((resolved_host, String::from_utf8_lossy(&out2.stdout).to_string()));
-    }
-    let stderr = String::from_utf8_lossy(&out.stderr).to_string();
-    Err(format!("BMC ({}) 命令返回非零: {}", resolved_host, stderr.trim()))
+
+    let mut local_sess = PersistentIpmiSession::default();
+    let s = match sess {
+        Some(existing) => existing,
+        None => &mut local_sess,
+    };
+
+    // Fast path: reuse already open session matching this host/user and either valid password
+    if s.handle > 0
+        && s.host == resolved_host
+        && s.user == user
+        && (s.pass == primary_pass || s.pass == alt_pass)
+        && unsafe { lib::c_ipmi_is_alive(s.handle) } != 0
+    {
+        match exec_freeipmi_op(s.handle, args) {
+            Ok(out) => return Ok((resolved_host, out)),
+            Err((false, e)) => return Err(format!("BMC ({}): {}", resolved_host, e)),
+            Err((true, _)) => {
+                // Mid-session drop or stale RMCP+ -> close & reconnect cleanly below
+                s.close();
+            }
+        }
+    }
+
+    let mut last_err = String::new();
+    for cand_pass in [primary_pass, alt_pass] {
+        if !s.ensure_connected(&resolved_host, user, cand_pass) {
+            last_err = format!("libfreeipmi 无法建立 RMCP+ 会话 ({})", resolved_host);
+            continue;
+        }
+        match exec_freeipmi_op(s.handle, args) {
+            Ok(out) => return Ok((resolved_host, out)),
+            Err((false, e)) => return Err(format!("BMC ({}): {}", resolved_host, e)),
+            Err((true, e)) => {
+                last_err = e;
+                s.close();
+            }
+        }
+    }
+
+    Err(format!(
+        "BMC ({}) IPMI 执行失败: {}",
+        resolved_host,
+        if last_err.is_empty() {
+            "连接或认证失败"
+        } else {
+            last_err.as_str()
+        }
+    ))
 }
 
 pub fn run_ipmi_cmd(host: &str, user: &str, pass: &str, args: &[&str]) -> Result<String, String> {
@@ -613,6 +627,7 @@ pub fn run_ipmi_cmd(host: &str, user: &str, pass: &str, args: &[&str]) -> Result
 /// Never writes to `st.chamber_current_c`!
 pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
     let now = now_ms();
+    let mut seen_valid = [false; 24];
     for line in sdr_output.lines() {
         let parts: Vec<&str> = line.split('|').map(|s| s.trim()).collect();
         if parts.len() < 2 {
@@ -635,6 +650,9 @@ pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
             }
         }
         if let Some(temp_c) = parsed_temp {
+            if slot_idx < 24 {
+                seen_valid[slot_idx] = true;
+            }
             if let Some(slot) = st.dimms.get_mut(slot_idx) {
                 slot.value_c = Some(temp_c);
                 slot.quality = "reported".to_string();
@@ -645,9 +663,19 @@ pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
                     slot.enabled = "enabled".to_string();
                 }
             }
+            st.backfill_completed_stages_for_slot(slot_idx);
             st.sync_dimm_to_soa(slot_idx);
         }
     }
+    for idx in 0..24 {
+        if !seen_valid[idx] && st.dimms[idx].source == "bmc_sdr" {
+            st.dimms[idx].value_c = None;
+            st.dimms[idx].quality = "unavailable".to_string();
+            st.dimms[idx].source.clear();
+            st.dimms[idx].received_ms = 0;
+            st.sync_dimm_to_soa(idx);
+        }
+    }
 }
 
 pub fn map_sdr_sensor_to_slot(sensor: &str) -> Option<usize> {

+ 187 - 9
native/stl_accel/src/lib.rs

@@ -2,6 +2,7 @@
 //          Monotonic 64-Bit mmap Ring Buffer, re2c DFA, epoll/timerfd & OpenCL FFI (v0.8.1.19)
 
 use crate::json::JsonVal;
+use std::path::Path;
 
 pub const STL_TAG_BRACKET: u32 = 1 << 0;
 pub const STL_TAG_PROMPT: u32 = 1 << 1;
@@ -261,21 +262,83 @@ extern "C" {
         out_master_fd: *mut i32,
         out_child_pid: *mut i32,
     ) -> i32;
-    pub fn c_spawn_persistent_ipmi_shell(
-        host: *const u8,
-        user: *const u8,
-        password: *const u8,
-        cipher_suite: i32,
-        out_stdin_fd: *mut i32,
-        out_stdout_fd: *mut i32,
-        out_child_pid: *mut i32,
-    ) -> i32;
     pub fn c_pty_read_nonblock(master_fd: i32, buf: *mut u8, cap: usize) -> isize;
     pub fn c_mcu_tty_read_nonblock(fd: i32, buf: *mut u8, cap: usize, is_serial: i32) -> isize;
     pub fn c_pty_write_bytes(master_fd: i32, buf: *const u8, len: usize) -> isize;
     pub fn c_pty_is_alive(child_pid: i32) -> i32;
     pub fn c_pty_close(master_fd: i32, child_pid: i32);
 
+    pub fn c_ssh_exec_capture(
+        host: *const u8,
+        port: i32,
+        user: *const u8,
+        password: *const u8,
+        cmd: *const u8,
+        out_buf: *mut u8,
+        out_cap: usize,
+        out_len: *mut usize,
+        timeout_ms: i32,
+    ) -> i32;
+    pub fn c_ssh_sftp_put_file(
+        host: *const u8,
+        port: i32,
+        user: *const u8,
+        password: *const u8,
+        local_path: *const u8,
+        remote_path: *const u8,
+        timeout_ms: i32,
+    ) -> i32;
+    pub fn c_ssh_sftp_get_file(
+        host: *const u8,
+        port: i32,
+        user: *const u8,
+        password: *const u8,
+        remote_path: *const u8,
+        local_path: *const u8,
+        timeout_ms: i32,
+    ) -> i32;
+
+    pub fn c_ipmi_open(
+        host: *const u8,
+        user: *const u8,
+        password: *const u8,
+        cipher_suite: i32,
+        timeout_ms: i32,
+    ) -> i32;
+    pub fn c_ipmi_close(handle: i32);
+    pub fn c_ipmi_is_alive(handle: i32) -> i32;
+    pub fn c_ipmi_chassis_status(
+        handle: i32,
+        out_power_on: *mut i32,
+        out_buf: *mut u8,
+        out_cap: usize,
+    ) -> i32;
+    pub fn c_ipmi_chassis_control(handle: i32, op: i32) -> i32;
+    pub fn c_ipmi_warm_reset(handle: i32) -> i32;
+    pub fn c_ipmi_raw(
+        handle: i32,
+        net_fn: u8,
+        cmd: u8,
+        payload: *const u8,
+        payload_len: usize,
+        out_buf: *mut u8,
+        out_cap: usize,
+        out_len: *mut usize,
+    ) -> i32;
+    pub fn c_ipmi_sdr_temp_list(
+        handle: i32,
+        out_buf: *mut u8,
+        out_cap: usize,
+        out_len: *mut usize,
+    ) -> i32;
+    pub fn c_ipmi_device_info(
+        handle: i32,
+        kind: *const u8,
+        out_buf: *mut u8,
+        out_cap: usize,
+        out_len: *mut usize,
+    ) -> i32;
+
     pub fn stl_opencl_query_info(out_info: *mut StlOpenClInfo);
     pub fn stl_batch_rescan_logs(
         buf_4k_aligned: *const u8,
@@ -677,3 +740,118 @@ pub fn opencl_or_cpu_reduce_rmt_margins(
     }
     (min_widths, eye_8x8)
 }
+
+pub const IPMI_CHASSIS_CONTROL_POWER_DOWN: i32 = 0x00;
+pub const IPMI_CHASSIS_CONTROL_POWER_UP: i32 = 0x01;
+pub const IPMI_CHASSIS_CONTROL_POWER_CYCLE: i32 = 0x02;
+pub const IPMI_CHASSIS_CONTROL_HARD_RESET: i32 = 0x03;
+pub const IPMI_CHASSIS_CONTROL_PULSE_DIAG: i32 = 0x04;
+pub const IPMI_CHASSIS_CONTROL_SOFT_SHUTDOWN: i32 = 0x05;
+
+#[inline]
+fn to_c_bytes(s: &str) -> Vec<u8> {
+    let mut v = Vec::with_capacity(s.len() + 1);
+    for &b in s.as_bytes() {
+        v.push(if b == 0 { b' ' } else { b });
+    }
+    v.push(0);
+    v
+}
+
+pub fn ssh_exec_capture(
+    host: &str,
+    port: u16,
+    user: &str,
+    password: &str,
+    cmd: &str,
+    timeout_ms: i32,
+) -> Result<(i32, String), String> {
+    let h = to_c_bytes(host.trim());
+    let u = to_c_bytes(user);
+    let p = to_c_bytes(password);
+    let c = to_c_bytes(cmd);
+    let mut buf = vec![0u8; 65536];
+    let mut out_len: usize = 0;
+    let rc = unsafe {
+        c_ssh_exec_capture(
+            h.as_ptr(),
+            port as i32,
+            u.as_ptr(),
+            p.as_ptr(),
+            c.as_ptr(),
+            buf.as_mut_ptr(),
+            buf.len(),
+            &mut out_len,
+            timeout_ms,
+        )
+    };
+    if rc < 0 {
+        return Err(format!("libssh exec failed (rc={})", rc));
+    }
+    let len = out_len.min(buf.len());
+    Ok((rc, String::from_utf8_lossy(&buf[..len]).into_owned()))
+}
+
+pub fn ssh_sftp_put_file(
+    host: &str,
+    port: u16,
+    user: &str,
+    password: &str,
+    local_path: &Path,
+    remote_path: &str,
+    timeout_ms: i32,
+) -> Result<(), String> {
+    let h = to_c_bytes(host.trim());
+    let u = to_c_bytes(user);
+    let p = to_c_bytes(password);
+    let lp = to_c_bytes(&local_path.to_string_lossy());
+    let rp = to_c_bytes(remote_path);
+    let rc = unsafe {
+        c_ssh_sftp_put_file(
+            h.as_ptr(),
+            port as i32,
+            u.as_ptr(),
+            p.as_ptr(),
+            lp.as_ptr(),
+            rp.as_ptr(),
+            timeout_ms,
+        )
+    };
+    if rc == 0 {
+        Ok(())
+    } else {
+        Err(format!("libssh SFTP put failed (rc={})", rc))
+    }
+}
+
+pub fn ssh_sftp_get_file(
+    host: &str,
+    port: u16,
+    user: &str,
+    password: &str,
+    remote_path: &str,
+    local_path: &Path,
+    timeout_ms: i32,
+) -> Result<(), String> {
+    let h = to_c_bytes(host.trim());
+    let u = to_c_bytes(user);
+    let p = to_c_bytes(password);
+    let rp = to_c_bytes(remote_path);
+    let lp = to_c_bytes(&local_path.to_string_lossy());
+    let rc = unsafe {
+        c_ssh_sftp_get_file(
+            h.as_ptr(),
+            port as i32,
+            u.as_ptr(),
+            p.as_ptr(),
+            rp.as_ptr(),
+            lp.as_ptr(),
+            timeout_ms,
+        )
+    };
+    if rc == 0 {
+        Ok(())
+    } else {
+        Err(format!("libssh SFTP get failed (rc={})", rc))
+    }
+}

Plik diff jest za duży
+ 840 - 275
native/stl_accel/src/main.rs


Plik diff jest za duży
+ 606 - 210
native/stl_accel/src/pxe.rs


Plik diff jest za duży
+ 709 - 55
native/stl_accel/src/results.rs


+ 15 - 13
native/stl_accel/src/storage.rs

@@ -74,7 +74,7 @@ pub fn load_station_settings(data_dir: &Path, stations: &mut BTreeMap<String, St
                     st.bmc_password = pw;
                 }
                 st.bmc_state = if st.bmc_enabled && !st.bmc_host.is_empty() {
-                    "online".to_string()
+                    "offline".to_string()
                 } else {
                     "disabled".to_string()
                 };
@@ -111,15 +111,6 @@ pub fn load_station_settings(data_dir: &Path, stations: &mut BTreeMap<String, St
                     }
                 }
             }
-            if let Some(ch_cfg) = conns.get("chamber") {
-                let sp = ch_cfg.get_str_or("serial_path", "");
-                if !sp.is_empty() && !sp.contains("ttyUSB1") {
-                    st.chamber_serial_path = sp;
-                }
-                if let Some(tc) = ch_cfg.get_f64("target_c") {
-                    st.chamber_target_c = Some(tc);
-                }
-            }
         }
         if st.bmc_host == "192.168.2.165" || st.console_host == "192.168.2.165" {
             st.hot.fw_family = 2;
@@ -147,7 +138,12 @@ pub fn load_station_settings(data_dir: &Path, stations: &mut BTreeMap<String, St
             st.boot_plan = bp.clone();
         }
         if let Some(tb) = saved.get("task_batch") {
-            st.task_batch = strip_private_keys_recursive(tb);
+            let mut clean_tb = strip_private_keys_recursive(tb);
+            if clean_tb.get_str_or("state", "idle") == "running" {
+                clean_tb.set("state", JsonVal::Str("interrupted".to_string()));
+                clean_tb.set("updated_unix_ms", JsonVal::Str(crate::results::now_ms().to_string()));
+            }
+            st.task_batch = clean_tb;
         }
         if let Some(th) = saved.get_arr("task_history") {
             st.task_history = th.iter().map(strip_private_keys_recursive).collect();
@@ -254,8 +250,10 @@ pub fn archive_task_run(
         o.set("cpu", JsonVal::Num(r.cpu as f64));
         o.set("state", JsonVal::Str(r.state.clone()));
         o.set("measurement_rows", JsonVal::Num(r.measurement_rows as f64));
-        o.set("min_dq_width", JsonVal::Num(r.min_dq_width as f64));
-        o.set("min_vref_width", JsonVal::Num(r.min_vref_width as f64));
+        let dq_w = if r.min_dq_width == i32::MAX { 0 } else { r.min_dq_width };
+        let vref_w = if r.min_vref_width == i32::MAX { 0 } else { r.min_vref_width };
+        o.set("min_dq_width", JsonVal::Num(dq_w as f64));
+        o.set("min_vref_width", JsonVal::Num(vref_w as f64));
         rmt_arr.push(o);
     }
     let mut amt_arr = Vec::new();
@@ -295,6 +293,10 @@ pub fn archive_task_run(
     disk_summary.set("amt_results", JsonVal::Arr(amt_arr));
     disk_summary.set("mt_result", st.mt_result.clone());
     disk_summary.set("stage_errors", stg_errs);
+    disk_summary.set(
+        "unsupported_commands",
+        JsonVal::Arr(st.unsupported_commands.clone()),
+    );
     disk_summary.set("profile_config", profile_cfg.clone());
     if !st.latest_mt_report_path.is_empty() {
         let src_html = Path::new(&st.latest_mt_report_path);

Plik diff jest za duży
+ 0 - 3730
native/stl_accel/src/thermal_mcu.rs


+ 192 - 71
native/stl_accel/src/workflow.rs

@@ -5,7 +5,9 @@ use crate::devices::{open_station_pty, write_station_paced};
 use crate::firmware::FirmwareContract;
 use crate::json::JsonVal;
 use crate::pxe::{render_mt86_cfg_text, sync_mt86_cfg_all_candidates};
-use crate::results::{has_firmware_error, now_ms, AsyncScriptStep, StationState};
+use crate::results::{
+    has_firmware_error, now_ms, patch_timing_fields, AsyncScriptStep, StationState,
+};
 use crate::storage::{archive_task_run, save_station_settings, strip_private_keys_recursive};
 use std::path::Path;
 
@@ -177,8 +179,26 @@ pub fn tick_async_script(st: &mut StationState) {
         st.async_script.collected_responses.push(entry);
 
         if st.async_script.reject_on_fw_error && (fw_rejected || !matched) {
-            if fw_rejected && st.async_script.allow_partial {
-                // Record partial rejection and continue to next command
+            if fw_rejected && matched && st.async_script.allow_partial {
+                let stage_tag = match st.async_script.context_tag.as_str() {
+                    "plan_uip2" => "ict_stage2",
+                    "plan_uip1" => "ict_stage1",
+                    "plan_amt" | "intent_amt" | "interactive_amt" => "amt",
+                    _ => {
+                        if st.observed_uip_stage.unwrap_or(1) > 1 {
+                            "ict_stage2"
+                        } else {
+                            "ict_stage1"
+                        }
+                    }
+                };
+                let sent_cmd = st.async_script.step_sent_line.clone();
+                st.record_unsupported_command(
+                    stage_tag,
+                    &sent_cmd,
+                    &out_str,
+                );
+                // Skip this unsupported command and continue remaining ICT commands + exit
             } else {
                 let err_msg = format!(
                     "固件拒绝或未响应命令 '{}': {}",
@@ -187,6 +207,11 @@ pub fn tick_async_script(st: &mut StationState) {
                 );
                 if st.async_script.context_tag.starts_with("plan_") {
                     st.task_status = "failed".to_string();
+                    let batch_continuing = st.task_batch.get_str_or("state", "idle") == "running"
+                        && !st.task_batch.get_bool("stop_on_fail").unwrap_or(true);
+                    if !batch_continuing {
+                        st.freeze_run_timing(now);
+                    }
                     st.boot_execution.set("state", JsonVal::Str("failed".to_string()));
                     st.boot_execution.set("error", JsonVal::Str(err_msg.clone()));
                     st.boot_execution.set("waiting_reason", JsonVal::Str(err_msg.clone()));
@@ -228,6 +253,11 @@ pub fn tick_async_script(st: &mut StationState) {
         if let Err(e) = write_station_paced(st, wire.as_bytes()) {
             if st.async_script.context_tag.starts_with("plan_") {
                 st.task_status = "failed".to_string();
+                let batch_continuing = st.task_batch.get_str_or("state", "idle") == "running"
+                    && !st.task_batch.get_bool("stop_on_fail").unwrap_or(true);
+                if !batch_continuing {
+                    st.freeze_run_timing(now);
+                }
                 st.boot_execution.set("state", JsonVal::Str("failed".to_string()));
                 st.boot_execution.set("error", JsonVal::Str(e.clone()));
                 st.boot_execution.set("waiting_reason", JsonVal::Str(e.clone()));
@@ -277,10 +307,6 @@ fn finish_async_script(st: &mut StationState, now: i64) {
     let tx_opt = st.async_script.completion_tx.take();
     st.async_script.clear();
 
-    let Some(tx) = tx_opt else {
-        return;
-    };
-
     let any_rejected = responses
         .iter()
         .any(|r| r.get_bool("rejected") == Some(true));
@@ -292,6 +318,30 @@ fn finish_async_script(st: &mut StationState, now: i64) {
         "submitted"
     };
 
+    if matches!(
+        tag.as_str(),
+        "interactive_uip" | "intent_uip" | "plan_uip1" | "plan_uip2"
+    ) && (!responses.is_empty() || !lines.is_empty())
+    {
+        let mut uip_res = JsonVal::obj();
+        uip_res.set("confirmation", JsonVal::Str(confirmation.to_string()));
+        uip_res.set(
+            "commands",
+            JsonVal::Arr(lines.iter().cloned().map(JsonVal::Str).collect()),
+        );
+        uip_res.set("responses", JsonVal::Arr(responses.clone()));
+        uip_res.set(
+            "unsupported_commands",
+            JsonVal::Arr(st.unsupported_commands.clone()),
+        );
+        uip_res.set("observed_unix_ms", JsonVal::Num(now as f64));
+        st.last_uip_apply = Some(uip_res);
+    }
+
+    let Some(tx) = tx_opt else {
+        return;
+    };
+
     let mut res = JsonVal::obj();
     match tag.as_str() {
         "interactive_uip" => {
@@ -301,6 +351,10 @@ fn finish_async_script(st: &mut StationState, now: i64) {
                 JsonVal::Arr(lines.into_iter().map(JsonVal::Str).collect()),
             );
             res.set("responses", JsonVal::Arr(responses));
+            res.set(
+                "unsupported_commands",
+                JsonVal::Arr(st.unsupported_commands.clone()),
+            );
             res.set("observed_unix_ms", JsonVal::Num(now as f64));
             st.last_uip_apply = Some(res.clone());
         }
@@ -431,6 +485,15 @@ pub fn control_boot_plan(
     st: &mut StationState,
     action: &str,
     data_dir: &Path,
+) -> Result<JsonVal, String> {
+    control_boot_plan_impl(st, action, data_dir, false)
+}
+
+pub fn control_boot_plan_impl(
+    st: &mut StationState,
+    action: &str,
+    data_dir: &Path,
+    preserve_batch_timer: bool,
 ) -> Result<JsonVal, String> {
     let now = now_ms();
     match action {
@@ -456,11 +519,16 @@ pub fn control_boot_plan(
                 st.diag_session_id = format!("D-{}-{}-{}", st.station_id, st.boot_seq, now);
                 st.hot.reset_for_new_boot(now);
                 st.hot.awaiting_reset_banner = true;
-                st.run_started_unix_ms = now;
+                st.in_internal_warm_reset = false;
+                if !preserve_batch_timer || st.run_started_unix_ms <= 0 {
+                    st.run_started_unix_ms = now;
+                }
+                st.run_ended_unix_ms = 0;
                 st.mt_started_unix_ms = 0;
                 st.mt_report_sync_pending = false;
                 st.mt_report_fetched_for_boot = false;
                 st.mt_waiting_report_until_ms = 0;
+                st.expected_mt_report_name.clear();
                 st.latest_mt_report_path.clear();
                 st.uefi_fs_candidates.clear();
                 st.resolved_mt_efi_path = None;
@@ -485,9 +553,12 @@ pub fn control_boot_plan(
                 }
                 st.reset_all_dimm_stages();
             } else {
-                if st.run_started_unix_ms == 0 {
+                if st.run_started_unix_ms <= 0
+                    || (!preserve_batch_timer && st.run_ended_unix_ms > 0)
+                {
                     st.run_started_unix_ms = now;
                 }
+                st.run_ended_unix_ms = 0;
                 st.diag_session_id = format!("D-{}-{}-{}", st.station_id, st.boot_seq.max(1), now);
             }
             st.awaiting_dimm_replacement = false;
@@ -505,7 +576,7 @@ pub fn control_boot_plan(
             if st.task_batch.get_str_or("state", "idle") != "running" {
                 st.single_run_active = true;
                 st.single_run_id = format!("RUN-{}-{}", st.station_id, now);
-                st.single_run_started_ms = now;
+                st.single_run_started_ms = st.run_started_unix_ms;
                 if matches!(st.single_run_profile, JsonVal::Null) {
                     st.single_run_profile = JsonVal::obj();
                 }
@@ -519,7 +590,8 @@ pub fn control_boot_plan(
             st.boot_execution.set("waiting_reason", JsonVal::Str(waiting_msg));
             st.boot_execution.set("handled_inputs", JsonVal::Arr(Vec::new()));
             st.boot_execution.set("error", JsonVal::Str(String::new()));
-            st.boot_execution.set("started_unix_ms", JsonVal::Num(now as f64));
+            st.boot_execution
+                .set("started_unix_ms", JsonVal::Num(st.run_started_unix_ms as f64));
             st.boot_execution.set("updated_unix_ms", JsonVal::Num(now as f64));
             if action == "restart" {
                 st.boot_execution
@@ -555,6 +627,10 @@ pub fn control_boot_plan(
         "stop" => {
             st.plan_paused = false;
             st.single_run_active = false;
+            st.freeze_run_timing(now);
+            if matches!(st.task_status.as_str(), "running" | "queued") {
+                st.task_status = "interrupted".to_string();
+            }
             st.async_script.clear();
             st.boot_execution.set("state", JsonVal::Str("stopped".to_string()));
             st.boot_execution.set(
@@ -713,55 +789,22 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
     if st.async_script.active || !st.tx_pacer.is_empty() {
         return;
     }
-    if st.awaiting_dimm_replacement || st.plan_paused || st.diag_state != "online" {
+    if st.awaiting_dimm_replacement || st.plan_paused {
         return;
     }
-
-    // Stop-on-Fail at stage boundaries before consuming any pre-stage intent
-    if st.prompt_ready {
-        let prompt_stage = match st.prompt_kind.as_str() {
-            "uip" => {
-                if st.prompt_uip_stage.unwrap_or(1) > 1 {
-                    "uip2"
-                } else {
-                    "uip1"
-                }
-            }
-            "amt" => "amt",
-            "uefi" => "uefi",
-            _ => "",
-        };
-        if matches!(prompt_stage, "amt" | "uip2" | "uefi")
-            && (st.check_and_latch_stage_failure("training")
-                || st.check_and_latch_stage_failure("rmt"))
-        {
-            return;
-        }
-        if matches!(prompt_stage, "uip2" | "uefi") {
-            st.finalize_running_amt_results();
-            if st.check_and_latch_stage_failure("amt") {
-                return;
-            }
-        }
-        consume_pending_stage_intent(st, contract);
-        if st.async_script.active || !st.tx_pacer.is_empty() {
-            return;
-        }
-    }
-
-    let state = st.boot_execution.get_str_or("state", "idle");
-    if matches!(
-        state.as_str(),
-        "idle" | "completed" | "blocked" | "failed" | "stopped" | "paused"
-    ) {
+    if st.hot.awaiting_reset_banner && st.bmc_enabled && !st.bmc_host.is_empty() {
         return;
     }
 
+    let state = st.boot_execution.get_str_or("state", "idle");
     let plan = normalize_boot_plan(&st.boot_plan);
     let mt_enabled = plan.get_bool("mt_enabled").unwrap_or(false) || st.plan_mt_started;
 
-    // Check MemTest86 completion (or explicit 118.efi not-found failure)
-    if mt_enabled
+    // Evaluate MemTest86 completion / failure / PXE HTML report sync timeout even if SOL transiently reconnecting
+    if !matches!(
+        state.as_str(),
+        "idle" | "completed" | "blocked" | "failed" | "stopped" | "paused"
+    ) && (mt_enabled || st.hot.mt_banner_seen)
         && (st.mt_result.get_bool("complete").unwrap_or(false) || st.hot.mt_fail_complete)
     {
         if st.mt_report_sync_pending && now_ms() < st.mt_waiting_report_until_ms {
@@ -780,6 +823,9 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
         let mt_status = st.mt_result.get_str_or("status", "pass");
         if mt_status == "pass" && st.hot.mt_pass_complete {
             st.task_status = "completed".to_string();
+            if st.task_batch.get_str_or("state", "idle") != "running" {
+                st.freeze_run_timing(now_ms());
+            }
             st.boot_execution
                 .set("state", JsonVal::Str("completed".to_string()));
             st.boot_execution
@@ -796,6 +842,58 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
         return;
     }
 
+    if st.diag_state != "online" {
+        return;
+    }
+
+    // Stop-on-Fail at stage boundaries before consuming any pre-stage intent
+    if st.prompt_ready {
+        let prompt_stage = match st.prompt_kind.as_str() {
+            "uip" => {
+                if st.prompt_uip_stage.unwrap_or(1) > 1 {
+                    "uip2"
+                } else {
+                    "uip1"
+                }
+            }
+            "amt" => "amt",
+            "uefi" => "uefi",
+            _ => "",
+        };
+        if matches!(prompt_stage, "amt" | "uip2" | "uefi")
+            && (st.check_and_latch_stage_failure("training")
+                || st.check_and_latch_stage_failure("rmt"))
+        {
+            return;
+        }
+        if matches!(prompt_stage, "uip2" | "uefi") {
+            st.finalize_running_amt_results();
+            if st.check_and_latch_stage_failure("amt") {
+                return;
+            }
+        }
+        let mt_finished = st.hot.mt_banner_seen
+            && (st.mt_result.get_bool("complete").unwrap_or(false)
+                || st.hot.mt_pass_complete
+                || st.hot.mt_fail_complete);
+        if !mt_finished {
+            consume_pending_stage_intent(st, contract);
+        }
+        if st.async_script.active || !st.tx_pacer.is_empty() {
+            return;
+        }
+    }
+
+    let plan = normalize_boot_plan(&st.boot_plan);
+    let mt_enabled = plan.get_bool("mt_enabled").unwrap_or(false) || st.plan_mt_started;
+    let state = st.boot_execution.get_str_or("state", "idle");
+    if matches!(
+        state.as_str(),
+        "idle" | "completed" | "blocked" | "failed" | "stopped" | "paused"
+    ) {
+        return;
+    }
+
     if !st.prompt_ready {
         return;
     }
@@ -858,6 +956,9 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
 
     if stage == "uefi" && !mt_enabled {
         st.task_status = "completed".to_string();
+        if st.task_batch.get_str_or("state", "idle") != "running" {
+            st.freeze_run_timing(now_ms());
+        }
         st.boot_execution
             .set("state", JsonVal::Str("completed".to_string()));
         st.boot_execution
@@ -906,7 +1007,7 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
                         st,
                         &format!("plan_{}", stage),
                         steps,
-                        false,
+                        true,
                         cmds,
                         JsonVal::Null,
                         None,
@@ -914,6 +1015,11 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
                 }
                 Err(e) => {
                     st.task_status = "failed".to_string();
+                    let batch_continuing = st.task_batch.get_str_or("state", "idle") == "running"
+                        && !st.task_batch.get_bool("stop_on_fail").unwrap_or(true);
+                    if !batch_continuing {
+                        st.freeze_run_timing(now_ms());
+                    }
                     st.boot_execution
                         .set("state", JsonVal::Str("failed".to_string()));
                     st.boot_execution.set("error", JsonVal::Str(e.clone()));
@@ -922,7 +1028,7 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
             }
         }
         "amt" => {
-            let act = st.amt_settings.get_str_or("action", "skip");
+            let act = st.amt_settings.get_str_or("action", "run");
             if act == "skip" {
                 // Exit dual-CPU AMT strictly in CPU0 then CPU1 order
                 if cpu > 0
@@ -942,7 +1048,8 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
                 let cmds = contract
                     .build_amt_commands_for_family(&st.amt_settings, fw_fam)
                     .unwrap_or_default();
-                let test_cmd = st.amt_settings.get_str_or("test_command", "amemdiag 1");
+                let raw_test_cmd = st.amt_settings.get_str_or("test_command", "amemdiag 1");
+                let test_cmd = st.resolve_amt_test_command(&raw_test_cmd);
                 let mut steps: Vec<AsyncScriptStep> = cmds
                     .iter()
                     .map(|ln| AsyncScriptStep {
@@ -1266,7 +1373,8 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
                 let cmds = contract
                     .build_amt_commands_for_family(&st.amt_settings, fw_fam)
                     .unwrap_or_default();
-                let test_cmd = st.amt_settings.get_str_or("test_command", "amemdiag 1");
+                let raw_test_cmd = st.amt_settings.get_str_or("test_command", "amemdiag 1");
+                let test_cmd = st.resolve_amt_test_command(&raw_test_cmd);
                 let mut steps: Vec<AsyncScriptStep> = cmds
                     .iter()
                     .map(|ln| AsyncScriptStep {
@@ -1349,6 +1457,9 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
             st.boot_plan.set("run_mt", JsonVal::Bool(false));
             st.hot.uefi_complete = true;
             st.task_status = "completed".to_string();
+            if st.task_batch.get_str_or("state", "idle") != "running" {
+                st.freeze_run_timing(now_ms());
+            }
             st.boot_execution
                 .set("state", JsonVal::Str("completed".to_string()));
             st.boot_execution
@@ -1392,13 +1503,6 @@ pub fn apply_profile_to_station(
         .or_else(|| profile.get("mt").and_then(|m| m.get_bool("enabled")))
         .unwrap_or(true);
 
-    if let Some(tc) = profile
-        .get_f64("target_temp")
-        .or_else(|| profile.get_f64("target_c"))
-    {
-        st.chamber_target_c = Some(tc);
-    }
-
     // 1. ICT overrides: accept either Web format `uip_overrides` or Qt format `memory_params` (`ecc`, `debuglog`, etc.) + `rmt`
     let mut uip_raws: Vec<String> = profile
         .get_arr("uip_raw_commands")
@@ -1422,7 +1526,7 @@ pub fn apply_profile_to_station(
         }
     }
 
-    let mut uip_ovs = if let Some(ovs) = profile.get_arr("uip_overrides") {
+    let mut uip_ovs = if let Some(ovs) = profile.get_arr("uip_overrides").filter(|v| !v.is_empty()) {
         ovs.clone()
     } else {
         let (built_ovs, built_raws) = FirmwareContract::memory_params_to_uip_overrides_for_family(
@@ -1438,6 +1542,11 @@ pub fn apply_profile_to_station(
         }
         built_ovs
     };
+    if profile.get_bool("run_rmt").is_some()
+        || profile.get("rmt").and_then(|r| r.get_bool("enabled")).is_some()
+    {
+        uip_ovs.retain(|x| x.get_str_or("id", "") != "rmt");
+    }
     if !uip_ovs.iter().any(|x| x.get_str_or("id", "") == "rmt") {
         let mut rmt_ov = JsonVal::obj();
         rmt_ov.set("id", JsonVal::Str("rmt".to_string()));
@@ -1522,8 +1631,7 @@ pub fn apply_profile_to_station(
         let pxe_server_ip = pxe_state.get_str_or("pxe_server_ip", "192.168.0.10");
         let cfg_text = render_mt86_cfg_text(&merged_mt, &pxe_server_ip);
         let pxe_host = pxe_state.get_str_or("pxe_host", "192.168.2.63");
-        let variant = pxe_state.get_str_or("active_variant", "118_serial.efi");
-        sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text, &variant);
+        sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text);
     }
 
     // 4. Boot plan: full auto with mt_enabled = run_mt
@@ -1603,6 +1711,8 @@ pub fn submit_task_batch(
         .unwrap_or_else(|| format!("TB-{}-{}", st.station_id, now));
     let stop_on_fail = args.get_bool("stop_on_fail").unwrap_or(true);
     let auto_start = args.get_bool("auto_start").unwrap_or(true);
+    let continue_timer =
+        args.get_bool("continue_timer") == Some(true) && st.run_started_unix_ms > 0;
 
     let first_profile = &normalized_profiles[0];
     apply_profile_to_station(st, first_profile, contract, pxe_state, data_dir, pxe_tftp_dir)?;
@@ -1616,7 +1726,7 @@ pub fn submit_task_batch(
 
     let mut runs_arr = Vec::new();
     if auto_start {
-        let _ = control_boot_plan(st, "restart", data_dir)?;
+        let _ = control_boot_plan_impl(st, "restart", data_dir, continue_timer)?;
         let mut r0 = JsonVal::obj();
         r0.set("run_id", JsonVal::Str(format!("{}-P1-R1", batch_id)));
         r0.set("profile_index", JsonVal::Num(0.0));
@@ -1700,7 +1810,9 @@ fn emit_complete_signal(
         "summary_path",
         JsonVal::Str(summary_obj.get_str_or("log_clean_path", "")),
     );
-    sig.set("observed_unix_ms", JsonVal::Str(now_ms().to_string()));
+    let now = now_ms();
+    sig.set("observed_unix_ms", JsonVal::Str(now.to_string()));
+    patch_timing_fields(&mut sig, st.run_started_unix_ms, st.run_ended_unix_ms, now);
     st.pending_complete_signal = Some(sig);
 }
 
@@ -1712,6 +1824,9 @@ pub fn step_task_batch(
     data_dir: &Path,
     pxe_tftp_dir: &Path,
 ) {
+    if st.mt_report_sync_pending && now_ms() < st.mt_waiting_report_until_ms {
+        return;
+    }
     let bp_state = st.boot_execution.get_str_or("state", "idle");
     if !matches!(bp_state.as_str(), "completed" | "failed" | "blocked") {
         return;
@@ -1719,10 +1834,11 @@ pub fn step_task_batch(
 
     let b_state = st.task_batch.get_str_or("state", "idle");
     if b_state != "running" {
+        let now = now_ms();
+        st.freeze_run_timing(now);
         // Universal archiving + active complete push for standalone / frontend-queue runs!
         if st.single_run_active {
             st.single_run_active = false;
-            let now = now_ms();
             let run_id = if st.single_run_id.is_empty() {
                 format!("RUN-{}-{}", st.station_id, now)
             } else {
@@ -1741,7 +1857,9 @@ pub fn step_task_batch(
                 st.task_status = "failed".to_string();
                 "fail"
             };
-            let started_ms = if st.single_run_started_ms > 0 {
+            let started_ms = if st.run_started_unix_ms > 0 {
+                st.run_started_unix_ms
+            } else if st.single_run_started_ms > 0 {
                 st.single_run_started_ms
             } else {
                 now
@@ -1785,6 +1903,7 @@ pub fn step_task_batch(
         st.task_batch
             .set("state", JsonVal::Str("completed".to_string()));
         st.task_status = "completed".to_string();
+        st.freeze_run_timing(now);
         return;
     }
     let cur_profile = &profiles[cur_p_idx];
@@ -1842,6 +1961,7 @@ pub fn step_task_batch(
         st.awaiting_dimm_replacement = true;
         st.hot.awaiting_dimm_replacement = true;
         st.plan_paused = true;
+        st.freeze_run_timing(now);
         emit_complete_signal(st, &run_id, &batch_id, verdict, &summary_obj, true);
         save_station_settings(data_dir, st);
         return;
@@ -1858,6 +1978,7 @@ pub fn step_task_batch(
         st.task_batch
             .set("state", JsonVal::Str("completed".to_string()));
         st.task_status = "completed".to_string();
+        st.freeze_run_timing(now);
         emit_complete_signal(st, &run_id, &batch_id, verdict, &summary_obj, true);
         save_station_settings(data_dir, st);
         return;
@@ -1873,7 +1994,7 @@ pub fn step_task_batch(
     st.single_run_active = false;
     st.task_batch
         .set("state", JsonVal::Str("running".to_string()));
-    let _ = control_boot_plan(st, "restart", data_dir);
+    let _ = control_boot_plan_impl(st, "restart", data_dir, true);
 
     let mut next_run = JsonVal::obj();
     next_run.set(

+ 82 - 0
native/stl_accel/stl_accel.h

@@ -3,6 +3,7 @@
 
 #include <stddef.h>
 #include <stdint.h>
+#include <sys/types.h>
 
 #ifdef __cplusplus
 extern "C" {
@@ -191,6 +192,87 @@ int     stl_open_tty_115200_raw(const char *path);
 int64_t stl_ws_writev2(int fd, const uint8_t *hdr, size_t hdr_len, const uint8_t *body, size_t body_len);
 void    stl_pin_thread_to_core(int core_index);
 
+int     c_pty_open_serial_115200(const char *path);
+int     c_open_tty_baud_raw(const char *path, int baud);
+int     c_open_mcu_tty_baud_raw(const char *path, int baud);
+int     c_pty_open_tcp_serial(const char *host, int port, int timeout_ms);
+int     c_pty_spawn_ssh_console(
+    const char *host,
+    int         port,
+    const char *user,
+    const char *password,
+    const char *known_hosts_path,
+    int        *out_master_fd,
+    int        *out_child_pid);
+int     c_pty_spawn_ipmi_sol(
+    const char *host,
+    const char *user,
+    const char *password,
+    int        *out_master_fd,
+    int        *out_child_pid);
+ssize_t c_pty_read_nonblock(int master_fd, uint8_t *buf, size_t cap);
+ssize_t c_mcu_tty_read_nonblock(int fd, uint8_t *buf, size_t cap, int is_serial);
+ssize_t c_pty_write_bytes(int master_fd, const uint8_t *buf, size_t len);
+int     c_pty_is_alive(int child_pid);
+void    c_pty_close(int master_fd, int child_pid);
+
+/* In-process libssh exec + SFTP atomic file transfer */
+int     c_ssh_exec_capture(
+    const char *host,
+    int         port,
+    const char *user,
+    const char *password,
+    const char *cmd,
+    char       *out_buf,
+    size_t      out_cap,
+    size_t     *out_len,
+    int         timeout_ms);
+int     c_ssh_sftp_put_file(
+    const char *host,
+    int         port,
+    const char *user,
+    const char *password,
+    const char *local_path,
+    const char *remote_path,
+    int         timeout_ms);
+int     c_ssh_sftp_get_file(
+    const char *host,
+    int         port,
+    const char *user,
+    const char *password,
+    const char *remote_path,
+    const char *local_path,
+    int         timeout_ms);
+
+/* In-process libfreeipmi persistent session & telemetry */
+int     c_ipmi_open(
+    const char *host,
+    const char *user,
+    const char *password,
+    int         cipher_suite,
+    int         timeout_ms);
+void    c_ipmi_close(int handle);
+int     c_ipmi_is_alive(int handle);
+int     c_ipmi_chassis_status(int handle, int *out_power_on, char *out_buf, size_t out_cap);
+int     c_ipmi_chassis_control(int handle, int op);
+int     c_ipmi_warm_reset(int handle);
+int     c_ipmi_raw(
+    int            handle,
+    uint8_t        net_fn,
+    uint8_t        cmd,
+    const uint8_t *payload,
+    size_t         payload_len,
+    uint8_t       *out_buf,
+    size_t         out_cap,
+    size_t        *out_len);
+int     c_ipmi_sdr_temp_list(int handle, char *out_buf, size_t out_cap, size_t *out_len);
+int     c_ipmi_device_info(
+    int         handle,
+    const char *kind,
+    char       *out_buf,
+    size_t      out_cap,
+    size_t     *out_len);
+
 /* =========================================================================
  * 6. OpenCL Gen7.5-Gen9.5 Zero-Copy Batch Offload (Auto CPU Fallback)
  * ========================================================================= */

+ 67 - 15
src/backendlink.cpp

@@ -15,6 +15,7 @@
 #include <QJsonObject>
 #include <QNetworkProxy>
 #include <QNetworkRequest>
+#include <QRegularExpression>
 #include <QSaveFile>
 #include <QUrl>
 #include <QUuid>
@@ -474,19 +475,27 @@ void BackendLink::onTextMessage(const QString &json)
                         m_stageErrorsJson[index].clear();
                         m_lastVerdict[index].clear();
                     }
+                    // 后端多 Profile 批次中间单轮完成(batch_complete=false 且未失败):
+                    // 只推快照和日志,不推进本地队列终态也不触发降温收尾。
+                    const QString verdict = result.value(QStringLiteral("verdict")).toString();
+                    const bool batchIntermediate = result.contains(QStringLiteral("batch_complete"))
+                                                   && !result.value(QStringLiteral("batch_complete")).toBool(true)
+                                                   && taskStatus != QStringLiteral("failed")
+                                                   && verdict != QStringLiteral("fail");
                     // 快照事件与「队列推进」分开去重:
                     // StageAction/GetCommand 的 complete=true 可能先到并占用
                     // m_lastTaskCompleteBoot;不能因此吞掉后到的 verdict/stage_completions。
                     const bool newSnapshot = bootId.isEmpty()
                                              || bootId != m_lastTaskCompleteEventBoot[index];
                     if (newSnapshot) {
-                        if (!bootId.isEmpty())
+                        if (!bootId.isEmpty() && !batchIntermediate)
                             m_lastTaskCompleteEventBoot[index] = bootId;
                         emit taskCompleteArrived(index, result);
                     }
 
                     // 队列终态单独去重,命令回执先到时事件只补快照、不重复推进。
-                    if (bootId.isEmpty() || bootId != m_lastTaskCompleteBoot[index]) {
+                    if (!batchIntermediate
+                        && (bootId.isEmpty() || bootId != m_lastTaskCompleteBoot[index])) {
                         if (!bootId.isEmpty())
                             m_lastTaskCompleteBoot[index] = bootId;
                         m_lastTaskStatus[index] = taskStatus;
@@ -700,7 +709,6 @@ void BackendLink::applyStation(int station, const QJsonObject &st)
         m_lastTaskCompleteBoot[station].clear();
         m_waitingNewBoot[station] = false;
         m_lastTaskStatus[station].clear();
-        m_uartSeen[station] = false;           // 新一轮重新统计,便于诊断
         m_stageErrorsJson[station].clear();    // 新一轮允许重新报告相同内容
         m_lastVerdict[station].clear();        // 新一轮的 verdict 重新计
     }
@@ -1079,7 +1087,7 @@ void BackendLink::submitStageAction(int station, const QString &inputId,
     });
 }
 
-bool BackendLink::startTest(int station)
+bool BackendLink::startTest(int station, bool continueTimer)
 {
     if (station < 0 || station >= kStationCount)
         return false;
@@ -1157,10 +1165,13 @@ bool BackendLink::startTest(int station)
     m_uartMuteMs[station] = nowMs();
     m_uartDropped[station] = 0;
     m_uartPending[station].clear();
+    m_uartLastWasCr[station] = false;
 
     QJsonObject params;
     params.insert(QStringLiteral("command_id"), commandId);
     params.insert(QStringLiteral("station_id"), stationId(station));
+    if (continueTimer)
+        params.insert(QStringLiteral("continue_timer"), true);
 
     trackCommand(commandId, station);
     m_startPending[station] = true;
@@ -1556,6 +1567,7 @@ void BackendLink::applyBiosUart(const QJsonObject &result)
         m_uartSession[station] = session;
         m_uartOffset[station] = 0;
         m_uartPending[station].clear();
+        m_uartLastWasCr[station] = false;
         m_uartMuted[station] = false;   // 新会话出现:解除静音,正常显示
         m_uartDropped[station] = 0;
     }
@@ -1568,11 +1580,14 @@ void BackendLink::applyBiosUart(const QJsonObject &result)
         return;                         // 重连重放的已显示字节,跳过
 
     if (first > m_uartOffset[station]) {
-        // 本地游标落后于后端这一包的起始偏移(后端清过缓存、或重连后从「当前偏移」推):
-        // 以前这里直接 return,游标就永久卡住、日志彻底断流。缺口丢掉,从这一包继续。
-        qInfo().noquote() << "[backend]" << sid << "UART 字节缺口" << m_uartOffset[station]
-                          << "→" << first << ",丢弃缺口并从新偏移继续";
+        // 首次连接回填往往从环形缓冲当前窗口起点开始(offset > 0 且本地 m_uartOffset == 0),
+        // 属于正常回填窗口跳过已滚动淘汰的旧字节,不记误导性的缺口告警。
+        if (m_uartOffset[station] > 0) {
+            qInfo().noquote() << "[backend]" << sid << "UART 字节缺口" << m_uartOffset[station]
+                              << "→" << first << ",丢弃缺口并从新偏移继续";
+        }
         m_uartPending[station].clear(); // 缺口后的残留半行不可信
+        m_uartLastWasCr[station] = false;
         m_uartOffset[station] = first;
     }
 
@@ -1599,13 +1614,50 @@ void BackendLink::applyBiosUart(const QJsonObject &result)
         return;
     }
 
+    // 兼容 \r\n、\n 与双路 AMT 菜单仅回显 \r 的切行,并在分包截断 \r\n 时吞掉下一包首字节 \n
     m_uartPending[station].append(bytes);
-    int newline = -1;
-    while ((newline = m_uartPending[station].indexOf('\n')) >= 0) {
-        QByteArray line = m_uartPending[station].left(newline);
-        m_uartPending[station].remove(0, newline + 1);
-        if (line.endsWith('\r'))
-            line.chop(1);
-        emit logLine(station, QString::fromUtf8(line));
+    QByteArray &pending = m_uartPending[station];
+    int pos = 0;
+    const int total = pending.size();
+    while (pos < total) {
+        if (m_uartLastWasCr[station]) {
+            m_uartLastWasCr[station] = false;
+            if (pending.at(pos) == '\n') {
+                ++pos;
+                continue;
+            }
+        }
+        int eol = -1;
+        char eolCh = 0;
+        for (int i = pos; i < total; ++i) {
+            const char ch = pending.at(i);
+            if (ch == '\r' || ch == '\n') {
+                eol = i;
+                eolCh = ch;
+                break;
+            }
+        }
+        if (eol < 0)
+            break;
+        const QByteArray line = pending.mid(pos, eol - pos);
+        QString text = QString::fromUtf8(line);
+        if (text.contains(QChar(0x1B))) {
+            static const QRegularExpression ansiRe(
+                QStringLiteral("\\x1B(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1B]*(?:\\x07|\\x1B\\\\))"));
+            text.remove(ansiRe);
+            text.remove(QChar(0x1B));
+        }
+        emit logLine(station, text);
+        pos = eol + 1;
+        if (eolCh == '\r') {
+            if (pos < total) {
+                if (pending.at(pos) == '\n')
+                    ++pos;
+            } else {
+                m_uartLastWasCr[station] = true;
+            }
+        }
     }
+    if (pos > 0)
+        pending.remove(0, pos);
 }

+ 3 - 1
src/backendlink.h

@@ -44,8 +44,9 @@ public:
     QString url() const { return m_url; }
 
     /** 点「开始测试」:StartTest(只有 station_id + command_id,不提交 plan、不保存参数)。
+     *  continueTimer=true 表示多任务队列延续同一批总计时,不重置后端 started_unix_ms。
      *  该工位已有未结束的 StartTest 时返回 false(防重复点击排入两次重启)。 */
-    bool startTest(int station);
+    bool startTest(int station, bool continueTimer = false);
 
     /** 0.8.1.19:换条停机挂起时确认已更换 DIMM,清掉后端 blocked 状态。
      *  旧版后端没有这个方法时只会记一条 UNIMPLEMENTED 日志,不影响继续点开始测试。 */
@@ -177,6 +178,7 @@ private:
     QString m_uartSession[4];
     quint64 m_uartOffset[4] = {0, 0, 0, 0};
     QByteArray m_uartPending[4];
+    bool m_uartLastWasCr[4] = {false, false, false, false}; // 上一包末尾是 \r,下一包若以 \n 开头需吞掉配对 LF
     bool m_uartMuted[4] = {false, false, false, false};   // 点了开始测试后:丢弃旧会话残留字节(限时,见 m_uartMuteMs)
     qint64 m_uartMuteMs[4] = {0, 0, 0, 0};                // 静音开始时间(超时自动解除,防止永久静音)
     int m_uartDropped[4] = {0, 0, 0, 0};                  // 静音窗口内丢弃的字节数(解除时提示一次)

+ 1 - 1
src/createtaskdialog.cpp

@@ -497,7 +497,7 @@ CreateTaskDialog::CreateTaskDialog(QWidget *parent)
     connect(ui->taskTabs, &QTabWidget::currentChanged, this, syncFooter);
     syncFooter(ui->taskTabs->currentIndex());
 
-    ui->targetTempEdit->setValidator(new QIntValidator(40, 90, ui->targetTempEdit));
+    ui->targetTempEdit->setValidator(new QIntValidator(1, 254, ui->targetTempEdit));
 
     // 配置页的初始值取 S1 已存配置(不再按工位分别维护一份)
     m_baseCfg = LocalPlans::stationConfig(0);

+ 27 - 2
src/detailview.cpp

@@ -40,6 +40,7 @@
 #include <QStyle>
 #include <QSplitter>
 #include <QVBoxLayout>
+#include <cmath>
 
 namespace {
 
@@ -440,8 +441,10 @@ void DetailView::setupCurvePlot()
     p->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight);
 
     // 最新点:一个白底蓝边的小圆点 + 下面的温度数值(跟着数据一起走,见 renderCurve)
+    // 初始无数据时不要绑定 graph,否则 QCustomPlot 重绘会刷 "QCPItemTracer::updatePosition() graph has no data"
     m_lastDot = new QCPItemTracer(p);
-    m_lastDot->setGraph(g);
+    m_lastDot->setGraph(nullptr);
+    m_lastDot->setVisible(false);
     m_lastDot->setStyle(QCPItemTracer::tsCircle);
     m_lastDot->setSize(5);
     m_lastDot->setPen(QPen(QColor("#2f7fc1"), 1.6));
@@ -497,9 +500,18 @@ void DetailView::renderCurve()
 
     QVector<double> keys(n);
     QVector<double> values(n);
+    double minV = 90.0;
+    double maxV = 20.0;
+    bool hasValid = false;
     for (int i = 0; i < n; ++i) {
         keys[i] = start + i;             // 全局采样序号,不回绕
-        values[i] = sel->history.at(i);
+        const double v = sel->history.at(i);
+        values[i] = v;
+        if (v >= 0.0) {
+            if (!hasValid || v < minV) minV = v;
+            if (!hasValid || v > maxV) maxV = v;
+            hasValid = true;
+        }
     }
 
     QCPGraph *g = p->graph(0);
@@ -515,11 +527,23 @@ void DetailView::renderCurve()
         lo = 0;                          // 还没满 200 点时从 0 开始铺,不从负数起
     p->xAxis->setRange(lo, lo + kTempHistorySize);
 
+    // 纵轴保持 20~90 °C 默认观感;若出现超出该区间的有效温度点则按 5 °C 对齐动态扩展,防止曲线裁剪
+    double yLo = 20.0;
+    double yHi = 90.0;
+    if (hasValid) {
+        if (minV < yLo)
+            yLo = qMax(0.0, std::floor((minV - 5.0) / 5.0) * 5.0);
+        if (maxV > yHi)
+            yHi = qMin(260.0, std::ceil((maxV + 5.0) / 5.0) * 5.0);
+    }
+    p->yAxis->setRange(yLo, yHi);
+
     // 最新点标记 + 数值标签:贴在最后一个采样点下方
     if (m_lastDot && m_lastLabel && n > 0) {
         const double k = keys.last();
         const double v = values.last();
 
+        m_lastDot->setGraph(g);
         m_lastDot->setGraphKey(k);
         m_lastDot->setVisible(true);
 
@@ -538,6 +562,7 @@ void DetailView::renderCurve()
         else
             m_lastLabel->setPositionAlignment(Qt::AlignTop | Qt::AlignHCenter);
     } else if (m_lastDot && m_lastLabel) {
+        m_lastDot->setGraph(nullptr);
         m_lastDot->setVisible(false);
         m_lastLabel->setVisible(false);
     }

+ 1 - 1
src/main.cpp

@@ -95,7 +95,7 @@ int main(int argc, char *argv[])
 
     app.setApplicationName(QStringLiteral("HOVSE SLT Pro"));
     app.setOrganizationName(QStringLiteral("XJKJ"));
-    app.setApplicationVersion(QStringLiteral("0.8.1.21"));
+    app.setApplicationVersion(QStringLiteral("0.8.1.22"));
 
     applyAppFont(app);
     applyStyleSheet(app);

+ 43 - 37
src/mainwindow.cpp

@@ -390,6 +390,18 @@ MainWindow::MainWindow(QWidget *parent)
         m_store->applyTaskComplete(station, result);
         const QString verdict = result.value(QStringLiteral("verdict")).toString();
         const QString status = result.value(QStringLiteral("task_status")).toString();
+        const bool batchIntermediate = result.contains(QStringLiteral("batch_complete"))
+                                       && !result.value(QStringLiteral("batch_complete")).toBool(true)
+                                       && verdict != QStringLiteral("fail")
+                                       && status != QStringLiteral("failed");
+        if (batchIntermediate) {
+            m_store->appendLog(station,
+                QStringLiteral("[backend] 批次单轮完成:%1,verdict=%2(后端继续下一轮配置)")
+                    .arg(status, verdict.isEmpty() ? QStringLiteral("unknown") : verdict));
+            return;
+        }
+        if (m_startClicked[station])
+            m_sawRunning[station] = true;
         m_taskCompleteVerdict[station] = verdict;
         m_endSignalReceived[station] = true;       // 后端明确的「结束指令」已到
         m_store->appendLog(station,
@@ -411,7 +423,7 @@ MainWindow::MainWindow(QWidget *parent)
         m_store->applyBackendState(station, st);
 
         // 按钮状态只由本地点击决定,不从后端同步:开屏一律「开始测试」,
-        // 点了才变「执行中」并下发 StartTest,之后完全锁死(hitButton 不命中)。
+        // 点了才变「重新开始」并下发 StartTest(运行过程中允许再次点击直接重跑)。
         // 现场口径:后端收到 StartTest 会立刻复位主机重跑本轮,界面不需要替它判断能不能跑。
         // 万一后端真的拒了,startTestReplied 会把按钮退回「开始测试」并写明原因。
         // 下面这段只负责把跑完的工位复位——且必须分清是「本轮跑完」还是「还没起跑的旧 idle」。
@@ -439,13 +451,20 @@ MainWindow::MainWindow(QWidget *parent)
                 m_taskCompleteVerdict[station].clear();
             }
             m_backendRunning[station] = true;
+            if (m_startClicked[station])
+                m_sawRunning[station] = true;   // 见过运行态,之后的 idle/终态 才算本轮结束
         }
+
+        // 点「开始测试」后,后端可能在几个心跳内仍推送上一轮的 completed/blocked/idle;
+        // 在尚未见到新轮次 running 之前,禁止被上一轮终态触发 finalizeRound / 降温 / 复位按钮。
+        const bool waitingInitialRun = m_startClicked[station] && !m_sawRunning[station];
+
         // 0.8.1.19:0x08 只认后端明确的「结束指令」(task_complete / complete=true),
         // 统一由 finalizeRound 下发。training / rmt / amt / mt 任一阶段 FAIL 时,
         // 后端要先跑完当前阶段再推结束事件;若这里看到 run_state 终态就抢发,
         // MCU 会提前结束控温,把还在跑的阶段温度带偏。
         // 旧后端不推结束事件时,等 kEndSignalWaitMs 后按 state 终态兜底收尾。
-        if (terminal) {
+        if (terminal && !waitingInitialRun) {
             if (!m_terminalSince[station].isValid())
                 m_terminalSince[station].start();
             const bool roundOwnedByUs = m_backendRunning[station] || m_startClicked[station];
@@ -471,8 +490,8 @@ MainWindow::MainWindow(QWidget *parent)
             // 多任务:温度取「当前任务」的 target_temp,不是 stations.Sn 的扁平值
             const QJsonObject planMemory = currentTaskConfig(station)
                                                .value(QStringLiteral("memory_params")).toObject();
-            const int targetTemp = qBound(40,
-                planMemory.value(QStringLiteral("target_temp")).toInt(kStartTargetTempC), 90);
+            const int targetTemp = qBound(1,
+                planMemory.value(QStringLiteral("target_temp")).toInt(kStartTargetTempC), 254);
             if (m_com)
                 m_com->setTargetTemp(station, targetTemp);
             const int ti = m_taskIndex[station];
@@ -489,18 +508,10 @@ MainWindow::MainWindow(QWidget *parent)
                           .arg(taskName).arg(targetTemp));
         }
 
-        if (terminal)
+        if (terminal && !waitingInitialRun)
             m_backendRunning[station] = false;
 
-        if (running && m_startClicked[station])
-            m_sawRunning[station] = true;   // 见过运行态,之后的 idle 才算本轮结束
-
-        // 后端报「本轮结束」就把计时停在这,秒数不再增长。
-        // 不看 m_startClicked:网页端 / 上一次运行起的测试,本机打开软件时也该显示最终时长,
-        // 而不是一路往上走。freezeRuntime 只认第一次,之后的 state 推送不会把时长一直往后拖。
-        if (terminal && m_store->station(station).startTime.isValid()) {
-            m_store->freezeRuntime(station);
-        }
+        // 终态冻结已由后端 ended_unix_ms / elapsed_ms 权威控制,前端不再私自停表或重置。
 
         if (m_startClicked[station]) {
             // completed / failed 是终态,可直接复位;
@@ -513,18 +524,20 @@ MainWindow::MainWindow(QWidget *parent)
             // 否则按钮会在新一轮刚开始时闪回「开始测试」,用户以为没起来又点一次。
             const bool restartClick = m_backend->lastStartWasRestart(station);
             const bool idleSettled = !restartClick || m_clickTimer[station].elapsed() > 60000;
-            bool finished = (runState == QStringLiteral("completed")
-                             || runState == QStringLiteral("failed")
-                             || runState == QStringLiteral("interrupted")
-                             || runState == QStringLiteral("blocked")
-                             || (runState == QStringLiteral("idle") && m_sawRunning[station]
-                                 && idleSettled));
+            bool finished = (!waitingInitialRun
+                             && (runState == QStringLiteral("completed")
+                                 || runState == QStringLiteral("failed")
+                                 || runState == QStringLiteral("interrupted")
+                                 || runState == QStringLiteral("blocked")))
+                            || (runState == QStringLiteral("idle") && m_sawRunning[station]
+                                && idleSettled);
             // 多任务队列还没跑完(后面还有任务在等着发):按钮保持「执行中」,不要复位
             if (m_taskIndex[station] >= 0 && m_taskIndex[station] < m_taskQueue[station].size())
                 finished = false;
             // 兜底:点了却始终没起跑(后端离线 / 被拒),超时后放行重试,避免按钮永久卡死
             bool neverStarted = false;
-            if (!finished && runState == QStringLiteral("idle") && !m_sawRunning[station]
+            if (!finished && (waitingInitialRun || runState == QStringLiteral("idle"))
+                && !m_sawRunning[station]
                 && m_clickTimer[station].isValid() && m_clickTimer[station].elapsed() > 20000) {
                 finished = true;
                 neverStarted = true;
@@ -535,9 +548,8 @@ MainWindow::MainWindow(QWidget *parent)
                 m_startClicked[station] = false;
                 m_sawRunning[station] = false;
                 if (neverStarted) {
-                    m_store->setStartTime(station, QDateTime());   // 根本没起跑:清回 00:00:00
+                    m_store->resetBackendTiming(station);   // 根本没起跑:清回 00:00:00
                 } else {
-                    m_store->freezeRuntime(station);  // 真的跑完了:停表
                     // 兜底:后端不推 completed/failed、直接回 idle 表示本轮结束时,也补发一次。
                     // 走到这里按钮已复位、队列已跑完或中止,按散热收尾。
                     if (!m_endCmdSent[station]) {
@@ -564,8 +576,6 @@ MainWindow::MainWindow(QWidget *parent)
             return;
         m_startClicked[station] = false;
         m_sawRunning[station] = false;
-        if (m_store->station(station).startTime.isValid())
-            m_store->freezeRuntime(station);
         // 多任务:某一轮的 StartTest 被拒 → 整条队列中止,别让后面的任务悬着
         if (m_taskIndex[station] >= 0) {
             m_store->appendLog(station,
@@ -606,12 +616,10 @@ MainWindow::MainWindow(QWidget *parent)
             finalizeRound(station, failed,
                           QStringLiteral("complete=true, task_status=%1").arg(taskStatus));
 
-            // 最后一个任务 / 失败 / 中断:立即恢复按钮并停表;有下一任务则继续显示执行中。
+            // 最后一个任务 / 失败 / 中断:立即恢复按钮;有下一任务则继续显示执行中。
             if (failed || m_taskIndex[station] < 0) {
                 m_startClicked[station] = false;
                 m_sawRunning[station] = false;
-                if (m_store->station(station).startTime.isValid())
-                    m_store->freezeRuntime(station);
                 m_overview->setStartRunning(station, false);
             }
         }
@@ -754,9 +762,8 @@ void MainWindow::startTest(int index)
     // 异常记录同样按轮次走:上一轮的报错不能带进这一轮
     m_store->clearAlarms(index);
 
-    // 先清掉上一轮计时显示 00:00:00;本轮起点完全等后端 started_unix_ms,
-    // 不再用本机时间起步。
-    m_store->setStartTime(index, QDateTime());
+    // 新一轮点击「开始测试」时先清显示为 00:00:00,等待后端下发新起点 started_unix_ms / elapsed_ms。
+    m_store->resetBackendTiming(index);
     m_backendRunning[index] = false;  // 本次 StartTest 是新一轮,等待后端重新进入运行态
     m_endCmdSent[index] = false;
     m_endSignalReceived[index] = false;
@@ -785,7 +792,7 @@ void MainWindow::startTest(int index)
     // 目标温度不在这里下发。协议 0x01 要等 DDR 训练阶段结束才发(判据见 stateArrived 里的
     // phaseAfterTraining):点开始时就发会让设备过早预加热,把训练阶段的温度曲线带偏。
     // 这里只算一遍并写进日志,方便现场对照实际下发的数值。
-    const int targetTemp = qBound(40, planMemory.value(QStringLiteral("target_temp")).toInt(kStartTargetTempC), 90);
+    const int targetTemp = qBound(1, planMemory.value(QStringLiteral("target_temp")).toInt(kStartTargetTempC), 254);
     m_store->appendLog(index, QStringLiteral("[qt] 目标温度 %1℃ 将在 DDR 训练阶段结束时下发(协议 0x01)")
                                   .arg(targetTemp));
 
@@ -1008,10 +1015,9 @@ void MainWindow::startNextTask(int station)
     loadTaskIntoBackend(station);
     m_taskAdvanceGuard[station] = false;    // 新任务允许再推进一次
 
-    // 新一轮:日志按任务清空,计时清回 00:00:00,等后端新的 started_unix_ms 起步
+    // 多任务同一批次延续后端总计时,不清空计时显示,也不重算 started_unix_ms;只清本任务日志与异常记录
     m_store->clearLogs(station);
     m_store->clearAlarms(station);
-    m_store->setStartTime(station, QDateTime());
     m_backendRunning[station] = false; // 新任务开始,重新识别运行态切换
     m_tempSent[station] = false;
     m_endCmdSent[station] = false;
@@ -1027,16 +1033,16 @@ void MainWindow::startNextTask(int station)
     const int total = m_taskQueue[station].size();
     const QString name = m_taskQueue[station].at(idx).toObject()
                              .value(QStringLiteral("name")).toString();
-    const int temp = qBound(40,
+    const int temp = qBound(1,
         currentTaskConfig(station).value(QStringLiteral("memory_params")).toObject()
-            .value(QStringLiteral("target_temp")).toInt(kStartTargetTempC), 90);
+            .value(QStringLiteral("target_temp")).toInt(kStartTargetTempC), 254);
     m_store->appendLog(station,
         QStringLiteral("[qt] %1 开始第 %2/%3 个任务「%4」,目标温度 %5℃(DDR 训练结束后下发)")
             .arg(dev).arg(idx + 1).arg(total).arg(name).arg(temp));
     m_store->appendLog(station, QStringLiteral("[%1] %2 已请求后端启动下一轮,等待 BIOS 可交互输入")
                                   .arg(QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss")), dev));
 
-    m_backend->startTest(station);
+    m_backend->startTest(station, true);
 }
 
 

+ 4 - 4
src/mainwindow.h

@@ -94,15 +94,15 @@ private:
     OverviewView *m_overview;   // 多机监控总览视图
     DetailView *m_detail;       // 设备详情页视图
     ComManager *m_com;          // 四工位 USB 转串口状态
-    // 按钮是否显示「执行中」= 本地点击 或 后端处于运行态:
-    //   m_startClicked   已点过开始测试(再点由 PowerButton::hitButton 挡掉)
+    // 按钮是否显示运行态(文案「重新开始」,允许随时点击重跑本轮)= 本地点击 或 后端处于运行态:
+    //   m_startClicked   本轮已在本地点击过开始测试(允许再次点击直接重跑本轮)
     //   m_sawRunning     点击后是否真的见到后端进入运行态——用来区分「本轮跑完回到 idle」
     //                    和「点击后还没起跑、后端仍在推上一包的 idle」
     //   m_backendRunning 后端当前是否在跑(starting/running/waiting_input)。网页端或其他客户端
-    //                    发起的测试,本机也要显示「执行中」,不能一直停在「开始测试」。
+    //                    发起的测试,本机也可感知运行态并在运行过程中随时点击重跑。
     //                    记忆式:见到运行态即置真,completed/failed 才清,避免复位主机时的短暂
     //                    idle 让按钮闪回「开始测试」。
-    //   m_clickTimer     兜底:点了却始终没起跑(后端无响应/被拒),超时后允许重试
+    //   m_clickTimer     兜底:点了却始终没起跑(后端无响应/被拒),超时后允许复位按钮
     bool m_startClicked[4] = {false, false, false, false};
     bool m_sawRunning[4] = {false, false, false, false};
     bool m_backendRunning[4] = {false, false, false, false};

+ 3 - 3
src/overviewview.cpp

@@ -75,13 +75,13 @@ void OverviewView::setStartRunning(int index, bool running)
         return;
 
     PowerButton *btn = m_start.at(index);
-    // 跑着的时候按钮显示「执行中」:表示这一轮已经起来了
-    const QString text = running ? QStringLiteral("执行中") : QStringLiteral("开始测试");
+    // 跑着的时候按钮显示「重新开始」,支持点击重置重跑
+    const QString text = running ? QStringLiteral("重新开始") : QStringLiteral("开始测试");
     if (btn->text() == text && btn->isRunning() == running)
         return;
 
     btn->setText(text);
-    btn->setRunning(running);           // 执行中换琥珀色,和待机的蓝色区分
+    btn->setRunning(running);           // 运行中换绿色,和待机的蓝色区分
     btn->update();                      // 圆钮是自绘的,文案变了要重绘
 }
 

+ 9 - 14
src/powerbutton.cpp

@@ -33,21 +33,10 @@ void PowerButton::setRunning(bool running)
     if (m_running == running)
         return;
     m_running = running;
-    // 执行中不当按钮用:光标回到箭头,避免「还能点」的暗示;
-    // 是否响应点击由 hitButton() 一并拦掉。
-    setCursor(running ? Qt::ArrowCursor : Qt::PointingHandCursor);
+    setCursor(Qt::PointingHandCursor);
     update();
 }
 
-bool PowerButton::hitButton(const QPoint &pos) const
-{
-    // 执行中完全点不动:按下既不进入按下态,也不会发出 clicked()。
-    // 这一轮要重跑,等它自己跑完(或先在别处停掉)再点。
-    if (m_running)
-        return false;
-    return QAbstractButton::hitButton(pos);
-}
-
 void PowerButton::enterEvent(QEvent *event)
 {
     QAbstractButton::enterEvent(event);
@@ -73,8 +62,14 @@ void PowerButton::paintEvent(QPaintEvent *)
     if (!isEnabled()) {
         top = QColor("#c9d3de"); bottom = QColor("#b7c3d0"); border = QColor("#aab6c4");
     } else if (m_running) {
-        // 执行中:绿色实心 + 白字(不可点,只当状态灯)
-        top = QColor("#2f9e63"); bottom = QColor("#1f7a4a"); border = QColor("#1a6b41");
+        // 运行中「重新开始」:绿色实心 + 悬停/按下态反馈(可随时点击重跑)
+        if (isDown()) {
+            top = QColor("#217c4c"); bottom = QColor("#175d37"); border = QColor("#145230");
+        } else if (underMouse()) {
+            top = QColor("#38ae6f"); bottom = QColor("#258a54"); border = QColor("#1e7647");
+        } else {
+            top = QColor("#2f9e63"); bottom = QColor("#1f7a4a"); border = QColor("#1a6b41");
+        }
     } else if (isDown()) {
         top = QColor("#1b4190"); bottom = QColor("#163a83"); border = QColor("#14357a");
     } else if (underMouse()) {

+ 3 - 4
src/powerbutton.h

@@ -20,9 +20,9 @@ public:
     QSize sizeHint() const override;
     QSize minimumSizeHint() const override;
 
-    /** 「执行中」状态:圆钮换成琥珀色,和待机时(可点「开始测试」)的蓝色区分开。
-     *  执行中这块**完全不可交互**:不吃鼠标、不换按下态、没有 hover 反馈,
-     *  圆钮只当状态指示灯用;本轮结束(idle/completed/failed)后自动恢复可点。 */
+    /** 「重新开始」状态:圆钮换成绿色,和待机时(可点「开始测试」)的蓝色区分开。
+     *  测试进行中也允许直接点击「重新开始」,提交 StartTest 重跑本轮;
+     *  本轮结束(idle/completed/failed)后自动恢复为「开始测试」。 */
     void setRunning(bool running);
     bool isRunning() const { return m_running; }
 
@@ -30,7 +30,6 @@ protected:
     void paintEvent(QPaintEvent *event) override;
     void enterEvent(QEvent *event) override;
     void leaveEvent(QEvent *event) override;
-    bool hitButton(const QPoint &pos) const override;
 
 private:
     void paintPowerGlyph(QPainter *p, const QRectF &circle) const;

+ 85 - 46
src/stationdata.cpp

@@ -33,8 +33,9 @@ StationStore::StationStore(int stationCount, QObject *parent)
 void StationStore::runtimeTick()
 {
     for (int i = 0; i < m_stations.size(); ++i) {
-        // 已经冻结(终态)的工位不用再重画:秒数不会再变了
-        if (m_stations.at(i).startTime.isValid() && m_stations.at(i).frozenMs < 0)
+        const StationData &d = m_stations.at(i);
+        // 已经冻结(ended_unix_ms > 0)或未起跑的工位不用再重画
+        if (d.backendStartedMs > 0 && d.backendEndedMs <= 0)
             touchRuntime(i);
     }
 }
@@ -168,19 +169,81 @@ void StationStore::setPort(int index, const QString &port)
     emit infoChanged(index);
 }
 
-void StationStore::setStartTime(int index, const QDateTime &start)
+static qint64 parseUnixMsValue(const QJsonValue &v)
+{
+    if (v.isString()) {
+        bool ok = false;
+        const qint64 n = v.toString().toLongLong(&ok);
+        return ok ? n : 0;
+    }
+    if (v.isDouble())
+        return static_cast<qint64>(v.toDouble());
+    return 0;
+}
+
+void StationStore::resetBackendTiming(int index)
 {
     if (index < 0 || index >= m_stations.size())
         return;
 
     StationData &d = m_stations[index];
-    d.startTime = start;                 // 后端 started_unix_ms 的转换值,不是本机时间
-    d.frozenMs = -1;
-    if (start.isValid())
-        d.runtimeClock.start();          // 单调时钟:从收到后端起点这一刻开始推进
-    else
-        d.runtimeClock.invalidate();     // 无效 = 等待后端起点,界面显示 00:00:00
-    emit infoChanged(index);
+    const bool hadTiming = (d.backendStartedMs != 0 || d.backendEndedMs != 0 || d.backendElapsedMs != 0);
+    d.backendStartedMs = 0;
+    d.backendEndedMs = 0;
+    d.backendElapsedMs = 0;
+    d.syncClock.invalidate();
+    if (hadTiming)
+        emit infoChanged(index);
+}
+
+void StationStore::applyBackendTiming(int index, const QJsonObject &obj)
+{
+    if (index < 0 || index >= m_stations.size())
+        return;
+    if (!obj.contains(QStringLiteral("started_unix_ms"))
+        && !obj.contains(QStringLiteral("elapsed_ms")))
+        return;
+
+    StationData &d = m_stations[index];
+    const qint64 started = parseUnixMsValue(obj.value(QStringLiteral("started_unix_ms")));
+    const qint64 ended = parseUnixMsValue(obj.value(QStringLiteral("ended_unix_ms")));
+    const qint64 elapsed = obj.contains(QStringLiteral("elapsed_ms"))
+                               ? qMax<qint64>(0, parseUnixMsValue(obj.value(QStringLiteral("elapsed_ms"))))
+                               : (started > 0 && ended > 0 ? qMax<qint64>(0, ended - started) : -1);
+
+    if (started <= 0) {
+        resetBackendTiming(index);
+        return;
+    }
+
+    const qint64 prevShown = runtimeMs(index);
+    const qint64 prevStarted = d.backendStartedMs;
+    const qint64 prevEnded = d.backendEndedMs;
+
+    if (ended > 0) {
+        const qint64 exactMs = (elapsed >= 0) ? elapsed : qMax<qint64>(0, ended - started);
+        d.backendStartedMs = started;
+        d.backendEndedMs = ended;
+        d.backendElapsedMs = exactMs;
+        d.syncClock.invalidate();
+    } else {
+        qint64 newElapsed = (elapsed >= 0) ? elapsed : 0;
+        if (prevStarted == started && prevEnded <= 0 && prevShown > newElapsed
+            && (prevShown - newElapsed) < 2000) {
+            newElapsed = prevShown;
+        }
+        d.backendStartedMs = started;
+        d.backendEndedMs = 0;
+        d.backendElapsedMs = newElapsed;
+        d.syncClock.start();
+    }
+
+    const qint64 nowShown = runtimeMs(index);
+    if (d.backendStartedMs != prevStarted
+        || d.backendEndedMs != prevEnded
+        || (nowShown / 1000) != (prevShown / 1000)) {
+        emit infoChanged(index);
+    }
 }
 
 void StationStore::setTaskProgress(int index, int done, int current)
@@ -220,29 +283,16 @@ void StationStore::resetChannelResults(int index)
     emit infoChanged(index);
 }
 
-void StationStore::freezeRuntime(int index)
-{
-    if (index < 0 || index >= m_stations.size())
-        return;
-    StationData &d = m_stations[index];
-    if (!d.startTime.isValid())
-        return;                                 // 没起过表,没有可停的
-    if (d.frozenMs >= 0)
-        return;                                 // 已冻结:state 每秒推送,别把时长一直往后拖
-    d.frozenMs = d.runtimeClock.isValid() ? d.runtimeClock.elapsed() : 0;
-    emit infoChanged(index);
-}
-
 qint64 StationStore::runtimeMs(int index) const
 {
     if (index < 0 || index >= m_stations.size())
         return -1;
     const StationData &d = m_stations.at(index);
-    if (!d.startTime.isValid())
-        return -1;                              // 后端还没确认本轮启动
-    if (d.frozenMs >= 0)
-        return d.frozenMs;                      // 终态:停在冻结值
-    return d.runtimeClock.isValid() ? d.runtimeClock.elapsed() : 0;
+    if (d.backendStartedMs <= 0)
+        return -1;                              // 空闲 / 尚未触发测试上电
+    if (d.backendEndedMs > 0)
+        return d.backendElapsedMs;              // 终态:停在后端冻结时长
+    return d.backendElapsedMs + (d.syncClock.isValid() ? qBound<qint64>(0, d.syncClock.elapsed(), 1500) : 0);
 }
 
 void StationStore::touchRuntime(int index)
@@ -343,7 +393,9 @@ void StationStore::applyBackendState(int index, const QJsonObject &station)
     // 0.8.1.19:boot_id 是轮次边界。即使本机不是点击 StartTest 的客户端,
     // 只要收到新 boot_id,也必须先清掉上一轮 24 路状态、温度与曲线。
     const QString incomingBootId = station.value(QStringLiteral("boot_id")).toString();
-    if (!incomingBootId.isEmpty() && incomingBootId != d.bootId) {
+    if (incomingBootId.isEmpty() && !d.bootId.isEmpty()) {
+        d.bootId.clear();
+    } else if (!incomingBootId.isEmpty() && incomingBootId != d.bootId) {
         d.bootId = incomingBootId;
         for (ChannelInfo &ch : d.channels) {
             ch.state = ChannelInfo::Idle;
@@ -436,23 +488,9 @@ void StationStore::applyBackendState(int index, const QJsonObject &station)
     if (infoDirty)
         emit infoChanged(index);
 
-    // 本轮启动时间(字符串形式的 Unix 毫秒;"0" 表示 Start 尚未确认)
-    // 运行时间完全由后端 started_unix_ms 驱动:
-    //   "0"(后端声明本轮尚未确认启动)→ 清掉上一轮计时,显示 00:00:00;
-    //   有效 Unix 毫秒 → 作为本轮起点,启动单调计时器。
-    // 不再用本机 QDateTime::currentDateTime() 起步或停表。
-    const QString startedMs = station.value(QStringLiteral("started_unix_ms")).toString();
-    if (startedMs == QLatin1String("0")) {
-        if (d.startTime.isValid())
-            setStartTime(index, QDateTime());
-    } else if (!startedMs.isEmpty()) {
-        const qint64 ms = startedMs.toLongLong();
-        if (ms > 0) {
-            const QDateTime started = QDateTime::fromMSecsSinceEpoch(ms);
-            if (d.startTime != started)
-                setStartTime(index, started);   // 新一轮:重置单调时钟与冻结状态
-        }
-    }
+    // 直接同步后端权威时间(started_unix_ms / ended_unix_ms / elapsed_ms);
+    // 不在前端按阶段切换重置,也不以本机墙钟计算。
+    applyBackendTiming(index, station);
 
     const QJsonArray channels = station.value(QStringLiteral("channels")).toArray();
     for (const QJsonValue &v : channels) {
@@ -584,6 +622,7 @@ void StationStore::applyTaskComplete(int index, const QJsonObject &result)
         d.stageCompletions = completions;
         changed = true;
     }
+    applyBackendTiming(index, result);
     if (changed)
         emit infoChanged(index);
 }

+ 13 - 11
src/stationdata.h

@@ -86,11 +86,14 @@ struct StationData {
 
     QVector<double> tempHistory;   // 最近 kTempHistorySize 个腔体温度,最老的在前
 
-    // 运行时间:起点只认后端 started_unix_ms(这里存转换值,仅作「本轮是否起跑」标记),
-    // 走表用单调计时器,终态冻结;计时链路不再使用本机墙钟 currentDateTime()。
-    QDateTime startTime;           // 无效 = 后端还没确认本轮启动,界面显示 00:00:00
-    QElapsedTimer runtimeClock;    // 单调时钟:收到后端起点时 start()
-    qint64 frozenMs = -1;          // 终态冻结的时长(ms);-1 = 未冻结
+    // 运行时间:直接以后端为准(started_unix_ms / ended_unix_ms / elapsed_ms);
+    // 后端只在测试命令触发上电/重启时记录一次 started_unix_ms,直到全部测试结束才冻结 ended_unix_ms,
+    // 跨阶段(ICT1/Training/RMT/AMT/ICT2/UEFI/MT)与多计划批内重启永不重置。
+    // 前端每秒借助 syncClock 做不超过 1.5s 的平滑内插,并由后端 state/task_complete 校正。
+    qint64 backendStartedMs = 0;   // <=0 表示空闲/未开始,界面显示 00:00:00
+    qint64 backendEndedMs = 0;     // >0 表示全部测试结束或停止,显示冻结值 backendElapsedMs
+    qint64 backendElapsedMs = 0;   // 后端权威已运行时长(ms)
+    QElapsedTimer syncClock;       // 最近一次收到后端运行中 elapsed_ms 锚点的单调计时器
 
     // 多任务执行进度(由主窗口维护):
     //   taskDone    本轮队列里已经跑完的任务数
@@ -130,12 +133,11 @@ public:
     void setCurrentTemp(int index, double temperature);
     void setPort(int index, const QString &port);
 
-    // 设置后端本轮起点(started_unix_ms 的转换值);传无效 QDateTime 清回 00:00:00。
-    // 只允许由 applyBackendState 用后端时间戳驱动,不再接受本机 currentDateTime()。
-    void setStartTime(int index, const QDateTime &start);
-    // 后端报「本轮结束」时冻结计时(只认第一次),秒数不再增长。
-    void freezeRuntime(int index);
-    // 当前应显示的运行时长(毫秒);-1 = 未起跑。起点来自后端,增量来自单调时钟。
+    // 直接消费后端权威时间字段(started_unix_ms / ended_unix_ms / elapsed_ms),
+    // 禁止前端在阶段切换或任务串联时私自重置或停表。
+    void resetBackendTiming(int index);
+    void applyBackendTiming(int index, const QJsonObject &obj);
+    // 当前应显示的运行时长(毫秒);<0 表示空闲未启动(界面显示 00:00:00)。
     qint64 runtimeMs(int index) const;
     // 多任务进度:done = 已完成任务数,current = 当前任务下标(-1 表示没有在跑的任务)
     void setTaskProgress(int index, int done, int current);

+ 3 - 3
src/uiformat.h

@@ -11,9 +11,9 @@
  */
 namespace ui {
 
-// 运行时长 HH:mm:ss。入参是「本轮已运行毫秒」,由 StationStore 按后端
-// started_unix_ms 起点 + 单调计时器算出;<0 表示本轮还没起跑,显示 00:00:00。
-// 这里不读本机墙钟,避免本机时间被修改 / 与后端时钟不同步时显示错乱。
+// 运行时长 HH:mm:ss。入参是「本轮已运行毫秒」,直接取自后端权威耗时 elapsed_ms
+// (由 StationStore 与后端 state/task_complete 对齐并在 1s 周期内平滑推进);<0 表示空闲未起跑,显示 00:00:00。
+// 这里不读本机墙钟,禁止在阶段切换时重新计时。
 inline QString formatRuntimeMs(qint64 ms)
 {
     qint64 secs = qMax<qint64>(0, ms) / 1000;

Plik diff jest za duży
+ 35 - 12
web/amt-controls.js


+ 49 - 21
web/app.js

@@ -8,7 +8,7 @@
     return Object.fromEntries(Object.entries(value).map(([key,item]) => [key,/^(password|token|api_token|secret)$/i.test(key) ? '已隐藏' : redact(item)]));
   }
 
-  let stationId = 'S1', stations = [], polling = false, selectionRevision = 0, connected = false;
+  let stationId = 'S1', stationUserChosen = false, stations = [], polling = false, repollPending = false, selectionRevision = 0, connected = false;
   const logs = new Map(), pending = new Map(), diagnostics = new Map();
   let queueItems = [], queuePolling = false, eventPolling = false, auditItems = [], auditPolling = false;
   const eventViews = new Map(), bmcPending = new Map();
@@ -100,7 +100,7 @@
       key: d.session_id ? `diag:${stationId}:${d.session_id}` : '',
       session_id: d.session_id || '',
       exists: !!d.session_id,
-      writable: connected && d.state === 'online',
+      writable: connected && (d.state === 'online' || !!current()?.console_online),
     };
   }
 
@@ -141,6 +141,11 @@
     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);
@@ -424,14 +429,16 @@
       const state = stage?.main?.label || '阶段待观测';
       const caps = window.stlFirmware.capabilities(s.station_id);
       const unavailable = !!caps && !caps.console && !caps.bmc_query;
-      const kind = unavailable ? 'offline' : 'idle';
       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 kind = (unavailable || !nodeOnline) ? 'offline' : 'idle';
       const bmcBadge = s.bmc_state === 'online' ? 'BMC 在线' : (s.bmc_address ? `BMC ${label(s.bmc_state || 'offline')}` : '仅串口模式');
       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}">
-        <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 ? '待换条' : label(state))}</span></div>
+        <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>
         <div class="station-info-row"><span>主板电源</span><span>${escape(label(s.server_power))} · ${escape(bmcBadge)}</span></div>
+        <div class="station-info-row"><span>测试用时</span><span>${escape(formatElapsed(s.elapsed_ms || 0))}</span></div>
         <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>
       </div>`;
     }).join('');
@@ -459,8 +466,9 @@
     }
     enable('btn-refresh-station', connected);
     enable('btn-query-bmc', available && !!caps.bmc_query && !bmcPending.has(stationId));
-    $('diagnostic-state').textContent = diagnosticError ? '读取失败' : label(d.state || 'closed');
-    $('diagnostic-state').classList.toggle('connected', d.state === 'online');
+    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);
   }
@@ -474,11 +482,19 @@
     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;
-    $('console-lock-badge').textContent = diag().state !== 'online' ? '未连接' : executionState === 'paused' ? '计划已暂停 · 人工接管' : executionState === 'waiting_user' ? '人工节点 · 可输入' : executionState === 'running' ? '自动计划执行中' : '手动调试';
-    $('sol-state-badge').textContent = label(diag().state || 'closed');
+    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)) {
@@ -564,7 +580,8 @@
     renderDetail(); renderLog();
   }
 
-  async function selectStation(next) {
+  async function selectStation(next, byUser = true) {
+    if (byUser) stationUserChosen = true;
     stationId = next; diagnosticError = ''; selectionRevision++;
     $('bmc-query-output').textContent = '点击查询显示 BMC 返回结果。'; $('bmc-query-time').textContent = '';
     renderCards(); renderDetail(); renderLog();
@@ -572,7 +589,10 @@
   }
 
   async function poll() {
-    if (polling) return;
+    if (polling) {
+      repollPending = true;
+      return;
+    }
     polling = true;
     try {
       const [info, list] = await Promise.all([callApi('GetSystemInfo'), callApi('ListStations')]);
@@ -586,6 +606,14 @@
       $('refresh-indicator').textContent = 'WebSocket 已连接';
       stations = list.stations || [];
       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'));
+        if (!curOnline) {
+          const live = stations.find(s => s.console_online || s.bmc_state === 'online');
+          if (live) stationId = live.station_id;
+        }
+      }
       renderCards(); renderDetail();
       await Promise.all([pollQueue(), pollDeviceEvents(), pollAuditLogs(), pollDiagnostic(), window.stlFirmware.refresh()]);
       renderDetail();
@@ -595,7 +623,13 @@
       $('refresh-indicator').classList.add('offline');
       status(`后端连接失败:${error.message}`, true);
       renderDetail();
-    } finally { polling = false; }
+    } finally {
+      polling = false;
+      if (repollPending) {
+        repollPending = false;
+        setTimeout(() => void poll(), 40);
+      }
+    }
   }
 
   async function sendBytes(bytes, description = '发送控制台') {
@@ -653,10 +687,6 @@
   bind('btn-fan-refresh', async () => { await refreshFanMode(stationId, false); });
   $('chk-fan-low-speed').onchange = async () => {
     const chk = $('chk-fan-low-speed'), wantLowSpeed = chk.checked;
-    if (!wantLowSpeed && !confirm(`关闭 ${stationId} 风扇降低转速并触发 BMC 热重启以恢复服务器默认自动温控 (00)?(不影响服务器主板供电)`)) {
-      chk.checked = true;
-      return;
-    }
     chk.dataset.busy = '1'; chk.disabled = true;
     try {
       const q = wantLowSpeed ? 'fan_low_speed_on' : 'fan_low_speed_off';
@@ -672,7 +702,6 @@
     }
   };
   bind('btn-bmc-warm-reset', async () => {
-    if (!confirm(`对 ${stationId} 执行 BMC 热重启以恢复服务器默认温控?服务器主板不断电。`)) return;
     await command('QueryBmc', {station_id: stationId, query: 'bmc_warm_reset'}, 'BMC 热重启 (恢复默认温控)');
   });
   bind('btn-query-bmc', async () => {
@@ -688,13 +717,11 @@
   });
   for (const [button, actionName, description] of [['btn-diag-open','open','连接 BIOS 控制台'],['btn-diag-close','close','断开 BIOS 控制台'],['btn-diag-reconnect','reconnect','重连 BIOS 控制台']]) {
     bind(button, async () => {
-      if (actionName === 'reconnect' && !confirm(`重新建立 ${stationId} 的 BIOS 控制台连接?`)) return;
       await command('SetDiagnosticSol', {station_id:stationId, action:actionName}, description);
     });
   }
   for (const [suffix, actionName, description] of [['on','host_on','主板开机'],['off','host_off','主板关机'],['reset','host_reset','主板复位'],['cycle','host_cycle','主板关开循环']]) {
     bind(`btn-host-${suffix}`, async () => {
-      if (suffix !== 'on' && !confirm(`对 ${stationId} 执行${description}?当前 BIOS / UEFI 操作会中断。`)) return;
       await command('StationPower', {station_id:stationId, action:actionName}, description);
     });
   }
@@ -733,7 +760,7 @@
   });
 
   const services = {
-    callApi, command, bind, status, time, terminalText,
+    callApi, command, bind, status, time, formatElapsed, terminalText,
     useLiveConsole: () => { renderDetail(); },
     stationId: () => stationId,
     station: current,
@@ -765,14 +792,15 @@
     }
   });
   window.addEventListener('stl:server-event', event => {
-    if (event.detail?.event === 'task_complete') {
+    const ev = event.detail?.event;
+    if (ev === 'station_dirty' || ev === 'task_complete') {
       void poll();
     }
   });
   window.addEventListener('load', async () => {
     renderDetail();
     await poll();
-    setInterval(poll, 1500);
+    setInterval(poll, 10000);
     void startLiveTailLoop();
   });
 })();

+ 5 - 4
web/boot-plan-controls.js

@@ -145,11 +145,11 @@
     const amt = p.amt || p.amt_settings || {};
     const runAmt = p.run_amt !== undefined ? p.run_amt : amt.action === 'run';
     const amtOvs = (amt.overrides || []).map(x => `${x.name} ${x.value}`.trim()).join('; ');
-    const amtText = !runAmt ? '跳过 (exit)' : `${amt.test_command || 'amemdiag 1'}${amtOvs ? ' · ' + amtOvs : ' · 默认24项'}`;
+    const amtText = !runAmt ? '跳过 (exit)' : `${amt.test_command || 'amemdiag 1'}${amtOvs ? ' · ' + amtOvs : ' · 默认全量'}`;
     const mt = p.mt || p.mt_selection || {};
     const runMt = p.run_mt !== undefined ? p.run_mt : true;
     const mtRange = mt.memory_range === 'custom' ? `${mt.addr_lim_lo || '0x0'}~${mt.addr_lim_hi || ''}` : '全内存';
-    const mtText = !runMt ? '跳过' : `TSTLIST=${mt.tstlist || (mt.only_tests ? mt.only_tests.join(',') : '0,1,2')} · ${mtRange}`;
+    const mtText = !runMt ? '跳过' : `TSTLIST=${mt.tstlist || (mt.only_tests ? mt.only_tests.join(',') : '0..25')} · ${mtRange}`;
     return { ictText, amtText, mtText, uipCount: uipOvs.length + uipRaws.length };
   }
   function fill() {
@@ -301,7 +301,8 @@
       $('tb-live-title').textContent = tb.batch_id ? `${tb.current_profile_name || 'Profile'} (第 ${tb.current_repeat || 1}/${tb.current_profile_repeats || 1} 次)` : '尚无活动批次队列';
     }
     if ($('tb-live-detail')) {
-      $('tb-live-detail').textContent = tb.batch_id ? `批次编号 ${tb.batch_id} · 状态 ${stateNames[tbState] || tbState} · 已完成 ${done}/${planned} 轮` : '添加 1 组或多组 Profile 后,点击下方按钮立即按序自动重启并执行。';
+      const fmtElapsed = api.formatElapsed ? api.formatElapsed(c.elapsed_ms || 0) : `${Math.floor((Number(c.elapsed_ms || 0)) / 1000)}s`;
+      $('tb-live-detail').textContent = tb.batch_id ? `批次编号 ${tb.batch_id} · 状态 ${stateNames[tbState] || tbState} · 已完成 ${done}/${planned} 轮 · 总用时 ${fmtElapsed}` : '添加 1 组或多组 Profile 后,点击下方按钮立即按序自动重启并执行。';
     }
     const runs = Array.isArray(tb.runs) && tb.runs.length ? tb.runs : (Array.isArray(c.task_history) ? c.task_history.slice(-20) : []);
     if ($('tb-runs-tbody')) {
@@ -455,7 +456,7 @@
       }
       const step = q.steps[q.index];
       api.status(`[前端自维护队列] ${sid} 正在下发第 ${q.index + 1}/${q.steps.length} 轮:${step._stepLabel}`);
-      await awaitCommand('SubmitTaskBatch', { station_id: sid, profiles: [step], stop_on_fail: q.stopOnFail, auto_start: true }, `前端队列第 ${q.index + 1}/${q.steps.length} 轮`);
+      await awaitCommand('SubmitTaskBatch', { station_id: sid, profiles: [step], stop_on_fail: q.stopOnFail, auto_start: true, continue_timer: q.index > 0 }, `前端队列第 ${q.index + 1}/${q.steps.length} 轮`);
       await window.stlFirmware.refresh();
       render();
     };

Plik diff jest za duży
+ 12 - 31
web/firmware-controls.js


Plik diff jest za duży
+ 19 - 279
web/index.html


+ 3 - 2
web/stage-progress.js

@@ -81,10 +81,11 @@
       $('station-task-status-badge').classList.toggle('error', tStatus === 'failed');
     }
 
-    // Render awaiting_dimm_replacement banner
+    // Render awaiting_dimm_replacement or stage_errors banner
     const awaitingRep = !!(control.awaiting_dimm_replacement || station.awaiting_dimm_replacement);
+    const hasStageErrs = Object.values(stageErrors).some(arr => Array.isArray(arr) && arr.length > 0);
     if ($('dimm-replacement-banner')) {
-      $('dimm-replacement-banner').classList.toggle('hidden', !awaitingRep);
+      $('dimm-replacement-banner').classList.toggle('hidden', !awaitingRep && !hasStageErrs);
     }
 
     // Render live pending StageIntents (last-write-wins)

+ 4 - 3
web/style.css

@@ -65,6 +65,7 @@ input[readonly] { background: var(--surface-soft); }
 .tag-running { background: #e9f5ff; color: #327eb2; }
 .tag-completed { background: var(--primary-soft); color: var(--primary); }
 .tag-failed { background: #fff0f0; color: var(--danger); }
+.tag-error { background: #fff0f0; color: var(--danger); }
 .tag-offline { background: #f3f5f7; color: #9aa5b3; }
 .station-info-row { display: flex; justify-content: space-between; gap: 8px; font-size: 11px; color: var(--muted); margin-top: 5px; }
 .station-info-row span:last-child { text-align: right; color: #4e5c70; overflow-wrap: anywhere; }
@@ -155,7 +156,10 @@ summary { cursor: pointer; width: fit-content; user-select: none; }
 .cpu-title span:first-child { color: #4c657b; font-weight: 650; }
 .dimm-grid { display: grid; grid-template-columns: repeat(6, minmax(0,1fr)); gap: 6px; }
 .dimm-slot { border: 1px solid #e5ebf0; background: #f9fbfc; border-radius: 6px; padding: 6px 4px; display: flex; flex-direction: column; align-items: center; gap: 2px; min-width: 0; }
+.dimm-slot.channel-pass { border-color: #93cfc4; background: #eef9f6; }
+.dimm-slot.channel-pass .slot-name .badge { background: #dcfce7; color: #166534; border-color: #86efac; }
 .dimm-slot.channel-fail { border-color: #e8a2aa; background: #fff6f6; }
+.dimm-slot.channel-fail .slot-name .badge { background: #fee2e2; color: #b91c1c; border-color: #fca5a5; }
 .slot-name { font-size: 10px; color: #8794a6; }
 .slot-temp { font: 600 14px/1.4 var(--mono); }
 .temp-cold { color: var(--success); }
@@ -672,9 +676,6 @@ body:not([data-current-page="overview"]) .workspace-split { grid-template-column
 .th-pill.is-warn { background:#fff5e4;color:#a46b13; }
 .th-pill.is-err { background:#fff0f1;color:#c5424b; }
 .th-meta-text { margin-left:auto;font:11.5px var(--mono);color:#657888; }
-.th-safety-bar { display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:10px;padding:8px 12px;background:#f0f8f6;border:1px solid #cce6df;border-radius:7px;font-size:12px;color:#305c54; }
-.th-safety-left, .th-safety-right { display:flex;flex-wrap:wrap;align-items:center;gap:9px; }
-.th-safety-bar select, .th-safety-bar input { padding:4px 8px;font-size:12px; }
 .th-two-col { display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;align-items:start; }
 .th-card-head { display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap; }
 .th-temp-control-row { display:flex;flex-wrap:wrap;align-items:flex-end;gap:12px; }

+ 0 - 970
web/thermal-console.js

@@ -1,970 +0,0 @@
-// thermal-console.js — High-Performance Zero-Lag MCU 24-Ch Thermal Console & Stream Recorder UI (v0.8.1.21)
-(() => {
-  const MAX_POINTS = 720;
-  const SERIES_META = [
-    { key: 'target', label: '目标温度', color: '#cf4b52', dashed: true },
-    { key: 'bmc_avg', label: 'MCU BMC均温', color: '#0d8b80', dashed: false },
-    { key: 'bmc_max', label: 'MCU BMC最高', color: '#e67e22', dashed: false },
-    { key: 'ct_avg', label: 'CT7428腔均温', color: '#2980b9', dashed: false },
-    { key: 'ipmi_avg', label: 'IPMI内存均温', color: '#8e44ad', dashed: false },
-  ];
-
-  const el = id => document.getElementById(id);
-  const rootPanel = document.querySelector('.thermal-console-panel');
-  if (!rootPanel) return;
-
-  let sinceSeq = 0;
-  let chartRing = [];
-  let pollInFlight = false;
-  let pollTimer = null;
-  let rafPending = false;
-  let hoverRatio = null;
-  let prefsSyncedOnce = false;
-  let lastFilesSig = '';
-  let lastAsciiSig = '';
-  let lastFrameSig = '';
-  const enabledSeries = new Set(['target', 'bmc_avg', 'bmc_max', 'ct_avg', 'ipmi_avg']);
-
-  // Pre-build fixed DOM cells once (zero DOM node creation during multi-day runs!)
-  const ctCells = [];
-  const ctGrid = el('th-ct8-grid');
-  for (let i = 0; i < 8; i++) {
-    const d = document.createElement('div');
-    d.className = 'th-ct-cell';
-    const sp = document.createElement('span');
-    sp.textContent = `CT0${i + 1}`;
-    const st = document.createElement('strong');
-    st.textContent = '--';
-    d.append(sp, st);
-    ctGrid.appendChild(d);
-    ctCells.push({ val: st, prev: '' });
-  }
-
-  const slotCells = [];
-  const bmcGrid = el('th-bmc24-grid');
-  for (let i = 0; i < 24; i++) {
-    const cpu = i < 12 ? 0 : 1;
-    const ch = String.fromCharCode(65 + (i % 12));
-    const card = document.createElement('div');
-    card.className = 'th-slot-card';
-    const top = document.createElement('div');
-    top.className = 'th-slot-top';
-    const lbl = document.createElement('span');
-    lbl.textContent = `CH${String(i + 1).padStart(2, '0')} · CPU${cpu}_${ch}`;
-    const diffSpan = document.createElement('span');
-    diffSpan.textContent = '';
-    top.append(lbl, diffSpan);
-
-    const vals = document.createElement('div');
-    vals.className = 'th-slot-vals';
-    const mcuStrong = document.createElement('span');
-    mcuStrong.className = 'th-slot-mcu';
-    mcuStrong.textContent = 'MCU: --';
-    const ipmiSpan = document.createElement('span');
-    ipmiSpan.className = 'th-slot-ipmi';
-    ipmiSpan.textContent = 'IPMI: --';
-    vals.append(mcuStrong, ipmiSpan);
-
-    card.append(top, vals);
-    bmcGrid.appendChild(card);
-    slotCells.push({ card, mcuStrong, ipmiSpan, diffSpan, prevCls: 'th-slot-card', prevMcu: '', prevIpmi: '', prevDiff: '' });
-  }
-
-  function setTextIfChanged(node, text) {
-    if (node && node.textContent !== text) node.textContent = text;
-  }
-
-  function setStatus(msg, isError = false) {
-    const bar = el('action-status');
-    if (!bar) return;
-    bar.textContent = msg;
-    bar.classList.toggle('error', Boolean(isError));
-  }
-
-  function fmtBytes(b) {
-    const n = Number(b) || 0;
-    if (n < 1024) return `${n} B`;
-    if (n < 1048576) return `${(n / 1024).toFixed(1)} KB`;
-    return `${(n / 1048576).toFixed(2)} MB`;
-  }
-
-  function fmtTimeShort(ms) {
-    if (!ms) return '--:--:--';
-    const d = new Date(ms);
-    return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
-  }
-
-  function stateLabel(st) {
-    switch (st) {
-      case 'disconnected': return '未连接';
-      case 'offline': return '串口已开 · 等待0xF0';
-      case 'cpld_lost': return 'CPLD采集失联';
-      case 'preheating': return '预加热升温中';
-      case 'pid': return 'PID闭环控温中';
-      case 'manual': return '手动出力保持';
-      case 'cooling_purge': return '风扇余温吹扫中';
-      case 'idle': return '在线待机 (0W)';
-      default: return st || '未知';
-    }
-  }
-
-  async function callThermalAction(action, extra = {}) {
-    const params = Object.assign({
-      action,
-      station_id: el('th-bound-station')?.value || 'S1',
-    }, extra);
-    return window.stlTransport.call('ThermalAction', params, 10000);
-  }
-
-  function updateModeVisibility() {
-    const mode = el('th-conn-mode').value;
-    el('th-serial-wrap').classList.toggle('hidden', mode !== 'serial');
-    el('th-tcp-wrap').classList.toggle('hidden', mode !== 'tcp');
-  }
-  el('th-conn-mode').addEventListener('change', updateModeVisibility);
-  updateModeVisibility();
-
-  async function scanPorts(silent = false) {
-    try {
-      const res = await callThermalAction('scan_ports');
-      const ports = Array.isArray(res?.ports) ? res.ports : [];
-      const dl = el('th-serial-datalist');
-      dl.replaceChildren();
-      for (const p of ports) {
-        const opt = document.createElement('option');
-        opt.value = p.path;
-        opt.label = p.label || p.path;
-        dl.appendChild(opt);
-      }
-      if (ports.length > 0 && !el('th-serial-path').value) {
-        const usb = ports.find(p => String(p.resolved_path || p.path).includes('ttyUSB')) || ports[0];
-        el('th-serial-path').value = usb.resolved_path || usb.path;
-      }
-      if (!silent) {
-        setStatus(ports.length
-          ? `已扫描到 ${ports.length} 个串口入口: ${ports.map(p => p.path).join(', ')}`
-          : '当前未扫描到 USB 串口设备,可切换为「离线虚拟仿真 (Mock)」测试全部功能');
-      }
-    } catch (err) {
-      if (!silent) setStatus(`扫描串口失败: ${err.message}`, true);
-    }
-  }
-
-  el('btn-th-scan-ports').addEventListener('click', () => scanPorts(false));
-
-  el('btn-th-connect').addEventListener('click', async () => {
-    const mode = el('th-conn-mode').value;
-    const payload = {
-      mode,
-      serial_path: el('th-serial-path').value.trim() || '/dev/ttyUSB0',
-      serial_baud: 115200,
-      tcp_host: el('th-tcp-host').value.trim() || '127.0.0.1',
-      tcp_port: Number(el('th-tcp-port').value) || 4002,
-    };
-    try {
-      await callThermalAction('connect', payload);
-      setStatus(`高温罩连接成功 (${mode === 'serial' ? payload.serial_path : mode}),正在读取 UID / 固件版本 / 实时温度...`);
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`连接高温罩失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-disconnect').addEventListener('click', async () => {
-    try {
-      await callThermalAction('disconnect');
-      setStatus('已断开 MCU 高温罩连接');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`断开失败: ${err.message}`, true);
-    }
-  });
-
-  el('th-bound-station').addEventListener('change', async () => {
-    try {
-      await callThermalAction('bind_station', { station_id: el('th-bound-station').value });
-      setStatus(`已切换高温罩关联工位至 ${el('th-bound-station').value}`);
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`切换关联工位失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-zero-probe').addEventListener('click', async () => {
-    try {
-      const res = await callThermalAction('zero_power_probe');
-      setStatus(`零功率安全链路体检完成 (0W 不动加热/风扇) · PID应答: ${res?.text || 'OK'}`);
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`零功率自检失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-estop').addEventListener('click', async () => {
-    try {
-      await callThermalAction('emergency_stop');
-      setStatus('已执行一键紧急全停:35路占空比清零 + 停止预热/PID (0x05) + 锁死全部加热块 (0x0A)');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`紧急全停命令异常: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-save-safety').addEventListener('click', async () => {
-    const leaseSec = Number(el('th-safety-lease').value) || 0;
-    const cutoff = Number(el('th-overtemp-cutoff').value) || 95;
-    try {
-      await callThermalAction('configure_safety', { lease_sec: leaseSec, overtemp_cutoff_c: cutoff });
-      setStatus(`远程安全护栏已更新:看门狗=${leaseSec > 0 ? leaseSec + '秒' : '不限时'},超温熔断=${cutoff}℃`);
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`保存安全护栏失败: ${err.message}`, true);
-    }
-  });
-
-  el('th-safety-lease').addEventListener('change', () => el('btn-th-save-safety').click());
-
-  el('btn-th-renew-lease').addEventListener('click', async () => {
-    try {
-      const res = await callThermalAction('renew_lease');
-      setStatus(`远程安全限时看门狗已续期重置 (${res?.lease_remaining_sec || 0} 秒)`);
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`续期失败: ${err.message}`, true);
-    }
-  });
-
-  document.querySelectorAll('.th-preset-btn').forEach(btn => {
-    btn.addEventListener('click', () => {
-      el('th-target-input').value = btn.dataset.temp;
-    });
-  });
-
-  el('btn-th-set-temp').addEventListener('click', async () => {
-    const targetC = Math.round(Number(el('th-target-input').value));
-    if (!Number.isFinite(targetC) || targetC < 0 || targetC > 254) {
-      setStatus('目标温度必须为 0 ~ 254 之间的整数 ℃', true);
-      return;
-    }
-    try {
-      await callThermalAction('set_temp', {
-        target_c: targetC,
-        auto_pre_stop: el('th-chk-auto-prestop').checked,
-        direct_pid: el('th-chk-direct-pid').checked,
-      });
-      setStatus(`已向 MCU 下发设温开启指令: ${targetC}℃ (0x01)`);
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`设温失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-skip-preheat').addEventListener('click', async () => {
-    try {
-      await callThermalAction('skip_preheat');
-      setStatus('已下发跳过预加热进入 PID 闭环指令 (0x06)');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`跳过预加热失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-start-pid').addEventListener('click', async () => {
-    try {
-      await callThermalAction('start_pid');
-      setStatus('已下发直接开启 PID 闭环指令 (0x07)');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`开启 PID 失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-stop-preheat').addEventListener('click', async () => {
-    try {
-      await callThermalAction('stop_preheat');
-      setStatus('已停止预加热与 PID 闭环,32路输出已清零 (0x05)');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`停止控温失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-finish-purge').addEventListener('click', async () => {
-    try {
-      await callThermalAction('finish_control', { cooling_purge: true });
-      setStatus('已结束控温并开启 8 路风扇 100% 余温吹扫散热 (0x08 00)');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`控温结束命令失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-finish-nopurge').addEventListener('click', async () => {
-    try {
-      await callThermalAction('finish_control', { cooling_purge: false });
-      setStatus('已结束控温并清零输出,不开启风扇吹扫 (0x08 01)');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`控温结束命令失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-stop-heaters').addEventListener('click', async () => {
-    try {
-      await callThermalAction('stop_heaters');
-      setStatus('已紧急停止并锁存禁用全部 24 路加热块 (0x0A)');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`锁死加热块失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-stop-fans').addEventListener('click', async () => {
-    try {
-      await callThermalAction('stop_fans');
-      setStatus('已停止并锁存禁用全部风扇 (0x0B)');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`锁死风扇失败: ${err.message}`, true);
-    }
-  });
-
-  // Recording controls
-  async function syncRecordPrefs() {
-    try {
-      await callThermalAction('configure_polling', {
-        record_interval_ms: Number(el('th-rec-interval').value) || 1000,
-        auto_record_on_heat: el('th-chk-auto-rec').checked,
-      });
-    } catch {}
-  }
-  el('th-rec-interval').addEventListener('change', syncRecordPrefs);
-  el('th-chk-auto-rec').addEventListener('change', syncRecordPrefs);
-
-  el('btn-th-rec-start').addEventListener('click', async () => {
-    try {
-      const res = await callThermalAction('start_record', {
-        tag: el('th-rec-tag').value.trim(),
-        note: el('th-mark-input').value.trim(),
-        record_interval_ms: Number(el('th-rec-interval').value) || 1000,
-      });
-      setStatus(`已开始本地全量流式记录: ${res?.csv_filename || ''}`);
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`启动记录失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-rec-stop').addEventListener('click', async () => {
-    try {
-      const res = await callThermalAction('stop_record');
-      setStatus(res?.csv_filename
-        ? `已停止并完成刷盘: ${res.csv_filename} (共 ${res.rows_written || 0} 行)`
-        : '当前没有正在运行的记录会话');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`停止记录失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-add-mark').addEventListener('click', async () => {
-    const note = el('th-mark-input').value.trim();
-    if (!note) {
-      setStatus('请先输入打标备注内容', true);
-      return;
-    }
-    try {
-      await callThermalAction('add_mark', { note });
-      setStatus(`已写入测试打标备注: ${note}`);
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`打标失败: ${err.message}`, true);
-    }
-  });
-
-  // Auxiliary remote debug actions
-  el('btn-th-whisper-fan-test').addEventListener('click', async () => {
-    const btn = el('btn-th-whisper-fan-test');
-    btn.disabled = true;
-    try {
-      await callThermalAction('manual_duty', {
-        ptc_all: 0,
-        ssr_all: 0,
-        fan_in_all: 15,
-        fan_out_all: 0,
-        keepalive: false,
-      });
-      setStatus('0W 加热 · 15% 进风微风点测已开启,将在 2 秒后自动归零...');
-      await pollConsole(true);
-      await new Promise(r => setTimeout(r, 2000));
-      await callThermalAction('manual_duty', {
-        ptc_all: 0,
-        ssr_all: 0,
-        fan_in_all: 0,
-        fan_out_all: 0,
-        keepalive: false,
-      });
-      await callThermalAction('stop_preheat');
-      setStatus('0W 微风 2 秒闭环点测已完成,全部 35 路输出已自动恢复归零!');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`微风闭环点测异常: ${err.message}`, true);
-    } finally {
-      btn.disabled = false;
-    }
-  });
-
-  el('btn-th-pid-read').addEventListener('click', async () => {
-    try {
-      const res = await callThermalAction('pid_calibrate', { expr: '' });
-      setStatus(`PID 回读成功: ${res?.text || ''}`);
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`PID 回读失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-pid-write').addEventListener('click', async () => {
-    const expr = el('th-pid-expr').value.trim();
-    try {
-      const res = await callThermalAction('pid_calibrate', { expr });
-      setStatus(`PID 标定成功: ${res?.text || ''}`);
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`PID 标定失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-man-apply').addEventListener('click', async () => {
-    try {
-      await callThermalAction('manual_duty', {
-        ptc_all: Number(el('th-man-ptc').value) || 0,
-        fan_in_all: Number(el('th-man-fan-in').value) || 0,
-        fan_out_all: Number(el('th-man-fan-out').value) || 0,
-        ssr_all: Number(el('th-man-ssr').value) || 0,
-        keepalive: el('th-man-keepalive').checked,
-      });
-      setStatus('已下发 35 路手动占空比 (0x46)');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`下发手动占空比失败: ${err.message}`, true);
-    }
-  });
-
-  el('btn-th-man-zero').addEventListener('click', async () => {
-    el('th-man-ptc').value = '0';
-    el('th-man-fan-in').value = '0';
-    el('th-man-fan-out').value = '0';
-    el('th-man-ssr').value = '0';
-    el('th-man-keepalive').checked = false;
-    try {
-      await callThermalAction('manual_duty', {
-        ptc_all: 0, fan_in_all: 0, fan_out_all: 0, ssr_all: 0, keepalive: false,
-      });
-      setStatus('35 路手动占空比已全部归零');
-      await pollConsole(true);
-    } catch (err) {
-      setStatus(`归零失败: ${err.message}`, true);
-    }
-  });
-
-  // Series visibility checkboxes
-  document.querySelectorAll('.th-chart-legend input[data-series]').forEach(chk => {
-    chk.addEventListener('change', () => {
-      if (chk.checked) enabledSeries.add(chk.dataset.series);
-      else enabledSeries.delete(chk.dataset.series);
-      scheduleChartDraw();
-    });
-  });
-
-  // Canvas hover crosshair
-  const canvas = el('th-trend-canvas');
-  const tooltip = el('th-canvas-tooltip');
-  canvas.addEventListener('mousemove', ev => {
-    const rect = canvas.getBoundingClientRect();
-    const padL = 44, padR = 14;
-    const plotW = Math.max(1, rect.width - padL - padR);
-    const x = ev.clientX - rect.left - padL;
-    if (x < 0 || x > plotW || chartRing.length === 0) {
-      hoverRatio = null;
-      tooltip.classList.add('hidden');
-    } else {
-      hoverRatio = Math.min(1, Math.max(0, x / plotW));
-    }
-    scheduleChartDraw();
-  });
-  canvas.addEventListener('mouseleave', () => {
-    hoverRatio = null;
-    tooltip.classList.add('hidden');
-    scheduleChartDraw();
-  });
-  window.addEventListener('resize', scheduleChartDraw);
-
-  function scheduleChartDraw() {
-    if (rafPending || document.body.dataset.currentPage !== 'thermal') return;
-    rafPending = true;
-    requestAnimationFrame(() => {
-      rafPending = false;
-      drawTrendChart();
-    });
-  }
-
-  function drawTrendChart() {
-    const rect = canvas.parentElement.getBoundingClientRect();
-    if (rect.width < 40 || rect.height < 40) return;
-    const dpr = Math.min(window.devicePixelRatio || 1, 2);
-    const w = Math.floor(rect.width);
-    const h = Math.floor(rect.height);
-    if (canvas.width !== w * dpr || canvas.height !== h * dpr) {
-      canvas.width = w * dpr;
-      canvas.height = h * dpr;
-    }
-    const ctx = canvas.getContext('2d');
-    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
-    ctx.clearRect(0, 0, w, h);
-
-    const padL = 44, padR = 14, padT = 14, padB = 26;
-    const plotW = w - padL - padR;
-    const plotH = h - padT - padB;
-
-    if (chartRing.length === 0) {
-      ctx.fillStyle = '#8b9ca8';
-      ctx.font = '12px sans-serif';
-      ctx.textAlign = 'center';
-      ctx.fillText('连接高温罩(或开启服务器 IPMI / 开始记录)后实时绘制温度曲线', w / 2, h / 2);
-      return;
-    }
-
-    let minY = Infinity, maxY = -Infinity;
-    for (let i = 0; i < chartRing.length; i++) {
-      const p = chartRing[i];
-      for (const s of SERIES_META) {
-        if (!enabledSeries.has(s.key)) continue;
-        const v = p[s.key];
-        if (typeof v === 'number' && Number.isFinite(v)) {
-          if (v < minY) minY = v;
-          if (v > maxY) maxY = v;
-        }
-      }
-    }
-    if (!Number.isFinite(minY) || !Number.isFinite(maxY)) {
-      minY = 20;
-      maxY = 80;
-    } else {
-      minY = Math.floor(Math.max(0, minY - 4) / 5) * 5;
-      maxY = Math.ceil((maxY + 4) / 5) * 5;
-      if (maxY - minY < 15) maxY = minY + 15;
-    }
-
-    // Horizontal grid & Y labels
-    ctx.strokeStyle = '#e7eff3';
-    ctx.lineWidth = 1;
-    ctx.fillStyle = '#738896';
-    ctx.font = '11px monospace';
-    ctx.textAlign = 'right';
-    const steps = 4;
-    for (let k = 0; k <= steps; k++) {
-      const val = minY + ((maxY - minY) * (steps - k)) / steps;
-      const y = padT + (plotH * k) / steps;
-      ctx.beginPath();
-      ctx.moveTo(padL, y);
-      ctx.lineTo(padL + plotW, y);
-      ctx.stroke();
-      ctx.fillText(`${Math.round(val)}°`, padL - 6, y + 4);
-    }
-
-    // Time X labels
-    const n = chartRing.length;
-    const xOf = idx => padL + (n <= 1 ? plotW / 2 : (idx / (n - 1)) * plotW);
-    const yOf = val => padT + plotH - ((val - minY) / (maxY - minY)) * plotH;
-
-    ctx.textAlign = 'center';
-    const tickCount = Math.min(5, n);
-    for (let t = 0; t < tickCount; t++) {
-      const idx = tickCount === 1 ? 0 : Math.round((t * (n - 1)) / (tickCount - 1));
-      ctx.fillText(fmtTimeShort(chartRing[idx].t), xOf(idx), h - 7);
-    }
-
-    // Series polylines
-    for (const s of SERIES_META) {
-      if (!enabledSeries.has(s.key)) continue;
-      ctx.save();
-      ctx.strokeStyle = s.color;
-      ctx.lineWidth = s.key === 'bmc_avg' ? 2.2 : 1.6;
-      if (s.dashed) ctx.setLineDash([5, 4]);
-      ctx.beginPath();
-      let penDown = false;
-      for (let i = 0; i < n; i++) {
-        const v = chartRing[i][s.key];
-        if (typeof v === 'number' && Number.isFinite(v)) {
-          const px = xOf(i);
-          const py = yOf(v);
-          if (!penDown) {
-            ctx.moveTo(px, py);
-            penDown = true;
-          } else {
-            ctx.lineTo(px, py);
-          }
-        } else {
-          penDown = false;
-        }
-      }
-      ctx.stroke();
-      ctx.restore();
-    }
-
-    // Hover crosshair
-    if (hoverRatio !== null && n > 0) {
-      const idx = Math.min(n - 1, Math.max(0, Math.round(hoverRatio * (n - 1))));
-      const pt = chartRing[idx];
-      const hx = xOf(idx);
-      ctx.save();
-      ctx.strokeStyle = '#95a8b6';
-      ctx.setLineDash([3, 3]);
-      ctx.beginPath();
-      ctx.moveTo(hx, padT);
-      ctx.lineTo(hx, padT + plotH);
-      ctx.stroke();
-      ctx.restore();
-
-      const parts = [`时间: ${fmtTimeShort(pt.t)} (${pt.phase || 'idle'})`];
-      if (pt.target != null) parts.push(`目标: ${pt.target}℃`);
-      if (pt.bmc_avg != null) parts.push(`MCU均/高: ${pt.bmc_avg} / ${pt.bmc_max ?? '--'}℃`);
-      if (pt.ct_avg != null) parts.push(`CT腔均: ${pt.ct_avg}℃`);
-      if (pt.ipmi_avg != null) parts.push(`IPMI均: ${pt.ipmi_avg}℃`);
-      setTextIfChanged(tooltip, parts.join('  |  '));
-      tooltip.classList.remove('hidden');
-    }
-  }
-
-  function setPill(id, text, tone) {
-    const node = el(id);
-    if (!node) return;
-    setTextIfChanged(node, text);
-    const cls = tone ? `th-pill is-${tone}` : 'th-pill';
-    if (node.className !== cls) node.className = cls;
-  }
-
-  function renderSnapshot(snap) {
-    const conn = snap.connection || {};
-    const mcu = snap.mcu || {};
-    const flags = mcu.flags || {};
-    const stats = snap.stats || {};
-    const act = snap.actuators || {};
-    const safety = snap.safety || {};
-    const rec = snap.recorder || {};
-    const stCtx = snap.station_context || {};
-
-    // Sync saved prefs once on initial load without overwriting user's active typing
-    if (!prefsSyncedOnce) {
-      prefsSyncedOnce = true;
-      if (conn.serial_path) el('th-serial-path').value = conn.serial_path;
-      if (conn.tcp_host) el('th-tcp-host').value = conn.tcp_host;
-      if (conn.tcp_port) el('th-tcp-port').value = String(conn.tcp_port);
-      if (stCtx.station_id) el('th-bound-station').value = stCtx.station_id;
-      if (mcu.last_set_target_c != null) el('th-target-input').value = String(mcu.last_set_target_c);
-      if (rec.interval_ms) el('th-rec-interval').value = String(rec.interval_ms);
-      if (typeof rec.auto_record_on_heat === 'boolean') el('th-chk-auto-rec').checked = rec.auto_record_on_heat;
-      if (safety.lease_sec != null) {
-        const ls = String(safety.lease_sec);
-        if ([...el('th-safety-lease').options].some(o => o.value === ls)) {
-          el('th-safety-lease').value = ls;
-        }
-      }
-      if (safety.overtemp_cutoff_c != null) el('th-overtemp-cutoff').value = String(safety.overtemp_cutoff_c);
-    }
-
-    // Overview quick badge
-    const ovBadge = el('ov-thermal-badge');
-    if (ovBadge) {
-      if (conn.mode === 'disconnected') {
-        setTextIfChanged(ovBadge, rec.active ? '未连接 · 记录中' : '未连接');
-        ovBadge.className = 'badge';
-      } else {
-        const bAvg = stats.ct_avg;
-        const tStr = mcu.target_c != null ? `/${mcu.target_c}℃` : '';
-        const recMark = rec.active ? ' · REC' : '';
-        setTextIfChanged(
-          ovBadge,
-          `${stateLabel(mcu.state)} ${bAvg != null ? bAvg + '℃' : '--'}${tStr}${recMark}`
-        );
-        ovBadge.className = conn.online ? 'badge connected' : 'badge error';
-      }
-    }
-
-    // Status strip pills
-    const modeDesc = conn.mode === 'serial'
-      ? `串口 ${conn.serial_path}`
-      : conn.mode === 'mock'
-        ? '虚拟仿真 Mock'
-        : conn.mode === 'tcp'
-          ? `TCP ${conn.tcp_host}:${conn.tcp_port}`
-          : '未连接';
-    setPill('th-pill-online', `链路: ${modeDesc}${conn.online ? ' (在线)' : ''}`, conn.online ? 'ok' : (conn.mode === 'disconnected' ? '' : 'err'));
-    setPill('th-pill-state', `状态: ${stateLabel(mcu.state)}`, (flags.preheating || flags.pid_running) ? 'active' : (flags.cpld_lost ? 'err' : ''));
-    setPill('th-pill-cpld', `CPLD: ${!conn.online ? '--' : (flags.cpld_lost ? '失联告警!' : '正常在线')}`, !conn.online ? '' : (flags.cpld_lost ? 'err' : 'ok'));
-    setPill('th-pill-preheat', `预加热: ${flags.preheating ? '运行中' : '否'}`, flags.preheating ? 'warn' : '');
-    setPill('th-pill-pid', `PID闭环: ${flags.pid_running ? '控温中' : '否'}`, flags.pid_running ? 'active' : '');
-    setPill('th-pill-hlatch', `加热锁存: ${flags.heater_latched_off ? '已锁死禁用' : '正常'}`, flags.heater_latched_off ? 'warn' : '');
-    setPill('th-pill-flatch', `风扇锁存: ${flags.fan_latched_off ? '已锁死禁用' : '正常'}`, flags.fan_latched_off ? 'warn' : '');
-    setPill('th-pill-bmc', `BMC温度源: ${!conn.online ? '--' : (flags.bmc_not_ready ? '待就绪(全FF)' : '已就绪')}`, !conn.online ? '' : (flags.bmc_not_ready ? 'warn' : 'ok'));
-    setPill('th-pill-manual', `手动保持: ${flags.manual_hold ? '运行中' : '否'}`, flags.manual_hold ? 'warn' : '');
-
-    const bi = mcu.boot_info;
-    const fwStr = bi ? `${bi.app_version || '--'} (${bi.product_id_hex || ''})` : '--';
-    setTextIfChanged(
-      el('th-hw-identity'),
-      `UID: ${mcu.uid_hex || '--'} · 固件: ${fwStr} · RX:${conn.rx_frames_ok || 0} TX:${conn.tx_frames_sent || 0} CRC错:${conn.crc_errors || 0}`
-    );
-
-    // Safety bar
-    const leaseNode = el('th-lease-countdown');
-    if (safety.overtemp_tripped) {
-      setTextIfChanged(leaseNode, `已触发超温熔断保护 (>=${safety.overtemp_cutoff_c}℃)!`);
-      leaseNode.className = 'badge error';
-    } else if (safety.lease_active) {
-      setTextIfChanged(leaseNode, `看门狗倒计时: ${safety.lease_remaining_sec}s`);
-      leaseNode.className = safety.lease_remaining_sec <= 60 ? 'badge error' : 'badge connected';
-    } else {
-      setTextIfChanged(leaseNode, safety.lease_sec > 0 ? `看门狗待命 (${safety.lease_sec}s)` : '看门狗已设为不限时');
-      leaseNode.className = 'badge';
-    }
-
-    setTextIfChanged(el('th-target-badge'), `当前目标: ${mcu.target_c != null ? mcu.target_c + ' ℃' : '--'}`);
-    setTextIfChanged(el('th-pid-current'), mcu.pid_text || '--');
-
-    // Actuators live feedback
-    const ssrArr = Array.isArray(act.ssr_applied) ? act.ssr_applied : [0, 0, 0];
-    const ffArr = Array.isArray(act.fan_front_applied) ? act.fan_front_applied : [0, 0, 0, 0];
-    const frArr = Array.isArray(act.fan_rear_applied) ? act.fan_rear_applied : [0, 0, 0, 0];
-    const ptcAvg = Number(act.ptc_avg_duty || 0);
-    setTextIfChanged(el('th-act-ssr'), conn.online ? `${ssrArr.join(' / ')} %` : '--');
-    setTextIfChanged(el('th-act-ptc'), conn.online ? `${ptcAvg.toFixed(1)} %` : '--');
-    setTextIfChanged(el('th-act-fan-f'), conn.online ? `${ffArr.join('/')} %` : '--');
-    setTextIfChanged(el('th-act-fan-r'), conn.online ? `${frArr.join('/')} %` : '--');
-    setTextIfChanged(el('th-act-ct0'), act.ct0_board_c != null ? `${act.ct0_board_c} ℃` : '--');
-    el('th-act-ssr').parentElement.classList.toggle('is-hot', conn.online && ssrArr.some(v => v > 0));
-    el('th-act-ptc').parentElement.classList.toggle('is-hot', conn.online && ptcAvg > 0);
-    setTextIfChanged(
-      el('th-diag-note'),
-      act.diag_line ? `CPLD/I2C 诊断: ${act.diag_line}` : (conn.online ? '等待 MCU [SNAP]/[DIAG] 周期状态行...' : '连接后实时显示 24PTC / 8风扇 / 3SSR 真实占空比')
-    );
-
-    // Recorder panel
-    const recBadge = el('th-rec-badge');
-    const dlCur = el('btn-th-rec-download-cur');
-    if (rec.active) {
-      setTextIfChanged(recBadge, `记录中 · ${rec.rows_written || 0} 行`);
-      recBadge.className = 'badge connected';
-      if (rec.download_url) {
-        dlCur.href = rec.download_url;
-        dlCur.classList.remove('hidden');
-      }
-      setTextIfChanged(
-        el('th-rec-stats'),
-        `正在写入: ${rec.csv_filename} (分卷 #${rec.part_index || 1}) · 已写 ${rec.rows_written || 0} 行 (${fmtBytes(rec.bytes_written)}) · 标签备注: ${rec.note || '无'}`
-      );
-    } else {
-      setTextIfChanged(recBadge, '未记录');
-      recBadge.className = 'badge';
-      dlCur.classList.add('hidden');
-      setTextIfChanged(
-        el('th-rec-stats'),
-        '落盘目录: data/thermal-logs/ · 包含 MCU 24路 + CT 8路 + 服务器 IPMI 24路 + 功率占空比 + 测试阶段共 106 列 (UTF-8 BOM 直接用 Excel 打开)'
-      );
-    }
-
-    // Files table (diffed by signature so buttons never flicker!)
-    const files = Array.isArray(rec.files) ? rec.files : [];
-    const filesSig = files
-      .map(f => `${f.filename}:${f.active ? Math.floor((f.size_bytes || 0) / 16384) : f.size_bytes}:${f.active}`)
-      .join('|');
-    if (filesSig !== lastFilesSig) {
-      lastFilesSig = filesSig;
-      const tbody = el('th-files-tbody');
-      tbody.replaceChildren();
-      if (files.length === 0) {
-        const tr = document.createElement('tr');
-        const td = document.createElement('td');
-        td.colSpan = 5;
-        td.textContent = '暂无本地记录文件(点击「开始本地记录」或开启控温自动生成)';
-        tr.appendChild(td);
-        tbody.appendChild(tr);
-      } else {
-        for (const f of files.slice(0, 30)) {
-          const tr = document.createElement('tr');
-          const tdName = document.createElement('td');
-          tdName.style.fontFamily = 'var(--mono)';
-          tdName.textContent = f.filename + (f.active ? ' (写入中)' : '');
-
-          const tdKind = document.createElement('td');
-          tdKind.textContent = f.kind === 'csv' ? '全量 CSV' : '事件 JSONL';
-
-          const tdSize = document.createElement('td');
-          tdSize.textContent = fmtBytes(f.size_bytes);
-
-          const tdTime = document.createElement('td');
-          tdTime.textContent = (f.modified_str || '').slice(5, 19);
-
-          const tdAct = document.createElement('td');
-          const a = document.createElement('a');
-          a.className = 'btn btn-xs';
-          a.href = f.download_url;
-          a.download = f.filename;
-          a.textContent = '下载';
-          tdAct.appendChild(a);
-          if (!f.active) {
-            const delBtn = document.createElement('button');
-            delBtn.type = 'button';
-            delBtn.className = 'btn btn-xs';
-            delBtn.style.marginLeft = '5px';
-            delBtn.textContent = '删除';
-            delBtn.addEventListener('click', async () => {
-              if (!confirm(`确认删除本地记录文件 ${f.filename} 吗?`)) return;
-              try {
-                await callThermalAction('delete_log', { filename: f.filename });
-                lastFilesSig = '';
-                await pollConsole(true);
-              } catch (err) {
-                setStatus(`删除失败: ${err.message}`, true);
-              }
-            });
-            tdAct.appendChild(delBtn);
-          }
-          tr.append(tdName, tdKind, tdSize, tdTime, tdAct);
-          tbody.appendChild(tr);
-        }
-      }
-    }
-
-    // Stats summary & 24-ch + 8-ch grids
-    setTextIfChanged(
-      el('th-stats-summary'),
-      `MCU BMC(${stats.mcu_bmc_valid || 0}/24): 均 ${stats.mcu_bmc_avg ?? '--'}℃ [低 ${stats.mcu_bmc_min ?? '--'} ~ 高 ${stats.mcu_bmc_max ?? '--'}℃, 温差 ${stats.mcu_bmc_spread ?? '--'}℃]  ·  ` +
-      `CT7428(${stats.ct_valid || 0}/8): 均 ${stats.ct_avg ?? '--'}℃ [高 ${stats.ct_max ?? '--'}℃]  ·  ` +
-      `服务器IPMI(${stats.ipmi_valid || 0}/24): 均 ${stats.ipmi_avg ?? '--'}℃ [高 ${stats.ipmi_max ?? '--'}℃]`
-    );
-    setTextIfChanged(
-      el('th-station-sync-note'),
-      `关联工位 ${stCtx.station_id || 'S1'} · 阶段: ${stCtx.phase || 'idle'} · 任务: ${stCtx.task_status || 'not_started'} · 电源: ${stCtx.server_power || '--'} · 累计错误: ${stCtx.stage_error_total || 0}`
-    );
-
-    const ctArr = Array.isArray(snap.ct7428_8) ? snap.ct7428_8 : [];
-    for (let i = 0; i < 8; i++) {
-      const v = ctArr[i];
-      const txt = v != null ? `${v} ℃` : '--';
-      if (ctCells[i].prev !== txt) {
-        ctCells[i].prev = txt;
-        ctCells[i].val.textContent = txt;
-      }
-    }
-
-    const mcuArr = Array.isArray(snap.mcu_bmc_24) ? snap.mcu_bmc_24 : [];
-    const ipmiArr = Array.isArray(snap.ipmi_dimm_24) ? snap.ipmi_dimm_24 : [];
-    for (let i = 0; i < 24; i++) {
-      const cell = slotCells[i];
-      const mv = mcuArr[i];
-      const iv = ipmiArr[i];
-      const mTxt = mv != null ? `MCU: ${mv}℃` : 'MCU: --';
-      const iTxt = iv != null ? `IPMI: ${Number(iv).toFixed(1)}℃` : 'IPMI: --';
-      const dTxt = (mv != null && iv != null) ? `Δ${(mv - iv >= 0 ? '+' : '') + (mv - iv).toFixed(1)}` : '';
-      const maxT = Math.max(mv ?? -1, iv ?? -1);
-      const cls = maxT > 80
-        ? 'th-slot-card is-hot'
-        : maxT >= 65
-          ? 'th-slot-card is-warn'
-          : maxT >= 0
-            ? 'th-slot-card is-valid'
-            : 'th-slot-card';
-      if (cell.prevCls !== cls) { cell.prevCls = cls; cell.card.className = cls; }
-      if (cell.prevMcu !== mTxt) { cell.prevMcu = mTxt; cell.mcuStrong.textContent = mTxt; }
-      if (cell.prevIpmi !== iTxt) { cell.prevIpmi = iTxt; cell.ipmiSpan.textContent = iTxt; }
-      if (cell.prevDiff !== dTxt) { cell.prevDiff = dTxt; cell.diffSpan.textContent = dTxt; }
-    }
-
-    // Incremental ring buffer update (O(1) bounded at 720 points)
-    if (snap.reset_ring) {
-      chartRing = Array.isArray(snap.points_delta) ? snap.points_delta.slice(-MAX_POINTS) : [];
-    } else if (Array.isArray(snap.points_delta) && snap.points_delta.length > 0) {
-      for (const pt of snap.points_delta) {
-        chartRing.push(pt);
-      }
-      if (chartRing.length > MAX_POINTS) {
-        chartRing.splice(0, chartRing.length - MAX_POINTS);
-      }
-    }
-    if (typeof snap.latest_point_seq === 'number') {
-      sinceSeq = snap.latest_point_seq;
-    }
-    scheduleChartDraw();
-
-    // Debug logs (only rendered when drawer is open)
-    if (el('th-debug-drawer').open) {
-      const ascii = Array.isArray(snap.ascii_logs) ? snap.ascii_logs : [];
-      const aSig = ascii.length ? `${ascii[0].unix_ms}:${ascii.length}` : 'empty';
-      if (aSig !== lastAsciiSig) {
-        lastAsciiSig = aSig;
-        el('th-ascii-log-pre').textContent = ascii.length
-          ? ascii.slice(0, 45).map(a => `[${(a.time_str || '').slice(11, 23)}] ${a.line}`).join('\n')
-          : '暂无 MCU 串口 ASCII 输出...';
-      }
-
-      const evs = Array.isArray(snap.events) ? snap.events.slice(0, 20) : [];
-      const frms = Array.isArray(snap.frames) ? snap.frames.slice(0, 25) : [];
-      const fSig = `${evs[0]?.unix_ms || 0}:${frms[0]?.unix_ms || 0}:${frms.length}`;
-      if (fSig !== lastFrameSig) {
-        lastFrameSig = fSig;
-        const evTxt = evs.map(e => `[事件 ${(e.time_str || '').slice(11, 19)} ${e.level}] ${e.message}`).join('\n');
-        const frTxt = frms.map(f => `[${f.dir} ${f.cmd} ${f.len}B] ${f.hex}`).join('\n');
-        el('th-frame-log-pre').textContent = [evTxt, frTxt].filter(Boolean).join('\n--- 最近协议报文 ---\n') || '暂无事件与协议帧...';
-      }
-    }
-  }
-
-  async function pollConsole(forceIncludeDebug = false) {
-    if (pollInFlight || document.hidden) return;
-    pollInFlight = true;
-    try {
-      const onThermalPage = document.body.dataset.currentPage === 'thermal';
-      const includeFrames = Boolean(forceIncludeDebug || (onThermalPage && el('th-debug-drawer')?.open));
-      const snap = await window.stlTransport.call('GetThermalConsole', {
-        since_seq: sinceSeq,
-        include_frames: includeFrames,
-      }, 8000);
-      if (snap) renderSnapshot(snap);
-    } catch {
-      // Transport layer handles reconnects gracefully
-    } finally {
-      pollInFlight = false;
-    }
-  }
-
-  function resetPollTimer() {
-    if (pollTimer) clearInterval(pollTimer);
-    const onThermalPage = document.body.dataset.currentPage === 'thermal';
-    pollTimer = setInterval(() => pollConsole(false), onThermalPage ? 1000 : 3500);
-  }
-
-  window.addEventListener('stl:page-change', ev => {
-    resetPollTimer();
-    if (ev.detail?.page === 'thermal') {
-      scanPorts(true);
-      pollConsole(false);
-      scheduleChartDraw();
-    }
-  });
-  document.addEventListener('visibilitychange', () => {
-    if (!document.hidden) pollConsole(false);
-  });
-  el('th-debug-drawer').addEventListener('toggle', () => {
-    if (el('th-debug-drawer').open) pollConsole(true);
-  });
-
-  // Initial bootstrap
-  resetPollTimer();
-  setTimeout(() => {
-    scanPorts(true);
-    pollConsole(false);
-  }, 300);
-})();
-