Просмотр исходного кода

Release 0.8.1.19: remove gRPC, add built-in UDP 69 TFTP, 26-test MT & UEFI FS*:\EFI\118.efi auto-discovery, 224-ICT/30-AMT dual-firmware adaptation, and Qt 0.8.1.19

XJKJ STL 2 недель назад
Родитель
Сommit
f106e6e73d
56 измененных файлов с 6699 добавлено и 5714 удалено
  1. 3 3
      Dockerfile
  2. 4 4
      README.md
  3. 1 1
      VERSION
  4. 1 1
      config.json
  5. 1 1
      deploy/stl-backend.service
  6. 4 4
      docker-compose.yml
  7. 39 0
      docs/QT_CLIENT_API_ZH.md
  8. 524 1077
      docs/WEBSOCKET_API_ZH.md
  9. 1 1
      native/stl_accel/c_bridge.c
  10. 1 1
      native/stl_accel/opencl_batch.c
  11. 96 24
      native/stl_accel/parser_re2c.re
  12. 1 1
      native/stl_accel/scan_asm.S
  13. 88 38
      native/stl_accel/src/actors.rs
  14. 43 2
      native/stl_accel/src/api.rs
  15. 219 26
      native/stl_accel/src/commands.rs
  16. 7 7
      native/stl_accel/src/config.rs
  17. 27 2
      native/stl_accel/src/devices.rs
  18. 188 46
      native/stl_accel/src/firmware.rs
  19. 0 1682
      native/stl_accel/src/grpc.rs
  20. 8 0
      native/stl_accel/src/json.rs
  21. 1 1
      native/stl_accel/src/lib.rs
  22. 699 48
      native/stl_accel/src/main.rs
  23. 767 19
      native/stl_accel/src/pxe.rs
  24. 267 5
      native/stl_accel/src/results.rs
  25. 32 2
      native/stl_accel/src/storage.rs
  26. 387 40
      native/stl_accel/src/workflow.rs
  27. 1 1
      native/stl_accel/zig_kernels.zig
  28. 0 469
      proto/stl/v1/bench.proto
  29. 402 89
      src/backendlink.cpp
  30. 40 23
      src/backendlink.h
  31. 8 3
      src/comanager.cpp
  32. 4 3
      src/comanager.h
  33. 8 8
      src/comworker.cpp
  34. 9 6
      src/comworker.h
  35. 172 29
      src/createtaskdialog.cpp
  36. 13 2
      src/createtaskdialog.h
  37. 64 4
      src/createtaskdialog.ui
  38. 18 1
      src/detailview.cpp
  39. 1 0
      src/detailview.h
  40. 417 315
      src/localplans.cpp
  41. 72 72
      src/localplans.h
  42. 2 2
      src/main.cpp
  43. 315 56
      src/mainwindow.cpp
  44. 21 1
      src/mainwindow.h
  45. 18 13
      src/overviewview.cpp
  46. 7 1
      src/powerbutton.cpp
  47. 5 7
      src/sltproto.cpp
  48. 7 6
      src/sltproto.h
  49. 589 468
      src/stationdata.cpp
  50. 183 159
      src/stationdata.h
  51. 850 832
      src/style/app.qss
  52. 19 11
      src/uiformat.h
  53. 1 68
      tools/validate_qt_clean.py
  54. 2 2
      web/boot-plan-controls.js
  55. 27 12
      web/firmware-controls.js
  56. 15 15
      web/index.html

+ 3 - 3
Dockerfile

@@ -14,9 +14,9 @@ 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.18
+ARG STL_VERSION=0.8.1.19
 ENV STL_BUILD_COMMIT=${STL_BUILD_COMMIT} \
     STL_VERSION=${STL_VERSION}
 
-EXPOSE 8080 50051
-CMD ["/usr/local/bin/stl_native_server", "--config", "/app/config/station0-live.json", "--web-listen", "0.0.0.0:8080", "--grpc-listen", "0.0.0.0:50051", "--data-dir", "/app/data", "--web-dir", "/app/web", "--contracts", "/app/contracts/firmware-vd012.json"]
+EXPOSE 8080 69/udp
+CMD ["/usr/local/bin/stl_native_server", "--config", "/app/config/station0-live.json", "--web-listen", "0.0.0.0:8080", "--tftp-listen", "0.0.0.0:69", "--data-dir", "/app/data", "--web-dir", "/app/web", "--contracts", "/app/contracts/firmware-vd012.json"]

+ 4 - 4
README.md

@@ -1,8 +1,8 @@
 # XJKJ-STL 高温内存测试工作台
 
-当前版本:`0.8.1.18`(分支:`dev`)。
+当前版本:`0.8.1.19`(分支:`dev`)。
 
-本仓库为 `XJKJ-STL` DDR5 内存高温测试与 BIOS 串口诊断工作台全栈源码(含原生高性能控制后端 `stl_native_server`、现代 Web 多页前端 `web/`、以及 Windows/Linux Qt 客户端 `src/`),同时提供完整 WebSocket(`/ws`)、原生 HTTP/2 gRPC(`:50051`,`stl.v1.BenchService`)及面向 Qt 的精简纯净接口(`/ws?view=qt-clean`)。
+本仓库为 `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 服务)。
 
 ## 目录结构
 
@@ -12,9 +12,9 @@
   - `parser_re2c.re` / `parser_re2c.c`:确定性 `re2c` DFA 固件阶段与报错状态机;
   - `zig_kernels.zig`:RFC 6455 WebSocket 握手摘要与 Base64 核;
   - `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`、`grpc.rs`、`commands.rs`、`workflow.rs`、`firmware.rs`、`results.rs`、`devices.rs`、`pxe.rs`、`storage.rs`、`config.rs`、`json.rs`、`lib.rs`)。
+  - `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.18`),对接 `/ws?view=qt-clean`。
+- `src/` + `DDR5_SLT_Monitor.pro`:Qt 客户端源码(`0.8.1.19`),对接 `/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.18
+0.8.1.19

Разница между файлами не показана из-за своего большого размера
+ 1 - 1
config.json


+ 1 - 1
deploy/stl-backend.service

@@ -9,7 +9,7 @@ User=stl
 Group=stl
 WorkingDirectory=/opt/xjkj-stl
 EnvironmentFile=/etc/xjkj-stl/stl-backend.env
-ExecStart=/usr/local/bin/stl_native_server --config /etc/xjkj-stl/station0-live.json --web-listen 0.0.0.0:8080 --data-dir /var/lib/xjkj-stl --web-dir /opt/xjkj-stl/web --contracts /opt/xjkj-stl/contracts/firmware-vd012.json
+ExecStart=/usr/local/bin/stl_native_server --config /etc/xjkj-stl/station0-live.json --web-listen 0.0.0.0:8080 --tftp-listen 0.0.0.0:69 --data-dir /var/lib/xjkj-stl --web-dir /opt/xjkj-stl/web --contracts /opt/xjkj-stl/contracts/firmware-vd012.json
 StateDirectory=xjkj-stl
 StateDirectoryMode=0750
 UMask=0027

+ 4 - 4
docker-compose.yml

@@ -3,9 +3,9 @@ services:
     build:
       context: .
       args:
-        STL_VERSION: ${STL_VERSION:-0.8.1.18}
+        STL_VERSION: ${STL_VERSION:-0.8.1.19}
         STL_BUILD_COMMIT: ${STL_BUILD_COMMIT:-vd012-native}
-    image: xjkj-stl:0.8.1.18
+    image: xjkj-stl:0.8.1.19
     container_name: xjkj-stl-backend
     restart: unless-stopped
     stop_grace_period: 30s
@@ -24,8 +24,8 @@ services:
       - /app/config/station0-live.json
       - --web-listen
       - 0.0.0.0:8080
-      - --grpc-listen
-      - 0.0.0.0:50051
+      - --tftp-listen
+      - 0.0.0.0:69
       - --data-dir
       - /app/data
       - --web-dir

+ 39 - 0
docs/QT_CLIENT_API_ZH.md

@@ -594,3 +594,42 @@ void BackendLink::applyBiosUart(const QJsonObject &result)
 2. **双模式队列、单调 64 位环形缓冲归档与审计**:
    - 同时支持**前端自维护队列**(基于 `task_complete` 主动推送 + `GetTaskStatus` 轮询 + `qt-plans.json` 任务编排)与**后端托管多 Profile 批次队列**(`SubmitTaskBatch` / `ControlTaskBatch` / `GetTaskBatch`)。
    - 无论批量队列、前端队列或单次测试,每轮从 `active_run_start_offset` 自动归档 `sol.raw`、`sol.clean.log`、`summary.json`;所有来自 Web 或 Qt 的配置与队列变更实时追加记录至 `data/config_audit.jsonl`。
+
+## 10. 0.8.1.19 变更与补充规范(gRPC 下线、26 项 MT、内建 TFTP、双固件 tRFCsb 适配及 Qt 单文件规范)
+
+本章节在完整保留第 0~8 章原始规范(第 1~507 行一字不改)与第 9 章 `0.8.1.18` 规范的基础上,补充 `0.8.1.19` 版本正式落地的协议收敛、测试项扩展与硬件实测修正。
+
+### 10.1 移除旧版 gRPC,接口收敛为双 WebSocket + 内建 UDP `:69` TFTP
+
+1. **彻底移除 `:50051` gRPC**:
+   - `stl_native_server` 自 `0.8.1.19` 起已删除旧版 gRPC 监听端口与 Protobuf 契约,对外仅保留 HTTP/WebSocket(`:8080`:`http://<host>:8080/`、`ws://<host>:8080/ws`、`ws://<host>:8080/ws?view=qt-clean`)与内建非阻塞 UDP `:69` TFTP 文件服务(默认监听 `0.0.0.0:69`,可通过 `--tftp-listen disabled` 关闭)。
+2. **`/ws?view=qt-clean` 精确白名单(12 个 RPC)**:
+   - `GetSystemInfo`、`GetState`、`StartTest`、`StageAction`、`GetCommand`、`ReadBiosUart`、`ConfirmDimmReplacement`、`SetStageIntent`、`GetTaskStatus`、`SubmitTaskBatch`、`ControlTaskBatch`、`GetTaskBatch`。其余管理/诊断接口(如 `GetStationControl`、`GetFirmwareCatalog`、`EnqueueCommand`、`ReadCleanedUart`、`ReadAuditLogs` 等)仅对 `/ws`(完整版)开放,在 `/ws?view=qt-clean` 上统一返回 `UNIMPLEMENTED`。
+
+### 10.2 MT 扩展至 26 项(`Test 0~25`)、内建 TFTP RRQ/WRQ 与 HTML 报告判定
+
+1. **26 项 MT 算法默认全量启用**:
+   - `mtParams` 默认 `TSTLIST="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25"`,兼容全部 26 项 MemTest86 子测试(原 `0..13` + 新增 `14: DMA Test`、`15: March C`、`16~23: Galloping Patterns (galpat / linear / randaddr / bankjump / victim / marchic / marchsse / butterfly)`、`24: March SS+`、`25: StressApp`)。
+   - 生成的 `mt86.cfg` 默认配置:`NUMPASS=1`、`CPUSEL=PARALLEL`、`CPUNUM=384`、`MAXCPUS=384`、`DISABLEMP=0`、`ENABLEHT=1`、`ECCPOLL=1`、`AUTOMODE=1`、`EXITMODE=2`(完成后退回 `FS0:\EFI>`,绝不自动关机/重启)、`SKIPSPLASH=1`、`AUTOREPORT=1`、`AUTOREPORTFMT=HTML`、`REPORTNUMERRS=100`;当 `AUTOREPORT > 0` 时写入 `TFTPSERVERIP=<pxe_server_ip>`(默认 `192.168.0.10`)。
+2. **内建 UDP `:69` TFTP RRQ/WRQ 闭环**:
+   - 支持 RFC 2347/2348/2349(`blksize` / `timeout` / `tsize`)选项协商;`RRQ` 自动分发三变体 `118.efi` 与多文件名候选 `mt86.cfg`;`WRQ` 自动接收 MemTest86 上传的 `.html/.htm` 测试报告(同时拒绝覆盖 `.efi` 与 `mt86.cfg` 保护启动文件),解析 `verdict` / `errors` / `tests_passed` / `elapsed` 后写入 `pxe_control.recent_reports` 并同步至当前处于 `uefi`/`mt` 阶段的工位 `mt_result`。
+   - 串口侧同步支持 `Test result:` 汇总行与多行错误坐标归位;若 UEFI Shell 输出 `'118.efi' is not recognized...` 或尚未观测到 MemTest86 启动横幅,绝不因返回 `FS0:\EFI>` 而误判为 `mt_pass_complete=true`。
+
+### 10.3 双固件参数映射修正与全量 224 ICT / 30 AMT 目录
+
+1. **Hovsee(`.166` `107_VD012`)与 CXMT(`.165` `CxmtDdrTest`)命令自适应**:
+   - `tRFCsb` 在 `.166`(`107_VD012`)实机上对应的底层指令为 **`(24) actm trfcfgrcsb(ns)`**(无单独 `actm trfcsb`);后端在构建 ICT Stage 1 命令时按识别到的 `firmware_family` 自动完成 `actm.trfcsb` → `actm trfcfgrcsb`(Hovsee)与 `actm.trfcfgrcsb` → `actm trfcsb`、`actm.trefsb` → `actm trefsbrd`(CXMT)的双向映射、去重与专属项过滤。
+   - 全量目录升级为 **224 项 ICT 参数**与 **30 项 AMT 菜单控制**(新增 `srdelay`、`mrw`、`mrr_count`);`SetStageIntent` 对 AMT/MT 下发时自动清理遗留的 `only_tests` / `skip_tests` / `selected` / `addr_lim_*` 与旧 `tp` 覆盖,并严格遵循 Last-Write-Wins。
+2. **安全时序拉偏 presets 同步适配**:
+   - 零加压非破坏性错误注入预设(如 `tRCD=22 / tRP=22`、`tRFC=180 / tRFCsb=110`)同步遵循上述双固件 `trfcfgrcsb`/`trfcsb` 自动适配规则。
+
+### 10.4 状态语义细分、`mt_fail_complete`、离线诚实上报与单文件 Qt 运行期目录
+
+1. **`stage_completions` 与失败锁存细节**:
+   - `stage_completions` 包含 7 项阶段完成标志(`ict_stage1_complete`、`training_complete`、`rmt_complete`、`amt_complete`、`ict_stage2_complete`、`uefi_complete`、`mt_pass_complete`)及 `mt_fail_complete` 诊断布尔位。
+   - 内存报错坐标解析严格校验 `0 <= bank < 32`;任意阶段报错待本阶段完整收尾后锁存 `awaiting_dimm_replacement = true`(`run_state = "blocked"`、`task_status = "failed"`),拦截进入下一阶段;通过 `ConfirmDimmReplacement`(或点击主界面 `开始测试` 重新发起测试)解除挂起。
+2. **离线工位诚实状态**:
+   - 当工位串口与 BMC IPMI 均不可达时(如离线测试台),`connection = "offline"`、`power = "unknown"`、`console_online = false`,不显示假在线。
+3. **Qt 单文件客户端与 `STL_QT_CONFIG_DIR` 外部落盘规范**:
+   - Qt 界面默认值更新为 `mem vdd = 1070` mV、`mem vddq = 1070` mV、`tRFCsb = 123`、MT 全选 26 项(`Test 0~25`);详情页「机台任务」支持 `排队中` / `执行中` / `等待换条` / `执行失败` / `已完成` / `未开始`。
+   - Windows 单文件自解压启动器运行时释放至 `%LOCALAPPDATA%\XJKJ-STL\runtime-0.8.1.19`,并将 `STL_QT_CONFIG_DIR` 指向外层 `DDR5_SLT_Monitor.exe` 所在目录,使 `config.json`、`port.json`、`qt-plans.json`、`client-id.txt`、`app.log` 始终保存于外层 EXE 同级目录。

Разница между файлами не показана из-за своего большого размера
+ 524 - 1077
docs/WEBSOCKET_API_ZH.md


+ 1 - 1
native/stl_accel/c_bridge.c

@@ -1,5 +1,5 @@
 /*
- * c_bridge.c — XJKJ-STL Native C Runtime Bridge (v0.8.1.18)
+ * c_bridge.c — XJKJ-STL Native C Runtime Bridge (v0.8.1.19)
  *
  * Compiled strictly with -O3 -march=x86-64 (pure SSE2 baseline, no AVX/POPCNT
  * emitted by the compiler) so dual-core Celeron/Pentium (Sandy Bridge..Coffee Lake)

+ 1 - 1
native/stl_accel/opencl_batch.c

@@ -1,5 +1,5 @@
 /*
- * opencl_batch.c — Intel Gen7.5..Gen9.5 OpenCL 1.2 Zero-Copy Shared Memory Batch Offload (v0.8.1.18)
+ * opencl_batch.c — Intel Gen7.5..Gen9.5 OpenCL 1.2 Zero-Copy Shared Memory Batch Offload (v0.8.1.19)
  *
  * Strictly OFF the real-time short serial path!
  * Dynamically loads libOpenCL.so.1 via dlopen; automatically falls back to pure

+ 96 - 24
native/stl_accel/parser_re2c.re

@@ -1,5 +1,5 @@
 /*
- * XJKJ-STL Deterministic re2c Line Lexer & Coordinate Extractor (v0.8.1.18)
+ * XJKJ-STL Deterministic re2c Line Lexer & Coordinate Extractor (v0.8.1.19)
  *
  * Compiled via: re2c -W --no-generation-date -o parser_re2c.c parser_re2c.re
  * Pure C11 / x86-64 SSE2 baseline; zero heap allocations; replaces per-line
@@ -56,6 +56,16 @@ static int parse_hex64_at(const uint8_t *p, const uint8_t *end, uint64_t *out) {
         p++;
     }
     if (digits == 0) return 0;
+    if (p < end) {
+        uint8_t nc = *p;
+        if (nc == '_' ||
+            (nc >= 'g' && nc <= 'z' && nc != 'h') ||
+            (nc >= 'G' && nc <= 'Z' && nc != 'H') ||
+            ((nc == 'h' || nc == 'H') && p + 1 < end &&
+             ((p[1] >= '0' && p[1] <= '9') || (p[1] >= 'a' && p[1] <= 'z') || (p[1] >= 'A' && p[1] <= 'Z')))) {
+            return 0;
+        }
+    }
     *out = v;
     return 1;
 }
@@ -99,6 +109,17 @@ 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 + 3 <= end && (q[1] == 'B' || q[1] == 'b') && q[2] >= '0' && q[2] <= '9') {
+                        int bk = 0;
+                        const uint8_t *bp = q + 2;
+                        while (bp < end && *bp >= '0' && *bp <= '9') {
+                            bk = bk * 10 + (*bp - '0');
+                            bp++;
+                        }
+                        if (bk >= 0 && bk < 32) {
+                            ev->bank = (int8_t)bk;
+                        }
+                        q = bp;
                     } else {
                         break;
                     }
@@ -148,6 +169,14 @@ static int match_ci_kw(const uint8_t *p, const uint8_t *end, const char *kw, con
     return 1;
 }
 
+static int match_ci_word(const uint8_t *buf_start, const uint8_t *p, const uint8_t *end, const char *kw, const uint8_t **after) {
+    if (p > buf_start) {
+        uint8_t prev = p[-1];
+        if ((prev >= 'a' && prev <= 'z') || (prev >= 'A' && prev <= 'Z') || prev == '_') return 0;
+    }
+    return match_ci_kw(p, end, kw, after);
+}
+
 /*
  * Extract physical topology coordinates from BIOS/Training/AMT/MemTest86 lines.
  * Strictly enforces 0 <= bank < 32 (never trusts broken historical >= 32 bank analyses).
@@ -537,7 +566,7 @@ scan_anywhere:
                 }
                 return STL_LK_DIMM_INVENTORY;
             }
-            "[" ("HS" | "HD") "_DisableDimm]" | "DisableDIMM()" | "MapOutDimm()" | "Mapping out DDR" {
+            "[" ("HS" | "HD") "_Disable" ("Dimm" | "DIMM") "]" | "DisableDIMM()" | "MapOutDimm()" | "Mapping out DDR" {
                 extract_coords_and_addr(s, end, ev);
                 ev->subkind = 3; /* disabled */
                 return STL_LK_DIMM_INVENTORY;
@@ -604,13 +633,23 @@ scan_anywhere:
                 }
                 return STL_LK_AMT_PROGRESS;
             }
-            "Failure detected - Advanced Memtest" | "Error Address" | "Fail Address" |
+            "Failure detected - Advanced Memtest" | "Failure detected - PPR Memtest" |
             "Data Compare Error" | "[AMT_ERR]" | "[AMEMDIAG_ERR]" |
             "[" ("HS" | "HD") "_MemoryError]" {
                 ev->subkind = 2;
                 extract_coords_and_addr(s, end, ev);
                 return STL_LK_AMT_ERROR;
             }
+            "Error Address" | "Fail Address" {
+                uint64_t ea = 0;
+                if (!parse_hex64_at(YYCURSOR, lim, &ea) || ea == 0) {
+                    continue;
+                }
+                ev->subkind = 2;
+                ev->addr = ea;
+                extract_coords_and_addr(s, end, ev);
+                return STL_LK_AMT_ERROR;
+            }
             "Logical Rank" WS "=" | "Error on rising strobe:" | "Error on falling strobe:" {
                 ev->subkind = 5; /* 3-line AMT diagnostic continuation */
                 extract_coords_and_addr(s, end, ev);
@@ -618,7 +657,9 @@ scan_anywhere:
             }
             "Failing DIMM" | "[BIOS][FailMode]" |
             "Training Fail" | "BIST Error" | "BIST FAIL" | "Uncorrectable" |
-            "Correctable error threshold exceeded" {
+            "Correctable error threshold exceeded" |
+            "No eye found" | "smaller than minimum critical margin" | "RxPerBitDeskew Failure" |
+            "Parity Error" | "Parity error" | "PEC Error" | "PEC error" {
                 ev->subkind = 2;
                 extract_coords_and_addr(s, end, ev);
                 return STL_LK_TRAINING_ERROR;
@@ -678,10 +719,12 @@ scan_anywhere:
                 ev->val2 = (ptot > 0) ? ((pno * 100) / ptot) : 50;
                 return STL_LK_MT_PROGRESS;
             }
-            ("Test Result" | "Result") WS ":" WS ("PASS" | "FAIL" | "FAILED") {
+            ("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, "fail", &af) || match_ci_kw(p, lim, "failed", &af)) {
+                    if (match_ci_kw(p, lim, "incomplete", &af) ||
+                        match_ci_kw(p, lim, "fail", &af) ||
+                        match_ci_kw(p, lim, "failed", &af)) {
                         ev->subkind = 2;
                         return STL_LK_MT_FAIL_COMPLETE;
                     }
@@ -717,22 +760,25 @@ scan_anywhere:
                 int32_t tid = 0;
                 if (parse_i32_at(tok + 14, lim, &tid, NULL)) {
                     ev->val0 = tid;
-                    ev->val1 = 13;
-                    ev->val2 = (tid >= 0 && tid <= 13) ? ((tid * 100) / 14) : 50;
+                    ev->val1 = 25;
+                    ev->val2 = (tid >= 0 && tid <= 25) ? ((tid * 100) / 26) : 50;
                 }
                 return STL_LK_MT_PROGRESS;
             }
-            "N" [01] ".C" DIG (".D" [01])? (".SC" [01])? ".R" DIG (".L" DIG)? WS ":" {
+            "N" [01] ".C" DIG (".D" [01])? (".SC" [01])? ".R" DIG (".L" DIG)? (".B" DIG)? WS ":" {
                 extract_ncd_token(s, end, ev);
                 for (const uint8_t *q = YYCURSOR; q + 4 <= lim; q++) {
                     const uint8_t *af = NULL;
-                    if (match_ci_kw(q, lim, "advanced memtest", &af) ||
-                        match_ci_kw(q, lim, "failure detected", &af)) {
+                    if (match_ci_word(YYCURSOR, q, lim, "advanced memtest", &af) ||
+                        match_ci_word(YYCURSOR, q, lim, "failure detected", &af) ||
+                        match_ci_word(YYCURSOR, q, lim, "ppr memtest", &af)) {
                         ev->subkind = 2;
                         extract_coords_and_addr(s, end, ev);
                         return STL_LK_AMT_ERROR;
                     }
-                    if (match_ci_kw(q, lim, "error", &af) || match_ci_kw(q, lim, "failed", &af)) {
+                    if (match_ci_word(YYCURSOR, q, lim, "error", &af) ||
+                        match_ci_word(YYCURSOR, q, lim, "failed", &af) ||
+                        match_ci_word(YYCURSOR, q, lim, "fail", &af)) {
                         ev->subkind = 2;
                         extract_coords_and_addr(s, end, ev);
                         return STL_LK_TRAINING_ERROR;
@@ -744,32 +790,51 @@ scan_anywhere:
                 extract_ncd_token(s, end, ev);
                 for (const uint8_t *q = tok; q + 11 <= lim; q++) {
                     const uint8_t *af_por = NULL;
-                    if (match_ci_kw(q, lim, "minimum por", &af_por)) {
+                    if (match_ci_word(tok, q, lim, "minimum por", &af_por)) {
                         ev->subkind = 4;
                         return STL_LK_DIMM_INVENTORY;
                     }
                 }
+                for (const uint8_t *p = tok; p + 11 <= lim; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_word(tok, p, lim, "failure detected", &af) ||
+                        match_ci_word(tok, p, lim, "advanced memtest", &af) ||
+                        match_ci_word(tok, p, lim, "ppr memtest", &af)) {
+                        ev->subkind = 2;
+                        extract_coords_and_addr(s, end, ev);
+                        return STL_LK_AMT_ERROR;
+                    }
+                }
                 for (const uint8_t *p = tok; p + 4 <= lim; p++) {
                     const uint8_t *af = NULL;
-                    if (match_ci_kw(p, lim, "disabled", &af)) {
+                    if (match_ci_word(tok, p, lim, "disabled", &af)) {
                         ev->subkind = 3;
                         return STL_LK_DIMM_INVENTORY;
                     }
-                    if (match_ci_kw(p, lim, "not", &af) || match_ci_kw(p, lim, "empty", &af) ||
-                        match_ci_kw(p, lim, "absent", &af)) {
+                    if (match_ci_word(tok, p, lim, "fail", &af) ||
+                        match_ci_word(tok, p, lim, "failed", &af) ||
+                        match_ci_word(tok, p, lim, "failure", &af) ||
+                        match_ci_word(tok, p, lim, "error", &af)) {
+                        ev->subkind = 2;
+                        extract_coords_and_addr(s, end, ev);
+                        return STL_LK_TRAINING_ERROR;
+                    }
+                }
+                for (const uint8_t *p = tok; p + 3 <= lim; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_word(tok, p, lim, "not", &af) ||
+                        match_ci_word(tok, p, lim, "empty", &af) ||
+                        match_ci_word(tok, p, lim, "absent", &af)) {
                         ev->subkind = 0;
                         return STL_LK_DIMM_INVENTORY;
                     }
-                    if (match_ci_kw(p, lim, "present", &af) || match_ci_kw(p, lim, "ddr5", &af) ||
-                        match_ci_kw(p, lim, "enabled", &af) || match_ci_kw(p, lim, "test", &af)) {
+                    if (match_ci_word(tok, p, lim, "present", &af) ||
+                        match_ci_word(tok, p, lim, "ddr5", &af) ||
+                        match_ci_word(tok, p, lim, "enabled", &af) ||
+                        match_ci_word(tok, p, lim, "test", &af)) {
                         ev->subkind = 4;
                         return STL_LK_DIMM_INVENTORY;
                     }
-                    if (match_ci_kw(p, lim, "fail", &af) || match_ci_kw(p, lim, "error", &af)) {
-                        ev->subkind = 2;
-                        extract_coords_and_addr(s, end, ev);
-                        return STL_LK_TRAINING_ERROR;
-                    }
                 }
                 continue;
             }
@@ -844,7 +909,14 @@ void stl_re2c_parse_line(const uint8_t *line, size_t len, uint32_t tag_mask, Stl
     if (s >= e) return;
 
     if (tag_mask == 0 && s[0] == '.') {
-        return;
+        int only_dots = 1;
+        for (const uint8_t *p = s; p < e; p++) {
+            if (*p != '.' && *p != ' ' && *p != '\t') {
+                only_dots = 0;
+                break;
+            }
+        }
+        if (only_dots) return;
     }
 
     ev->kind = re2c_scan_token(s, e, ev);

+ 1 - 1
native/stl_accel/scan_asm.S

@@ -1,5 +1,5 @@
 /*
- * XJKJ-STL Native Hand-Written x86-64 Assembly Kernels (v0.8.1.18)
+ * XJKJ-STL Native Hand-Written x86-64 Assembly Kernels (v0.8.1.19)
  *
  * Strictly retains ONLY:
  *   1. asm_xgetbv_eax0: OSXSAVE YMM state check for runtime CPUID dispatch.

+ 88 - 38
native/stl_accel/src/actors.rs

@@ -146,6 +146,7 @@ pub enum StationMsg {
         resolved_host: Option<String>,
         power: Option<String>,
         sdr_output: Option<String>,
+        bmc_state: Option<String>,
     },
     /// Deterministic test/simulation helper (used by unit tests & local dry verification)
     TestInjectSerial {
@@ -158,6 +159,11 @@ pub enum StationMsg {
         pxe_snapshot: JsonVal,
         reply_tx: mpsc::Sender<()>,
     },
+    MtReportUploaded {
+        report: JsonVal,
+        full_path: String,
+        force: bool,
+    },
 }
 
 pub enum IpmiJob {
@@ -694,7 +700,10 @@ 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()));
-    let conn = if st.diag_state == "online" || (st.bmc_enabled && !st.bmc_host.is_empty()) {
+    let conn = if st.diag_state == "online"
+        || st.console_online
+        || (st.bmc_enabled && !st.bmc_host.is_empty() && st.bmc_state == "online")
+    {
         "online"
     } else {
         "offline"
@@ -703,7 +712,11 @@ fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
     s.set("console_online", JsonVal::Bool(st.console_online));
     let power_str = if st.server_power == "off" {
         "off"
-    } else if st.bmc_enabled && !st.bmc_host.is_empty() && st.server_power == "unknown" {
+    } else if st.bmc_enabled
+        && !st.bmc_host.is_empty()
+        && st.bmc_state == "online"
+        && st.server_power == "unknown"
+    {
         "on"
     } else {
         st.server_power.as_str()
@@ -727,10 +740,12 @@ fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
         st.boot_execution.get_str_or("state", "idle")
     };
     s.set("run_state", JsonVal::Str(run_state));
-    let started_ms = if st.observed_unix_ms > 0 {
-        st.observed_unix_ms
+    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 {
-        0
+        st.observed_unix_ms
     };
     s.set("started_unix_ms", JsonVal::Str(started_ms.to_string()));
     s.set("boot_id", JsonVal::Str(st.boot_id.clone()));
@@ -771,18 +786,7 @@ fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
     temp_obj.set("state", JsonVal::Str(st.chamber_state.clone()));
     s.set("temperature", temp_obj);
 
-    let stage_str = match st.prompt_kind.as_str() {
-        "uip" => {
-            if st.prompt_uip_stage.unwrap_or(1) > 1 {
-                "uip2"
-            } else {
-                "uip1"
-            }
-        }
-        "amt" => "amt",
-        "uefi" => "uefi",
-        _ => "uip1",
-    };
+    let stage_str = st.current_input_stage();
     let actions_vec: Vec<JsonVal> = match stage_str {
         "uip1" => vec![
             JsonVal::Str("continue_uip".to_string()),
@@ -807,14 +811,7 @@ fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
         .map(|r| r.status == "pass" && r.algorithm_count > 0)
         .unwrap_or(false);
     let mut input_obj = JsonVal::obj();
-    input_obj.set(
-        "id",
-        JsonVal::Str(if st.prompt_ready {
-            format!("{}:{}:{}", st.boot_id, stage_str, cpu_idx)
-        } else {
-            String::new()
-        }),
-    );
+    input_obj.set("id", JsonVal::Str(st.current_input_id()));
     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));
@@ -957,10 +954,12 @@ pub fn spawn_station_actor(
                             .map(|(rh, _)| rh),
                             Err(_) => None,
                         };
+                        let bmc_ok = resolved.is_some();
                         let _ = actor_tx_for_ipmi.send(StationMsg::IpmiTelemetry {
                             resolved_host: resolved,
-                            power: Some("on".to_string()),
+                            power: if bmc_ok { Some("on".to_string()) } else { None },
                             sdr_output: None,
+                            bmc_state: Some(if bmc_ok { "online" } else { "offline" }.to_string()),
                         });
                         if ev_fd_for_ipmi >= 0 {
                             unsafe {
@@ -972,6 +971,19 @@ pub fn spawn_station_actor(
                         if host.is_empty() || !probe_tcp_port(&host, 22, 220) {
                             let alt = resolve_reachable_bmc_host(&host, 22);
                             if alt == host || !probe_tcp_port(&alt, 22, 220) {
+                                if !host.is_empty() {
+                                    let _ = actor_tx_for_ipmi.send(StationMsg::IpmiTelemetry {
+                                        resolved_host: None,
+                                        power: Some("unknown".to_string()),
+                                        sdr_output: None,
+                                        bmc_state: Some("offline".to_string()),
+                                    });
+                                    if ev_fd_for_ipmi >= 0 {
+                                        unsafe {
+                                            lib::stl_eventfd_notify(ev_fd_for_ipmi);
+                                        }
+                                    }
+                                }
                                 continue;
                             }
                         }
@@ -984,8 +996,10 @@ pub fn spawn_station_actor(
                         );
                         let mut resolved_host = None;
                         let mut power_opt = None;
+                        let mut bmc_online = false;
                         if let Ok((rh, txt)) = pwr_res {
                             resolved_host = Some(rh);
+                            bmc_online = true;
                             let low = txt.to_ascii_lowercase();
                             if low.contains(" is on") {
                                 power_opt = Some("on".to_string());
@@ -993,7 +1007,7 @@ pub fn spawn_station_actor(
                                 power_opt = Some("off".to_string());
                             }
                         }
-                        let sdr_opt = if power_opt.as_deref() != Some("off") {
+                        let sdr_opt = if bmc_online && power_opt.as_deref() != Some("off") {
                             run_ipmi_with_session(
                                 Some(&mut session),
                                 resolved_host.as_deref().unwrap_or(&host),
@@ -1006,16 +1020,19 @@ pub fn spawn_station_actor(
                         } else {
                             None
                         };
-                        if resolved_host.is_some() || power_opt.is_some() || sdr_opt.is_some() {
-                            let _ = actor_tx_for_ipmi.send(StationMsg::IpmiTelemetry {
-                                resolved_host,
-                                power: power_opt,
-                                sdr_output: sdr_opt,
-                            });
-                            if ev_fd_for_ipmi >= 0 {
-                                unsafe {
-                                    lib::stl_eventfd_notify(ev_fd_for_ipmi);
-                                }
+                        let _ = actor_tx_for_ipmi.send(StationMsg::IpmiTelemetry {
+                            resolved_host,
+                            power: if bmc_online {
+                                power_opt
+                            } else {
+                                Some("unknown".to_string())
+                            },
+                            sdr_output: sdr_opt,
+                            bmc_state: Some(if bmc_online { "online" } else { "offline" }.to_string()),
+                        });
+                        if ev_fd_for_ipmi >= 0 {
+                            unsafe {
+                                lib::stl_eventfd_notify(ev_fd_for_ipmi);
                             }
                         }
                     }
@@ -1049,6 +1066,7 @@ pub fn spawn_station_actor(
                                         resolved_host: Some(rh),
                                         power: Some(pwr.to_string()),
                                         sdr_output: None,
+                                        bmc_state: Some("online".to_string()),
                                     });
                                     if ev_fd_for_ipmi >= 0 {
                                         unsafe {
@@ -1163,6 +1181,7 @@ pub fn spawn_station_actor(
                                                 resolved_host: None,
                                                 power: None,
                                                 sdr_output: sdr_opt,
+                                                bmc_state: Some("online".to_string()),
                                             });
                                         if ev_fd_for_ipmi >= 0 {
                                             unsafe {
@@ -1223,7 +1242,7 @@ pub fn spawn_station_actor(
             }
 
             let mut registered_pty_fd: i32 = -1;
-            let mut cached_pxe_state = crate::pxe::default_pxe_state();
+            let mut cached_pxe_state = crate::storage::load_pxe_state(&data_dir);
             let mut next_ipmi_poll_ms = now_ms() + 6000;
             let mut ev_tokens = [0u64; 8];
             let mut ev_masks = [0u32; 8];
@@ -1443,7 +1462,14 @@ pub fn spawn_station_actor(
                             resolved_host,
                             power,
                             sdr_output,
+                            bmc_state,
                         } => {
+                            if let Some(bs) = bmc_state {
+                                if st.bmc_state != bs {
+                                    st.bmc_state = bs;
+                                    state_dirty = true;
+                                }
+                            }
                             if let Some(rh) = resolved_host {
                                 if !rh.is_empty() && rh != st.bmc_host {
                                     if st.console_host == st.bmc_host {
@@ -1529,6 +1555,30 @@ pub fn spawn_station_actor(
                             }
                             let _ = reply_tx.send(());
                         }
+                        StationMsg::MtReportUploaded {
+                            report,
+                            full_path,
+                            force,
+                        } => {
+                            st.apply_mt_html_report(&report, &full_path, force);
+                            step_boot_plan(&mut st, &contract);
+                            step_task_batch(
+                                &mut st,
+                                &contract,
+                                &mut cached_pxe_state,
+                                &data_dir,
+                                &pxe_tftp_dir,
+                            );
+                            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);
+                            if let Some(sig) = st.pending_complete_signal.take() {
+                                push_hub.broadcast_task_complete(&sig);
+                            }
+                        }
                     }
                 }
 

+ 43 - 2
native/stl_accel/src/api.rs

@@ -1,7 +1,7 @@
 // api.rs — Lock-Free Actor-Backed HTTP Static File Server, RFC 6455 WebSocket JSON v1
 //          Dispatcher (`/ws` Full + `/ws?view=qt-clean` Clean View), `stl_ws_writev2`
 //          Zero-Delay Merged Framing, `X-Client-Id` Session Persistence, Dirty-Bitmap
-//          Zero-Copy 1Hz State Broadcaster, and Condvar Pseudo-Push Live Tail (v0.8.1.18)
+//          Zero-Copy 1Hz State Broadcaster, and Condvar Pseudo-Push Live Tail (v0.8.1.19)
 
 use crate::actors::{
     spawn_station_actor, IpmiJob, PushBroadcaster, RingReadReply, StationHandle, StationMsg,
@@ -171,6 +171,20 @@ impl AppHub {
         }
 
         let pxe_state = load_pxe_state(&args.data_dir);
+        let pxe_cfg_path = pxe_tftp_dir.join("mt86.cfg");
+        let need_seed_cfg = match fs::read_to_string(&pxe_cfg_path) {
+            Ok(txt) => !txt.contains("AUTOREPORT="),
+            Err(_) => true,
+        };
+        if need_seed_cfg {
+            let cfg_obj = pxe_state
+                .get("mt86_cfg")
+                .cloned()
+                .unwrap_or_else(JsonVal::obj);
+            let pxe_server_ip = pxe_state.get_str_or("pxe_server_ip", "192.168.0.10");
+            let cfg_text = crate::pxe::render_mt86_cfg_text(&cfg_obj, &pxe_server_ip);
+            let _ = crate::pxe::write_local_mt86_candidates(&pxe_tftp_dir, &cfg_text);
+        }
         let (audit_items, audit_seq) = load_audit_logs(&args.data_dir);
         let contract = Arc::new(FirmwareContract::load(&args.contracts_path));
         let started_ms = now_ms();
@@ -616,6 +630,24 @@ impl AppHub {
         }
     }
 
+    pub fn force_tick(&self, sid: &str) {
+        let pxe_snap = self
+            .pxe_state
+            .read()
+            .map(|g| g.clone())
+            .unwrap_or_else(|_| JsonVal::obj());
+        if let Some(handle) = self.stations.get(sid) {
+            let (tx, rx) = mpsc::channel();
+            if handle.send(StationMsg::ForceTick {
+                pxe_snapshot: pxe_snap,
+                reply_tx: tx,
+            }) {
+                let _ = rx.recv_timeout(Duration::from_secs(5));
+                self.refresh_and_broadcast_qt_state();
+            }
+        }
+    }
+
     pub fn background_tick(&self) {
         let pxe_snap = self
             .pxe_state
@@ -995,7 +1027,16 @@ impl AppHub {
                         item.set("state", JsonVal::Str("succeeded".to_string()));
                         item.set("complete", JsonVal::Bool(true));
                         item.set("error", JsonVal::Null);
-                        item.set("result", strip_private_keys_recursive(&res_val));
+                        let stripped = strip_private_keys_recursive(&res_val);
+                        if mapped_method == "SetStageIntent" {
+                            for k in ["confirmation", "stage", "action", "sequence", "stage_intents"]
+                            {
+                                if let Some(v) = stripped.get(k) {
+                                    item.set(k, v.clone());
+                                }
+                            }
+                        }
+                        item.set("result", stripped);
                     }),
                     Err(err_msg) => self.finalize_command(&cmd_id, |item| {
                         item.set("state", JsonVal::Str("failed".to_string()));

+ 219 - 26
native/stl_accel/src/commands.rs

@@ -12,8 +12,8 @@ use crate::pxe::{
 use crate::results::{now_ms, AsyncScriptStep, StationState};
 use crate::storage::save_station_settings;
 use crate::workflow::{
-    apply_profile_to_station, build_uefi_mt_steps, control_boot_plan, normalize_boot_plan,
-    start_async_script, submit_task_batch,
+    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,
 };
 use std::path::Path;
 use std::sync::mpsc;
@@ -41,6 +41,23 @@ pub enum StationCmdExec {
     },
 }
 
+fn input_id_mismatch_err(st: &StationState, args: &JsonVal) -> Option<String> {
+    let req_id = args.get_str("input_id").unwrap_or("").trim();
+    if req_id.is_empty() {
+        return None;
+    }
+    let cur_id = st.current_input_id();
+    if !st.prompt_ready || cur_id.is_empty() || cur_id != req_id {
+        Some(format!(
+            "输入节点 {} 已失效或已处理 (current={})",
+            req_id,
+            if cur_id.is_empty() { "none" } else { cur_id.as_str() }
+        ))
+    } else {
+        None
+    }
+}
+
 pub fn build_diag_snapshot(st: &StationState) -> JsonVal {
     let mut d = JsonVal::obj();
     d.set("station_id", JsonVal::Str(st.station_id.clone()));
@@ -153,8 +170,61 @@ pub fn handle_station_command_nonblocking(
             };
             let seq = st.set_stage_intent(&stage, &action, args);
             match stage.as_str() {
+                "uip" | "uip1" | "uip2" => {
+                    if let Some(ovs) = args.get_arr("uip_overrides") {
+                        st.uip_overrides = ovs.clone();
+                    } else if args.get("memory_params").is_some() {
+                        // Full Qt memory_params snapshot replaces previous ICT parameter overrides
+                        // while preserving any prior explicit RMT/PXE directives unless overwritten below.
+                        st.uip_overrides.retain(|x| x.get_str_or("id", "") == "rmt");
+                        if args.get_arr("uip_raw_commands").is_none() {
+                            st.uip_raw_commands
+                                .retain(|c| c.trim().to_ascii_lowercase().starts_with("pxe "));
+                        }
+                    }
+                    if let Some(raws) = args.get_arr("uip_raw_commands") {
+                        st.uip_raw_commands = raws
+                            .iter()
+                            .filter_map(|x| x.as_str().map(|s| s.to_string()))
+                            .collect();
+                    }
+                    let want_rmt = args
+                        .get_bool("run_rmt")
+                        .or_else(|| args.get("rmt").and_then(|r| r.get_bool("enabled")));
+                    if let Some(en) = want_rmt {
+                        st.boot_plan.set("run_rmt", JsonVal::Bool(en));
+                    }
+                    if args.get("memory_params").is_some()
+                        || want_rmt.is_some()
+                        || args.get("rmt").is_some()
+                    {
+                        let mem_params = args
+                            .get("memory_params")
+                            .cloned()
+                            .unwrap_or_else(JsonVal::obj);
+                        let (built_ovs, built_raws) =
+                            FirmwareContract::memory_params_to_uip_overrides_for_family(
+                                &mem_params,
+                                want_rmt,
+                                args.get("rmt"),
+                                fw_fam,
+                            );
+                        for ov in built_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);
+                            }
+                        }
+                        for r in built_raws {
+                            if !st.uip_raw_commands.contains(&r) {
+                                st.uip_raw_commands.push(r);
+                            }
+                        }
+                    }
+                }
                 "rmt" => {
-                    let en = !matches!(action.as_str(), "disable" | "skip" | "off" | "false");
+                    let en = !matches!(action.as_str(), "disable" | "skip" | "skip_rmt" | "off" | "false");
                     st.boot_plan.set("run_rmt", JsonVal::Bool(en));
                     st.uip_overrides.retain(|x| x.get_str_or("id", "") != "rmt");
                     let mut o = JsonVal::obj();
@@ -171,6 +241,47 @@ pub fn handle_station_command_nonblocking(
                         action.as_str(),
                         "disable" | "skip" | "skip_amt" | "off" | "false"
                     );
+                    let amt_map_opt = args.get("amt").or_else(|| args.get("settings"));
+                    if en {
+                        for stale in [
+                            "selected_algorithms",
+                            "selected",
+                            "only_tests",
+                            "skip_tests",
+                            "tp_end_step",
+                            "end_step",
+                            "max_step",
+                        ] {
+                            st.amt_settings.remove(stale);
+                        }
+                        let has_explicit_amt_sel = amt_map_opt
+                            .map(|a| {
+                                a.get("selected").is_some()
+                                    || a.get("selected_algorithms").is_some()
+                                    || a.get("only_tests").is_some()
+                                    || a.get("skip_tests").is_some()
+                            })
+                            .unwrap_or(false);
+                        let has_explicit_ovs = amt_map_opt
+                            .and_then(|a| a.get_arr("overrides"))
+                            .is_some();
+                        if !has_explicit_ovs && (operator == "qt" || has_explicit_amt_sel) {
+                            if let Some(JsonVal::Arr(ref mut ovs)) =
+                                st.amt_settings.as_obj_mut().and_then(|m| m.get_mut("overrides"))
+                            {
+                                ovs.retain(|ov| {
+                                    ov.get_str_or("name", &ov.get_str_or("id", "")).trim() != "tp"
+                                });
+                            }
+                        }
+                    }
+                    if let Some(JsonVal::Obj(map)) = amt_map_opt {
+                        for (k, v) in map {
+                            if k != "enabled" {
+                                st.amt_settings.set(k, v.clone());
+                            }
+                        }
+                    }
                     st.boot_plan.set("run_amt", JsonVal::Bool(en));
                     st.amt_settings
                         .set("action", JsonVal::Str(if en { "run" } else { "skip" }.to_string()));
@@ -180,6 +291,47 @@ pub fn handle_station_command_nonblocking(
                         action.as_str(),
                         "disable" | "skip" | "skip_mt" | "off" | "false"
                     );
+                    if en {
+                        for stale in [
+                            "only_tests",
+                            "skip_tests",
+                            "selected",
+                            "algorithms",
+                            "addr_lim_lo",
+                            "addr_lim_hi",
+                        ] {
+                            st.mt_selection.remove(stale);
+                        }
+                        st.mt_selection
+                            .set("memory_range", JsonVal::Str("all".to_string()));
+                        st.mt_selection.set(
+                            "tstlist",
+                            JsonVal::Str(crate::pxe::DEFAULT_FORMAL_TSTLIST.to_string()),
+                        );
+                        st.mt_selection.set("exit_mode", JsonVal::Num(2.0));
+                        if let Some(JsonVal::Obj(map)) =
+                            args.get("mt").or_else(|| args.get("selection"))
+                        {
+                            for (k, v) in map {
+                                if k != "enabled" {
+                                    st.mt_selection.set(k, v.clone());
+                                }
+                            }
+                        }
+                        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);
+                    } else if let Some(JsonVal::Obj(map)) =
+                        args.get("mt").or_else(|| args.get("selection"))
+                    {
+                        for (k, v) in map {
+                            if k != "enabled" {
+                                st.mt_selection.set(k, v.clone());
+                            }
+                        }
+                    }
                     st.boot_plan.set("run_mt", JsonVal::Bool(en));
                     st.boot_plan.set("mt_enabled", JsonVal::Bool(en));
                 }
@@ -190,7 +342,7 @@ pub fn handle_station_command_nonblocking(
             res.set("stage", JsonVal::Str(stage.clone()));
             res.set("action", JsonVal::Str(action.clone()));
             res.set("sequence", JsonVal::Num(seq as f64));
-            res.set("confirmation", JsonVal::Str("queued_intent".to_string()));
+            res.set("confirmation", JsonVal::Str("staged".to_string()));
             res.set("stage_intents", st.stage_intents_json());
             let audit = AuditRecordDraft {
                 category: "stage_intent".to_string(),
@@ -236,6 +388,9 @@ pub fn handle_station_command_nonblocking(
             StationCmdExec::Immediate(Ok(found), Some(audit))
         }
         "ContinueUip" => {
+            if let Some(err) = input_id_mismatch_err(st, args) {
+                return StationCmdExec::Immediate(Err(err), None);
+            }
             let mut extra_lines: Vec<String> = Vec::new();
             let is_uip1 = st.prompt_uip_stage.unwrap_or(1) <= 1;
             let want_rmt = args
@@ -334,8 +489,22 @@ pub fn handle_station_command_nonblocking(
             }
         }
         "SkipAmt" => {
-            st.amt_settings
-                .set("action", JsonVal::Str("skip".to_string()));
+            if let Some(err) = input_id_mismatch_err(st, args) {
+                return StationCmdExec::Immediate(Err(err), None);
+            }
+            let cur_cpu = st.prompt_cpu.unwrap_or(0);
+            let this_cpu_done = st
+                .amt_results
+                .get(&cur_cpu)
+                .map(|r| {
+                    matches!(r.status.as_str(), "pass" | "fail" | "block")
+                        && (r.algorithm_count > 0 || r.completed_count > 0 || r.status != "running")
+                })
+                .unwrap_or(false);
+            if !(st.prompt_ready && st.prompt_kind == "amt" && this_cpu_done) {
+                st.amt_settings
+                    .set("action", JsonVal::Str("skip".to_string()));
+            }
             if st.diag_state != "online" || !st.prompt_ready || st.prompt_kind != "amt" {
                 let seq = st.set_stage_intent("amt", "skip_amt", args);
                 save_station_settings(data_dir, st);
@@ -347,6 +516,8 @@ pub fn handle_station_command_nonblocking(
                 st.last_phase_action = Some(res.clone());
                 return StationCmdExec::Immediate(Ok(res), None);
             }
+            st.plan_done
+                .insert(format!("{}:amt:cpu{}", st.boot_id, cur_cpu));
             if let Err(e) = write_station_paced(st, b"exit\r") {
                 return StationCmdExec::Immediate(Err(e), None);
             }
@@ -375,10 +546,11 @@ pub fn handle_station_command_nonblocking(
             st.uip_raw_commands = raws;
             if let Some(mt) = args.get("mt_selection") {
                 st.mt_selection = mt.clone();
-                let cfg_text = render_mt86_cfg_text(mt);
+                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_orig.efi");
-                let _ = sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text, &variant);
+                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);
             }
             save_station_settings(data_dir, st);
             let mut details = JsonVal::obj();
@@ -405,6 +577,9 @@ pub fn handle_station_command_nonblocking(
             StationCmdExec::Immediate(Ok(res), Some(audit))
         }
         "ApplyUipParameters" => {
+            if let Some(err) = input_id_mismatch_err(st, args) {
+                return StationCmdExec::Immediate(Err(err), None);
+            }
             let mut ovs = args
                 .get_arr("overrides")
                 .or_else(|| args.get_arr("uip_overrides"))
@@ -551,6 +726,9 @@ pub fn handle_station_command_nonblocking(
             StationCmdExec::Immediate(Ok(res), Some(audit))
         }
         "ApplyAmtSettings" => {
+            if let Some(err) = input_id_mismatch_err(st, args) {
+                return StationCmdExec::Immediate(Err(err), None);
+            }
             let settings = args
                 .get("settings")
                 .cloned()
@@ -654,6 +832,9 @@ pub fn handle_station_command_nonblocking(
             }
         }
         "StartAmt" => {
+            if let Some(err) = input_id_mismatch_err(st, args) {
+                return StationCmdExec::Immediate(Err(err), None);
+            }
             if args.get_bool("run_amt") == Some(false)
                 || args.get("amt").and_then(|a| a.get_bool("enabled")) == Some(false)
             {
@@ -745,6 +926,9 @@ pub fn handle_station_command_nonblocking(
             }
         }
         "SkipMt" => {
+            if let Some(err) = input_id_mismatch_err(st, args) {
+                return StationCmdExec::Immediate(Err(err), None);
+            }
             st.boot_plan.set("mt_enabled", JsonVal::Bool(false));
             st.boot_plan.set("run_mt", JsonVal::Bool(false));
             if st.diag_state != "online" || !st.prompt_ready || st.prompt_kind != "uefi" {
@@ -775,15 +959,19 @@ pub fn handle_station_command_nonblocking(
             StationCmdExec::Immediate(Ok(res), None)
         }
         "StartMt" => {
+            if let Some(err) = input_id_mismatch_err(st, args) {
+                return StationCmdExec::Immediate(Err(err), None);
+            }
             let sel = args
                 .get("mt")
                 .or_else(|| args.get("selection"))
                 .cloned()
                 .unwrap_or_else(|| st.mt_selection.clone());
-            let cfg_text = render_mt86_cfg_text(&sel);
+            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_orig.efi");
-            let _ = sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text, &variant);
+            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);
 
             st.mt_selection = sel.clone();
             st.boot_plan.set("mt_enabled", JsonVal::Bool(true));
@@ -804,23 +992,27 @@ pub fn handle_station_command_nonblocking(
                 res.set("observed_unix_ms", JsonVal::Num(now_ms() as f64));
                 return StationCmdExec::Immediate(Ok(res), None);
             }
-            let steps = build_uefi_mt_steps(st, &sel);
-            st.plan_mt_started = true;
+            let (tag, steps, allow_partial, mut meta, mark_mt_started) =
+                if needs_uefi_efi_probe(st, &sel) {
+                    let probe_steps = build_uefi_efi_probe_steps(st);
+                    let mut m = JsonVal::obj();
+                    m.set("start_mt_sel", sel.clone());
+                    ("probe_mt_efi", probe_steps, false, m, false)
+                } else {
+                    let mt_steps = build_uefi_mt_steps(st, &sel);
+                    let m = JsonVal::obj();
+                    ("interactive_start_mt", mt_steps, true, m, true)
+                };
+            meta.set("command", JsonVal::Str(raw_path));
+            if mark_mt_started {
+                st.plan_mt_started = true;
+            }
             st.boot_execution
                 .set("state", JsonVal::Str("running".to_string()));
-            let mut meta = JsonVal::obj();
-            meta.set("command", JsonVal::Str(raw_path));
-            let timeout_ms = (steps.len() as u64) * 4000 + 2000;
+            let extra_steps = if mark_mt_started { 0 } else { 24 };
+            let timeout_ms = ((steps.len() + extra_steps) as u64) * 4000 + 2000;
             let (tx, rx) = mpsc::channel();
-            start_async_script(
-                st,
-                "interactive_start_mt",
-                steps,
-                true,
-                Vec::new(),
-                meta,
-                Some(tx),
-            );
+            start_async_script(st, tag, steps, allow_partial, Vec::new(), meta, Some(tx));
             StationCmdExec::WaitScript {
                 rx,
                 timeout_ms,
@@ -1131,6 +1323,7 @@ pub fn handle_station_command_nonblocking(
                             st.bmc_password = pw.to_string();
                         }
                     }
+                    st.ssh_alt_password = false;
                     st.bmc_state = if st.bmc_enabled && !st.bmc_host.is_empty() {
                         "online".to_string()
                     } else {

+ 7 - 7
native/stl_accel/src/config.rs

@@ -1,4 +1,4 @@
-// config.rs — Server CLI arguments, version/commit metadata, and station config loader (v0.8.1.18)
+// config.rs — Server CLI arguments, version/commit metadata, and station config loader (v0.8.1.19)
 
 use crate::json::{parse_json, JsonVal};
 use std::env;
@@ -12,7 +12,7 @@ pub struct ServerArgs {
     pub config_path: PathBuf,
     pub data_dir: PathBuf,
     pub web_listen: String,
-    pub grpc_listen: String,
+    pub tftp_listen: String,
     pub web_dir: PathBuf,
     pub contracts_path: PathBuf,
     pub version: String,
@@ -25,7 +25,7 @@ impl ServerArgs {
         let mut config_path = PathBuf::from("config/station0-live.json");
         let mut data_dir = PathBuf::from("data");
         let mut web_listen = "0.0.0.0:8080".to_string();
-        let mut grpc_listen = "0.0.0.0:50051".to_string();
+        let mut tftp_listen = "0.0.0.0:69".to_string();
         let mut web_dir = PathBuf::from("web");
         let mut contracts_path = PathBuf::from("contracts/firmware-vd012.json");
 
@@ -44,8 +44,8 @@ impl ServerArgs {
                     web_listen = args[i + 1].clone();
                     i += 2;
                 }
-                "--listen" | "--grpc-listen" if i + 1 < args.len() => {
-                    grpc_listen = args[i + 1].clone();
+                "--tftp-listen" if i + 1 < args.len() => {
+                    tftp_listen = args[i + 1].clone();
                     i += 2;
                 }
                 "--web-dir" if i + 1 < args.len() => {
@@ -58,7 +58,7 @@ impl ServerArgs {
                 }
                 other => {
                     return Err(format!(
-                        "未知命令行参数 '{}'。支持参数: --config <path> --data-dir <dir> --web-listen <addr> --listen <grpc_addr> --web-dir <dir> --contracts <path>",
+                        "未知命令行参数 '{}'。支持参数: --config <path> --data-dir <dir> --web-listen <addr> --tftp-listen <udp_addr|disabled> --web-dir <dir> --contracts <path>",
                         other
                     ));
                 }
@@ -78,7 +78,7 @@ impl ServerArgs {
             config_path,
             data_dir,
             web_listen,
-            grpc_listen,
+            tftp_listen,
             web_dir,
             contracts_path,
             version,

+ 27 - 2
native/stl_accel/src/devices.rs

@@ -143,11 +143,20 @@ pub fn open_station_pty(st: &mut StationState, data_dir: &Path) -> Result<(), St
             st.diag_last_error = format!("目标串口 {}:{} 当前不可达", st.console_host, port_u16);
             return Err(st.diag_last_error.clone());
         }
-        let effective_pass = if st.bmc_password.is_empty() || st.bmc_password == "ADMIN" {
+        let primary_pass = if st.bmc_password.is_empty() {
             "Admin123@pl"
         } else {
             st.bmc_password.as_str()
         };
+        let effective_pass = if st.ssh_alt_password {
+            if primary_pass == "ADMIN" {
+                "Admin123@pl"
+            } else {
+                "ADMIN"
+            }
+        } else {
+            primary_pass
+        };
         let host_c = format!("{}\0", st.console_host);
         let user_c = format!("{}\0", st.bmc_user);
         let pass_c = format!("{}\0", effective_pass);
@@ -188,6 +197,8 @@ pub fn open_station_pty(st: &mut StationState, data_dir: &Path) -> Result<(), St
     let now = now_ms();
     st.pty_master_fd = mfd;
     st.pty_child_pid = cpid;
+    st.pty_opened_ms = now;
+    st.pty_rx_bytes_this_session = 0;
     st.diag_state = "online".to_string();
     st.console_online = true;
     st.hot.console_online = true;
@@ -221,15 +232,29 @@ pub fn poll_station_pty(st: &mut StationState) -> isize {
         return 0;
     }
     let mut total: isize = 0;
+    let mut auth_failed = false;
     let mut buf = [0u8; 16384];
     loop {
         let n = unsafe { lib::c_pty_read_nonblock(st.pty_master_fd, buf.as_mut_ptr(), buf.len()) };
         if n > 0 {
             total += n;
+            st.pty_rx_bytes_this_session = st.pty_rx_bytes_this_session.saturating_add(n as u64);
+            let txt = String::from_utf8_lossy(&buf[..n as usize]);
+            if txt.contains("Permission denied") || txt.contains("Authentication failed") {
+                auth_failed = true;
+                st.diag_last_error = "SSH 认证失败,自动切换兼容密码重试".to_string();
+            }
             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) {
+            let elapsed = now_ms().saturating_sub(st.pty_opened_ms);
+            if auth_failed
+                || st.diag_last_error.starts_with("SSH 认证失败")
+                || (elapsed < 4000 && st.pty_rx_bytes_this_session < 512)
+            {
+                st.ssh_alt_password = !st.ssh_alt_password;
+            }
             close_station_pty(st);
             return -1;
         } else {
@@ -452,7 +477,7 @@ pub fn run_ipmi_with_session(
         return Err("BMC IP 未配置".to_string());
     }
     let resolved_host = resolve_reachable_bmc_host(host, 22);
-    let primary_pass = if pass.is_empty() || pass == "ADMIN" {
+    let primary_pass = if pass.is_empty() {
         "Admin123@pl"
     } else {
         pass

+ 188 - 46
native/stl_accel/src/firmware.rs

@@ -1,5 +1,5 @@
 // firmware.rs — Authoritative 107_VD012 & CxmtDdrTest Dual-Firmware Contract,
-//               224-Item ICT (IMC Config Tool) + 30-Item AMT Builders & Safe Timing Presets (v0.8.1.18)
+//               224-Item ICT (IMC Config Tool) + 30-Item AMT Builders & Safe Timing Presets (v0.8.1.19)
 
 use crate::json::{parse_json, JsonVal};
 use std::collections::{BTreeMap, BTreeSet};
@@ -134,14 +134,20 @@ impl FirmwareContract {
             JsonVal::Arr(a) => a,
             _ => Vec::new(),
         };
-        if fw_family_name == "cxmt" {
+        if fw_family_name != "cxmt" {
+            // Hovsee 107_VD012 (.166) implements `(24) actm trfcfgrcsb(ns)` rather than `actm trfcsb`.
             for p in &mut presets {
                 if let Some(ovs) = p.get_arr("uip_overrides").cloned() {
-                    let filtered: Vec<JsonVal> = ovs
+                    let mapped: Vec<JsonVal> = ovs
                         .into_iter()
-                        .filter(|o| o.get_str_or("id", "") != "actm.trfcsb")
+                        .map(|mut o| {
+                            if o.get_str_or("id", "") == "actm.trfcsb" {
+                                o.set("id", JsonVal::Str("actm.trfcfgrcsb".to_string()));
+                            }
+                            o
+                        })
                         .collect();
-                    p.set("uip_overrides", JsonVal::Arr(filtered));
+                    p.set("uip_overrides", JsonVal::Arr(mapped));
                 }
             }
         }
@@ -157,20 +163,43 @@ impl FirmwareContract {
     ) -> (Vec<JsonVal>, Vec<String>) {
         let (ovs, raws) = Self::memory_params_to_uip_overrides(mem_params, run_rmt, rmt_cfg);
         if fw_family_name == "cxmt" {
-            let has_trfc = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trfc");
+            let has_trfcsb = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trfcsb");
+            let has_trefsbrd = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trefsbrd");
             let mut mapped = Vec::with_capacity(ovs.len());
             for mut o in ovs {
-                if o.get_str_or("id", "") == "actm.trfcsb" {
-                    if has_trfc {
-                        continue;
+                match o.get_str_or("id", "").as_str() {
+                    "actm.trfcfgrcsb" => {
+                        if has_trfcsb {
+                            continue;
+                        }
+                        o.set("id", JsonVal::Str("actm.trfcsb".to_string()));
                     }
-                    o.set("id", JsonVal::Str("actm.trfc".to_string()));
+                    "actm.trefsb" => {
+                        if has_trefsbrd {
+                            continue;
+                        }
+                        o.set("id", JsonVal::Str("actm.trefsbrd".to_string()));
+                    }
+                    "actm.trrd" | "actm.tcssr" | "actm.tcshsrexit" | "actm.tcwl" => continue,
+                    _ => {}
                 }
                 mapped.push(o);
             }
             return (mapped, raws);
         }
-        (ovs, raws)
+        // Hovsee 107_VD012 (.166): translate canonical `actm.trfcsb` -> `actm.trfcfgrcsb`
+        let has_trfcfgrcsb = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trfcfgrcsb");
+        let mut mapped = Vec::with_capacity(ovs.len());
+        for mut o in ovs {
+            if o.get_str_or("id", "") == "actm.trfcsb" {
+                if has_trfcfgrcsb {
+                    continue;
+                }
+                o.set("id", JsonVal::Str("actm.trfcfgrcsb".to_string()));
+            }
+            mapped.push(o);
+        }
+        (mapped, raws)
     }
 
     pub fn memory_params_to_uip_overrides(
@@ -416,8 +445,10 @@ impl FirmwareContract {
     }
 
     /// Dual-firmware ICT command builder:
-    /// `fw_family == 1` -> Hovsee 107_VD012 (.166, supports extended actm trfcsb/trfcfgrcsb/tcwl/trefsb)
-    /// `fw_family == 2` -> CxmtDdrTest (.165, skips Hovsee-only extended actm subcommands or maps trfcsb->trfc)
+    /// `fw_family == 1` (or `0` default) -> Hovsee 107_VD012 (.166): uses `actm trfcfgrcsb` (translating `actm.trfcsb`),
+    ///   `actm trrd`, `actm tcssr`, `actm tcshsrexit`, `actm tcwl`, `actm trefsb`
+    /// `fw_family == 2` -> CxmtDdrTest (.165): uses `actm trfcsb` (translating `actm.trfcfgrcsb`), `actm trefsbrd`,
+    ///   and skips Hovsee-only `actm.trrd` / `actm.tcssr` / `actm.tcshsrexit` / `actm.tcwl`
     pub fn build_uip_commands_for_fw(
         &self,
         overrides: &[JsonVal],
@@ -425,6 +456,16 @@ impl FirmwareContract {
         target_stage: Option<u8>,
         fw_family: u8,
     ) -> Result<Vec<String>, String> {
+        let has_override_id = |target: &str| {
+            overrides.iter().any(|ov| {
+                ov.get_str_or("id", "") == target
+                    && ov.get_str_or("mode", "override") != "default"
+            })
+        };
+        let has_trfcfgrcsb = has_override_id("actm.trfcfgrcsb");
+        let has_trfcsb = has_override_id("actm.trfcsb");
+        let has_trefsbrd = has_override_id("actm.trefsbrd");
+
         let mut seen_ids = BTreeSet::new();
         let mut active_ids = BTreeSet::new();
         let mut expanded_lines = Vec::new();
@@ -468,19 +509,36 @@ impl FirmwareContract {
                 }
             }
 
-            // Dual-firmware adaptation for CxmtDdrTest (.165, fw_family == 2)
+            // Dual-firmware adaptation:
+            //   fw_family == 2 -> CxmtDdrTest (.165): supports `actm trfcsb`, `actm trefsbrd`
+            //   fw_family != 2 -> Hovsee 107_VD012 (.166): supports `actm trfcfgrcsb` (not `actm trfcsb`)
             if fw_family == 2 {
                 if matches!(
                     item_id.as_str(),
-                    "actm.trfcfgrcsb" | "actm.tcssr" | "actm.tcshsrexit" | "actm.tcwl" | "actm.trefsb"
+                    "actm.trrd" | "actm.tcssr" | "actm.tcshsrexit" | "actm.tcwl"
                 ) {
                     continue;
                 }
-                if item_id == "actm.trfcsb" && !seen_ids.contains("actm.trfc") {
-                    expanded_lines.push(format!("actm trfc {}", val));
-                    active_ids.insert(item_id);
+                if item_id == "actm.trfcfgrcsb" {
+                    if !has_trfcsb {
+                        expanded_lines.push(format!("actm trfcsb {}", val));
+                        active_ids.insert(item_id);
+                    }
                     continue;
                 }
+                if item_id == "actm.trefsb" {
+                    if !has_trefsbrd {
+                        expanded_lines.push(format!("actm trefsbrd {}", val));
+                        active_ids.insert(item_id);
+                    }
+                    continue;
+                }
+            } else if item_id == "actm.trfcsb" {
+                if !has_trfcfgrcsb {
+                    expanded_lines.push(format!("actm trfcfgrcsb {}", val));
+                    active_ids.insert(item_id);
+                }
+                continue;
             }
 
             let base_cmd = self.uip_commands.get(&item_id).unwrap();
@@ -518,10 +576,11 @@ impl FirmwareContract {
             if trimmed.contains('\r') || trimmed.contains('\n') || trimmed.contains('\0') {
                 return Err("补充 ICT 命令不能包含换行符".to_string());
             }
-            if trimmed.len() >= 127 {
-                return Err(format!("补充 ICT 命令超过 126 字节固件上限: {}", trimmed));
+            let normalized = translate_raw_uip_cmd(trimmed, fw_family);
+            if normalized.len() >= 127 {
+                return Err(format!("补充 ICT 命令超过 126 字节固件上限: {}", normalized));
             }
-            expanded_lines.push(trimmed.to_string());
+            expanded_lines.push(normalized);
         }
 
         if let Some(stg) = target_stage {
@@ -603,16 +662,7 @@ impl FirmwareContract {
                 if !sel_strs.is_empty() {
                     let mut indices = Vec::new();
                     for item in sel_strs {
-                        let idx_opt = match item {
-                            JsonVal::Num(n) => Some(*n as i64),
-                            JsonVal::Str(s) => s
-                                .trim()
-                                .split(|c: char| !c.is_ascii_digit())
-                                .next()
-                                .and_then(|d| d.parse::<i64>().ok()),
-                            _ => None,
-                        };
-                        if let Some(idx) = idx_opt {
+                        if let Some(idx) = parse_amt_selected_item(item) {
                             if (0..=23).contains(&idx)
                                 && (idx as u32) <= max_algo_id
                                 && !indices.contains(&(idx as u32))
@@ -621,11 +671,13 @@ impl FirmwareContract {
                             }
                         }
                     }
+                    let explicit_step = settings
+                        .get_i64("tp_end_step")
+                        .or_else(|| settings.get_i64("end_step"))
+                        .or_else(|| settings.get_i64("max_step"));
                     if !indices.is_empty()
                         && (indices.len() < total_algos as usize
-                            || settings.get_i64("tp_end_step").is_some()
-                            || settings.get_i64("end_step").is_some()
-                            || settings.get_i64("max_step").is_some())
+                            || explicit_step.map(|s| s < 255).unwrap_or(false))
                     {
                         algo_indices = Some(indices);
                     }
@@ -634,13 +686,16 @@ impl FirmwareContract {
                 if !only_arr.is_empty() {
                     let raw_nums: Vec<i64> = only_arr
                         .iter()
-                        .filter_map(|x| match x {
-                            JsonVal::Num(n) => Some(*n as i64),
-                            JsonVal::Str(s) => s.trim().split(':').next()?.parse::<i64>().ok(),
-                            _ => None,
-                        })
+                        .filter_map(parse_amt_selected_item)
                         .collect();
-                    let one_based = raw_nums.iter().all(|&n| (1..=24).contains(&n)) && !raw_nums.contains(&0);
+                    let all_str_names = only_arr.iter().all(|x| {
+                        x.as_str()
+                            .map(|s| amt_algo_name_to_idx(s).is_some())
+                            .unwrap_or(false)
+                    });
+                    let one_based = !all_str_names
+                        && raw_nums.iter().all(|&n| (1..=24).contains(&n))
+                        && !raw_nums.contains(&0);
                     let mut indices = Vec::new();
                     for n in raw_nums {
                         let z = if one_based { n - 1 } else { n };
@@ -659,13 +714,16 @@ impl FirmwareContract {
                 if !skip_arr.is_empty() {
                     let raw_nums: Vec<i64> = skip_arr
                         .iter()
-                        .filter_map(|x| match x {
-                            JsonVal::Num(n) => Some(*n as i64),
-                            JsonVal::Str(s) => s.trim().split(':').next()?.parse::<i64>().ok(),
-                            _ => None,
-                        })
+                        .filter_map(parse_amt_selected_item)
                         .collect();
-                    let one_based = raw_nums.iter().all(|&n| (1..=24).contains(&n)) && !raw_nums.contains(&0);
+                    let all_str_names = skip_arr.iter().all(|x| {
+                        x.as_str()
+                            .map(|s| amt_algo_name_to_idx(s).is_some())
+                            .unwrap_or(false)
+                    });
+                    let one_based = !all_str_names
+                        && raw_nums.iter().all(|&n| (1..=24).contains(&n))
+                        && !raw_nums.contains(&0);
                     let skip_set: BTreeSet<u32> = raw_nums
                         .into_iter()
                         .filter_map(|n| {
@@ -752,6 +810,33 @@ impl FirmwareContract {
     }
 }
 
+fn translate_raw_uip_cmd(trimmed: &str, fw_family: u8) -> String {
+    let parts: Vec<&str> = trimmed.split_whitespace().collect();
+    if parts.len() >= 3 && parts[0].eq_ignore_ascii_case("actm") {
+        let mut sub = parts[1].to_ascii_lowercase();
+        if let Some(base) = sub.strip_suffix("(ns)") {
+            sub = base.to_string();
+        } else if sub == "trrd(trrd_s)" {
+            sub = "trrd".to_string();
+        }
+        let mapped_sub = if fw_family == 2 {
+            match sub.as_str() {
+                "trfcfgrcsb" => "trfcsb",
+                "trefsb" => "trefsbrd",
+                _ => sub.as_str(),
+            }
+        } else {
+            match sub.as_str() {
+                "trfcsb" => "trfcfgrcsb",
+                "trrd_s" => "trrd",
+                _ => sub.as_str(),
+            }
+        };
+        return format!("actm {} {}", mapped_sub, parts[2..].join(" "));
+    }
+    trimmed.to_string()
+}
+
 pub fn format_vd012_tp_entry_with_step(algo_idx_zero_based: u32, end_step: u32) -> String {
     let step = end_step.min(255);
     if algo_idx_zero_based == 15 || algo_idx_zero_based == 20 {
@@ -798,3 +883,60 @@ fn normalize_tp_plan_str(val: &str, max_algo_id: u32) -> Result<String, String>
     }
     Ok(out.join(" "))
 }
+
+fn amt_algo_name_to_idx(raw: &str) -> Option<i64> {
+    match raw.trim().to_ascii_lowercase().as_str() {
+        "b-wrup" | "b-mats+" | "b-wrup/b-mats+" | "wrup" | "mats+" => Some(0),
+        "b-scm" => Some(1),
+        "s-si" => Some(2),
+        "a-mss" => Some(3),
+        "a-mmda" => Some(4),
+        "a-hds" => Some(5),
+        "a-hwd" => Some(6),
+        "a-la" => Some(7),
+        "a-md1" => Some(8),
+        "b-crosswr" => Some(9),
+        "a-hdsx" => Some(10),
+        "r-vrt" => Some(11),
+        "r-srt0" => Some(12),
+        "r-srt1" => Some(13),
+        "b-scm2" => Some(14),
+        "b-hammer" => Some(15),
+        "b-butterfly" => Some(16),
+        "b-random" => Some(17),
+        "a-marx" => Some(18),
+        "b-decode" => Some(19),
+        "b-hammersec" => Some(20),
+        "a-wldvlk" => Some(21),
+        "r-sr" => Some(22),
+        "f-mrrc" => Some(23),
+        _ => None,
+    }
+}
+
+fn parse_amt_selected_item(item: &JsonVal) -> Option<i64> {
+    match item {
+        JsonVal::Num(n) => Some(*n as i64),
+        JsonVal::Str(s) => {
+            let t = s.trim();
+            if let Some((left, right)) = t.split_once(':') {
+                if let Some(idx) = amt_algo_name_to_idx(right) {
+                    return Some(idx);
+                }
+                if let Ok(idx) = left.trim().parse::<i64>() {
+                    return Some(idx);
+                }
+            }
+            if let Ok(idx) = t.parse::<i64>() {
+                return Some(idx);
+            }
+            if let Some(idx) = amt_algo_name_to_idx(t) {
+                return Some(idx);
+            }
+            t.split(|c: char| !c.is_ascii_digit())
+                .next()
+                .and_then(|d| d.parse::<i64>().ok())
+        }
+        _ => None,
+    }
+}

Разница между файлами не показана из-за своего большого размера
+ 0 - 1682
native/stl_accel/src/grpc.rs


+ 8 - 0
native/stl_accel/src/json.rs

@@ -29,6 +29,14 @@ impl JsonVal {
         }
     }
 
+    pub fn remove(&mut self, k: &str) -> Option<JsonVal> {
+        if let JsonVal::Obj(ref mut m) = self {
+            m.remove(k)
+        } else {
+            None
+        }
+    }
+
     pub fn get(&self, k: &str) -> Option<&JsonVal> {
         if let JsonVal::Obj(ref m) = self {
             m.get(k)

+ 1 - 1
native/stl_accel/src/lib.rs

@@ -1,5 +1,5 @@
 // lib.rs — Native Hardware Dispatch, ASM Base64 & Single-Pass Clean/Split/Classify,
-//          Monotonic 64-Bit mmap Ring Buffer, re2c DFA, epoll/timerfd & OpenCL FFI (v0.8.1.18)
+//          Monotonic 64-Bit mmap Ring Buffer, re2c DFA, epoll/timerfd & OpenCL FFI (v0.8.1.19)
 
 use crate::json::JsonVal;
 

+ 699 - 48
native/stl_accel/src/main.rs

@@ -1,4 +1,4 @@
-// main.rs — Entrypoint for stl_native_server (v0.8.1.18)
+// main.rs — Entrypoint for stl_native_server (v0.8.1.19)
 #![allow(special_module_name)]
 #![allow(dead_code)]
 
@@ -8,7 +8,6 @@ mod commands;
 mod config;
 mod devices;
 mod firmware;
-mod grpc;
 mod json;
 mod lib;
 mod pxe;
@@ -18,7 +17,6 @@ mod workflow;
 
 use api::{handle_http_client, AppHub};
 use config::ServerArgs;
-use grpc::spawn_grpc_server;
 use std::net::TcpListener;
 use std::process;
 use std::sync::Arc;
@@ -36,23 +34,7 @@ fn main() {
 
     let hub = AppHub::init(&args);
 
-    if !args.grpc_listen.is_empty() && args.grpc_listen != "disabled" {
-        match TcpListener::bind(&args.grpc_listen) {
-            Ok(grpc_listener) => {
-                eprintln!(
-                    "[stl_native_server] gRPC BenchService (h2c) listening on {}",
-                    args.grpc_listen
-                );
-                spawn_grpc_server(grpc_listener, Arc::clone(&hub));
-            }
-            Err(e) => {
-                eprintln!(
-                    "[stl_native_server] Warning: failed to bind gRPC {}: {}",
-                    args.grpc_listen, e
-                );
-            }
-        }
-    }
+    let _ = crate::pxe::spawn_tftp_server(&args.tftp_listen, Arc::clone(&hub));
 
     let listener = TcpListener::bind(&args.web_listen).expect("Failed to bind web-listen port");
     eprintln!(
@@ -76,35 +58,22 @@ mod tests {
     use crate::api::AppHub;
     use crate::config::ServerArgs;
     use crate::firmware::FirmwareContract;
-    use crate::grpc::{decode_pb_struct, encode_pb_struct, HuffTree};
     use crate::json::{parse_json, JsonVal};
     use crate::lib::{self, MonotonicRingBuffer, NativeStreamCleaner};
+    use crate::pxe::{parse_mt86_html_report, render_mt86_cfg_text, spawn_tftp_server};
     use crate::results::{now_ms, StationState};
     use crate::storage::strip_private_keys_recursive;
     use std::env;
+    use std::io::{Read, Write};
+    use std::net::{TcpListener, UdpSocket};
     use std::path::Path;
+    use std::time::Duration;
 
     #[test]
-    fn test_isa_tiers_monotonic_ring_asm_clean_and_hpack_protobuf() {
+    fn test_isa_tiers_monotonic_ring_and_asm_clean() {
         lib::init_hardware();
 
-        // 1. Verify RFC 7541 Appendix B Huffman code table is a mathematically complete prefix code (Kraft sum == 1)
-        let huff = HuffTree::build();
-        assert!(
-            huff.is_complete_prefix_code(),
-            "HPACK Huffman table must have 513 nodes (257 leaves) with zero incomplete internal nodes"
-        );
-
-        // 2. Verify JsonVal <-> google.protobuf.Struct binary wire roundtrip
-        let orig_struct = parse_json(
-            r#"{"station_id":"S1","count":24,"active":true,"empty_str":"","nested":{"arr":[1,"ict",false,null]}}"#,
-        )
-        .unwrap();
-        let pb_bytes = encode_pb_struct(&orig_struct);
-        let decoded_struct = decode_pb_struct(&pb_bytes).unwrap();
-        assert_eq!(decoded_struct, orig_struct);
-
-        // 3. Test forced ISA tiers 0 (SSE2), 1 (SSE4.2+POPCNT), 2 (AVX2+BMI2)
+        // Test forced ISA tiers 0 (SSE2), 1 (SSE4.2+POPCNT), 2 (AVX2+BMI2)
         let mut caps: lib::StlHwCaps = unsafe { std::mem::zeroed() };
         unsafe {
             lib::c_get_hw_caps(&mut caps);
@@ -174,7 +143,7 @@ mod tests {
         );
         assert_eq!(contract.amt_allowed.len(), 27);
 
-        // Dual firmware family: .166 ("vd012" -> actm trfcsb) vs .165 ("cxmt" -> actm trfc)
+        // Dual firmware family: .166 ("vd012"/"hovsee" -> actm trfcfgrcsb) vs .165 ("cxmt" -> actm trfcsb)
         let mp = parse_json(r#"{"trfcsb":"320","tcl":"40"}"#).unwrap();
         let (ovs_166, _) = FirmwareContract::memory_params_to_uip_overrides_for_family(
             &mp,
@@ -183,9 +152,10 @@ mod tests {
             "vd012",
         );
         let cmds_166 = contract
-            .build_uip_commands_for_family(&ovs_166, &[], Some(1), "vd012")
+            .build_uip_commands_for_family(&ovs_166, &["actm trfcsb(ns) 123".to_string()], Some(1), "vd012")
             .unwrap();
-        assert!(cmds_166.iter().any(|c| c == "actm trfcsb 320"));
+        assert!(cmds_166.iter().any(|c| c == "actm trfcfgrcsb 320"));
+        assert!(cmds_166.iter().any(|c| c == "actm trfcfgrcsb 123"));
 
         let (ovs_165, _) = FirmwareContract::memory_params_to_uip_overrides_for_family(
             &mp,
@@ -194,9 +164,10 @@ mod tests {
             "cxmt",
         );
         let cmds_165 = contract
-            .build_uip_commands_for_family(&ovs_165, &[], Some(1), "cxmt")
+            .build_uip_commands_for_family(&ovs_165, &["actm trfcfgrcsb 123".to_string()], Some(1), "cxmt")
             .unwrap();
-        assert!(cmds_165.iter().any(|c| c == "actm trfc 320"));
+        assert!(cmds_165.iter().any(|c| c == "actm trfcsb 320"));
+        assert!(cmds_165.iter().any(|c| c == "actm trfcsb 123"));
 
         // Qt CreateTaskDialog boolean memory_params (errhandle, ap, ecc, debuglog) must map to valid firmware choices
         let mp_qt_off = parse_json(r#"{"errhandle":false,"ap":false,"ecc":false,"debuglog":false}"#).unwrap();
@@ -312,6 +283,14 @@ mod tests {
         assert!(st_166.hot.amt_complete);
         assert!(st_166.awaiting_dimm_replacement);
         assert_eq!(st_166.task_status, "failed");
+
+        // Regression test: match_ci_word must match "N0.C01.D0: Failure detected - PPR Memtest" as fail even with "test" in "Memtest"
+        let mut st_ppr = StationState::new("S1", "Station 1", "192.168.2.166", "Admin123@pl");
+        st_ppr.observe_serial_chunk(
+            b"[SYS_BIOS]Version:107_VD012\r\n[0][Hovsee]Current stage is 1\r\nN0.C01.D0: Failure detected - PPR Memtest\r\n",
+        );
+        assert_eq!(st_ppr.dimms[1].stage_training, "fail");
+        assert!(!st_ppr.stage_errors.get("training").unwrap().is_empty());
     }
 
     #[test]
@@ -326,10 +305,10 @@ mod tests {
             config_path: Path::new("config/backend.example.json").to_path_buf(),
             data_dir: tmp_dir.clone(),
             web_listen: "127.0.0.1:0".to_string(),
-            grpc_listen: "disabled".to_string(),
+            tftp_listen: "disabled".to_string(),
             web_dir: Path::new("web").to_path_buf(),
             contracts_path: Path::new("contracts/firmware-vd012.json").to_path_buf(),
-            version: "0.8.1.18".to_string(),
+            version: "0.8.1.19".to_string(),
             commit: "unit-test".to_string(),
         };
         let hub = AppHub::init_for_test(&args);
@@ -342,7 +321,7 @@ mod tests {
         let sys = hub
             .dispatch_rpc("GetSystemInfo", &JsonVal::obj(), false)
             .unwrap();
-        assert_eq!(sys.get_str_or("version", ""), "0.8.1.18");
+        assert_eq!(sys.get_str_or("version", ""), "0.8.1.19");
 
         for removed in ["InventedMethod", "ListRuns", "ListRecipes"] {
             let err_rpc = hub.dispatch_rpc(removed, &JsonVal::obj(), false);
@@ -474,7 +453,7 @@ mod tests {
             .unwrap();
         assert_eq!(uart_after_clr.get_str_or("text", ""), "");
 
-        // Verify Pre-Stage Intent last-write-wins (enable -> disable -> enable => final enable)
+        // Verify Pre-Stage Intent last-write-wins (enable -> disable -> enable => final enable) and "confirmation":"staged"
         for enabled in [true, false, true] {
             let intent_req = parse_json(&format!(
                 r#"{{"station_id":"S2","stage":"amt","enabled":{}}}"#,
@@ -483,6 +462,7 @@ mod tests {
             .unwrap();
             let res = hub.dispatch_rpc("SetStageIntent", &intent_req, true).unwrap();
             assert_eq!(res.get_str_or("state", ""), "succeeded");
+            assert_eq!(res.get_str_or("confirmation", ""), "staged");
         }
         let s2_ctl = hub.build_station_control("S2").unwrap();
         assert_eq!(
@@ -493,6 +473,36 @@ mod tests {
             Some("enable")
         );
 
+        // Verify skipped AMT leaves amt_results empty (NEVER fabricates PASS)
+        hub.test_inject_serial(
+            "S2",
+            b"[SYS_BIOS]Version:107_VD012\r\n[0][Hovsee]Current stage is 1\r\n[0][Hovsee]Exit Hovsee UIP\r\n[0] AMT Version GNR-4.3.3 (Aug 13 2026)\r\n[0][AMT #]exit\r\n[0][Hovsee]Current stage is 2\r\nUEFI Interactive Shell v2.2\r\nFS0:\\EFI\\> ",
+            None,
+            true,
+        );
+        let s2_skipped_status = hub
+            .dispatch_rpc(
+                "GetTaskStatus",
+                &parse_json(r#"{"station_id":"S2"}"#).unwrap(),
+                true,
+            )
+            .unwrap();
+        assert_eq!(
+            s2_skipped_status
+                .get("stage_completions")
+                .unwrap()
+                .get_bool("amt_complete"),
+            Some(false)
+        );
+        let s2_ctl_after_skip = hub.build_station_control("S2").unwrap();
+        assert_eq!(
+            s2_ctl_after_skip
+                .get("firmware")
+                .and_then(|f| f.get_arr("amt_results"))
+                .map(|a| a.len()),
+            Some(0)
+        );
+
         // Verify Multi-Profile Task Batch submission, auto-advancement, and universal archiving on S2
         let batch_req = parse_json(
             r#"{
@@ -584,4 +594,645 @@ mod tests {
 
         let _ = std::fs::remove_dir_all(&tmp_dir);
     }
+
+    #[test]
+    fn test_embedded_tftp_rrq_wrq_html_report_and_mt_26_tests() {
+        lib::init_hardware();
+        let tmp_dir = env::temp_dir().join(format!(
+            "stl-tftp-test-{}-{}",
+            std::process::id(),
+            now_ms()
+        ));
+        let args = ServerArgs {
+            config_path: Path::new("config/backend.example.json").to_path_buf(),
+            data_dir: tmp_dir.clone(),
+            web_listen: "127.0.0.1:0".to_string(),
+            tftp_listen: "disabled".to_string(),
+            web_dir: Path::new("web").to_path_buf(),
+            contracts_path: Path::new("contracts/firmware-vd012.json").to_path_buf(),
+            version: "0.8.1.19".to_string(),
+            commit: "unit-test".to_string(),
+        };
+        let hub = AppHub::init_for_test(&args);
+
+        // 1. Verify full 26 MT tests (0..=25) & AUTOREPORT directives in mt86.cfg
+        let default_cfg_val = crate::pxe::default_pxe_state()
+            .get("mt86_cfg")
+            .unwrap()
+            .clone();
+        let cfg_text = render_mt86_cfg_text(&default_cfg_val, "192.168.0.10");
+        assert!(cfg_text.contains("TSTLIST=0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25\r\n"));
+        assert!(cfg_text.contains("AUTOREPORT=1\r\n"));
+        assert!(cfg_text.contains("AUTOREPORTFMT=HTML\r\n"));
+        assert!(cfg_text.contains("REPORTNUMERRS=100\r\n"));
+        assert!(cfg_text.contains("TFTPSERVERIP=192.168.0.10\r\n"));
+
+        // Verify 0..=25 also work when passed via `only_tests`, and canonical MT86 names (not mid-string digits!)
+        let mt_only_25 = parse_json(r#"{"only_tests":[0,25]}"#).unwrap();
+        let cfg_25 = render_mt86_cfg_text(&mt_only_25, "192.168.0.10");
+        assert!(cfg_25.contains("TSTLIST=0,25\r\n"));
+
+        let mt_names_val = parse_json(
+            r#"{"selected":["Adress test, walking ones, 1 CPU","Moving inversions, 8-bit pattern","Hammer test","Stressapp memory stress test"]}"#,
+        )
+        .unwrap();
+        let cfg_names = render_mt86_cfg_text(&mt_names_val, "192.168.0.10");
+        assert!(cfg_names.contains("TSTLIST=0,4,13,25\r\n"));
+
+        // 2. Verify HTML report parser on PASS and FAIL samples
+        let pass_html = "<html><body><h1>MemTest86 Report</h1><table><tr><td>Result</td><td>PASS</td></tr><tr><td>Tests Passed</td><td>26/26</td></tr><tr><td>Total Errors</td><td>0</td></tr><tr><td>Elapsed Time</td><td>0:01:20</td></tr></table></body></html>";
+        let pass_rep = parse_mt86_html_report("MemTest86-PASS.html", pass_html);
+        assert_eq!(pass_rep.get_str_or("verdict", ""), "pass");
+        assert_eq!(pass_rep.get_i64("errors"), Some(0));
+        assert_eq!(pass_rep.get_str_or("tests_passed", ""), "26/26");
+
+        let fail_html = "<html><body><h1>MemTest86 Report</h1><table><tr><td>Result</td><td>FAIL</td></tr><tr><td>Tests Passed</td><td>25/26</td></tr><tr><td>Total Errors</td><td>4</td></tr></table></body></html>";
+        let fail_rep = parse_mt86_html_report("MemTest86-FAIL.html", fail_html);
+        assert_eq!(fail_rep.get_str_or("verdict", ""), "fail");
+        assert_eq!(fail_rep.get_i64("errors"), Some(4));
+
+        // 3. Real UDP TFTP server loopback RRQ + WRQ with RFC 2348 OACK negotiation
+        let tftp_addr = spawn_tftp_server("127.0.0.1:0", std::sync::Arc::clone(&hub))
+            .expect("TFTP ephemeral port bind failed");
+        let client = UdpSocket::bind("127.0.0.1:0").unwrap();
+        client
+            .set_read_timeout(Some(Duration::from_secs(3)))
+            .unwrap();
+
+        // RRQ for mt86.cfg with blksize=1024, tsize=0
+        let mut rrq = Vec::new();
+        rrq.extend_from_slice(&1u16.to_be_bytes());
+        rrq.extend_from_slice(b"mt86.cfg\0octet\0blksize\01024\0tsize\00\0");
+        client.send_to(&rrq, tftp_addr).unwrap();
+
+        let mut buf = [0u8; 2048];
+        let (n, tid_peer) = client.recv_from(&mut buf).unwrap();
+        assert_eq!(u16::from_be_bytes([buf[0], buf[1]]), 6); // OACK
+        let mut ack0 = Vec::new();
+        ack0.extend_from_slice(&4u16.to_be_bytes());
+        ack0.extend_from_slice(&0u16.to_be_bytes());
+        client.send_to(&ack0, tid_peer).unwrap();
+
+        let (dn, _) = client.recv_from(&mut buf).unwrap();
+        assert_eq!(u16::from_be_bytes([buf[0], buf[1]]), 3); // DATA
+        assert_eq!(u16::from_be_bytes([buf[2], buf[3]]), 1);
+        let rrq_body = String::from_utf8_lossy(&buf[4..dn]).to_string();
+        assert!(rrq_body.contains("TSTLIST=0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25"));
+        assert!(rrq_body.contains("AUTOREPORT=1"));
+        let mut ack1 = Vec::new();
+        ack1.extend_from_slice(&4u16.to_be_bytes());
+        ack1.extend_from_slice(&1u16.to_be_bytes());
+        client.send_to(&ack1, tid_peer).unwrap();
+        let _ = n;
+
+        // Put S1 into MT phase before uploading FAIL HTML report over TFTP WRQ
+        hub.test_inject_serial(
+            "S1",
+            b"[SYS_BIOS]Version:107_VD012\r\nUEFI Interactive Shell v2.2\r\nFS0:\\EFI\\> \r\nPassMark MemTest86 v11.8 Pro\r\n",
+            Some("running"),
+            true,
+        );
+
+        let mut wrq = Vec::new();
+        wrq.extend_from_slice(&2u16.to_be_bytes());
+        wrq.extend_from_slice(b"MemTest86-Report-20261113.html\0octet\0blksize\0512\0");
+        client.send_to(&wrq, tftp_addr).unwrap();
+
+        let (wn, wrq_peer) = client.recv_from(&mut buf).unwrap();
+        assert!(wn >= 4);
+        assert_eq!(u16::from_be_bytes([buf[0], buf[1]]), 6); // OACK
+
+        let mut data_pkt = Vec::new();
+        data_pkt.extend_from_slice(&3u16.to_be_bytes());
+        data_pkt.extend_from_slice(&1u16.to_be_bytes());
+        data_pkt.extend_from_slice(fail_html.as_bytes());
+        client.send_to(&data_pkt, wrq_peer).unwrap();
+
+        let (an, _) = client.recv_from(&mut buf).unwrap();
+        assert!(an >= 4);
+        assert_eq!(u16::from_be_bytes([buf[0], buf[1]]), 4); // ACK 1
+        assert_eq!(u16::from_be_bytes([buf[2], buf[3]]), 1);
+
+        for _ in 0..50 {
+            let has_rpt = hub
+                .build_station_control("S1")
+                .ok()
+                .and_then(|c| c.get("pxe_control").and_then(|p| p.get_arr("recent_reports")).map(|a| !a.is_empty()))
+                .unwrap_or(false);
+            if has_rpt {
+                break;
+            }
+            std::thread::sleep(Duration::from_millis(20));
+        }
+        hub.force_tick("S1");
+
+        let pxe_snap = hub.build_station_control("S1").unwrap();
+        let rpts = pxe_snap
+            .get("pxe_control")
+            .and_then(|p| p.get_arr("recent_reports"))
+            .unwrap();
+        assert_eq!(rpts[0].get_str_or("filename", ""), "MemTest86-Report-20261113.html");
+        assert_eq!(rpts[0].get_str_or("verdict", ""), "fail");
+        assert_eq!(rpts[0].get_i64("errors"), Some(4));
+
+        let s1_after_wrq = hub.read_station_view("S1").unwrap();
+        assert!(s1_after_wrq.awaiting_dimm_replacement);
+        assert_eq!(s1_after_wrq.qt_clean_station.get_str_or("verdict", ""), "fail");
+        assert!(!s1_after_wrq
+            .qt_clean_station
+            .get("stage_errors")
+            .and_then(|e| e.get_arr("mt"))
+            .unwrap()
+            .is_empty());
+
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+    }
+
+    #[test]
+    fn test_amt_selected_pure_names_and_stale_intent_filter_cleanup() {
+        let contract = FirmwareContract::load(Path::new("contracts/firmware-vd012.json"));
+
+        // 1. Qt pure-name selection ("B-WRUP", "B-Hammer") + end_step=0 -> 0-based 0 & 15 (10-field RowHammer)
+        let amt_pure = parse_json(
+            r#"{"selected":["B-WRUP","B-Hammer"],"end_step":0,"test_command":"amemdiag 1"}"#,
+        )
+        .unwrap();
+        let cmds_pure = contract
+            .build_amt_commands_for_family(&amt_pure, "vd012")
+            .unwrap();
+        assert_eq!(cmds_pure, vec!["tp 0,1,0,0,0,255 15,1,0,0,0,255,0,0,0x1d4c00,8"]);
+
+        // 2. Web prefixed-name selection without end_step -> defaults to full step range (0..255)
+        let amt_web = parse_json(r#"{"selected":["16:B-Hammer"]}"#).unwrap();
+        let cmds_web = contract
+            .build_amt_commands_for_family(&amt_web, "vd012")
+            .unwrap();
+        assert_eq!(cmds_web, vec!["tp 15,1,0,255,0,255,0,0,0x1d4c00,8"]);
+
+        // 3. Stale MT/AMT filter cleanup across repeated SetStageIntent calls
+        lib::init_hardware();
+        let tmp_dir = env::temp_dir().join(format!(
+            "stl-intent-cleanup-{}-{}",
+            std::process::id(),
+            now_ms()
+        ));
+        let args = ServerArgs {
+            config_path: Path::new("config/backend.example.json").to_path_buf(),
+            data_dir: tmp_dir.clone(),
+            web_listen: "127.0.0.1:0".to_string(),
+            tftp_listen: "disabled".to_string(),
+            web_dir: Path::new("web").to_path_buf(),
+            contracts_path: Path::new("contracts/firmware-vd012.json").to_path_buf(),
+            version: "0.8.1.19".to_string(),
+            commit: "unit-test".to_string(),
+        };
+        let hub = AppHub::init_for_test(&args);
+
+        hub.dispatch_rpc(
+            "SetStageIntent",
+            &parse_json(r#"{"station_id":"S2","stage":"mt","enabled":true,"mt":{"only_tests":[1,2],"addr_lim_lo":"0x100000"}}"#).unwrap(),
+            true,
+        )
+        .unwrap();
+        // Second call omits `mt` sub-object (e.g. Qt selecting all 26 items): stale filters must be cleared!
+        hub.dispatch_rpc(
+            "SetStageIntent",
+            &parse_json(r#"{"station_id":"S2","stage":"mt","enabled":true}"#).unwrap(),
+            true,
+        )
+        .unwrap();
+        let s2_ctl = hub.build_station_control("S2").unwrap();
+        let mt_sel = s2_ctl
+            .get("firmware_settings")
+            .and_then(|f| f.get("mt_selection"))
+            .unwrap();
+        assert!(mt_sel.get("only_tests").is_none());
+        assert!(mt_sel.get("addr_lim_lo").is_none());
+        assert_eq!(
+            mt_sel.get_str_or("tstlist", ""),
+            "0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25"
+        );
+
+        // Repeat AMT SetStageIntent: old only_tests must not leak when overwritten with `selected`
+        hub.dispatch_rpc(
+            "SetStageIntent",
+            &parse_json(r#"{"station_id":"S2","stage":"amt","enabled":true,"amt":{"only_tests":[2,3]}}"#).unwrap(),
+            true,
+        )
+        .unwrap();
+        hub.dispatch_rpc(
+            "SetStageIntent",
+            &parse_json(r#"{"station_id":"S2","stage":"amt","enabled":true,"amt":{"selected":["B-WRUP","B-Hammer"],"test_command":"amemdiag 1"}}"#).unwrap(),
+            true,
+        )
+        .unwrap();
+        let s2_ctl_amt = hub.build_station_control("S2").unwrap();
+        let amt_st = s2_ctl_amt.get("amt_settings").unwrap();
+        assert!(amt_st.get("only_tests").is_none());
+        assert_eq!(amt_st.get_arr("selected").map(|a| a.len()), Some(2));
+
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+    }
+
+    #[test]
+    fn test_dual_cpu_start_test_without_params_plus_stage_intents_and_stale_input_id() {
+        lib::init_hardware();
+        let tmp_dir = env::temp_dir().join(format!(
+            "stl-dual-intent-{}-{}",
+            std::process::id(),
+            now_ms()
+        ));
+        let args = ServerArgs {
+            config_path: Path::new("config/backend.example.json").to_path_buf(),
+            data_dir: tmp_dir.clone(),
+            web_listen: "127.0.0.1:0".to_string(),
+            tftp_listen: "disabled".to_string(),
+            web_dir: Path::new("web").to_path_buf(),
+            contracts_path: Path::new("contracts/firmware-vd012.json").to_path_buf(),
+            version: "0.8.1.19".to_string(),
+            commit: "unit-test".to_string(),
+        };
+        let hub = AppHub::init_for_test(&args);
+
+        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+        let tcp_port = listener.local_addr().unwrap().port();
+
+        // Point S1 at our loopback tcp_serial mock DUT with BMC disabled (Web/admin EnqueueCommand)
+        hub.dispatch_rpc(
+            "EnqueueCommand",
+            &parse_json(&format!(
+                r#"{{
+                    "station_id":"S1",
+                    "method":"ConfigureConnections",
+                    "arguments":{{
+                        "connections":{{
+                            "bmc":{{"enabled":false,"host":""}},
+                            "console":{{"enabled":true,"transport":"tcp_serial","host":"127.0.0.1","port":{},"write_chunk_bytes":256,"write_gap_ms":1}}
+                        }}
+                    }}
+                }}"#,
+                tcp_port
+            ))
+            .unwrap(),
+            false,
+        )
+        .unwrap();
+
+        let (mut dut_sock, _) = listener.accept().unwrap();
+        dut_sock
+            .set_read_timeout(Some(Duration::from_secs(4)))
+            .unwrap();
+
+        let read_cmd = |sock: &mut std::net::TcpStream| -> String {
+            let mut line = Vec::new();
+            let mut b = [0u8; 1];
+            loop {
+                let n = sock.read(&mut b).expect("DUT socket read timeout");
+                if n == 0 {
+                    break;
+                }
+                if b[0] == b'\r' || b[0] == b'\n' {
+                    if !line.is_empty() {
+                        break;
+                    }
+                    continue;
+                }
+                line.push(b[0]);
+            }
+            String::from_utf8_lossy(&line).to_string()
+        };
+
+        // StartTest WITHOUT task_params -> starts in manual preset, then Qt sends 4 SetStageIntents!
+        let st_res = hub
+            .dispatch_rpc(
+                "StartTest",
+                &parse_json(r#"{"command_id":"st-no-params","station_id":"S1"}"#).unwrap(),
+                true,
+            )
+            .unwrap();
+        assert!(matches!(
+            st_res.get_str_or("state", "").as_str(),
+            "succeeded" | "running" | "queued"
+        ));
+
+        hub.dispatch_rpc(
+            "SetStageIntent",
+            &parse_json(r#"{"station_id":"S1","stage":"uip1","action":"continue_uip","run_rmt":true,"memory_params":{"ecc":true}}"#).unwrap(),
+            true,
+        )
+        .unwrap();
+        hub.dispatch_rpc(
+            "SetStageIntent",
+            &parse_json(r#"{"station_id":"S1","stage":"amt","action":"start_amt","run_amt":true,"amt":{"selected":["B-WRUP","B-Hammer"],"test_command":"amemdiag 1"}}"#).unwrap(),
+            true,
+        )
+        .unwrap();
+        hub.dispatch_rpc(
+            "SetStageIntent",
+            &parse_json(r#"{"station_id":"S1","stage":"uip2","action":"continue_uip"}"#).unwrap(),
+            true,
+        )
+        .unwrap();
+        hub.dispatch_rpc(
+            "SetStageIntent",
+            &parse_json(r#"{"station_id":"S1","stage":"mt","action":"start_mt","run_mt":true}"#).unwrap(),
+            true,
+        )
+        .unwrap();
+
+        // CPU0 arrives at ICT Stage 1
+        dut_sock
+            .write_all(
+                b"[SYS_BIOS]Version:107_VD012\r\n[0][Hovsee]Current stage is 1\r\n[0][Hovsee]Please input your command:",
+            )
+            .unwrap();
+        let mut cpu0_uip1_cmds = Vec::new();
+        loop {
+            let cmd = read_cmd(&mut dut_sock);
+            cpu0_uip1_cmds.push(cmd.clone());
+            if cmd == "exit" {
+                dut_sock.write_all(b"[0][Hovsee]Exit Hovsee UIP\r\n").unwrap();
+                break;
+            }
+            dut_sock
+                .write_all(b"\r\n[0][Hovsee]Please input your command:")
+                .unwrap();
+        }
+        assert!(cpu0_uip1_cmds.iter().any(|c| c == "ecc enable"));
+        assert!(cpu0_uip1_cmds.iter().any(|c| c == "rmt enable"));
+
+        // Wait briefly so CPU0 finishes UIP1 -> verify CPU1 ALSO automatically runs ICT Stage 1!
+        dut_sock
+            .write_all(
+                b"[1][Hovsee]Current stage is 1\r\n[1][Hovsee]Please input your command:",
+            )
+            .unwrap();
+        let mut cpu1_uip1_cmds = Vec::new();
+        loop {
+            let cmd = read_cmd(&mut dut_sock);
+            cpu1_uip1_cmds.push(cmd.clone());
+            if cmd == "exit" {
+                dut_sock
+                    .write_all(b"[1][Hovsee]Exit ICT ddr test and go on training\r\n")
+                    .unwrap();
+                break;
+            }
+            dut_sock
+                .write_all(b"\r\n[1][Hovsee]Please input your command:")
+                .unwrap();
+        }
+        assert!(cpu1_uip1_cmds.iter().any(|c| c == "ecc enable"));
+
+        // Training + RMT -> CPU0 AMT menu
+        dut_sock
+            .write_all(
+                b"START_RMT_N1\r\nSTOP_RMT_N1\r\n[0] AMT Version GNR-4.3.3 (Aug 13 2026)\r\n[0][AMT #]",
+            )
+            .unwrap();
+        let amt0_tp = read_cmd(&mut dut_sock);
+        assert_eq!(amt0_tp, "tp 0,1,0,255,0,255 15,1,0,255,0,255,0,0,0x1d4c00,8");
+        dut_sock.write_all(b"\r\n[0][AMT #]").unwrap();
+        let amt0_run = read_cmd(&mut dut_sock);
+        assert_eq!(amt0_run, "amemdiag 1");
+
+        // CPU0 AMT finishes and auto-exits; also verify late/stale StageAction(skip_amt) is rejected cleanly without touching CPU1!
+        dut_sock
+            .write_all(b"[0] AMT Test Result: pass\r\n[0] AMT Test Algo Count: 2\r\n[0][AMT #]")
+            .unwrap();
+        let amt0_exit = read_cmd(&mut dut_sock);
+        assert_eq!(amt0_exit, "exit");
+
+        let stale_res = hub
+            .dispatch_rpc(
+                "StageAction",
+                &parse_json(r#"{"command_id":"stale-amt-0","station_id":"S1","input_id":"stale:amt:cpu0","action":"skip_amt"}"#).unwrap(),
+                true,
+            )
+            .unwrap();
+        assert_eq!(stale_res.get_str_or("state", ""), "failed");
+        assert_eq!(
+            stale_res
+                .get("error")
+                .and_then(|e| e.get_str("code")),
+            Some("FAILED_PRECONDITION")
+        );
+
+        // CPU1 arrives at AMT -> MUST still run `tp` + `amemdiag 1`!
+        dut_sock
+            .write_all(b"[1] AMT Version GNR-4.3.3 (Aug 13 2026)\r\n[1][AMT #]")
+            .unwrap();
+        let amt1_tp = read_cmd(&mut dut_sock);
+        assert_eq!(amt1_tp, "tp 0,1,0,255,0,255 15,1,0,255,0,255,0,0,0x1d4c00,8");
+        dut_sock.write_all(b"\r\n[1][AMT #]").unwrap();
+        let amt1_run = read_cmd(&mut dut_sock);
+        assert_eq!(amt1_run, "amemdiag 1");
+        dut_sock
+            .write_all(b"[1] AMT Test Result: pass\r\n[1] AMT Test Algo Count: 2\r\n[1][AMT #]")
+            .unwrap();
+        let amt1_exit = read_cmd(&mut dut_sock);
+        assert_eq!(amt1_exit, "exit");
+
+        // CPU0 & CPU1 ICT Stage 2
+        dut_sock
+            .write_all(b"[0][Hovsee]Current stage is 2\r\n[0][Hovsee]Please input your command:")
+            .unwrap();
+        assert_eq!(read_cmd(&mut dut_sock), "exit");
+        dut_sock
+            .write_all(b"[1][Hovsee]Current stage is 2\r\n[1][Hovsee]Please input your command:")
+            .unwrap();
+        assert_eq!(read_cmd(&mut dut_sock), "exit");
+
+        // UEFI Shell -> auto MT (`118.efi`)
+        dut_sock
+            .write_all(b"UEFI Interactive Shell v2.2\r\nFS0:\\EFI\\> ")
+            .unwrap();
+        let mut saw_118 = false;
+        for _ in 0..30 {
+            let cmd = read_cmd(&mut dut_sock);
+            if cmd == "118.efi" {
+                saw_118 = true;
+                break;
+            }
+            dut_sock.write_all(b"\r\nFS0:\\EFI\\> ").unwrap();
+        }
+        assert!(saw_118);
+
+        // MemTest86 completes PASS
+        dut_sock
+            .write_all(b"PassMark MemTest86 v11.8 Pro\r\nTest Complete - 0 Errors\r\nFS0:\\EFI\\> ")
+            .unwrap();
+        let mut final_pass = false;
+        for _ in 0..40 {
+            let ts = hub
+                .dispatch_rpc(
+                    "GetTaskStatus",
+                    &parse_json(r#"{"station_id":"S1"}"#).unwrap(),
+                    true,
+                )
+                .unwrap();
+            if ts
+                .get("stage_completions")
+                .and_then(|c| c.get_bool("mt_pass_complete"))
+                == Some(true)
+            {
+                final_pass = true;
+                break;
+            }
+            std::thread::sleep(Duration::from_millis(25));
+        }
+        assert!(final_pass);
+
+        drop(dut_sock);
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+    }
+
+    #[test]
+    fn test_uefi_mapping_table_auto_discovers_fs1_118_efi() {
+        lib::init_hardware();
+        let tmp_dir = env::temp_dir().join(format!(
+            "stl-uefi-fs1-{}-{}",
+            std::process::id(),
+            now_ms()
+        ));
+        let args = ServerArgs {
+            config_path: Path::new("config/backend.example.json").to_path_buf(),
+            data_dir: tmp_dir.clone(),
+            web_listen: "127.0.0.1:0".to_string(),
+            tftp_listen: "disabled".to_string(),
+            web_dir: Path::new("web").to_path_buf(),
+            contracts_path: Path::new("contracts/firmware-vd012.json").to_path_buf(),
+            version: "0.8.1.19".to_string(),
+            commit: "unit-test".to_string(),
+        };
+        let hub = AppHub::init_for_test(&args);
+
+        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+        let tcp_port = listener.local_addr().unwrap().port();
+
+        hub.dispatch_rpc(
+            "EnqueueCommand",
+            &parse_json(&format!(
+                r#"{{
+                    "station_id":"S1",
+                    "method":"ConfigureConnections",
+                    "arguments":{{
+                        "connections":{{
+                            "bmc":{{"enabled":false,"host":""}},
+                            "console":{{"enabled":true,"transport":"tcp_serial","host":"127.0.0.1","port":{},"write_chunk_bytes":256,"write_gap_ms":1}}
+                        }}
+                    }}
+                }}"#,
+                tcp_port
+            ))
+            .unwrap(),
+            false,
+        )
+        .unwrap();
+
+        let (mut dut_sock, _) = listener.accept().unwrap();
+        dut_sock
+            .set_read_timeout(Some(Duration::from_secs(5)))
+            .unwrap();
+
+        let read_cmd = |sock: &mut std::net::TcpStream| -> String {
+            let mut line = Vec::new();
+            let mut b = [0u8; 1];
+            loop {
+                let n = sock.read(&mut b).expect("DUT socket read timeout");
+                if n == 0 {
+                    break;
+                }
+                if b[0] == b'\r' || b[0] == b'\n' {
+                    if !line.is_empty() {
+                        break;
+                    }
+                    continue;
+                }
+                line.push(b[0]);
+            }
+            String::from_utf8_lossy(&line).to_string()
+        };
+
+        // StartTest with auto MT enabled (omits efi_path -> defaults to FS0:\EFI\118.efi -> triggers probe!)
+        hub.dispatch_rpc(
+            "StartTest",
+            &parse_json(
+                r#"{"command_id":"st-fs1","station_id":"S1","run_rmt":false,"run_amt":false,"run_mt":true,"mt":{"exitmode":2,"numpass":1}}"#,
+            )
+            .unwrap(),
+            true,
+        )
+        .unwrap();
+
+        // Simulate real USB+NVMe UEFI Mapping table where FS0: is USB (no \EFI\118.efi) and FS1: is NVMe ESP (has \EFI\118.efi)
+        dut_sock
+            .write_all(
+                b"UEFI Interactive Shell v2.2\r\nMapping table\r\n      FS0: Alias(s):HD0c0a0b:;BLK1:\r\n          PciRoot(0x11)/USB(0x2,0x0)/HD(1,MBR,0x1)\r\n      FS1: Alias(s):HD1b:;BLK3:\r\n          PciRoot(0x11)/NVMe(0x1)/HD(1,GPT,0x2)\r\nShell> ",
+            )
+            .unwrap();
+
+        // Expect `ls fs0:\EFI\118.efi` -> respond File Not Found
+        let probe0 = read_cmd(&mut dut_sock);
+        assert_eq!(probe0, r"ls fs0:\EFI\118.efi");
+        dut_sock
+            .write_all(b"ls fs0:\\EFI\\118.efi\r\nls: File Not Found - 'fs0:\\EFI\\'\r\nShell> ")
+            .unwrap();
+
+        // Expect `ls fs1:\EFI\118.efi` -> respond 118.efi directory listing!
+        let probe1 = read_cmd(&mut dut_sock);
+        assert_eq!(probe1, r"ls fs1:\EFI\118.efi");
+        dut_sock
+            .write_all(b"ls fs1:\\EFI\\118.efi\r\nDirectory of: fs1:\\EFI\\\r\n11/13/2026  12:41  1,318,912  118.efi\r\n          1 File(s)   1,318,912 bytes\r\nShell> ")
+            .unwrap();
+
+        // Expect `fs1:` -> switch drive prompt
+        let cmd_fs1 = read_cmd(&mut dut_sock);
+        assert_eq!(cmd_fs1, "fs1:");
+        dut_sock.write_all(b"fs1:\r\nFS1:\\> ").unwrap();
+
+        // Expect `cd \EFI` -> enter FS1:\EFI\>
+        let cmd_cd = read_cmd(&mut dut_sock);
+        assert_eq!(cmd_cd, r"cd \EFI");
+        dut_sock.write_all(b"cd \\EFI\r\nFS1:\\EFI\\> ").unwrap();
+
+        // Subsequent config echo/cp lines ending with 118.efi
+        let mut saw_118 = false;
+        for _ in 0..30 {
+            let cmd = read_cmd(&mut dut_sock);
+            if cmd == "118.efi" {
+                saw_118 = true;
+                break;
+            }
+            dut_sock.write_all(b"\r\nFS1:\\EFI\\> ").unwrap();
+        }
+        assert!(saw_118);
+
+        // Complete MT PASS
+        dut_sock
+            .write_all(b"PassMark MemTest86 v11.8 Pro\r\nTest Complete - 0 Errors\r\nFS1:\\EFI\\> ")
+            .unwrap();
+        let mut final_pass = false;
+        for _ in 0..40 {
+            let ts = hub
+                .dispatch_rpc(
+                    "GetTaskStatus",
+                    &parse_json(r#"{"station_id":"S1"}"#).unwrap(),
+                    true,
+                )
+                .unwrap();
+            if ts
+                .get("stage_completions")
+                .and_then(|c| c.get_bool("mt_pass_complete"))
+                == Some(true)
+            {
+                final_pass = true;
+                break;
+            }
+            std::thread::sleep(Duration::from_millis(25));
+        }
+        assert!(final_pass);
+
+        drop(dut_sock);
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+    }
 }

+ 767 - 19
native/stl_accel/src/pxe.rs

@@ -1,15 +1,20 @@
-// pxe.rs — Three-variant 118.efi PXE & mt86.cfg manager with non-blocking .63 TFTP multi-candidate sync
+// pxe.rs — Three-variant 118.efi PXE & mt86.cfg manager, embedded non-blocking
+//          UDP :69 TFTP server (RRQ + WRQ MemTest86 HTML report ingestion), and optional .63 sync
 
+use crate::actors::StationMsg;
 use crate::json::JsonVal;
 use crate::results::now_ms;
 use std::fs;
-use std::net::{SocketAddr, TcpStream};
+use std::io::ErrorKind;
+use std::net::{SocketAddr, TcpStream, UdpSocket};
 use std::path::{Path, PathBuf};
 use std::process::Command;
+use std::sync::Arc;
 use std::thread;
 use std::time::Duration;
 
-pub const DEFAULT_FORMAL_TSTLIST: &str = "0,1,2,3,4,5,6,7,8,9,10,11,12,13";
+pub const DEFAULT_FORMAL_TSTLIST: &str =
+    "0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25";
 
 pub const PXE_VARIANTS: [(&str, &str, &str, &str, &str); 3] = [
     (
@@ -74,6 +79,9 @@ pub fn default_pxe_state() -> JsonVal {
     cfg.set("automode", JsonVal::Num(1.0));
     cfg.set("exitmode", JsonVal::Num(2.0));
     cfg.set("skipsplash", JsonVal::Num(1.0));
+    cfg.set("autoreport", JsonVal::Num(1.0));
+    cfg.set("autoreportfmt", JsonVal::Str("HTML".to_string()));
+    cfg.set("reportnumerrs", JsonVal::Num(100.0));
 
     let mut st = JsonVal::obj();
     st.set("active_variant", JsonVal::Str("118_serial.efi".to_string()));
@@ -83,6 +91,7 @@ pub fn default_pxe_state() -> JsonVal {
     st.set("pxe_subnet_mask", JsonVal::Str("255.255.255.0".to_string()));
     st.set("pxe_client_ip", JsonVal::Str("192.168.0.160".to_string()));
     st.set("mt86_cfg", cfg);
+    st.set("recent_reports", JsonVal::Arr(Vec::new()));
     st.set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
     st
 }
@@ -130,28 +139,101 @@ pub fn build_pxe_snapshot(pxe_state: &JsonVal) -> JsonVal {
     if let Some(ok) = pxe_state.get_bool("remote_synced") {
         snap.set("remote_synced", JsonVal::Bool(ok));
     }
-    snap.set("recent_reports", JsonVal::Arr(Vec::new()));
+    let reports = pxe_state
+        .get_arr("recent_reports")
+        .cloned()
+        .unwrap_or_default();
+    snap.set("recent_reports", JsonVal::Arr(reports));
     snap
 }
 
+fn mt_test_name_to_idx(name: &str) -> Option<i64> {
+    let lower = name.trim().to_ascii_lowercase();
+    if lower.is_empty() {
+        return None;
+    }
+    match lower.as_str() {
+        "address test, walking ones, 1 cpu"
+        | "adress test, walking ones, 1 cpu"
+        | "walking 1s"
+        | "walking 1s 1cpu" => Some(0),
+        "address test, own address, 1 cpu" | "own addr 1cpu" => Some(1),
+        "address test, own address" | "own addr" => Some(2),
+        "moving inversions, ones & zeroes"
+        | "moving inversions, ones and zeroes"
+        | "movinv 1&0" => Some(3),
+        "moving inversions, 8-bit pattern" | "movinv 8b" => Some(4),
+        "moving inversions, random pattern" | "movinv rand" => Some(5),
+        "block move, 64-byte blocks" | "block move" => Some(6),
+        "moving inversions, 32-bit pattern" | "movinv 32b" => Some(7),
+        "random number sequence" | "rand seq" => Some(8),
+        "modulo 20, random pattern" | "modulo 20" => Some(9),
+        "bit fade test, 2 patterns, 1 cpu"
+        | "bit fade"
+        | "bit fade 2pat"
+        | "bit fade(2)" => Some(10),
+        "random number sequence, 64-bit" | "rand 64-bit" => Some(11),
+        "random number sequence, 128-bit" | "rand 128-bit" => Some(12),
+        "hammer test" => Some(13),
+        "dma test (experimental)" | "dma test" => Some(14),
+        "march c algorithm" | "march c" => Some(15),
+        "galloping pattern (galpat)" | "galpat" => Some(16),
+        "galloping pattern (linear)" | "galpat linear" => Some(17),
+        "galloping pattern (randomaddress)" | "galpat randaddr" => Some(18),
+        "galloping pattern (bankjump)" | "galpat bankjump" => Some(19),
+        "galloping pattern (victim)" | "galpat victim" => Some(20),
+        "galloping pattern (marchic)" | "galpat marchic" => Some(21),
+        "galloping pattern (marchsse)" | "galpat marchsse" => Some(22),
+        "galloping pattern (butterfly)" | "galpat butterfly" => Some(23),
+        "march ss+ algorithm" | "march ss+" => Some(24),
+        "stressapp memory stress test" | "stressapp" => Some(25),
+        _ => {
+            if let Some(rest) = lower.strip_prefix("test ") {
+                if let Ok(n) = rest.trim().parse::<i64>() {
+                    if (0..=25).contains(&n) {
+                        return Some(n);
+                    }
+                }
+            }
+            // Match explicit leading integer prefix only (e.g. "0", "15", "4:MovInv Rand"),
+            // never mid-string digits like "8-bit" or "1 CPU".
+            let digit_len = lower
+                .bytes()
+                .take_while(|b| b.is_ascii_digit())
+                .count();
+            if digit_len > 0 {
+                let tail = &lower.as_bytes()[digit_len..];
+                let ok_boundary = tail.is_empty()
+                    || matches!(tail[0], b':' | b'.' | b'-' | b')' | b' ' | b'\t');
+                if ok_boundary {
+                    if let Ok(n) = lower[..digit_len].parse::<i64>() {
+                        if (0..=25).contains(&n) {
+                            return Some(n);
+                        }
+                    }
+                }
+            }
+            None
+        }
+    }
+}
+
 fn parse_test_id_list(arr: &[JsonVal]) -> Vec<i64> {
     let mut out = Vec::new();
     for x in arr {
         let parsed = match x {
-            JsonVal::Num(n) => Some(*n as i64),
-            JsonVal::Str(s) => {
-                let t = s.trim();
-                let digits: String = t
-                    .chars()
-                    .skip_while(|c| !c.is_ascii_digit())
-                    .take_while(|c| c.is_ascii_digit())
-                    .collect();
-                digits.parse::<i64>().ok()
+            JsonVal::Num(n) => {
+                if n.is_finite() && *n >= 0.0 && (*n as i64) as f64 == *n {
+                    Some(*n as i64)
+                } else {
+                    None
+                }
             }
+            JsonVal::Str(s) => mt_test_name_to_idx(s),
             _ => None,
         };
         if let Some(n) = parsed {
-            if (0..=13).contains(&n) && !out.contains(&n) {
+            if (0..=25).contains(&n) && !out.contains(&n) {
                 out.push(n);
             }
         }
@@ -159,7 +241,7 @@ fn parse_test_id_list(arr: &[JsonVal]) -> Vec<i64> {
     out
 }
 
-pub fn render_mt86_cfg_text(cfg: &JsonVal) -> String {
+pub fn render_mt86_cfg_text(cfg: &JsonVal, tftp_server_ip: &str) -> String {
     let fallback_tst = cfg.get_str_or("tstlist", DEFAULT_FORMAL_TSTLIST);
     let tstlist = if let Some(only) = cfg.get_arr("only_tests") {
         let nums = parse_test_id_list(only);
@@ -184,7 +266,7 @@ pub fn render_mt86_cfg_text(cfg: &JsonVal) -> String {
         }
     } else if let Some(skip) = cfg.get_arr("skip_tests") {
         let skip_set = parse_test_id_list(skip);
-        let nums: Vec<String> = (0..=13)
+        let nums: Vec<String> = (0..=25)
             .filter(|n| !skip_set.contains(n))
             .map(|n| n.to_string())
             .collect();
@@ -218,11 +300,23 @@ pub fn render_mt86_cfg_text(cfg: &JsonVal) -> String {
         .unwrap_or(2)
         .clamp(0, 3);
     let skipsplash = cfg.get_i64("skipsplash").unwrap_or(1).clamp(0, 1);
+    let autoreport = cfg.get_i64("autoreport").unwrap_or(1).clamp(0, 1);
+    let raw_fmt = cfg.get_str_or("autoreportfmt", "HTML");
+    let autoreportfmt = if raw_fmt.trim().is_empty() {
+        "HTML".to_string()
+    } else {
+        raw_fmt.trim().to_ascii_uppercase()
+    };
+    let reportnumerrs = cfg.get_i64("reportnumerrs").unwrap_or(100).clamp(0, 10000);
 
     let mut out = format!(
-        "TSTLIST={}\r\nNUMPASS={}\r\nCPUSEL={}\r\nCPUNUM={}\r\nMAXCPUS={}\r\nDISABLEMP={}\r\nENABLEHT={}\r\nECCPOLL={}\r\nAUTOMODE={}\r\nEXITMODE={}\r\nSKIPSPLASH={}\r\n",
-        tstlist, numpass, cpusel, cpunum, maxcpus, disablemp, enableht, eccpoll, automode, exitmode, skipsplash
+        "TSTLIST={}\r\nNUMPASS={}\r\nCPUSEL={}\r\nCPUNUM={}\r\nMAXCPUS={}\r\nDISABLEMP={}\r\nENABLEHT={}\r\nECCPOLL={}\r\nAUTOMODE={}\r\nEXITMODE={}\r\nSKIPSPLASH={}\r\nAUTOREPORT={}\r\nAUTOREPORTFMT={}\r\nREPORTNUMERRS={}\r\n",
+        tstlist, numpass, cpusel, cpunum, maxcpus, disablemp, enableht, eccpoll, automode, exitmode, skipsplash, autoreport, autoreportfmt, reportnumerrs
     );
+    let trimmed_tftp = tftp_server_ip.trim();
+    if !trimmed_tftp.is_empty() && autoreport > 0 {
+        out.push_str(&format!("TFTPSERVERIP={}\r\n", trimmed_tftp));
+    }
 
     if let Some(dbg) = cfg.get_i64("debuglog").or_else(|| cfg.get_bool("debuglog").map(|b| if b { 1 } else { 0 })) {
         if dbg > 0 {
@@ -404,6 +498,16 @@ pub fn apply_pxe_configuration(
             pxe_state.set("pxe_host", JsonVal::Str(h.trim().to_string()));
         }
     }
+    if let Some(ip) = args.get_str("pxe_server_ip") {
+        if !ip.trim().is_empty() {
+            pxe_state.set("pxe_server_ip", JsonVal::Str(ip.trim().to_string()));
+        }
+    }
+    if let Some(ip) = args.get_str("pxe_client_ip") {
+        if !ip.trim().is_empty() {
+            pxe_state.set("pxe_client_ip", JsonVal::Str(ip.trim().to_string()));
+        }
+    }
     let cfg_obj = args
         .get("mt86_cfg")
         .cloned()
@@ -411,7 +515,8 @@ pub fn apply_pxe_configuration(
         .unwrap_or_else(|| default_pxe_state().get("mt86_cfg").cloned().unwrap_or_else(JsonVal::obj));
     pxe_state.set("mt86_cfg", cfg_obj.clone());
 
-    let cfg_text = render_mt86_cfg_text(&cfg_obj);
+    let pxe_server_ip = pxe_state.get_str_or("pxe_server_ip", "192.168.0.10");
+    let cfg_text = render_mt86_cfg_text(&cfg_obj, &pxe_server_ip);
     let cfg_path = write_local_mt86_candidates(pxe_tftp_dir, &cfg_text);
     let src_efi = pxe_tftp_dir.join(&variant);
     let dst_efi = pxe_tftp_dir.join("118.efi");
@@ -429,3 +534,646 @@ pub fn apply_pxe_configuration(
     let _ = fs::write(data_dir.join("pxe_control_state.json"), pxe_state.to_json());
     Ok(build_pxe_snapshot(pxe_state))
 }
+
+fn strip_html_tags_to_text(html: &str) -> String {
+    let mut raw_clean = String::with_capacity(html.len());
+    let mut in_tag = false;
+    let mut prev_space = false;
+    for ch in html.chars() {
+        if ch == '<' {
+            in_tag = true;
+            if !prev_space {
+                raw_clean.push(' ');
+                prev_space = true;
+            }
+        } else if ch == '>' {
+            in_tag = false;
+        } else if !in_tag {
+            if ch.is_whitespace() {
+                if !prev_space {
+                    raw_clean.push(' ');
+                    prev_space = true;
+                }
+            } else {
+                raw_clean.push(ch);
+                prev_space = false;
+            }
+        }
+    }
+    raw_clean
+        .replace("&nbsp;", " ")
+        .replace("&amp;", "&")
+        .replace("&lt;", "<")
+        .replace("&gt;", ">")
+        .split_whitespace()
+        .collect::<Vec<_>>()
+        .join(" ")
+}
+
+fn extract_i64_after_labels(lower_txt: &str, labels: &[&str]) -> Option<i64> {
+    for lbl in labels {
+        let mut start_from = 0usize;
+        while let Some(pos) = lower_txt[start_from..].find(lbl) {
+            let abs = start_from + pos + lbl.len();
+            let rest = lower_txt[abs..].trim_start_matches(|c: char| c == ':' || c == '=' || c.is_whitespace());
+            let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
+            if !digits.is_empty() {
+                if let Ok(v) = digits.parse::<i64>() {
+                    return Some(v);
+                }
+            }
+            start_from = abs;
+        }
+    }
+    None
+}
+
+fn extract_token_after_labels(orig_txt: &str, lower_txt: &str, labels: &[&str]) -> String {
+    for lbl in labels {
+        if let Some(pos) = lower_txt.find(lbl) {
+            let abs = pos + lbl.len();
+            if abs <= orig_txt.len() {
+                let mut slice = &orig_txt[abs..];
+                slice = slice.trim_start_matches(|c: char| c == ':' || c == '=' || c.is_whitespace());
+                let tok = slice.split_whitespace().next().unwrap_or("");
+                if !tok.is_empty() && tok.chars().any(|c| c.is_ascii_digit()) {
+                    return tok.to_string();
+                }
+            }
+        }
+    }
+    String::new()
+}
+
+pub fn parse_mt86_html_report(filename: &str, html: &str) -> JsonVal {
+    let clean_txt = strip_html_tags_to_text(html);
+    let lower_html = html.to_ascii_lowercase();
+    let lower_txt = clean_txt.to_ascii_lowercase();
+
+    let errors = extract_i64_after_labels(
+        &lower_txt,
+        &["total errors", "error count", "errors:", "errors"],
+    )
+    .unwrap_or_else(|| {
+        // Fallback: "<N> errors"
+        let words: Vec<&str> = lower_txt.split_whitespace().collect();
+        for w in words.windows(2) {
+            if w[1].starts_with("error") {
+                if let Ok(n) = w[0].trim_matches(|c: char| !c.is_ascii_digit()).parse::<i64>() {
+                    return n;
+                }
+            }
+        }
+        0
+    });
+
+    let tests_passed = extract_token_after_labels(
+        &clean_txt,
+        &lower_txt,
+        &["tests passed", "tests completed"],
+    );
+    let elapsed = extract_token_after_labels(
+        &clean_txt,
+        &lower_txt,
+        &["elapsed time", "test time", "elapsed"],
+    );
+
+    let has_fail_marker = lower_html.contains("failstamp")
+        || lower_txt.contains("result: fail")
+        || lower_txt.contains("result fail")
+        || lower_txt.contains("result: incomplete")
+        || lower_txt.contains("test result fail")
+        || lower_txt.contains("test result: fail")
+        || lower_txt.contains("incomplete")
+        || errors > 0;
+    let has_pass_marker = !has_fail_marker
+        && (lower_html.contains("passstamp")
+            || lower_txt.contains("result: pass")
+            || lower_txt.contains("result pass")
+            || lower_txt.contains("test result pass")
+            || lower_txt.contains("test result: pass")
+            || lower_txt.contains("pass complete")
+            || lower_txt.contains("0 errors")
+            || lower_txt.contains("total errors 0"));
+
+    let verdict = if has_fail_marker {
+        "fail"
+    } else if has_pass_marker {
+        "pass"
+    } else {
+        "unknown"
+    };
+
+    let mut obj = JsonVal::obj();
+    obj.set("filename", JsonVal::Str(filename.to_string()));
+    obj.set("verdict", JsonVal::Str(verdict.to_string()));
+    obj.set("errors", JsonVal::Num(errors as f64));
+    if !tests_passed.is_empty() {
+        obj.set("tests_passed", JsonVal::Str(tests_passed));
+    }
+    if !elapsed.is_empty() {
+        obj.set("elapsed", JsonVal::Str(elapsed));
+    }
+    obj.set("uploaded_unix_ms", JsonVal::Num(now_ms() as f64));
+    obj.set("size_bytes", JsonVal::Num(html.len() as f64));
+    obj
+}
+
+fn sanitize_tftp_rel_path(raw: &str) -> Option<PathBuf> {
+    let norm = raw.replace('\\', "/");
+    let mut pb = PathBuf::new();
+    for seg in norm.split('/') {
+        let s = seg.trim();
+        if s.is_empty() || s == "." {
+            continue;
+        }
+        if s == ".." || s.contains('\0') {
+            return None;
+        }
+        pb.push(s);
+    }
+    if pb.as_os_str().is_empty() {
+        None
+    } else {
+        Some(pb)
+    }
+}
+
+fn send_tftp_error(sock: &UdpSocket, peer: SocketAddr, code: u16, msg: &str) {
+    let mut pkt = Vec::with_capacity(5 + msg.len());
+    pkt.extend_from_slice(&5u16.to_be_bytes());
+    pkt.extend_from_slice(&code.to_be_bytes());
+    pkt.extend_from_slice(msg.as_bytes());
+    pkt.push(0);
+    let _ = sock.send_to(&pkt, peer);
+}
+
+fn parse_tftp_request(pkt: &[u8]) -> Option<(u16, String, String, Vec<(String, String)>)> {
+    if pkt.len() < 4 {
+        return None;
+    }
+    let op = u16::from_be_bytes([pkt[0], pkt[1]]);
+    if op != 1 && op != 2 {
+        return None;
+    }
+    let mut raw_fields: Vec<String> = Vec::new();
+    let mut idx = 2usize;
+    while idx < pkt.len() {
+        let rel_nul = pkt[idx..].iter().position(|&b| b == 0).unwrap_or(pkt.len() - idx);
+        let part = String::from_utf8_lossy(&pkt[idx..idx + rel_nul]).to_string();
+        raw_fields.push(part);
+        idx += rel_nul + 1;
+    }
+    if raw_fields.len() < 2 || raw_fields[0].is_empty() {
+        return None;
+    }
+    let filename = raw_fields[0].clone();
+    let mode = raw_fields[1].to_ascii_lowercase();
+    let mut opts = Vec::new();
+    let mut i = 2usize;
+    while i + 1 < raw_fields.len() {
+        let k = raw_fields[i].to_ascii_lowercase();
+        let v = raw_fields[i + 1].clone();
+        if !k.is_empty() {
+            opts.push((k, v));
+        }
+        i += 2;
+    }
+    Some((op, filename, mode, opts))
+}
+
+fn is_mt86_cfg_name(base_lower: &str) -> bool {
+    matches!(
+        base_lower,
+        "mt86.cfg" | "memtest86.cfg" | "118.cfg" | "default string-mt86.cfg"
+    ) || base_lower.ends_with("-mt86.cfg")
+}
+
+fn resolve_tftp_rrq_bytes(hub: &crate::api::AppHub, raw_name: &str) -> Option<Vec<u8>> {
+    let rel = sanitize_tftp_rel_path(raw_name)?;
+    let fname = rel.file_name()?.to_string_lossy().to_string();
+    let base_lower = fname.to_ascii_lowercase();
+
+    if is_mt86_cfg_name(&base_lower) {
+        for cand in [hub.pxe_tftp_dir.join(&fname), hub.pxe_tftp_dir.join("mt86.cfg")] {
+            if cand.is_file() {
+                if let Ok(b) = fs::read(&cand) {
+                    if b.windows(11).any(|w| w == b"AUTOREPORT=") {
+                        return Some(b);
+                    }
+                }
+            }
+        }
+        if let Ok(st) = hub.pxe_state.read() {
+            let cfg_val = st
+                .get("mt86_cfg")
+                .cloned()
+                .unwrap_or_else(JsonVal::obj);
+            let tftp_ip = st.get_str_or("pxe_server_ip", "192.168.0.10");
+            return Some(render_mt86_cfg_text(&cfg_val, &tftp_ip).into_bytes());
+        }
+    }
+
+    let exact = hub.pxe_tftp_dir.join(&rel);
+    if exact.is_file() {
+        if let Ok(b) = fs::read(&exact) {
+            return Some(b);
+        }
+    }
+
+    let flat = hub.pxe_tftp_dir.join(&fname);
+    if flat.is_file() {
+        if let Ok(b) = fs::read(&flat) {
+            return Some(b);
+        }
+    }
+
+    if let Ok(entries) = fs::read_dir(&hub.pxe_tftp_dir) {
+        for ent in entries.flatten() {
+            let p = ent.path();
+            if p.is_file() {
+                if let Some(en) = p.file_name().and_then(|s| s.to_str()) {
+                    if en.eq_ignore_ascii_case(&fname) {
+                        if let Ok(b) = fs::read(&p) {
+                            return Some(b);
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    if base_lower == "118.efi" {
+        if let Ok(st) = hub.pxe_state.read() {
+            let var_name = st.get_str_or("active_variant", "118_serial.efi");
+            let var_path = hub.pxe_tftp_dir.join(&var_name);
+            if var_path.is_file() {
+                if let Ok(b) = fs::read(&var_path) {
+                    return Some(b);
+                }
+            }
+        }
+    }
+    None
+}
+
+fn negotiate_tftp_options(
+    opts: &[(String, String)],
+    file_size_for_rrq: Option<usize>,
+) -> (usize, u64, Vec<(String, String)>) {
+    let mut blksize: usize = 512;
+    let mut timeout_secs: u64 = 2;
+    let mut oack_pairs: Vec<(String, String)> = Vec::new();
+    for (k, v) in opts {
+        match k.as_str() {
+            "blksize" => {
+                if let Ok(b) = v.parse::<usize>() {
+                    blksize = b.clamp(8, 8192);
+                    oack_pairs.push(("blksize".to_string(), blksize.to_string()));
+                }
+            }
+            "timeout" => {
+                if let Ok(t) = v.parse::<u64>() {
+                    timeout_secs = t.clamp(1, 30);
+                    oack_pairs.push(("timeout".to_string(), timeout_secs.to_string()));
+                }
+            }
+            "tsize" => {
+                if let Some(sz) = file_size_for_rrq {
+                    oack_pairs.push(("tsize".to_string(), sz.to_string()));
+                } else {
+                    oack_pairs.push(("tsize".to_string(), v.clone()));
+                }
+            }
+            _ => {}
+        }
+    }
+    (blksize, timeout_secs, oack_pairs)
+}
+
+fn build_oack_pkt(pairs: &[(String, String)]) -> Vec<u8> {
+    let mut pkt = Vec::with_capacity(64);
+    pkt.extend_from_slice(&6u16.to_be_bytes());
+    for (k, v) in pairs {
+        pkt.extend_from_slice(k.as_bytes());
+        pkt.push(0);
+        pkt.extend_from_slice(v.as_bytes());
+        pkt.push(0);
+    }
+    pkt
+}
+
+fn recv_from_peer_matching(
+    sock: &UdpSocket,
+    buf: &mut [u8],
+    peer: SocketAddr,
+) -> Option<usize> {
+    match sock.recv_from(buf) {
+        Ok((n, from)) if from == peer => Some(n),
+        Ok(_) => None,
+        Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => None,
+        Err(_) => None,
+    }
+}
+
+fn handle_tftp_rrq(
+    hub: Arc<crate::api::AppHub>,
+    peer: SocketAddr,
+    filename: String,
+    opts: Vec<(String, String)>,
+) {
+    let Ok(sock) = UdpSocket::bind("0.0.0.0:0") else {
+        return;
+    };
+    let Some(data) = resolve_tftp_rrq_bytes(&hub, &filename) else {
+        send_tftp_error(&sock, peer, 1, "File not found");
+        return;
+    };
+    let (blksize, timeout_secs, oack_pairs) = negotiate_tftp_options(&opts, Some(data.len()));
+    let _ = sock.set_read_timeout(Some(Duration::from_secs(timeout_secs)));
+
+    let mut rx = vec![0u8; 64];
+    if !oack_pairs.is_empty() {
+        let oack = build_oack_pkt(&oack_pairs);
+        let mut acked = false;
+        for _ in 0..5 {
+            if sock.send_to(&oack, peer).is_err() {
+                return;
+            }
+            if let Some(n) = recv_from_peer_matching(&sock, &mut rx, peer) {
+                if n >= 4 && u16::from_be_bytes([rx[0], rx[1]]) == 4 {
+                    let bno = u16::from_be_bytes([rx[2], rx[3]]);
+                    if bno == 0 {
+                        acked = true;
+                        break;
+                    }
+                }
+            }
+        }
+        if !acked {
+            return;
+        }
+    }
+
+    let mut block_num: u16 = 1;
+    let mut offset: usize = 0;
+    loop {
+        let end = (offset + blksize).min(data.len());
+        let slice = &data[offset..end];
+        let mut pkt = Vec::with_capacity(4 + slice.len());
+        pkt.extend_from_slice(&3u16.to_be_bytes());
+        pkt.extend_from_slice(&block_num.to_be_bytes());
+        pkt.extend_from_slice(slice);
+
+        let mut acked = false;
+        for _ in 0..5 {
+            if sock.send_to(&pkt, peer).is_err() {
+                return;
+            }
+            if let Some(n) = recv_from_peer_matching(&sock, &mut rx, peer) {
+                if n >= 4 && u16::from_be_bytes([rx[0], rx[1]]) == 4 {
+                    let bno = u16::from_be_bytes([rx[2], rx[3]]);
+                    if bno == block_num {
+                        acked = true;
+                        break;
+                    }
+                }
+            }
+        }
+        if !acked {
+            return;
+        }
+        if slice.len() < blksize {
+            break;
+        }
+        offset = end;
+        block_num = block_num.wrapping_add(1);
+    }
+}
+
+fn handle_tftp_wrq(
+    hub: Arc<crate::api::AppHub>,
+    peer: SocketAddr,
+    filename: String,
+    opts: Vec<(String, String)>,
+) {
+    let Ok(sock) = UdpSocket::bind("0.0.0.0:0") else {
+        return;
+    };
+    let Some(rel) = sanitize_tftp_rel_path(&filename) else {
+        send_tftp_error(&sock, peer, 2, "Access violation");
+        return;
+    };
+    let Some(clean_name) = rel.file_name().and_then(|s| s.to_str()).map(|s| s.to_string()) else {
+        send_tftp_error(&sock, peer, 2, "Access violation");
+        return;
+    };
+    let lower_name = clean_name.to_ascii_lowercase();
+    if lower_name.ends_with(".efi") || is_mt86_cfg_name(&lower_name) {
+        send_tftp_error(&sock, peer, 2, "Protected boot file");
+        return;
+    }
+
+    let (blksize, timeout_secs, oack_pairs) = negotiate_tftp_options(&opts, None);
+    let _ = sock.set_read_timeout(Some(Duration::from_secs(timeout_secs)));
+
+    let first_reply = if !oack_pairs.is_empty() {
+        build_oack_pkt(&oack_pairs)
+    } else {
+        let mut ack0 = Vec::with_capacity(4);
+        ack0.extend_from_slice(&4u16.to_be_bytes());
+        ack0.extend_from_slice(&0u16.to_be_bytes());
+        ack0
+    };
+    if sock.send_to(&first_reply, peer).is_err() {
+        return;
+    }
+
+    let mut payload: Vec<u8> = Vec::with_capacity(65536);
+    let mut expected_block: u16 = 1;
+    let mut rx = vec![0u8; 4 + blksize + 64];
+    let mut timeouts = 0u32;
+    let max_upload_bytes = 64 * 1024 * 1024usize;
+
+    loop {
+        match sock.recv_from(&mut rx) {
+            Ok((n, from)) => {
+                if from != peer {
+                    continue;
+                }
+                if n >= 4 && u16::from_be_bytes([rx[0], rx[1]]) == 3 {
+                    let bno = u16::from_be_bytes([rx[2], rx[3]]);
+                    let chunk = &rx[4..n];
+                    let mut ack = [0u8; 4];
+                    ack[0..2].copy_from_slice(&4u16.to_be_bytes());
+                    ack[2..4].copy_from_slice(&bno.to_be_bytes());
+                    let _ = sock.send_to(&ack, peer);
+                    timeouts = 0;
+
+                    if bno == expected_block {
+                        if payload.len() + chunk.len() > max_upload_bytes {
+                            send_tftp_error(&sock, peer, 3, "Disk full or allocation exceeded");
+                            return;
+                        }
+                        payload.extend_from_slice(chunk);
+                        if chunk.len() < blksize {
+                            break;
+                        }
+                        expected_block = expected_block.wrapping_add(1);
+                    }
+                } else if n >= 4 && u16::from_be_bytes([rx[0], rx[1]]) == 5 {
+                    return;
+                }
+            }
+            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
+                timeouts += 1;
+                if timeouts >= 5 {
+                    return;
+                }
+                if expected_block == 1 {
+                    let _ = sock.send_to(&first_reply, peer);
+                } else {
+                    let mut ack = [0u8; 4];
+                    ack[0..2].copy_from_slice(&4u16.to_be_bytes());
+                    ack[2..4].copy_from_slice(&expected_block.wrapping_sub(1).to_be_bytes());
+                    let _ = sock.send_to(&ack, peer);
+                }
+            }
+            Err(_) => return,
+        }
+    }
+
+    let _ = fs::create_dir_all(&hub.pxe_tftp_dir);
+    let dest_path = hub.pxe_tftp_dir.join(&clean_name);
+    let tmp_path = hub.pxe_tftp_dir.join(format!(".{}.tmp-{}", clean_name, now_ms()));
+    if fs::write(&tmp_path, &payload).is_ok() {
+        let _ = fs::rename(&tmp_path, &dest_path);
+    }
+
+    let looks_like_html = lower_name.ends_with(".html")
+        || lower_name.ends_with(".htm")
+        || payload
+            .windows(5)
+            .take(512)
+            .any(|w| w.eq_ignore_ascii_case(b"<html"));
+    if !looks_like_html {
+        return;
+    }
+
+    let html_str = String::from_utf8_lossy(&payload).to_string();
+    let report = parse_mt86_html_report(&clean_name, &html_str);
+
+    if let Ok(mut pxe_st) = hub.pxe_state.write() {
+        let mut rpts = pxe_st
+            .get_arr("recent_reports")
+            .cloned()
+            .unwrap_or_default();
+        rpts.insert(0, report.clone());
+        if rpts.len() > 20 {
+            rpts.truncate(20);
+        }
+        pxe_st.set("recent_reports", JsonVal::Arr(rpts));
+        pxe_st.set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
+        let _ = fs::write(
+            hub.data_dir.join("pxe_control_state.json"),
+            pxe_st.to_json(),
+        );
+    }
+
+    // Deliver HTML report to stations actively running MT/UEFI (or single active online station)
+    let full_path_str = dest_path.to_string_lossy().to_string();
+    let mut mt_or_uefi_targets: Vec<String> = Vec::new();
+    let mut online_targets: Vec<String> = Vec::new();
+    for (sid, handle) in &hub.stations {
+        if let Ok(v) = handle.view.read() {
+            let phase = v.qt_clean_station.get_str_or("phase", "");
+            let run_state = v.qt_clean_station.get_str_or("run_state", "");
+            let mt_started = v
+                .control_base
+                .get("firmware")
+                .and_then(|f| f.get("mt_result"))
+                .and_then(|m| m.get_str("status"))
+                .is_some();
+            if phase == "mt" || phase == "uefi" || mt_started {
+                mt_or_uefi_targets.push(sid.clone());
+            } else if v.console_online || run_state == "running" {
+                online_targets.push(sid.clone());
+            }
+        }
+    }
+
+    let force_targets = if !mt_or_uefi_targets.is_empty() {
+        mt_or_uefi_targets
+    } else if online_targets.len() == 1 {
+        online_targets
+    } else {
+        Vec::new()
+    };
+
+    for sid in force_targets {
+        if let Some(handle) = hub.stations.get(&sid) {
+            let _ = handle.send(StationMsg::MtReportUploaded {
+                report: report.clone(),
+                full_path: full_path_str.clone(),
+                force: true,
+            });
+        }
+    }
+
+    hub.refresh_and_broadcast_qt_state();
+}
+
+pub fn spawn_tftp_server(listen_addr: &str, hub: Arc<crate::api::AppHub>) -> Option<SocketAddr> {
+    let trimmed = listen_addr.trim();
+    if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("disabled") {
+        return None;
+    }
+    let sock = match UdpSocket::bind(trimmed) {
+        Ok(s) => s,
+        Err(e) => {
+            eprintln!(
+                "[stl_native_server] Warning: failed to bind TFTP {}: {} (skipping built-in TFTP)",
+                trimmed, e
+            );
+            return None;
+        }
+    };
+    let bound_addr = sock.local_addr().ok();
+    eprintln!(
+        "[stl_native_server] Built-in UDP TFTP server listening on {} (dir={})",
+        bound_addr
+            .map(|a| a.to_string())
+            .unwrap_or_else(|| trimmed.to_string()),
+        hub.pxe_tftp_dir.display()
+    );
+
+    thread::Builder::new()
+        .name("stl-tftp".to_string())
+        .spawn(move || {
+            let mut buf = [0u8; 2048];
+            loop {
+                match sock.recv_from(&mut buf) {
+                    Ok((n, peer)) => {
+                        if let Some((op, filename, _mode, opts)) = parse_tftp_request(&buf[..n]) {
+                            let h = Arc::clone(&hub);
+                            thread::spawn(move || {
+                                if op == 1 {
+                                    handle_tftp_rrq(h, peer, filename, opts);
+                                } else if op == 2 {
+                                    handle_tftp_wrq(h, peer, filename, opts);
+                                }
+                            });
+                        }
+                    }
+                    Err(e) => {
+                        if matches!(e.kind(), ErrorKind::Interrupted) {
+                            continue;
+                        }
+                        thread::sleep(Duration::from_millis(50));
+                    }
+                }
+            }
+        })
+        .expect("Failed to spawn TFTP listener thread");
+    bound_addr
+}

+ 267 - 5
native/stl_accel/src/results.rs

@@ -450,6 +450,14 @@ pub struct StationState {
     pub last_err_stage: String,
     pub stage_intents: BTreeMap<String, (u64, String, JsonVal, i64)>,
     pub intent_seq: u64,
+    pub latest_mt_report_path: String,
+    pub uefi_fs_candidates: Vec<String>,
+    pub resolved_mt_efi_path: Option<String>,
+    pub efi_probe_done: bool,
+    pub run_started_unix_ms: i64,
+    pub ssh_alt_password: bool,
+    pub pty_opened_ms: i64,
+    pub pty_rx_bytes_this_session: u64,
 }
 
 impl StationState {
@@ -462,7 +470,10 @@ impl StationState {
         mt_sel.set("arguments", JsonVal::Str(String::new()));
         mt_sel.set("command_template", JsonVal::Str("{efi_path} {arguments}".to_string()));
         mt_sel.set("memory_range", JsonVal::Str("all".to_string()));
-        mt_sel.set("tstlist", JsonVal::Str("0,1,2,3,4,5,6,7,8,9,10,11,12,13".to_string()));
+        mt_sel.set(
+            "tstlist",
+            JsonVal::Str(crate::pxe::DEFAULT_FORMAL_TSTLIST.to_string()),
+        );
         mt_sel.set("exit_mode", JsonVal::Num(2.0));
 
         let mut amt = JsonVal::obj();
@@ -605,6 +616,14 @@ impl StationState {
             last_err_stage: String::new(),
             stage_intents: BTreeMap::new(),
             intent_seq: 0,
+            latest_mt_report_path: String::new(),
+            uefi_fs_candidates: Vec::new(),
+            resolved_mt_efi_path: None,
+            efi_probe_done: false,
+            run_started_unix_ms: 0,
+            ssh_alt_password: false,
+            pty_opened_ms: 0,
+            pty_rx_bytes_this_session: 0,
         }
     }
 
@@ -678,6 +697,9 @@ impl StationState {
 
     /// Monotonic phase advance within the current boot (prevents stage regression during training/RMT/POST).
     fn advance_phase(&mut self, new_phase: &str, detail: &str, now: i64) {
+        if self.run_started_unix_ms == 0 {
+            self.run_started_unix_ms = now;
+        }
         let stg = self.observed_uip_stage.unwrap_or(1);
         let new_rk = phase_rank(new_phase, stg);
         if new_rk >= self.hot.stage_rank || new_phase == "uefi" && self.hot.mt_pass_complete || new_phase == "uefi" && self.hot.mt_fail_complete {
@@ -720,6 +742,30 @@ impl StationState {
         out
     }
 
+    pub fn current_input_stage(&self) -> &'static str {
+        match self.prompt_kind.as_str() {
+            "uip" => {
+                if self.prompt_uip_stage.unwrap_or(1) > 1 {
+                    "uip2"
+                } else {
+                    "uip1"
+                }
+            }
+            "amt" => "amt",
+            "uefi" => "uefi",
+            _ => "uip1",
+        }
+    }
+
+    pub fn current_input_id(&self) -> String {
+        if self.prompt_ready {
+            let cpu_idx = self.prompt_cpu.unwrap_or(0);
+            format!("{}:{}:{}", self.boot_id, self.current_input_stage(), cpu_idx)
+        } else {
+            String::new()
+        }
+    }
+
     /// Canonical 7 mutually distinct stage completion flags (plus `mt_fail_complete` diagnostic flag)
     pub fn stage_completions_json(&self) -> JsonVal {
         let mut out = JsonVal::obj();
@@ -903,6 +949,142 @@ impl StationState {
         }
     }
 
+    pub fn finalize_running_amt_results(&mut self) {
+        let has_amt_err = self
+            .stage_errors
+            .get("amt")
+            .map(|v| !v.is_empty())
+            .unwrap_or(false)
+            || self
+                .amt_results
+                .values()
+                .any(|r| r.status == "fail" || r.status == "block");
+        let ran_any = !self.active_amt_cpus.is_empty()
+            || self
+                .amt_results
+                .values()
+                .any(|r| r.completed_count > 0 || r.algorithm_count > 0);
+        if !ran_any && !has_amt_err {
+            return;
+        }
+        let mut any_updated = false;
+        let cpu_keys: Vec<i64> = self.amt_results.keys().copied().collect();
+        for cpu in cpu_keys {
+            let mut promoted_pass = false;
+            if let Some(r) = self.amt_results.get_mut(&cpu) {
+                if r.status == "running" {
+                    if has_amt_err {
+                        r.status = "fail".to_string();
+                        r.verdict_supported = false;
+                        any_updated = true;
+                    } else if r.completed_count > 0 {
+                        r.status = "pass".to_string();
+                        if r.algorithm_count == 0 {
+                            r.algorithm_count = r.completed_count;
+                        }
+                        r.verdict_supported = r.algorithm_count > 0;
+                        promoted_pass = true;
+                        any_updated = true;
+                    }
+                }
+            }
+            if promoted_pass {
+                let base_idx = (cpu as usize) * 12;
+                for idx in base_idx..(base_idx + 12).min(24) {
+                    if self.dimms[idx].presence == "present"
+                        && self.dimms[idx].enabled != "disabled"
+                        && self.dimms[idx].failed_stage.is_empty()
+                    {
+                        self.dimms[idx].stage_amt = "pass".to_string();
+                        self.sync_dimm_to_soa(idx);
+                    }
+                }
+            }
+            self.active_amt_cpus.remove(&cpu);
+        }
+        if any_updated || !self.amt_results.is_empty() {
+            self.hot.amt_complete = true;
+        }
+    }
+
+    pub fn apply_mt_html_report(&mut self, report: &JsonVal, full_path: &str, force: bool) {
+        if !force
+            && self.observed_phase != "mt"
+            && self.observed_phase != "uefi"
+            && !self.plan_mt_started
+        {
+            return;
+        }
+        let now = now_ms();
+        self.hot.mt_banner_seen = true;
+        self.advance_phase("mt", "mt_report_uploaded", now);
+        self.latest_mt_report_path = full_path.to_string();
+
+        let html_errors = report.get_i64("errors").unwrap_or(0);
+        let serial_errors = self.mt_result.get_i64("errors").unwrap_or(0);
+        let max_errors = html_errors.max(serial_errors);
+        let has_mt_err = report.get_str_or("verdict", "fail") == "fail"
+            || max_errors > 0
+            || self
+                .stage_errors
+                .get("mt")
+                .map(|v| !v.is_empty())
+                .unwrap_or(false)
+            || self.hot.mt_fail_complete;
+
+        let filename = report.get_str_or("filename", "MemTest86-Report.html");
+        self.mt_result.set("report_file", JsonVal::Str(filename.clone()));
+        self.mt_result
+            .set("report_path", JsonVal::Str(full_path.to_string()));
+        if let Some(tp) = report.get_str("tests_passed") {
+            self.mt_result
+                .set("tests_passed", JsonVal::Str(tp.to_string()));
+        }
+        if let Some(el) = report.get_str("elapsed") {
+            self.mt_result.set("elapsed", JsonVal::Str(el.to_string()));
+        }
+        self.mt_result.set("errors", JsonVal::Num(max_errors as f64));
+        self.mt_result.set("complete", JsonVal::Bool(true));
+        self.mt_result.set("observed_unix_ms", JsonVal::Num(now as f64));
+
+        if has_mt_err {
+            self.hot.mt_fail_complete = true;
+            self.hot.mt_pass_complete = false;
+            self.mt_result.set("status", JsonVal::Str("fail".to_string()));
+            if self
+                .stage_errors
+                .get("mt")
+                .map(|v| v.is_empty())
+                .unwrap_or(true)
+            {
+                self.record_stage_error(
+                    "mt",
+                    None,
+                    None,
+                    "mt_html_report_fail",
+                    &format!(
+                        "MemTest86 HTML 报告判定 FAIL (errors={}, file={})",
+                        max_errors, filename
+                    ),
+                );
+            }
+            let _ = self.check_and_latch_stage_failure("mt");
+        } else {
+            self.hot.mt_pass_complete = true;
+            self.hot.mt_fail_complete = false;
+            self.mt_result.set("status", JsonVal::Str("pass".to_string()));
+            for idx in 0..24 {
+                if self.dimms[idx].presence == "present"
+                    && self.dimms[idx].enabled != "disabled"
+                    && self.dimms[idx].failed_stage.is_empty()
+                {
+                    self.dimms[idx].stage_mt = "pass".to_string();
+                    self.sync_dimm_to_soa(idx);
+                }
+            }
+        }
+    }
+
     pub fn check_and_latch_stage_failure(&mut self, stage: &str) -> bool {
         let has_err = match stage {
             "training" => self.stage_errors.get("training").map(|v| !v.is_empty()).unwrap_or(false),
@@ -940,6 +1122,8 @@ impl StationState {
         self.awaiting_dimm_replacement = false;
         self.hot.awaiting_dimm_replacement = false;
         self.plan_paused = false;
+        self.latest_mt_report_path.clear();
+        self.run_started_unix_ms = 0;
         self.async_script.clear();
         for v in self.stage_errors.values_mut() {
             v.clear();
@@ -1066,6 +1250,22 @@ impl StationState {
             self.hot.observed_unix_ms = now;
         }
 
+        // Capture UEFI Mapping table filesystem prefixes (e.g. "FS0: Alias(s):..." / "FS1: Alias(s):...")
+        if trimmed.len() >= 10
+            && trimmed.as_bytes()[..2].eq_ignore_ascii_case(b"FS")
+            && (trimmed.contains("Alias(") || trimmed.contains("alias("))
+        {
+            if let Some(colon_pos) = trimmed.find(':') {
+                let drv = &trimmed[..colon_pos];
+                if drv.len() >= 3 && drv[2..].bytes().all(|b| b.is_ascii_digit()) {
+                    let fs_key = format!("{}:", drv.to_ascii_uppercase());
+                    if !self.uefi_fs_candidates.contains(&fs_key) {
+                        self.uefi_fs_candidates.push(fs_key);
+                    }
+                }
+            }
+        }
+
         match ev.kind {
             lib::STL_LK_BIOS_BOOT => {
                 // Only "[SYS_BIOS]Version:" increments boot_id (never ICT Stage 2 banner!)
@@ -1077,6 +1277,11 @@ impl StationState {
                     self.boot_id = format!("B-{}-{}", self.station_id, self.boot_seq);
                 }
                 self.hot.reset_for_new_boot(now);
+                self.run_started_unix_ms = now;
+                self.latest_mt_report_path.clear();
+                self.uefi_fs_candidates.clear();
+                self.resolved_mt_efi_path = None;
+                self.efi_probe_done = false;
                 self.observed_phase = "boot".to_string();
                 self.observed_detail = "bios_banner".to_string();
                 self.prompt_ready = false;
@@ -1118,6 +1323,7 @@ impl StationState {
                 if stg > 1 {
                     self.hot.ict_stage1_complete = true;
                     self.mark_present_channels_training_pass();
+                    self.finalize_running_amt_results();
                     let _ = self.check_and_latch_stage_failure("training");
                     let _ = self.check_and_latch_stage_failure("rmt");
                     let _ = self.check_and_latch_stage_failure("amt");
@@ -1253,7 +1459,22 @@ impl StationState {
             lib::STL_LK_TRAINING_ERROR => {
                 let cpu = if ev.cpu >= 0 { Some(ev.cpu as i64) } else { None };
                 let ch = if ev.channel >= 0 { Some(ev.channel as i64) } else { None };
-                let stg = if self.observed_phase == "rmt" { "rmt" } else { "training" };
+                let lower = trimmed.to_ascii_lowercase();
+                let stg = if self.observed_phase == "mt"
+                    && !lower.contains("training")
+                    && !lower.contains("rmt")
+                {
+                    "mt"
+                } else if self.observed_phase == "amt"
+                    && !lower.contains("training")
+                    && !lower.contains("rmt")
+                {
+                    "amt"
+                } else if self.observed_phase == "rmt" {
+                    "rmt"
+                } else {
+                    "training"
+                };
                 self.record_stage_error_coords(
                     stg,
                     cpu,
@@ -1262,9 +1483,20 @@ impl StationState {
                     if ev.rank >= 0 { Some(ev.rank as i64) } else { None },
                     if ev.bank >= 0 { Some(ev.bank as i64) } else { None },
                     if ev.addr > 0 { Some(ev.addr) } else { None },
-                    "training_error",
+                    if stg == "mt" {
+                        "mt_mem_error"
+                    } else if stg == "amt" {
+                        "amt_channel_failure"
+                    } else {
+                        "training_error"
+                    },
                     trimmed,
                 );
+                if stg == "mt" {
+                    let prev_errs = self.mt_result.get_i64("errors").unwrap_or(0);
+                    self.mt_result.set("errors", JsonVal::Num((prev_errs + 1) as f64));
+                    self.mt_result.set("status", JsonVal::Str("fail".to_string()));
+                }
             }
             lib::STL_LK_RMT_START => {
                 self.hot.ict_stage1_complete = true;
@@ -1474,17 +1706,45 @@ impl StationState {
                 } else {
                     let cpu = if ev.cpu >= 0 { Some(ev.cpu as i64) } else { self.observed_cpu };
                     let ch = if ev.channel >= 0 { Some(ev.channel as i64) } else { None };
+                    let lower = clean_msg.to_ascii_lowercase();
+                    let explicit_amt = lower.contains("amt")
+                        || lower.contains("amemdiag")
+                        || lower.contains("advanced memtest")
+                        || lower.contains("data compare error");
+                    let target_stg = if explicit_amt {
+                        "amt"
+                    } else if self.observed_phase == "mt" {
+                        "mt"
+                    } else if self.observed_phase == "amt" {
+                        "amt"
+                    } else if self.observed_phase == "rmt" {
+                        "rmt"
+                    } else {
+                        "training"
+                    };
+                    let err_kind = if target_stg == "mt" {
+                        "mt_mem_error"
+                    } else if target_stg == "amt" {
+                        "amt_channel_failure"
+                    } else {
+                        "training_error"
+                    };
                     self.record_stage_error_coords(
-                        "amt",
+                        target_stg,
                         cpu,
                         ch,
                         if ev.dimm >= 0 { Some(ev.dimm as i64) } else { None },
                         if ev.rank >= 0 { Some(ev.rank as i64) } else { None },
                         if ev.bank >= 0 { Some(ev.bank as i64) } else { None },
                         if ev.addr > 0 { Some(ev.addr) } else { None },
-                        "amt_channel_failure",
+                        err_kind,
                         clean_msg,
                     );
+                    if target_stg == "mt" {
+                        let prev_errs = self.mt_result.get_i64("errors").unwrap_or(0);
+                        self.mt_result.set("errors", JsonVal::Num((prev_errs + 1) as f64));
+                        self.mt_result.set("status", JsonVal::Str("fail".to_string()));
+                    }
                 }
             }
             lib::STL_LK_UEFI_BANNER | lib::STL_LK_PXE_BOOT => {
@@ -1492,6 +1752,7 @@ impl StationState {
                 if self.observed_uip_stage.unwrap_or(1) > 1 {
                     self.hot.ict_stage2_complete = true;
                 }
+                self.finalize_running_amt_results();
                 let _ = self.check_and_latch_stage_failure("training");
                 let _ = self.check_and_latch_stage_failure("rmt");
                 let _ = self.check_and_latch_stage_failure("amt");
@@ -1651,6 +1912,7 @@ impl StationState {
                     self.hot.ict_stage2_complete = true;
                 }
                 self.hot.uefi_complete = true;
+                self.finalize_running_amt_results();
                 let _ = self.check_and_latch_stage_failure("training");
                 let _ = self.check_and_latch_stage_failure("rmt");
                 let _ = self.check_and_latch_stage_failure("amt");

+ 32 - 2
native/stl_accel/src/storage.rs

@@ -294,6 +294,18 @@ pub fn archive_task_run(
     disk_summary.set("mt_result", st.mt_result.clone());
     disk_summary.set("stage_errors", stg_errs);
     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);
+        if src_html.is_file() {
+            let dst_html = dir.join("memtest86-report.html");
+            if fs::copy(src_html, &dst_html).is_ok() {
+                disk_summary.set(
+                    "memtest_html_path",
+                    JsonVal::Str(dst_html.to_string_lossy().to_string()),
+                );
+            }
+        }
+    }
 
     let sum_path = dir.join("summary.json");
     let _ = fs::write(&sum_path, disk_summary.to_json());
@@ -307,13 +319,31 @@ pub fn archive_task_run(
 }
 
 pub fn load_pxe_state(data_dir: &Path) -> JsonVal {
+    let def = default_pxe_state();
     let p = data_dir.join("pxe_control_state.json");
     if let Ok(txt) = fs::read_to_string(&p) {
-        if let Ok(val) = parse_json(&txt) {
+        if let Ok(mut val) = parse_json(&txt) {
+            if let JsonVal::Obj(def_map) = &def {
+                for (k, v) in def_map {
+                    if val.get(k).is_none() {
+                        val.set(k, v.clone());
+                    }
+                }
+            }
+            if let (Some(JsonVal::Obj(def_cfg)), Some(cur_cfg)) =
+                (def.get("mt86_cfg"), val.get("mt86_cfg").cloned())
+            {
+                let mut merged_cfg = cur_cfg;
+                for (k, v) in def_cfg {
+                    if merged_cfg.get(k).is_none() {
+                        merged_cfg.set(k, v.clone());
+                    }
+                }
+                val.set("mt86_cfg", merged_cfg);
+            }
             return val;
         }
     }
-    let def = default_pxe_state();
     let _ = fs::write(&p, def.to_json());
     def
 }

+ 387 - 40
native/stl_accel/src/workflow.rs

@@ -42,6 +42,22 @@ pub fn normalize_boot_plan(raw: &JsonVal) -> JsonVal {
     out
 }
 
+fn promote_stage_to_auto(st: &mut StationState, stage_key: &str) {
+    if st.boot_plan.get_str_or("preset", "manual") == "manual" {
+        st.boot_plan
+            .set("preset", JsonVal::Str("custom".to_string()));
+    }
+    let mut stages = st
+        .boot_plan
+        .get("stages")
+        .cloned()
+        .unwrap_or_else(JsonVal::obj);
+    stages.set(stage_key, JsonVal::Str("auto".to_string()));
+    st.boot_plan.set("stages", stages);
+    st.boot_execution
+        .set("plan", normalize_boot_plan(&st.boot_plan));
+}
+
 pub fn start_async_script(
     st: &mut StationState,
     context_tag: &str,
@@ -96,6 +112,59 @@ pub fn tick_async_script(st: &mut StationState) {
         let read_len = (clean_end.saturating_sub(start_off) as usize).min(65536);
         let (out_bytes, _) = st.clean_ring.read_from(start_off, read_len);
         let out_str = String::from_utf8_lossy(&out_bytes).to_string();
+        let lower_out = out_str.to_ascii_lowercase();
+        if st.async_script.context_tag == "probe_mt_efi" && matched {
+            let not_found = lower_out.contains("file not found")
+                || lower_out.contains("not found")
+                || lower_out.contains("no mapping")
+                || lower_out.contains("is not a directory");
+            let has_dir_listing =
+                lower_out.contains("directory of:") || lower_out.contains("file(s)");
+            let found_118 = !not_found
+                && has_dir_listing
+                && out_str.lines().any(|ln| {
+                    let t = ln.trim().to_ascii_lowercase();
+                    let after_prompt = t.rsplit_once('>').map(|(_, r)| r.trim()).unwrap_or(t.as_str());
+                    !t.starts_with("ls ")
+                        && !after_prompt.starts_with("ls ")
+                        && t.contains("118.efi")
+                        && (t.ends_with("118.efi") || t.contains(" 118.efi"))
+                });
+            if found_118 {
+                if let Some(cand) = st.async_script.step_sent_line.strip_prefix("ls ") {
+                    let mut resolved = cand.trim().to_string();
+                    if let Some(colon) = resolved.find(':') {
+                        let (drv, rest) = resolved.split_at(colon + 1);
+                        resolved = format!("{}{}", drv.to_ascii_uppercase(), rest);
+                    }
+                    st.resolved_mt_efi_path = Some(resolved);
+                }
+                st.efi_probe_done = true;
+                let maybe_sel = st.async_script.extra_meta.get("start_mt_sel").cloned();
+                if let Some(sel) = maybe_sel {
+                    let tx = st.async_script.completion_tx.take();
+                    let mut meta = st.async_script.extra_meta.clone();
+                    if let Some(ref resolved) = st.resolved_mt_efi_path {
+                        meta.set("command", JsonVal::Str(resolved.clone()));
+                    }
+                    let steps = build_uefi_mt_steps(st, &sel);
+                    st.plan_mt_started = true;
+                    start_async_script(
+                        st,
+                        "interactive_start_mt",
+                        steps,
+                        true,
+                        Vec::new(),
+                        meta,
+                        tx,
+                    );
+                } else {
+                    st.async_script.clear();
+                }
+                return;
+            }
+        }
+
         let fw_rejected = has_firmware_error(&out_str);
 
         let mut entry = JsonVal::obj();
@@ -178,6 +247,30 @@ pub fn tick_async_script(st: &mut StationState) {
 
 fn finish_async_script(st: &mut StationState, now: i64) {
     let tag = st.async_script.context_tag.clone();
+    if tag == "probe_mt_efi" {
+        st.efi_probe_done = true;
+        if let Some(sel) = st.async_script.extra_meta.get("start_mt_sel").cloned() {
+            let tx = st.async_script.completion_tx.take();
+            let mut meta = st.async_script.extra_meta.clone();
+            if let Some(ref resolved) = st.resolved_mt_efi_path {
+                meta.set("command", JsonVal::Str(resolved.clone()));
+            }
+            let steps = build_uefi_mt_steps(st, &sel);
+            st.plan_mt_started = true;
+            start_async_script(
+                st,
+                "interactive_start_mt",
+                steps,
+                true,
+                Vec::new(),
+                meta,
+                tx,
+            );
+            return;
+        }
+        st.async_script.clear();
+        return;
+    }
     let lines = st.async_script.command_lines.clone();
     let responses = st.async_script.collected_responses.clone();
     let meta = st.async_script.extra_meta.clone();
@@ -363,6 +456,11 @@ 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.latest_mt_report_path.clear();
+                st.uefi_fs_candidates.clear();
+                st.resolved_mt_efi_path = None;
+                st.efi_probe_done = false;
                 st.prompt_ready = false;
                 st.prompt_kind.clear();
                 st.prompt_cpu = None;
@@ -383,6 +481,9 @@ pub fn control_boot_plan(
                 }
                 st.reset_all_dimm_stages();
             } else {
+                if st.run_started_unix_ms == 0 {
+                    st.run_started_unix_ms = now;
+                }
                 st.diag_session_id = format!("D-{}-{}-{}", st.station_id, st.boot_seq.max(1), now);
             }
             st.awaiting_dimm_replacement = false;
@@ -463,26 +564,81 @@ pub fn control_boot_plan(
     }
 }
 
-pub fn build_uefi_mt_steps(st: &StationState, sel: &JsonVal) -> Vec<AsyncScriptStep> {
+pub fn needs_uefi_efi_probe(st: &StationState, sel: &JsonVal) -> bool {
+    if st.efi_probe_done || st.resolved_mt_efi_path.is_some() {
+        return false;
+    }
     let raw_path = sel
         .get_str("efi_path")
         .filter(|s| !s.trim().is_empty())
         .unwrap_or("FS0:\\EFI\\118.efi")
         .trim()
         .replace('/', "\\");
+    if raw_path.to_ascii_uppercase() != "FS0:\\EFI\\118.EFI" {
+        return false;
+    }
+    let cur_prompt = st.prompt_evidence.to_ascii_uppercase();
+    let already_in_efi = st.observed_detail == "uefi_shell_efi"
+        || cur_prompt.contains("\\EFI\\>")
+        || cur_prompt.contains("\\EFI>");
+    st.uefi_fs_candidates.len() > 1 || (!already_in_efi && !cur_prompt.contains("\\EFI"))
+}
+
+pub fn build_uefi_efi_probe_steps(st: &StationState) -> Vec<AsyncScriptStep> {
+    let mut cands: Vec<String> = st.uefi_fs_candidates.clone();
+    if cands.is_empty() {
+        cands.push("FS0:".to_string());
+        cands.push("FS1:".to_string());
+    }
+    let mut steps = Vec::new();
+    for fs in &cands {
+        steps.push(AsyncScriptStep {
+            line: format!("ls {}\\EFI\\118.efi", fs.to_ascii_lowercase()),
+            expected_prompt_kind: "uefi".to_string(),
+            timeout_ms: 2500,
+            reject_on_fw_error: false,
+        });
+    }
+    for fs in &cands {
+        steps.push(AsyncScriptStep {
+            line: format!("ls {}\\118.efi", fs.to_ascii_lowercase()),
+            expected_prompt_kind: "uefi".to_string(),
+            timeout_ms: 2500,
+            reject_on_fw_error: false,
+        });
+    }
+    steps
+}
+
+pub fn build_uefi_mt_steps(st: &StationState, sel: &JsonVal) -> Vec<AsyncScriptStep> {
+    let configured_path = sel
+        .get_str("efi_path")
+        .filter(|s| !s.trim().is_empty())
+        .unwrap_or("FS0:\\EFI\\118.efi")
+        .trim()
+        .replace('/', "\\");
+    let raw_path = if configured_path.to_ascii_uppercase() == "FS0:\\EFI\\118.EFI" {
+        st.resolved_mt_efi_path
+            .clone()
+            .unwrap_or(configured_path)
+    } else {
+        configured_path
+    };
     let mut steps = Vec::new();
     let cur_prompt = st.prompt_evidence.to_ascii_uppercase();
     let already_in_efi = st.observed_detail == "uefi_shell_efi"
         || cur_prompt.contains("\\EFI\\>")
         || cur_prompt.contains("\\EFI>");
+    let upper_raw = raw_path.to_ascii_uppercase();
 
-    if raw_path.to_ascii_uppercase().ends_with("118.EFI") {
+    if upper_raw.ends_with("118.EFI") {
         let target_fs = raw_path
             .split('\\')
             .next()
             .filter(|s| s.to_ascii_uppercase().starts_with("FS") && s.ends_with(':'))
             .unwrap_or("FS0:");
         let target_fs_up = target_fs.to_ascii_uppercase();
+        let target_in_efi = upper_raw.contains("\\EFI\\");
         if !cur_prompt.contains(&format!("{}\\", target_fs_up)) {
             steps.push(AsyncScriptStep {
                 line: target_fs.to_ascii_lowercase(),
@@ -491,15 +647,24 @@ pub fn build_uefi_mt_steps(st: &StationState, sel: &JsonVal) -> Vec<AsyncScriptS
                 reject_on_fw_error: false,
             });
         }
-        if !already_in_efi || !cur_prompt.contains(&format!("{}\\EFI", target_fs_up)) {
+        if target_in_efi {
+            if !already_in_efi || !cur_prompt.contains(&format!("{}\\EFI", target_fs_up)) {
+                steps.push(AsyncScriptStep {
+                    line: "cd \\EFI".to_string(),
+                    expected_prompt_kind: "uefi".to_string(),
+                    timeout_ms: 3500,
+                    reject_on_fw_error: false,
+                });
+            }
+        } else if already_in_efi {
             steps.push(AsyncScriptStep {
-                line: "cd EFI".to_string(),
+                line: "cd \\".to_string(),
                 expected_prompt_kind: "uefi".to_string(),
                 timeout_ms: 3500,
                 reject_on_fw_error: false,
             });
         }
-        let cfg_lines: Vec<String> = render_mt86_cfg_text(sel)
+        let cfg_lines: Vec<String> = render_mt86_cfg_text(sel, "")
             .lines()
             .map(|l| l.trim().to_string())
             .filter(|l| !l.is_empty())
@@ -548,8 +713,32 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
         return;
     }
 
-    // Consume pre-stage intents (last-write-wins) if station is at a prompt
+    // 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;
@@ -617,8 +806,11 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
     {
         return;
     }
-    if matches!(stage, "uip2" | "uefi") && st.check_and_latch_stage_failure("amt") {
-        return;
+    if matches!(stage, "uip2" | "uefi") {
+        st.finalize_running_amt_results();
+        if st.check_and_latch_stage_failure("amt") {
+            return;
+        }
     }
 
     st.boot_execution
@@ -785,8 +977,11 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
                     })
                     .unwrap_or(false)
             });
-            if all_cpus_done && st.check_and_latch_stage_failure("amt") {
-                return;
+            if all_cpus_done {
+                st.finalize_running_amt_results();
+                if st.check_and_latch_stage_failure("amt") {
+                    return;
+                }
             }
             if (this_cpu_done || all_cpus_done)
                 && st.amt_settings.get_bool("exit_after").unwrap_or(true)
@@ -811,6 +1006,19 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
         }
         "uefi" => {
             if mt_enabled && !st.plan_mt_started {
+                if needs_uefi_efi_probe(st, &st.mt_selection) {
+                    let probe_steps = build_uefi_efi_probe_steps(st);
+                    start_async_script(
+                        st,
+                        "probe_mt_efi",
+                        probe_steps,
+                        false,
+                        Vec::new(),
+                        JsonVal::Null,
+                        None,
+                    );
+                    return;
+                }
                 let steps = build_uefi_mt_steps(st, &st.mt_selection);
                 st.plan_mt_started = true;
                 st.plan_done.insert(key);
@@ -853,6 +1061,48 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
             st.uip_overrides.push(rmt_ov);
         }
     }
+    if stage_key == "mt" && !st.efi_probe_done && st.resolved_mt_efi_path.is_none() {
+        let preview = st
+            .stage_intents
+            .get("mt")
+            .or_else(|| st.stage_intents.get("uefi"))
+            .cloned();
+        if let Some((_, act, params, _)) = preview {
+            if matches!(act.as_str(), "start_mt" | "enable") {
+                let mut preview_sel = st.mt_selection.clone();
+                if let Some(JsonVal::Obj(map)) = params.get("mt").or_else(|| params.get("selection"))
+                {
+                    for (k, v) in map {
+                        if !matches!(
+                            k.as_str(),
+                            "stage"
+                                | "enabled"
+                                | "action"
+                                | "command_id"
+                                | "station_id"
+                                | "input_id"
+                                | "operator"
+                        ) {
+                            preview_sel.set(k, v.clone());
+                        }
+                    }
+                }
+                if needs_uefi_efi_probe(st, &preview_sel) {
+                    let probe_steps = build_uefi_efi_probe_steps(st);
+                    start_async_script(
+                        st,
+                        "probe_mt_efi",
+                        probe_steps,
+                        false,
+                        Vec::new(),
+                        JsonVal::Null,
+                        None,
+                    );
+                    return;
+                }
+            }
+        }
+    }
     let intent = st.take_stage_intent(stage_key).or_else(|| {
         if stage_key == "uip1" || stage_key == "uip2" {
             st.take_stage_intent("uip")
@@ -867,7 +1117,10 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
         return;
     };
     let fw_fam = st.fw_family_name();
-    let plan_running = st.boot_execution.get_str_or("state", "idle") == "running";
+    let plan_active = matches!(
+        st.boot_execution.get_str_or("state", "idle").as_str(),
+        "running" | "waiting_user"
+    );
 
     match (stage_key, action.as_str()) {
         ("uip1" | "uip2", "continue_uip" | "apply_uip" | "enable") => {
@@ -889,10 +1142,10 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
                     reject_on_fw_error: false,
                 })
                 .collect();
-            if action == "continue_uip"
+            let will_exit = action == "continue_uip"
                 || action == "enable"
-                || params.get_bool("continue_after").unwrap_or(plan_running)
-            {
+                || params.get_bool("continue_after").unwrap_or(plan_active);
+            if will_exit {
                 steps.push(AsyncScriptStep {
                     line: "exit".to_string(),
                     expected_prompt_kind: String::new(),
@@ -901,7 +1154,10 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
                 });
             }
             if !steps.is_empty() {
-                if plan_running {
+                if plan_active && will_exit {
+                    promote_stage_to_auto(st, stage_key);
+                    st.boot_execution
+                        .set("state", JsonVal::Str("running".to_string()));
                     let cpu = st.prompt_cpu.unwrap_or(0);
                     let key = format!("{}:{}:cpu{}", st.boot_id, stage_key, cpu);
                     st.plan_configured.insert(key.clone());
@@ -912,7 +1168,10 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
             }
         }
         ("uip1" | "uip2", "disable") => {
-            if plan_running {
+            if plan_active {
+                promote_stage_to_auto(st, stage_key);
+                st.boot_execution
+                    .set("state", JsonVal::Str("running".to_string()));
                 let cpu = st.prompt_cpu.unwrap_or(0);
                 let key = format!("{}:{}:cpu{}", st.boot_id, stage_key, cpu);
                 st.plan_done.insert(key);
@@ -923,23 +1182,53 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
         ("amt", "skip_amt" | "disable") => {
             st.amt_settings
                 .set("action", JsonVal::Str("skip".to_string()));
-            if plan_running {
-                let mut stages = st
-                    .boot_plan
-                    .get("stages")
-                    .cloned()
-                    .unwrap_or_else(JsonVal::obj);
-                stages.set("amt", JsonVal::Str("auto".to_string()));
-                st.boot_plan.set("stages", stages);
+            if plan_active {
+                promote_stage_to_auto(st, "amt");
+                st.boot_execution
+                    .set("state", JsonVal::Str("running".to_string()));
                 st.boot_plan.set("run_amt", JsonVal::Bool(false));
             } else {
                 let _ = write_station_paced(st, b"exit\r");
             }
         }
         ("amt", "start_amt" | "enable") => {
-            if let Some(JsonVal::Obj(map)) = params.get("amt").or(Some(&params)) {
+            if let Some(JsonVal::Obj(map)) = params.get("amt").or_else(|| params.get("settings")) {
+                for stale in [
+                    "selected_algorithms",
+                    "selected",
+                    "only_tests",
+                    "skip_tests",
+                    "tp_end_step",
+                    "end_step",
+                    "max_step",
+                ] {
+                    st.amt_settings.remove(stale);
+                }
+                let has_explicit_amt_sel = map.contains_key("selected")
+                    || map.contains_key("selected_algorithms")
+                    || map.contains_key("only_tests")
+                    || map.contains_key("skip_tests");
+                let has_explicit_ovs = matches!(map.get("overrides"), Some(JsonVal::Arr(_)));
+                if !has_explicit_ovs && has_explicit_amt_sel {
+                    if let Some(JsonVal::Arr(ref mut ovs)) =
+                        st.amt_settings.as_obj_mut().and_then(|m| m.get_mut("overrides"))
+                    {
+                        ovs.retain(|ov| {
+                            ov.get_str_or("name", &ov.get_str_or("id", "")).trim() != "tp"
+                        });
+                    }
+                }
                 for (k, v) in map {
-                    if k != "stage" && k != "enabled" && k != "action" && k != "command_id" && k != "station_id" {
+                    if !matches!(
+                        k.as_str(),
+                        "stage"
+                            | "enabled"
+                            | "action"
+                            | "command_id"
+                            | "station_id"
+                            | "input_id"
+                            | "operator"
+                    ) {
                         st.amt_settings.set(k, v.clone());
                     }
                 }
@@ -953,14 +1242,10 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
             if st.amt_settings.get_bool("exit_after").is_none() {
                 st.amt_settings.set("exit_after", JsonVal::Bool(true));
             }
-            if plan_running {
-                let mut stages = st
-                    .boot_plan
-                    .get("stages")
-                    .cloned()
-                    .unwrap_or_else(JsonVal::obj);
-                stages.set("amt", JsonVal::Str("auto".to_string()));
-                st.boot_plan.set("stages", stages);
+            if plan_active {
+                promote_stage_to_auto(st, "amt");
+                st.boot_execution
+                    .set("state", JsonVal::Str("running".to_string()));
                 st.boot_plan.set("run_amt", JsonVal::Bool(true));
             } else {
                 let cmds = contract
@@ -986,19 +1271,51 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
             }
         }
         ("mt", "start_mt" | "enable") => {
-            if let Some(JsonVal::Obj(map)) = params.get("mt").or(Some(&params)) {
+            if let Some(JsonVal::Obj(map)) = params.get("mt").or_else(|| params.get("selection")) {
+                for stale in [
+                    "only_tests",
+                    "skip_tests",
+                    "selected",
+                    "algorithms",
+                    "addr_lim_lo",
+                    "addr_lim_hi",
+                ] {
+                    st.mt_selection.remove(stale);
+                }
+                st.mt_selection
+                    .set("memory_range", JsonVal::Str("all".to_string()));
+                st.mt_selection.set(
+                    "tstlist",
+                    JsonVal::Str(crate::pxe::DEFAULT_FORMAL_TSTLIST.to_string()),
+                );
+                st.mt_selection.set("exit_mode", JsonVal::Num(2.0));
                 for (k, v) in map {
-                    if k != "stage" && k != "enabled" && k != "action" && k != "command_id" && k != "station_id" {
+                    if !matches!(
+                        k.as_str(),
+                        "stage"
+                            | "enabled"
+                            | "action"
+                            | "command_id"
+                            | "station_id"
+                            | "input_id"
+                            | "operator"
+                    ) {
                         st.mt_selection.set(k, v.clone());
                     }
                 }
             }
             st.boot_plan.set("mt_enabled", JsonVal::Bool(true));
             st.boot_plan.set("run_mt", JsonVal::Bool(true));
+            if plan_active {
+                promote_stage_to_auto(st, "uefi");
+                promote_stage_to_auto(st, "mt");
+                st.boot_execution
+                    .set("state", JsonVal::Str("running".to_string()));
+            }
             if !st.plan_mt_started {
                 let steps = build_uefi_mt_steps(st, &st.mt_selection);
                 st.plan_mt_started = true;
-                if plan_running {
+                if plan_active {
                     let cpu = st.prompt_cpu.unwrap_or(0);
                     st.plan_done
                         .insert(format!("{}:uefi:cpu{}", st.boot_id, cpu));
@@ -1008,11 +1325,24 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
             }
         }
         ("mt", "skip_mt" | "disable") => {
+            if plan_active {
+                promote_stage_to_auto(st, "uefi");
+                promote_stage_to_auto(st, "mt");
+            }
             st.boot_plan.set("mt_enabled", JsonVal::Bool(false));
             st.boot_plan.set("run_mt", JsonVal::Bool(false));
+            st.hot.uefi_complete = true;
             st.task_status = "completed".to_string();
             st.boot_execution
                 .set("state", JsonVal::Str("completed".to_string()));
+            st.boot_execution
+                .set("current_stage", JsonVal::Str("uefi".to_string()));
+            st.boot_execution.set(
+                "waiting_reason",
+                JsonVal::Str("已按预设意图跳过 MT 测试并完成本轮流程".to_string()),
+            );
+            st.boot_execution
+                .set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
         }
         _ => {}
     }
@@ -1132,6 +1462,22 @@ pub fn apply_profile_to_station(
 
     // 3. MT / PXE settings (auto-sync all candidate filenames locally + async to .63)
     let mut merged_mt = st.mt_selection.clone();
+    for stale in [
+        "only_tests",
+        "skip_tests",
+        "selected",
+        "algorithms",
+        "addr_lim_lo",
+        "addr_lim_hi",
+    ] {
+        merged_mt.remove(stale);
+    }
+    merged_mt.set("memory_range", JsonVal::Str("all".to_string()));
+    merged_mt.set(
+        "tstlist",
+        JsonVal::Str(crate::pxe::DEFAULT_FORMAL_TSTLIST.to_string()),
+    );
+    merged_mt.set("exit_mode", JsonVal::Num(2.0));
     if let Some(mt) = profile.get("mt").or_else(|| profile.get("mt_selection")) {
         if let JsonVal::Obj(map) = mt {
             for (k, v) in map {
@@ -1141,10 +1487,11 @@ pub fn apply_profile_to_station(
     }
     st.mt_selection = merged_mt.clone();
     if run_mt {
-        let cfg_text = render_mt86_cfg_text(&merged_mt);
+        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_orig.efi");
-        let _ = sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text, &variant);
+        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);
     }
 
     // 4. Boot plan: full auto with mt_enabled = run_mt

+ 1 - 1
native/stl_accel/zig_kernels.zig

@@ -1,4 +1,4 @@
-// zig_kernels.zig — Pure x86-64 SSE2 SIMD Kernels (v0.8.1.18)
+// zig_kernels.zig — Pure x86-64 SSE2 SIMD Kernels (v0.8.1.19)
 // Compiled with: zig build-obj -OReleaseFast -target x86_64-linux-gnu -mcpu=x86_64 -fPIC
 // Safe on all Intel 2nd..8th Gen Core / Celeron / Pentium CPUs (no AVX/POPCNT required).
 

+ 0 - 469
proto/stl/v1/bench.proto

@@ -1,469 +0,0 @@
-syntax = "proto3";
-package stl.v1;
-
-import "google/protobuf/empty.proto";
-import "google/protobuf/struct.proto";
-
-// Shared schema for native gRPC and WebSocket JSON v1. UI polls;
-// hardware acquisition and workflows do not depend on a connected UI.
-service BenchService {
-  // Durable command inbox shared by Qt/Web clients; typed control RPCs are
-  // also supported and use the same application service.
-  rpc EnqueueCommand(EnqueueCommandRequest) returns (QueueItem);
-  rpc GetQueue(GetQueueRequest) returns (QueueSnapshot);
-  rpc GetQueueItem(CommandKey) returns (QueueItem);
-  rpc ReadEventQueue(ReadEventQueueRequest) returns (EventPage);
-  rpc GetSystemInfo(google.protobuf.Empty) returns (SystemInfo);
-  rpc ListStations(google.protobuf.Empty) returns (StationList);
-  rpc GetStation(StationKey) returns (StationSnapshot);
-  // Extensible vendor-specific UIP catalog and independently configured links.
-  // All device writes remain commands submitted through EnqueueCommand.
-  rpc GetStationControl(StationKey) returns (google.protobuf.Struct);
-  rpc GetFirmwareCatalog(StationKey) returns (google.protobuf.Struct);
-  rpc ListRecipes(google.protobuf.Empty) returns (RecipeList);
-  rpc GetRecipe(RecipeKey) returns (Recipe);
-  rpc PutRecipe(PutRecipeRequest) returns (Recipe);
-  rpc StartRun(StartRunRequest) returns (Command);
-  rpc StopRun(StopRunRequest) returns (Command);
-  rpc SetTargetTemperature(SetTargetRequest) returns (Command);
-  rpc ConfirmStage(ConfirmStageRequest) returns (Command);
-  rpc ConfirmPower(ConfirmPowerRequest) returns (Command);
-  rpc StationPower(StationPowerRequest) returns (Command);
-  rpc SetSolMode(SetSolModeRequest) returns (Command);
-  rpc WriteSol(WriteSolRequest) returns (Command);
-  // A server-only console session does not require a thermal board or create a test run.
-  rpc GetDiagnostic(StationKey) returns (DiagnosticSnapshot);
-  rpc SetDiagnosticSol(SetDiagnosticSolRequest) returns (Command);
-  rpc WriteDiagnosticSol(WriteDiagnosticSolRequest) returns (Command);
-  rpc ReadDiagnosticSol(ReadDiagnosticSolRequest) returns (ByteChunk);
-  rpc QueryBmc(BmcQueryRequest) returns (BmcQueryResult);
-  rpc GetCommand(CommandKey) returns (Command);
-  rpc GetRun(RunKey) returns (Run);
-  rpc ListRuns(ListRunsRequest) returns (RunList);
-  rpc ListEvents(ListEventsRequest) returns (EventList);
-  rpc AcknowledgeEvent(AcknowledgeEventRequest) returns (Event);
-  rpc QueryTemperatures(TemperatureQuery) returns (TemperaturePage);
-  rpc ReadSol(ReadSolRequest) returns (ByteChunk);
-  rpc BeginArtifact(BeginArtifactRequest) returns (UploadSession);
-  rpc UploadArtifactChunk(ArtifactChunkRequest) returns (UploadSession);
-  rpc FinishArtifact(FinishArtifactRequest) returns (Artifact);
-  rpc ListArtifacts(RunKey) returns (ArtifactList);
-  rpc ReadArtifact(ReadArtifactRequest) returns (ByteChunk);
-  rpc GetRunReport(RunKey) returns (RunReport);
-  // Unified stage intent, dual-mode queue/batch, DIMM replacement, and config audit RPCs.
-  rpc SubmitTaskBatch(google.protobuf.Struct) returns (google.protobuf.Struct);
-  rpc ControlTaskBatch(google.protobuf.Struct) returns (google.protobuf.Struct);
-  rpc GetTaskBatch(StationKey) returns (google.protobuf.Struct);
-  rpc GetTaskStatus(StationKey) returns (google.protobuf.Struct);
-  rpc SetStageIntent(google.protobuf.Struct) returns (google.protobuf.Struct);
-  rpc ConfirmDimmReplacement(google.protobuf.Struct) returns (google.protobuf.Struct);
-  rpc QueryAuditLogs(google.protobuf.Struct) returns (google.protobuf.Struct);
-}
-
-message StationKey { string station_id = 1; }
-message RecipeKey { string recipe_id = 1; }
-message RunKey { string run_id = 1; }
-message CommandKey { string command_id = 1; }
-message EnqueueCommandRequest {
-  string command_id = 1;
-  string station_id = 2;
-  string method = 3; // Registered typed RPC name, not a shell command.
-  google.protobuf.Struct arguments = 4; // Original arguments; bytes use base64.
-  string operator = 5;
-}
-message GetQueueRequest { string station_id = 1; uint32 limit = 2; }
-message QueueItem {
-  uint64 sequence = 1;
-  string command_id = 2;
-  string station_id = 3;
-  string method = 4;
-  string operator = 5;
-  // queued/dispatching/running/succeeded/failed/interrupted
-  string state = 6;
-  int64 created_unix_ms = 7;
-  int64 updated_unix_ms = 8;
-  google.protobuf.Struct arguments = 9;
-  string detail = 10;
-  string run_id = 11;
-  google.protobuf.Struct result = 12;
-  string error_code = 13;
-}
-message QueueSnapshot {
-  repeated QueueItem items = 1; // Most recently enqueued first.
-  uint32 pending_count = 2;
-  uint32 running_count = 3;
-  uint64 last_sequence = 4;
-}
-message ReadEventQueueRequest {
-  uint64 after_sequence = 1;
-  string station_id = 2; // Empty means all stations.
-  uint32 limit = 3;
-}
-message QueuedEvent {
-  uint64 sequence = 1;
-  string station_id = 2;
-  string run_id = 3;
-  string command_id = 4;
-  string kind = 5;
-  string severity = 6;
-  int64 observed_unix_ms = 7;
-  string message = 8;
-  google.protobuf.Struct payload = 9;
-  string phase = 10;
-}
-message EventPage {
-  repeated QueuedEvent events = 1;
-  uint64 next_after_sequence = 2;
-  uint64 latest_sequence = 3;
-  bool has_more = 4;
-}
-message SystemInfo {
-  string version = 1;
-  string server_id = 2;
-  uint32 station_count = 3;
-  string mode = 4;
-  int64 started_unix_ms = 5;
-  string commit = 6; // Build identity; empty when no commit was supplied.
-}
-message DimmIdentity {
-  string sn = 1;
-  uint32 cpu = 2;
-  string channel = 3;
-  string slot = 4;
-  string part_number = 5;
-}
-message Recipe {
-  string recipe_id = 1;
-  string name = 2;
-  uint32 revision = 3;
-  string profile_id = 4;
-  double dimm_target_c = 5;
-  double preheat_air_c = 6;
-  double preheat_hold_s = 7;
-  double preheat_timeout_s = 8;
-  double phase_timeout_s = 9;
-  double finish_timeout_s = 10;
-  bool run_rmt = 11;
-  bool run_amt = 12;
-  bool run_mt = 13;
-  repeated string stage1_commands = 14;
-  string mt_command = 15;
-  // Artifact kinds required for PASS if MT was actually entered.
-  repeated string required_artifact_kinds = 16;
-  string notes = 17;
-  bool stop_on_test_error = 18;
-  map<string, string> metadata = 19;
-  // Explicit UIP overrides and selected EFI/config paths frozen into this run.
-  google.protobuf.Struct firmware_settings = 20;
-  // Station execution plan frozen when this run uses the saved plan.
-  google.protobuf.Struct boot_plan = 21;
-  // Independent AMT choices frozen alongside the saved execution plan.
-  google.protobuf.Struct amt_settings = 22;
-}
-message RecipeList { repeated Recipe recipes = 1; }
-message PutRecipeRequest {
-  Recipe recipe = 1;
-  // 0 creates; updates must match the current revision.
-  uint32 expected_revision = 2;
-}
-message StartRunRequest {
-  string command_id = 1;
-  string station_id = 2;
-  string recipe_id = 3;
-  string work_order = 4;
-  string batch_no = 5;
-  repeated DimmIdentity dimms = 6;
-  string operator = 7;
-  string notes = 8;
-  string retest_of = 9;
-}
-message StopRunRequest {
-  string command_id = 1;
-  string run_id = 2;
-  string operator = 3;
-  string reason = 4;
-}
-message SetTargetRequest {
-  string command_id = 1;
-  string run_id = 2;
-  double target_c = 3;
-  string operator = 4;
-}
-message ConfirmStageRequest {
-  string command_id = 1;
-  string run_id = 2;
-  string step_id = 3;
-  string operator = 4;
-  string evidence = 5;
-  bool succeeded = 6;
-}
-message ConfirmPowerRequest {
-  string command_id = 1;
-  string station_id = 2;
-  string expected_run_id = 3;
-  bool supply_on = 4;
-  string operator = 5;
-}
-message StationPowerRequest {
-  string command_id = 1;
-  string station_id = 2;
-  // supply_on, supply_off, host_on, host_off, host_cycle, host_reset.
-  // No active test run. Server power operations also work with a diagnostic console.
-  string action = 3;
-  string operator = 4;
-}
-message SetSolModeRequest {
-  string command_id = 1;
-  string run_id = 2;
-  // manual pauses automation input; auto explicitly resumes.
-  string mode = 3;
-  string operator = 4;
-}
-message WriteSolRequest {
-  string command_id = 1;
-  string run_id = 2;
-  bytes data = 3;
-  string operator = 4;
-}
-message SetDiagnosticSolRequest {
-  string command_id = 1;
-  string station_id = 2;
-  string action = 3; // open/close/reconnect; open is idempotent while connected.
-  string operator = 4;
-}
-message WriteDiagnosticSolRequest {
-  string command_id = 1;
-  string station_id = 2;
-  string session_id = 3; // Prevents delayed input reaching a different console session.
-  bytes data = 4;
-  string operator = 5;
-}
-message ReadDiagnosticSolRequest {
-  string station_id = 1;
-  string session_id = 2;
-  uint64 offset = 3;
-  uint32 max_bytes = 4;
-}
-message DiagnosticObservation {
-  uint64 sequence = 1;
-  string phase = 2;
-  int64 observed_unix_ms = 3;
-  string evidence = 4;
-  string kind = 5; // console evidence or an explicitly identified power command/observation.
-  google.protobuf.Struct details = 6;
-}
-message DiagnosticSnapshot {
-  string station_id = 1;
-  string session_id = 2;
-  string state = 3; // closed/connecting/online/error
-  string phase = 4; // unknown/boot/training/uip/rmt/amt/amemdiag/uefi/mt/off
-  int64 opened_unix_ms = 5;
-  int64 updated_unix_ms = 6;
-  string last_error = 7;
-  uint64 bytes_received = 8;
-  repeated DiagnosticObservation observations = 9;
-  TemperatureSnapshot temperature = 10;
-  string mode = 11;
-  string current_evidence = 12;
-  google.protobuf.Struct current_details = 13;
-  string transport = 14; // simulated / ipmi_sol / ssh_console:2200
-}
-message BmcQueryRequest {
-  string station_id = 1;
-  // info/sol/sessions/temperatures/sel/chassis/events/fru; read-only allowlist.
-  string query = 2;
-}
-message BmcQueryResult {
-  string station_id = 1;
-  string query = 2;
-  string text = 3;
-  int64 observed_unix_ms = 4;
-  string mode = 5;
-}
-message Command {
-  string command_id = 1;
-  string action = 2;
-  string station_id = 3;
-  string run_id = 4;
-  // accepted/running/succeeded/failed/interrupted
-  string state = 5;
-  string detail = 6;
-  int64 created_unix_ms = 7;
-  int64 updated_unix_ms = 8;
-  google.protobuf.Struct result = 9;
-}
-message Measurement {
-  optional double value_c = 1;
-  // valid/unavailable_in_phase/stale/read_error/powered_off/unknown
-  string quality = 2;
-  string source = 3;
-  int64 observed_unix_ms = 4;
-  string slot = 5;
-  optional uint32 cpu = 6;
-  string channel = 7;
-}
-message TemperatureSnapshot {
-  optional double requested_target_c = 1;
-  optional double applied_target_c = 2;
-  Measurement hood_air = 3;
-  repeated Measurement dimms = 4;
-  string dimm_quality = 5;
-  string board_state = 6;
-}
-message ChannelStatus {
-  uint32 cpu = 1;
-  string channel = 2;
-  // idle/running/pass/fail/unknown; empty channel never becomes PASS.
-  string state = 3;
-  repeated string sns = 4;
-  uint64 error_count = 5;
-}
-message StationSnapshot {
-  string station_id = 1;
-  uint32 frontend_index = 2;
-  string name = 3;
-  string mode = 4;
-  string bmc_address = 5;
-  string run_id = 6;
-  string last_run_id = 7;
-  string phase = 8;
-  string execution_state = 9;
-  string supply_state = 10;
-  string supply_confirmation = 11;
-  string server_power = 12;
-  string bmc_state = 13;
-  string sol_state = 14;
-  string control_mode = 15;
-  TemperatureSnapshot temperature = 16;
-  optional double progress_percent = 17;
-  int64 phase_started_unix_ms = 18;
-  int64 updated_unix_ms = 19;
-  repeated ChannelStatus channels = 20;
-  string pending_step_id = 21;
-  string pending_instruction = 22;
-  string verdict = 23;
-  string artifact_state = 24;
-  uint64 revision = 25;
-  // Source firmware phase and sample time for the optional percentage above.
-  // Cleared when the workflow/observed firmware phase changes or a run starts.
-  string progress_phase = 26;
-  int64 progress_observed_unix_ms = 27;
-}
-message StationList { repeated StationSnapshot stations = 1; }
-message Run {
-  string run_id = 1;
-  string station_id = 2;
-  string work_order = 3;
-  string batch_no = 4;
-  string operator = 5;
-  repeated DimmIdentity dimms = 6;
-  Recipe recipe = 7;
-  string state = 8;
-  string phase = 9;
-  string verdict = 10;
-  string artifact_state = 11;
-  string supply_state = 12;
-  string supply_confirmation = 13;
-  string end_reason = 14;
-  int64 created_unix_ms = 15;
-  int64 started_unix_ms = 16;
-  int64 finished_unix_ms = 17;
-  int64 updated_unix_ms = 18;
-  string notes = 19;
-  string retest_of = 20;
-  map<string, string> tests = 21;
-  string mode = 22;
-  bool workflow_complete = 23;
-  uint64 error_count = 24;
-  google.protobuf.Struct evidence = 25;
-  uint64 sequence = 26;
-  // Immutable copy of station hardware identity (no credentials) and profile.
-  google.protobuf.Struct hardware_snapshot = 27;
-  google.protobuf.Struct profile_snapshot = 28;
-  uint64 revision = 29;
-}
-message ListRunsRequest {
-  string station_id = 1;
-  string batch_no = 2;
-  string sn = 3;
-  string state = 4;
-  uint64 before_sequence = 5;
-  uint32 limit = 6;
-}
-message RunList { repeated Run runs = 1; uint64 next_before_sequence = 2; }
-message Event {
-  uint64 event_id = 1;
-  string run_id = 2;
-  string station_id = 3;
-  int64 observed_unix_ms = 4;
-  string kind = 5;
-  string severity = 6;
-  string phase = 7;
-  string message = 8;
-  google.protobuf.Struct details = 9;
-  string raw_line = 10;
-  uint64 line_no = 11;
-  string artifact_id = 12;
-  string acknowledged_by = 13;
-  int64 acknowledged_unix_ms = 14;
-}
-message ListEventsRequest {
-  string run_id = 1;
-  string station_id = 2;
-  string severity = 3;
-  uint64 after_event_id = 4;
-  uint32 limit = 5;
-}
-message EventList { repeated Event events = 1; uint64 next_after_event_id = 2; }
-message AcknowledgeEventRequest { uint64 event_id = 1; string operator = 2; }
-message TemperatureSample {
-  uint64 sample_id = 1;
-  string run_id = 2;
-  string station_id = 3;
-  int64 observed_unix_ms = 4;
-  TemperatureSnapshot temperature = 5;
-}
-message TemperatureQuery { string run_id = 1; uint64 after_sample_id = 2; uint32 limit = 3; }
-message TemperaturePage { repeated TemperatureSample samples = 1; uint64 next_after_sample_id = 2; }
-message ReadSolRequest {
-  string run_id = 1;
-  uint64 offset = 2;
-  uint32 max_bytes = 3;
-}
-message ByteChunk { bytes data = 1; uint64 next_offset = 2; bool eof = 3; uint64 total_bytes = 4; }
-message BeginArtifactRequest {
-  string upload_id = 1;
-  string run_id = 2;
-  string filename = 3;
-  string kind = 4;
-  uint64 total_bytes = 5;
-  string operator = 6;
-}
-message UploadSession { string upload_id = 1; uint64 next_offset = 2; string state = 3; string artifact_id = 4; }
-message ArtifactChunkRequest { string upload_id = 1; uint64 offset = 2; bytes data = 3; }
-message FinishArtifactRequest { string upload_id = 1; string sha256 = 2; }
-message Artifact {
-  string artifact_id = 1;
-  string run_id = 2;
-  string filename = 3;
-  string kind = 4;
-  uint64 size_bytes = 5;
-  string sha256 = 6;
-  int64 imported_unix_ms = 7;
-  string operator = 8;
-  string parser_version = 9;
-  google.protobuf.Struct summary = 10;
-  repeated string warnings = 11;
-}
-message ArtifactList { repeated Artifact artifacts = 1; }
-message ReadArtifactRequest { string artifact_id = 1; uint64 offset = 2; uint32 max_bytes = 3; }
-message RunReport {
-  Run run = 1;
-  repeated Artifact artifacts = 2;
-  uint64 event_count = 3;
-  uint64 temperature_sample_count = 4;
-  uint64 sol_bytes = 5;
-  repeated string missing_artifact_kinds = 6;
-  string interpretation = 7;
-}
-

+ 402 - 89
src/backendlink.cpp

@@ -2,6 +2,7 @@
 
 #include "appconfig.h"
 #include "localplans.h"
+#include "uiformat.h"
 
 #include <QCoreApplication>
 #include <QDateTime>
@@ -12,8 +13,10 @@
 #include <QJsonArray>
 #include <QJsonDocument>
 #include <QJsonObject>
+#include <QNetworkProxy>
 #include <QNetworkRequest>
 #include <QSaveFile>
+#include <QUrl>
 #include <QUuid>
 
 namespace {
@@ -145,7 +148,11 @@ BackendLink::BackendLink(QObject *parent)
     connect(&m_ws, &QWebSocket::textMessageReceived, this, &BackendLink::onTextMessage);
     connect(&m_ws, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
             this, [this](QAbstractSocket::SocketError) {
-        qInfo().noquote() << "[backend]" << m_ws.errorString();
+        const QString err = m_ws.errorString();
+        qInfo().noquote() << "[backend]" << err;
+        if (err.contains(QStringLiteral("proxy"), Qt::CaseInsensitive))
+            qInfo().noquote() << "[backend] 提示:连接受本机代理影响;内网后端已强制直连,"
+                                 "若仍失败请核对 config.json 的 url 与系统代理设置";
     });
 
     m_reconnect.setSingleShot(true);
@@ -216,6 +223,23 @@ void BackendLink::openSocket()
     qInfo().noquote() << "[backend] 连接" << m_url << "...";
     m_connectStartMs = nowMs();
 
+    // 内网 / 本机后端一律直连,不让 QWebSocket 去用系统或环境变量代理。
+    // 开发机上常设 http_proxy(本机抓包/加速代理),Qt 会把它拿去连 ws://,
+    // 握手前就报 "The proxy type is invalid for this operation",于是每 3s 重连、
+    // 界面一直「控制台离线」,点开始测试就提示「后端未连接,本次未下发任务」。
+    // 后端在局域网,本来也不该经过代理;外网地址仍沿用系统默认代理。
+    const QUrl url(m_url);
+    const QString host = url.host();
+    const bool direct = host.isEmpty()
+                        || host == QStringLiteral("localhost")
+                        || host == QStringLiteral("127.0.0.1")
+                        || host == QLatin1String("::1")
+                        || host.startsWith(QStringLiteral("192.168."))
+                        || host.startsWith(QStringLiteral("10."))
+                        || host.startsWith(QStringLiteral("172."));
+    m_ws.setProxy(direct ? QNetworkProxy(QNetworkProxy::NoProxy)
+                         : QNetworkProxy(QNetworkProxy::DefaultProxy));
+
     QNetworkRequest request{QUrl(m_url)};
     request.setRawHeader("X-Client-Id", m_clientId.toUtf8());
     m_ws.open(request);
@@ -225,7 +249,8 @@ void BackendLink::onConnected()
 {
     qInfo().noquote() << "[backend] 已连上" << m_url << "client_id =" << m_clientId;
     m_lastMessageMs = nowMs();
-    m_autoPaused = false;               // 重新连上后允许再次自动下发
+    // 断线后不自动恢复阶段动作:手册要求连接变化时暂停本地自动下发。
+    // 只有用户明确发起新一轮 StartTest 才解除暂停,避免重连后对旧 input_id 误操作。
     m_reconnect.stop();
     m_disconnectDebounce.stop();
     if (!m_reportedConnected) {
@@ -313,14 +338,19 @@ void BackendLink::flushDeferredUart(int station)
 
 void BackendLink::onDisconnected()
 {
-    qInfo().noquote() << "[backend] 连接断开," << kReconnectMs / 1000 << "s 后重试";
+    qInfo().noquote() << "[backend] 连接断开," << QString::number(kReconnectMs / 1000.0, 'f', 1) << "s 后重试";
     m_autoPaused = true;                // 连接变化 → 暂停自动下发
     m_handlers.clear();
+    m_errorHandlers.clear();
 
     // 旧的推送包属于上一条连接:重连后后端会重放当前会话,回填也会重新走,这里直接丢掉
     for (int i = 0; i < kStationCount; ++i) {
         m_backfillHoldUntil[i] = 0;
         m_uartDeferred[i].clear();
+        // 在途 SetStageIntent 的回执可能随断线丢失,不能让 pending 永久卡住;
+        // ready 也不能在重连后被当成当前轮次已可靠预置。
+        m_stageIntentPending[i].clear();
+        m_stageIntentReady[i].clear();
     }
 
     if (m_reportedConnected && !m_disconnectDebounce.isActive())
@@ -397,9 +427,9 @@ void BackendLink::onTextMessage(const QString &json)
     const QString event = obj.value(QStringLiteral("event")).toString();
     if (!event.isEmpty()) {
         const QJsonObject result = obj.value(QStringLiteral("result")).toObject();
-        if (event == QStringLiteral("state"))
+        if (event == QStringLiteral("state")) {
             applyState(result);
-        else if (event == QStringLiteral("bios_uart")) {
+        } else if (event == QStringLiteral("bios_uart")) {
             // 回填期间先把推送压住:等 ReadBiosUart 把历史补齐再按原顺序放,
             // 否则推送把游标先推到很后面,回填回来的前几万字节会被当成重复整包丢掉。
             const int index = stationIndex(result.value(QStringLiteral("station_id")).toString());
@@ -408,13 +438,61 @@ void BackendLink::onTextMessage(const QString &json)
             else
                 applyBiosUart(result);
         } else if (event == QStringLiteral("task_complete")) {
+            // 0.8.1.19:每轮终态主动推送。只接受当前 boot_id 的事件,避免旧轮次迟到包推进新任务。
             const int index = stationIndex(result.value(QStringLiteral("station_id")).toString());
-            if (index >= 0) {
-                const QString verdict = result.value(QStringLiteral("verdict")).toString();
-                const QString status = result.value(QStringLiteral("task_status")).toString();
-                emit logLine(index, QStringLiteral("[qt] 收到本轮测试完成推送(verdict=%1, task_status=%2)")
-                                        .arg(verdict, status));
-                emit taskCompleted(index, result);
+            const QString bootId = result.value(QStringLiteral("boot_id")).toString();
+            const QString taskStatus = result.value(QStringLiteral("task_status")).toString();
+            const bool complete = result.value(QStringLiteral("complete")).toBool();
+            const bool terminal = taskStatus == QStringLiteral("completed")
+                                  || taskStatus == QStringLiteral("failed");
+            if (index >= 0 && complete && terminal) {
+                const bool eventIsOld = !m_waitingNewBoot[index] && !bootId.isEmpty()
+                                        && !m_bootId[index].isEmpty() && bootId != m_bootId[index];
+                const bool stillOldDuringRestart = m_waitingNewBoot[index]
+                                                   && (bootId.isEmpty()
+                                                       || bootId == m_bootId[index]);
+                if (eventIsOld || stillOldDuringRestart) {
+                    qInfo().noquote() << "[backend] 忽略旧轮次 task_complete:"
+                                      << stationId(index) << bootId
+                                      << "当前 boot_id =" << m_bootId[index];
+                } else {
+                    // 新轮次的 task_complete 可能先于下一帧 state 到达;boot_id 不同且正等待新轮次时,
+                    // 以该事件确认轮次切换,避免误丢真正的终态通知。
+                    if (!bootId.isEmpty() && m_waitingNewBoot[index]
+                        && bootId != m_bootId[index]) {
+                        m_bootId[index] = bootId;
+                        m_waitingNewBoot[index] = false;
+                        m_appliedCpu[index].clear();
+                        m_handledInput[index].clear();
+                        m_stageDoneKeys[index].clear();
+                        m_stagePendingCmd[index].clear();
+                        m_stagePendingKey[index].clear();
+                        m_stationPaused[index] = false;
+                        m_blockedWarned[index] = false;
+                        m_lastCompleteCmd[index].clear();
+                        m_lastTaskStatus[index].clear();
+                        m_stageErrorsJson[index].clear();
+                        m_lastVerdict[index].clear();
+                    }
+                    // 快照事件与「队列推进」分开去重:
+                    // StageAction/GetCommand 的 complete=true 可能先到并占用
+                    // m_lastTaskCompleteBoot;不能因此吞掉后到的 verdict/stage_completions。
+                    const bool newSnapshot = bootId.isEmpty()
+                                             || bootId != m_lastTaskCompleteEventBoot[index];
+                    if (newSnapshot) {
+                        if (!bootId.isEmpty())
+                            m_lastTaskCompleteEventBoot[index] = bootId;
+                        emit taskCompleteArrived(index, result);
+                    }
+
+                    // 队列终态单独去重,命令回执先到时事件只补快照、不重复推进。
+                    if (bootId.isEmpty() || bootId != m_lastTaskCompleteBoot[index]) {
+                        if (!bootId.isEmpty())
+                            m_lastTaskCompleteBoot[index] = bootId;
+                        m_lastTaskStatus[index] = taskStatus;
+                        emit taskProgressReported(index, true, taskStatus);
+                    }
+                }
             }
         }
         return;
@@ -460,16 +538,110 @@ void BackendLink::onTextMessage(const QString &json)
 // ---------------------------------------------------------------------------
 // 状态推送:四工位快照 → 落库 + 本地 plan
 // ---------------------------------------------------------------------------
+// 手册 9.2:StartTest / StageAction / GetCommand 的命令结果对象新增
+// complete(当前任务是否到终态)与 task_status(任务状态枚举)。
+// complete 也可能表示「这条命令自己到终态」,所以上层只有同时看到
+// task_status=completed/failed 才把它当作任务终态,避免阶段动作提前推进队列。
+void BackendLink::reportCommandProgress(int station, const QString &commandId,
+                                        const QJsonObject &result)
+{
+    if (station < 0 || station >= kStationCount)
+        return;
+
+    // 字段可能在命令结果顶层,也可能嵌在 result.result 里(GetCommand 把业务结果
+    // 放在嵌套 result 下),两处都认,兼容后端不同实现。
+    bool complete = result.value(QStringLiteral("complete")).toBool();
+    QString taskStatus = result.value(QStringLiteral("task_status")).toString();
+    const QJsonObject inner = result.value(QStringLiteral("result")).toObject();
+    if (!complete)
+        complete = inner.value(QStringLiteral("complete")).toBool();
+    if (taskStatus.isEmpty())
+        taskStatus = inner.value(QStringLiteral("task_status")).toString();
+
+    // complete 只有与任务终态同时出现才可推进本地队列。
+    const bool terminalTask = taskStatus == QStringLiteral("completed")
+                              || taskStatus == QStringLiteral("failed")
+                              || taskStatus == QStringLiteral("interrupted");
+
+    // task_complete 推送与 GetCommand 可能描述同一轮终态:按 boot_id 跨通道去重,
+    // 防止先收到推送推进到下一任务后,又被迟到的 GetCommand 把下一任务误推进一次。
+    const bool alreadyReportedForBoot = !m_bootId[station].isEmpty()
+                                        && m_lastTaskCompleteBoot[station] == m_bootId[station];
+
+    // 换条停机(run_state=blocked)期间不再上报 complete:命令结果包可能比 state 包先到,
+    // 那时上层还没看到 awaiting_dimm_replacement,会误把队列推进到下一条任务。
+    if (complete && terminalTask && !alreadyReportedForBoot
+        && !m_blockedWarned[station] && m_lastCompleteCmd[station] != commandId) {
+        m_lastCompleteCmd[station] = commandId;
+        m_lastTaskStatus[station] = taskStatus;
+        if (!m_bootId[station].isEmpty())
+            m_lastTaskCompleteBoot[station] = m_bootId[station];
+        emit taskProgressReported(station, true, taskStatus);
+    } else if (!taskStatus.isEmpty() && taskStatus != m_lastTaskStatus[station]) {
+        m_lastTaskStatus[station] = taskStatus;
+        emit taskProgressReported(station, false, taskStatus);
+    }
+}
+
+// 手册 9.5:确认已更换 DIMM,清除后端换条停机挂起(awaiting_dimm_replacement)。
+void BackendLink::confirmDimmReplacement(int station)
+{
+    if (station < 0 || station >= kStationCount)
+        return;
+    if (!isConnected()) {
+        emit dimmConfirmed(station, false, QStringLiteral("后端未连接"));
+        return;
+    }
+
+    const QString commandId = newCommandId(QStringLiteral("dimm"), station);
+    QJsonObject params;
+    params.insert(QStringLiteral("command_id"), commandId);
+    params.insert(QStringLiteral("station_id"), stationId(station));
+    // ConfirmDimmReplacement 只要求 command_id + station_id。
+    // 该工位可能因为 blocked 被暂停自动下发,确认换条后恢复(下一轮 boot_id 也会再清一次)。
+    m_stationPaused[station] = false;
+    emit logLine(station, QStringLiteral("[qt] 提交更换异常内存条确认(%1)").arg(commandId));
+
+    sendRequest(QStringLiteral("ConfirmDimmReplacement"), params,
+                [this, station](const QJsonObject &result) {
+        const QString state = result.value(QStringLiteral("state")).toString();
+        if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) {
+            const QJsonObject err = result.value(QStringLiteral("error")).toObject();
+            const QString msg = QStringLiteral("%1 %2")
+                                    .arg(err.value(QStringLiteral("code")).toString(),
+                                         err.value(QStringLiteral("message")).toString())
+                                    .trimmed();
+            emit logLine(station, QStringLiteral("[qt] 确认更换内存条失败:%1").arg(msg));
+            emit dimmConfirmed(station, false, msg);
+            return;
+        }
+        emit logLine(station, QStringLiteral("[qt] 已确认更换异常内存条,后端换条停机挂起已解除"));
+        emit dimmConfirmed(station, true, QString());
+    }, [this, station](const QString &code, const QString &message) {
+        const QString msg = QStringLiteral("%1 %2").arg(code, message).trimmed();
+        emit logLine(station, QStringLiteral("[qt] 确认更换内存条失败:%1").arg(msg));
+        emit dimmConfirmed(station, false, msg);
+    });
+}
+
 void BackendLink::applyState(const QJsonObject &result)
 {
     const QString serverId = result.value(QStringLiteral("server_id")).toString();
     if (!m_serverId.isEmpty() && serverId != m_serverId) {
         // 后端重启:清掉旧输入节点与自动运行归属,不重放任何动作
         qInfo().noquote() << "[backend] server_id 变化,清理旧输入节点与自动运行状态";
+        // 后端实例变化后,旧命令、输入节点与阶段意图均不可继续使用。
+        // 暂停自动动作,要求用户明确重新开始,避免对新后端会话误发旧计划。
+        m_autoPaused = true;
         for (int i = 0; i < kStationCount; ++i) {
             m_handledInput[i].clear();
             m_appliedCpu[i].clear();
             m_bootId[i].clear();
+            m_lastTaskCompleteBoot[i].clear();
+            m_lastTaskCompleteEventBoot[i].clear();
+            m_stageIntentPending[i].clear();
+            m_stageIntentReady[i].clear();
+            m_waitingNewBoot[i] = false;
         }
         m_pending.clear();
         m_pollCount.clear();
@@ -513,7 +685,7 @@ void BackendLink::applyStation(int station, const QJsonObject &st)
     m_lastInputId[station] = st.value(QStringLiteral("input")).toObject()
                                  .value(QStringLiteral("id")).toString();
 
-    // boot_id 变化 = 新一轮启动:内存参数要在新的 UIP1 重新下发
+    // boot_id 变化 = 新一轮启动:内存参数要在新的 ICT1 重新下发
     const QString bootId = st.value(QStringLiteral("boot_id")).toString();
     if (!bootId.isEmpty() && bootId != m_bootId[station]) {
         m_bootId[station] = bootId;
@@ -523,6 +695,11 @@ void BackendLink::applyStation(int station, const QJsonObject &st)
         m_stagePendingCmd[station].clear();
         m_stagePendingKey[station].clear();
         m_stationPaused[station] = false;      // 新一轮启动,恢复自动化
+        m_blockedWarned[station] = false;      // 新一轮允许重新提示换条停机
+        m_lastCompleteCmd[station].clear();    // 新任务允许再报一次 complete
+        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 重新计
@@ -569,8 +746,33 @@ void BackendLink::applyStation(int station, const QJsonObject &st)
         }
     }
 
+    // 手册 9.2:state 推送的 station.command 同样带 complete / task_status;
+    // 工位对象自己也有 task_status,变化时才上报(每秒一包,不去重会刷屏)。
+    const QJsonObject command = st.value(QStringLiteral("command")).toObject();
+    if (!command.isEmpty())
+        reportCommandProgress(station,
+                              command.value(QStringLiteral("command_id")).toString(), command);
+    const QString taskStatus = st.value(QStringLiteral("task_status")).toString();
+    if (!taskStatus.isEmpty() && taskStatus != m_lastTaskStatus[station]) {
+        m_lastTaskStatus[station] = taskStatus;
+        emit taskProgressReported(station, false, taskStatus);
+    }
+
+    // 手册 9.2/9.5:阶段 FAIL 后后端把 run_state 置为 blocked 并挂起换条,
+    // 此时停止该工位的自动下发,等测试员换条后点「开始测试」强制重启新一轮。
+    const QString runState = st.value(QStringLiteral("run_state")).toString();
+    const bool awaitingDimm = st.value(QStringLiteral("awaiting_dimm_replacement")).toBool();
+    if ((runState == QStringLiteral("blocked") || awaitingDimm) && !m_blockedWarned[station]) {
+        m_blockedWarned[station] = true;
+        m_stationPaused[station] = true;
+        emit logLine(station, QStringLiteral("[qt] 后端换条停机(run_state=blocked):本阶段已跑完,"
+                                            "等待更换异常内存条;换好后点「开始测试」可强制重启新一轮"));
+        emit alarmReported(station, QString(),
+                           QStringLiteral("换条停机:等待更换异常内存条并重新开始测试"));
+    }
+
     // FAIL 之后该工位停止自动动作,等人工处理(其他工位不受影响)
-    if (st.value(QStringLiteral("run_state")).toString() == QStringLiteral("failed")) {
+    if (runState == QStringLiteral("failed")) {
         if (!m_stationPaused[station]) {
             qInfo().noquote() << "[backend] 工位" << stationId(station) << "进入 failed,暂停该工位自动下发";
             m_stationPaused[station] = true;
@@ -578,6 +780,108 @@ void BackendLink::applyStation(int station, const QJsonObject &st)
     }
 }
 
+// 0.8.1.19:在新的 StartTest 已受理后,将四个阶段意图提前写入后端。
+ // 每个阶段的最后一次意图由后端 Last-Write-Wins 规则决定;成功预置后不再
+ // 在 input.ready 时重复发送 StageAction,防止后端自动消费与前端动作撞车。
+void BackendLink::stageStationIntents(int station)
+{
+    if (station < 0 || station >= kStationCount || !isConnected())
+        return;
+
+    m_stageIntentPending[station].clear();
+    m_stageIntentReady[station].clear();
+
+    auto sendIntent = [this, station](const QString &stage,
+                                      const QString &action,
+                                      const QJsonObject &extra) {
+        m_stageIntentPending[station].insert(stage);
+
+        QJsonObject params;
+        params.insert(QStringLiteral("station_id"), stationId(station));
+        params.insert(QStringLiteral("stage"), stage);
+        params.insert(QStringLiteral("action"), action);
+        for (auto it = extra.constBegin(); it != extra.constEnd(); ++it)
+            params.insert(it.key(), it.value());
+
+        sendRequest(QStringLiteral("SetStageIntent"), params,
+                    [this, station, stage, action](const QJsonObject &result) {
+            m_stageIntentPending[station].remove(stage);
+            const QString confirmation = result.value(QStringLiteral("confirmation")).toString();
+            QString stageText = ui::inputStageText(stage);
+            if (stageText == stage)
+                stageText = stage.toUpper();
+            if (confirmation == QStringLiteral("staged")) {
+                m_stageIntentReady[station].insert(stage);
+                emit logLine(station, QStringLiteral("[qt] 阶段意图已预置:%1 / %2(staged)")
+                                          .arg(stageText, action));
+            } else {
+                // 只有明确返回 staged 才能认定后端已接管;否则保留 input.ready 回退路径。
+                m_stageIntentReady[station].remove(stage);
+                emit logLine(station, QStringLiteral("[qt] %1 阶段未确认预置(confirmation=%2),到达提示符后回退普通动作")
+                                          .arg(stageText, confirmation.isEmpty()
+                                               ? QStringLiteral("missing") : confirmation));
+            }
+        }, [this, station, stage, action](const QString &code, const QString &message) {
+            // 旧版后端不支持 SetStageIntent 时自动回退到 input.ready -> StageAction。
+            m_stageIntentPending[station].remove(stage);
+            m_stageIntentReady[station].remove(stage);
+            emit logLine(station, QStringLiteral("[qt] %1 阶段预置失败(%2 %3),到达提示符后回退普通动作")
+                                      .arg(stage, code, message));
+        });
+    };
+
+    // ICT1:完整透传本地 memory_params(包含快捷参数及扩展目录参数),并单独指定 RMT 开关。
+    QJsonObject ict1;
+    const bool runRmt = m_rmtParams[station].value(QStringLiteral("enabled")).toBool(true);
+    ict1.insert(QStringLiteral("run_rmt"), runRmt);
+    if (!m_memoryParams[station].isEmpty())
+        ict1.insert(QStringLiteral("memory_params"), m_memoryParams[station]);
+    sendIntent(QStringLiteral("uip1"), QStringLiteral("continue_uip"), ict1);
+
+    // AMT:按启用开关预置 start_amt / skip_amt;selected、only_tests、skip_tests 均透传。
+    const QJsonObject amt = m_amtParams[station];
+    const bool runAmt = amt.value(QStringLiteral("enabled")).toBool(true);
+    QJsonObject amtExtra;
+    amtExtra.insert(QStringLiteral("run_amt"), runAmt);
+    if (runAmt) {
+        QJsonObject payload;
+        QString testCommand = amt.value(QStringLiteral("test_command")).toString().trimmed();
+        if (testCommand.isEmpty())
+            testCommand = QStringLiteral("amemdiag 1");
+        payload.insert(QStringLiteral("test_command"), testCommand);
+        const char *const amtKeys[] = {"selected", "only_tests", "skip_tests"};
+        for (const char *key : amtKeys) {
+            const QJsonValue value = amt.value(QLatin1String(key));
+            if (!value.isUndefined() && !value.isNull()
+                && (!value.isArray() || !value.toArray().isEmpty()))
+                payload.insert(QLatin1String(key), value);
+        }
+        if (amt.contains(QStringLiteral("end_step")))
+            payload.insert(QStringLiteral("end_step"), amt.value(QStringLiteral("end_step")));
+        amtExtra.insert(QStringLiteral("amt"), payload);
+    }
+    sendIntent(QStringLiteral("amt"),
+               runAmt ? QStringLiteral("start_amt") : QStringLiteral("skip_amt"),
+               amtExtra);
+
+    // ICT2:继续固件流程,不重复应用 ICT1 参数。
+    sendIntent(QStringLiteral("uip2"), QStringLiteral("continue_uip"), QJsonObject());
+
+    // MT:后端按 mt86.cfg / PXE 规则处理文件与地址范围;这里只传本地明确配置项。
+    const QJsonObject mt = m_mtParams[station];
+    const bool runMt = mt.value(QStringLiteral("enabled")).toBool(true);
+    QJsonObject mtExtra;
+    mtExtra.insert(QStringLiteral("run_mt"), runMt);
+    if (runMt) {
+        const QJsonObject payload = LocalPlans::mtStagePayload(mt);
+        if (!payload.isEmpty())
+            mtExtra.insert(QStringLiteral("mt"), payload);
+    }
+    sendIntent(QStringLiteral("mt"),
+               runMt ? QStringLiteral("start_mt") : QStringLiteral("skip_mt"),
+               mtExtra);
+}
+
 void BackendLink::autoPlan(int station, const QJsonObject &st)
 {
     if (m_autoPaused || m_stationPaused[station])
@@ -610,6 +914,14 @@ void BackendLink::autoPlan(int station, const QJsonObject &st)
     if (stage == QStringLiteral("amt") && testComplete && amtWanted)
         key = QStringLiteral("amt-exit/%1").arg(cpu);
 
+    // SetStageIntent 已成功预置时,后端会在该阶段提示符自动消费;
+    // AMT 跑完后后端也会按 exit_after=true 自动提交 exit,不重复发送 skip_amt。
+    const QString intentStage = (stage == QStringLiteral("uefi"))
+                                    ? QStringLiteral("mt") : stage;
+    if (m_stageIntentPending[station].contains(intentStage)
+        || m_stageIntentReady[station].contains(intentStage))
+        return;
+
     if (m_stageDoneKeys[station].contains(key))
         return;
 
@@ -617,23 +929,17 @@ void BackendLink::autoPlan(int station, const QJsonObject &st)
     QJsonObject extra;
 
     if (stage == QStringLiteral("uip1")) {
-        // 每个 CPU 的 UIP1 各下发一次内存参数;同一 CPU 再次进入 UIP1 只发空回车。
-        // 手册 3.4:UIP1 的 continue_uip 要带 run_rmt(默认 true),后端据此决定
+        // 每个 CPU 的 ICT1 各下发一次内存参数;同一 CPU 再次进入 ICT1 只发空回车。
+        // 手册 3.4:ICT1 的 continue_uip 要带 run_rmt(默认 true),后端据此决定
         // 下发 rmt enable 跑完整 RMT 扫描,还是直接空回车跳过。
         action = QStringLiteral("continue_uip");
         const bool wantRmt = m_rmtParams[station].value(QStringLiteral("enabled")).toBool(true);
         extra.insert(QStringLiteral("run_rmt"), wantRmt);
-        if (!m_rmtParams[station].isEmpty())
-            extra.insert(QStringLiteral("rmt"), m_rmtParams[station]);
         const bool firstCpu = m_appliedCpu[station].isEmpty();
         if (!m_appliedCpu[station].contains(cpu) && !m_memoryParams[station].isEmpty()) {
             extra.insert(QStringLiteral("memory_params"), m_memoryParams[station]);
             m_appliedCpu[station].insert(cpu);
         }
-        // StartTest 协议只收 command_id / station_id,本轮任务列表随第一个 CPU 的
-        // ICT1 一次性带下去;后端按列表顺序执行(一个机台可以挂多条任务)。
-        if (firstCpu && !m_stationTasks[station].isEmpty())
-            extra.insert(QStringLiteral("tasks"), m_stationTasks[station]);
     } else if (stage == QStringLiteral("uip2")) {
         action = QStringLiteral("continue_uip");        // 空参数,只发一个 CR
     } else if (stage == QStringLiteral("amt")) {
@@ -649,11 +955,24 @@ void BackendLink::autoPlan(int station, const QJsonObject &st)
                 action = QStringLiteral("start_amt");
                 extra.insert(QStringLiteral("run_amt"), true);
 
+                // 只带测试命令;旧版 overrides / raw_commands 纯净接口会忽略,不再传
                 QString testCommand = amt.value(QStringLiteral("test_command")).toString().trimmed();
                 if (testCommand.isEmpty())
                     testCommand = QStringLiteral("amemdiag 1");
-                QJsonObject amtPayload = amt;
+                QJsonObject amtPayload;
                 amtPayload.insert(QStringLiteral("test_command"), testCommand);
+                // 手册 9.4:后端按 amt.selected(或 only_tests / skip_tests)自动生成
+                // 合规的 tp 表指令;end_step=0 可单步快跑全部算法。没勾就完全不传,
+                // 由后端按默认「19 项全跑」执行,避免把空数组误读成「一项都不跑」。
+                const char *const amtKeys[] = {"selected", "only_tests", "skip_tests"};
+                for (const char *key : amtKeys) {
+                    const QJsonValue value = amt.value(QLatin1String(key));
+                    if (!value.isUndefined() && !value.isNull()
+                        && (!value.isArray() || !value.toArray().isEmpty()))
+                        amtPayload.insert(QLatin1String(key), value);
+                }
+                if (amt.contains(QStringLiteral("end_step")))
+                    amtPayload.insert(QStringLiteral("end_step"), amt.value(QStringLiteral("end_step")));
                 extra.insert(QStringLiteral("amt"), amtPayload);
             }
         } else {
@@ -691,7 +1010,10 @@ void BackendLink::autoPlan(int station, const QJsonObject &st)
             }
         }
         if (!ok) {
-            qInfo().noquote() << "[backend] 工位" << stationId(station) << stage
+            QString stageText = ui::inputStageText(stage);
+            if (stageText == stage)
+                stageText = stage.toUpper();
+            qInfo().noquote() << "[backend] 工位" << stationId(station) << stageText
                               << "当前不允许" << action << ",等待状态变化";
             return;
         }
@@ -724,13 +1046,36 @@ void BackendLink::submitStageAction(int station, const QString &inputId,
     sendRequest(QStringLiteral("StageAction"), params, [this, commandId, station](const QJsonObject &result) {
         const QString state = result.value(QStringLiteral("state")).toString();
         qInfo().noquote() << "[backend] StageAction" << commandId << "state =" << state;
+        reportCommandProgress(station, commandId, result);   // 手册 9.2:complete / task_status
         if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) {
-            m_stagePendingCmd[station].clear();
-            m_stationPaused[station] = true;
-            emit logLine(station, QStringLiteral("[qt] 阶段动作 %1(已暂停该工位自动下发)").arg(state));
+            forgetCommand(commandId);
+            if (m_stagePendingCmd[station] == commandId)
+                m_stagePendingCmd[station].clear();
+            const QJsonObject err = result.value(QStringLiteral("error")).toObject();
+            const QString code = err.value(QStringLiteral("code")).toString();
+            const QString msg = err.value(QStringLiteral("message")).toString();
+            emit logLine(station, QStringLiteral("[qt] 阶段动作 %1:%2 %3")
+                                      .arg(state, code, msg).trimmed());
+            if (state == QStringLiteral("failed") && code == QStringLiteral("FAILED_PRECONDITION")) {
+                m_stageDoneKeys[station].remove(m_stagePendingKey[station]);
+            } else {
+                m_stationPaused[station] = true;
+                emit logLine(station, QStringLiteral("[qt] 阶段动作 %1(已暂停该工位自动下发)").arg(state));
+            }
         } else if (state == QStringLiteral("succeeded")) {
-            m_stagePendingCmd[station].clear();
+            forgetCommand(commandId);
+            if (m_stagePendingCmd[station] == commandId)
+                m_stagePendingCmd[station].clear();
         }
+    }, [this, commandId, station](const QString &code, const QString &message) {
+        forgetCommand(commandId);
+        if (m_stagePendingCmd[station] == commandId)
+            m_stagePendingCmd[station].clear();
+        emit logLine(station, QStringLiteral("[qt] 阶段动作被后端拒绝:%1 %2").arg(code, message).trimmed());
+        if (code == QStringLiteral("FAILED_PRECONDITION"))
+            m_stageDoneKeys[station].remove(m_stagePendingKey[station]);
+        else
+            m_stationPaused[station] = true;
     });
 }
 
@@ -783,14 +1128,12 @@ bool BackendLink::startTest(int station)
                                              "照常提交开始测试,由后端核验").arg(power, phase));
     }
 
-    // 同一工位已有未结束的 StartTest 时支持强制抢占重发:忘记旧 command_id,签发新一轮命令
+    // 同一工位已有未结束的 StartTest:拒绝重复排入(后端也会拒),直接告诉调用方
     if (m_startPending[station]) {
-        qInfo().noquote() << "[backend]" << stationId(station) << "抢占未完成的 StartTest"
-                          << m_startCmd[station] << ",重新签发开始测试";
-        if (!m_startCmd[station].isEmpty())
-            forgetCommand(m_startCmd[station]);
-        m_startPending[station] = false;
-        m_startCmd[station].clear();
+        qInfo().noquote() << "[backend]" << stationId(station) << "已有未完成的 StartTest"
+                          << m_startCmd[station] << ",忽略本次点击";
+        emit logLine(station, QStringLiteral("[qt] 该工位已有未完成的 StartTest,忽略本次点击"));
+        return false;
     }
 
     const QString commandId = newCommandId(QStringLiteral("start"), station);
@@ -801,8 +1144,11 @@ bool BackendLink::startTest(int station)
     m_stageDoneKeys[station].clear();
     m_stagePendingCmd[station].clear();
     m_stagePendingKey[station].clear();
+    m_stageIntentPending[station].clear();
+    m_stageIntentReady[station].clear();
     m_stationPaused[station] = false;
     m_autoPaused = false;
+    m_waitingNewBoot[station] = true;
 
     // 日志区会被上层清空:短时间内丢弃旧会话的残留字节,等新会话再显示。
     // 注意必须是「限时」静音:后端在一次重启前后可能沿用同一个会话编号,
@@ -824,12 +1170,17 @@ bool BackendLink::startTest(int station)
     sendRequest(QStringLiteral("StartTest"), params, [this, station, commandId](const QJsonObject &result) {
         const QString state = result.value(QStringLiteral("state")).toString();
         qInfo().noquote() << "[backend] StartTest" << commandId << "state =" << state;
+        reportCommandProgress(station, commandId, result);   // 手册 9.2:complete / task_status
         if (state == QStringLiteral("queued") || state == QStringLiteral("running")
             || state == QStringLiteral("dispatching")) {
+            // StartTest 已受理,当前旧启动已被后端接管;现在预置新一轮四阶段意图,
+            // 请求帧按 WebSocket 顺序先于后续阶段状态处理,不会抢写旧 BIOS 会话。
+            stageStationIntents(station);
             emit logLine(station, QStringLiteral("[qt] StartTest 已受理(%1),等待新 BIOS 启动与可交互输入")
                                      .arg(state));
             emit startTestReplied(station, true, state);
         } else if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) {
+            forgetCommand(commandId);
             m_startPending[station] = false;
             if (m_startCmd[station] == commandId)
                 m_startCmd[station].clear();
@@ -840,13 +1191,16 @@ bool BackendLink::startTest(int station)
             emit logLine(station, QStringLiteral("[qt] StartTest %1:%2 %3").arg(state, code, msg));
             emit startTestReplied(station, false, QStringLiteral("%1 %2").arg(code, msg).trimmed());
         } else if (state == QStringLiteral("succeeded")) {
-            // 直接终态(复位/开机已确认并进入可交互窗口)
+            forgetCommand(commandId);
+            // 直接终态(复位/开机已确认并进入可交互窗口),仍先预置后续阶段意图。
+            stageStationIntents(station);
             m_startPending[station] = false;
             if (m_startCmd[station] == commandId)
                 m_startCmd[station].clear();
             emit startTestReplied(station, true, state);
         }
     }, [this, station, commandId](const QString &code, const QString &message) {
+        forgetCommand(commandId);
         // 后端在 RPC 层直接拒掉 StartTest(典型:FAILED_PRECONDITION,
         // 该工位正被另一个客户端/网页端执行)。此时不会有任何命令记录,
         // 必须在这里就把在途闸门放开、并通知界面复位按钮,
@@ -953,41 +1307,6 @@ void BackendLink::listUefiFiles(int station, const QString &path)
     });
 }
 
-void BackendLink::confirmDimmReplacement(int station)
-{
-    if (station < 0 || station >= kStationCount)
-        return;
-    if (!isConnected()) {
-        emit dimmConfirmed(station, false, QStringLiteral("后端未连接"));
-        return;
-    }
-
-    const QString commandId = newCommandId(QStringLiteral("dimm"), station);
-    QJsonObject params;
-    params.insert(QStringLiteral("command_id"), commandId);
-    params.insert(QStringLiteral("station_id"), stationId(station));
-
-    m_stationPaused[station] = false;
-    emit logLine(station, QStringLiteral("[qt] 提交更换异常内存条确认(%1)").arg(commandId));
-
-    sendRequest(QStringLiteral("ConfirmDimmReplacement"), params,
-                [this, station](const QJsonObject &result) {
-        const QString state = result.value(QStringLiteral("state")).toString();
-        if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) {
-            const QString msg = rpcErrorText(result);
-            emit logLine(station, QStringLiteral("[qt] 确认更换内存条失败:%1").arg(msg));
-            emit dimmConfirmed(station, false, msg);
-            return;
-        }
-        emit logLine(station, QStringLiteral("[qt] 已确认更换异常内存条,解除停机挂起状态"));
-        emit dimmConfirmed(station, true, QString());
-    }, [this, station](const QString &code, const QString &message) {
-        const QString msg = QStringLiteral("%1 %2").arg(code, message).trimmed();
-        emit logLine(station, QStringLiteral("[qt] 确认更换内存条失败:%1").arg(msg));
-        emit dimmConfirmed(station, false, msg);
-    });
-}
-
 void BackendLink::trackCommand(const QString &commandId, int station)
 {
     m_pending.insert(commandId, station);
@@ -1052,12 +1371,14 @@ void BackendLink::pollCommand(const QString &commandId)
     sendRequest(QStringLiteral("GetCommand"), params, [this, commandId](const QJsonObject &result) {
         const QString state = result.value(QStringLiteral("state")).toString();
         const int station = m_pending.value(commandId, -1);
+        reportCommandProgress(station, commandId, result);   // 手册 9.2:complete / task_status
         const bool terminal = (state == QStringLiteral("succeeded")
                                || state == QStringLiteral("failed")
                                || state == QStringLiteral("interrupted"));
+        const bool isStartCommand = station >= 0 && m_startCmd[station] == commandId;
         if (terminal) {
             forgetCommand(commandId);
-            if (station >= 0 && m_startCmd[station] == commandId) {
+            if (isStartCommand) {
                 m_startCmd[station].clear();
                 m_startPending[station] = false;   // 放开工位,允许再次点「开始测试」
             } else if (station >= 0 && m_stagePendingCmd[station] == commandId) {
@@ -1075,16 +1396,18 @@ void BackendLink::pollCommand(const QString &commandId)
             }
         }
 
-        if (station >= 0 && state == QStringLiteral("failed")) {
+        if (station >= 0 && (state == QStringLiteral("failed")
+                             || state == QStringLiteral("interrupted"))) {
             const QJsonObject err = result.value(QStringLiteral("error")).toObject();
             const QString code = err.value(QStringLiteral("code")).toString();
             const QString msg = err.value(QStringLiteral("message")).toString();
-            emit logLine(station, QStringLiteral("[qt] 命令 %1 失败:%2 %3")
-                                     .arg(commandId, code, msg));
+            emit logLine(station, QStringLiteral("[qt] 命令 %1 %2:%3 %4")
+                                     .arg(commandId, state == QStringLiteral("interrupted")
+                                          ? QStringLiteral("中断") : QStringLiteral("失败"), code, msg));
 
             // 输入节点已变化:撤回该节点的「已完成」标记,等新状态用新 input.id 重试;
             // 其他错误(链路不可用 / 后端 INTERNAL 等)才真正暂停该工位。
-            if (code == QStringLiteral("FAILED_PRECONDITION")) {
+            if (state == QStringLiteral("failed") && code == QStringLiteral("FAILED_PRECONDITION")) {
                 m_stageDoneKeys[station].remove(m_stagePendingKey[station]);
             } else {
                 m_stationPaused[station] = true;
@@ -1094,10 +1417,10 @@ void BackendLink::pollCommand(const QString &commandId)
             // 必须像 RPC 层拒绝一样放开在途闸门、通知界面把按钮退回「开始测试」。
             // 少了这一步,按钮会永久卡在「执行中」,再点还会被「已有未完成 StartTest」
             // 吞掉 —— 现场表现就是「点了没反应,只能重启软件」。
-            if (m_startCmd[station] == commandId) {
-                m_startCmd[station].clear();
-                m_startPending[station] = false;
-                emit startTestReplied(station, false, QStringLiteral("%1 %2").arg(code, msg).trimmed());
+            if (isStartCommand) {
+                // 上面的终态处理已清空 m_startCmd,这里用预先捕获的标记通知界面复位按钮。
+                emit startTestReplied(station, false,
+                                      QStringLiteral("%1 %2").arg(code, msg).trimmed());
             }
         }
         qInfo().noquote() << "[backend] GetCommand" << commandId << "→" << state;
@@ -1146,16 +1469,6 @@ QString BackendLink::newCommandId(const QString &kind, int station)
             .arg(++m_commandSeq);
 }
 
-void BackendLink::setStationTasks(int station, const QJsonArray &tasks)
-{
-    if (station < 0 || station >= kStationCount)
-        return;
-    m_stationTasks[station] = tasks;
-    qInfo().noquote() << "[backend]" << stationId(station)
-                      << "本轮任务已装载,条数 =" << tasks.size()
-                      << "(随 ICT1 阶段下发)";
-}
-
 void BackendLink::setMemoryParams(int station, const QJsonObject &memoryParams)
 {
     if (station < 0 || station >= kStationCount)

+ 40 - 23
src/backendlink.h

@@ -15,19 +15,19 @@
 #include <QWebSocket>
 
 /**
- * 后端 WebSocket 链路(Qt 纯净接口 v1 / 0.8.1.18)
+ * 后端 WebSocket 链路(Qt 纯净接口 v1 / 0.8.1.19)
  * ------------------------------------------------------------------
  * 对应《QT_CLIENT_API_ZH.md》:
- *   · 连接 ws://<host>:8080/ws?view=qt-clean(携带 X-Client-Id)
- *   · 自动推送:每秒 state(四工位状态快照)、有新增字节时 bios_uart(原始串口字节)、轮次收尾 task_complete
- *   · 上行:StartTest(支持运行中抢占重发)、StageAction、ConfirmDimmReplacement
+ *   · 连接 ws://<host>:8080/ws?view=qt-clean(StartTest / StageAction / SetStageIntent / ConfirmDimmReplacement 等)
+ *   · 自动推送:每秒 state(四工位状态快照)、有新增字节时 bios_uart(原始串口字节)
+ *   · 上行:StartTest、SetStageIntent、StageAction、ConfirmDimmReplacement
  *   · 按 (session_id, offset) 去重拼接 BIOS UART,切行后作为日志原文输出
  *   · 健康检查:连接 10s 无响应 → 断开;已连时 20s 无任何消息 → 断开;每 3s 重连
  *
- * 参数不走「保存」接口:内存参数与 AMT 参数都存在本机 qt-plans.json,
- * 内存参数只在本轮每个 CPU 的 ICT1 节点随 StageAction 的 memory_params 下发一次;
- * AMT 参数在 AMT 菜单就绪时随 start_amt 的 amt 字段下发(勾选了「启用 AMT 测试」才有,
- * 否则照旧 skip_amt 发 exit);ICT2 只发 exit。UEFI 按计划下发 MT 或等人工操作。
+ * 参数不走「保存」接口:内存参数与 RMT / AMT / MT 参数都存在本机 qt-plans.json;
+ * 优先在 StartTest 受理后用 SetStageIntent 预置 ICT1 / AMT / ICT2 / MT,
+ * 后端到达对应提示符时自动消费;预置失败时回退到 input.ready -> StageAction。
+ * ICT2 不重复应用 ICT1 参数;AMT 默认执行 amemdiag 1;MT 默认启动 118.efi。
  *
  * 工位映射:界面工位 0..3 ↔ station_id "S1".."S4"。
  */
@@ -47,14 +47,15 @@ public:
      *  该工位已有未结束的 StartTest 时返回 false(防重复点击排入两次重启)。 */
     bool startTest(int station);
 
+    /** 0.8.1.19:换条停机挂起时确认已更换 DIMM,清掉后端 blocked 状态。
+     *  旧版后端没有这个方法时只会记一条 UNIMPLEMENTED 日志,不影响继续点开始测试。 */
+    void confirmDimmReplacement(int station);
+
     /** 0.8.1.14:列 UEFI 目录(StageAction action=list_uefi_files)。
      *  只能在 UEFI Shell 节点可用,其它阶段后端回 FAILED_PRECONDITION。
      *  结果走 uefiFilesArrived。path 为空表示当前目录。 */
     void listUefiFiles(int station, const QString &path);
 
-    /** 0.8.1.18:确认已更换异常内存条(ConfirmDimmReplacement),解除停机换条挂起状态 */
-    void confirmDimmReplacement(int station);
-
     /** 上一次 startTest 是否是在「正在跑」的状态下点的(即复位重跑)。
      *  界面靠它区分「复位过程中的 idle」和「本轮真的跑完了」。 */
     bool lastStartWasRestart(int station) const
@@ -62,15 +63,11 @@ public:
         return station >= 0 && station < 4 && m_restartFromRunning[station];
     }
 
-    /** 本地保存的内存参数(qt-plans.json),供下一次 UIP1 下发用 */
+    /** 本地保存的内存参数(qt-plans.json),供下一次 ICT1 下发用 */
     void setMemoryParams(int station, const QJsonObject &memoryParams);
 
-    /** 该工位本轮要跑的任务列表(qt-plans.json 的 stations.Sn.tasks)。
-     *  StartTest 协议只收 command_id / station_id,任务列表随 UIP1 的 StageAction 带下去。 */
-    void setStationTasks(int station, const QJsonArray &tasks);
-
     /** 本地保存的 RMT 参数(qt-plans.json)。
-     *  enabled=true(手册 0.8.1.9 默认)时 UIP1 的 continue_uip 带 run_rmt=true,
+     *  enabled=true(手册 0.8.1.9 默认)时 ICT1 的 continue_uip 带 run_rmt=true,
      *  后端下发 rmt enable 跑完整 RMT 扫描;false 则跳过。 */
     void setRmtParams(int station, const QJsonObject &rmt);
 
@@ -102,10 +99,14 @@ signals:
     /** 0.8.1.14 list_uefi_files 的结果:path 是查询的目录,files 只有文件名 */
     void uefiFilesArrived(int station, bool ok, const QString &path,
                           const QStringList &files, const QString &message);
-    /** 0.8.1.18 确认更换异常内存条的结果 */
+    /** 手册 9.2:命令结果里的 complete / task_status,以及工位级 task_status 变化。
+     *  complete=true 表示当前任务已到达终态,上层据此安全地衔接下一条本地任务;
+     *  同一个 command_id 只报一次(GetCommand 会反复轮询同一个结果对象)。 */
+    void taskProgressReported(int station, bool complete, const QString &taskStatus);
+    /** 确认更换异常内存条的结果 */
     void dimmConfirmed(int station, bool ok, const QString &message);
-    /** 0.8.1.18 后端主动推送本轮测试完成事件(task_complete) */
-    void taskCompleted(int station, const QJsonObject &result);
+    /** 后端每轮终态主动推送 task_complete,供模型更新阶段完成快照。 */
+    void taskCompleteArrived(int station, const QJsonObject &result);
 
 private slots:
     void onConnected();
@@ -126,6 +127,9 @@ private:
     void applyState(const QJsonObject &result);
     void applyStation(int station, const QJsonObject &st);
     void applyBiosUart(const QJsonObject &result);
+    /** 手册 9.2:从命令结果对象(StartTest / StageAction / GetCommand)里读
+     *  complete / task_status,去重后发 taskProgressReported。 */
+    void reportCommandProgress(int station, const QString &commandId, const QJsonObject &result);
 
     /** 主动回填某工位当前 UART 会话的历史字节(连接 / 重连后调一次)。
      *  后端只在「有新字节」时推 bios_uart:程序刚起来时 BIOS 若停在提示符不再输出,
@@ -138,6 +142,9 @@ private:
 
     /** 本地 plan:按 input.stage 决定动作并提交 StageAction(每个 input.id 只发一次) */
     void autoPlan(int station, const QJsonObject &st);
+    /** 0.8.1.18:StartTest 前将 ICT1 / AMT / ICT2 / MT 意图预置到后端;
+     *  SetStageIntent 成功后由后端在对应提示符自动消费,失败时回退旧 autoPlan。 */
+    void stageStationIntents(int station);
     void submitStageAction(int station, const QString &inputId, const QString &action,
                            const QJsonObject &extra);
     void pollCommand(const QString &commandId);
@@ -191,6 +198,14 @@ private:
     bool m_connOfflineWarned[4] = {false, false, false, false}; // offline 但 UART 仍在流,只提示一次
     // 上一次已写进工位日志的 stage_errors(0.8.1.13):内容没变就不重复刷
     QString m_stageErrorsJson[4];
+    // 手册 9.2:每个工位最后一次报过 complete=true 的 command_id
+    // (GetCommand 会反复轮询同一结果对象,用最后一个 id 去重即可,不会无限增长)。
+    // 工位级 task_status 也在这里去重,避免每秒一包 state 把日志刷屏。
+    QString m_lastCompleteCmd[4];
+    QString m_lastTaskCompleteBoot[4]; // 命令 complete / task_complete 共用的队列终态去重
+    QString m_lastTaskCompleteEventBoot[4]; // task_complete 快照独立去重,不能被命令回执抢先占位
+    bool m_waitingNewBoot[4] = {false, false, false, false}; // StartTest 后忽略旧 boot_id 的迟到终态事件
+    QString m_lastTaskStatus[4];
     // 上一次的 verdict:只在变成 fail 的那一下记一条异常(pass/idle/unknown 不记)
     QString m_lastVerdict[4];
     // 最近的 input.id(list_uefi_files 要原样带回,否则后端认不出当前节点)
@@ -203,15 +218,17 @@ private:
     QSet<QString> m_stageDoneKeys[4];   // 已处理过的「阶段/CPU」:uip1/0、uip2/1…
     QString m_stagePendingCmd[4];       // 该工位在途的 StageAction command_id(空=空闲)
     QString m_stagePendingKey[4];       // 在途动作对应的「阶段/CPU」键
+    QSet<QString> m_stageIntentPending[4]; // SetStageIntent 请求在途的阶段键,避免同时发旧 StageAction
+    QSet<QString> m_stageIntentReady[4];   // 已成功预置的阶段键,由后端自动消费
     QSet<int> m_appliedCpu[4];          // 本轮已下发内存参数的 CPU(每个 CPU 的 UIP1 各一次)
     QString m_bootId[4];                // 本轮 boot_id,变化则清空 appliedCpu
     bool m_autoPaused = false;          // 断线时暂停全部自动下发
     bool m_stationPaused[4] = {false, false, false, false};   // 某工位失败后单独暂停
     bool m_startPending[4] = {false, false, false, false};    // 该工位 StartTest 未到终态
+    bool m_blockedWarned[4] = {false, false, false, false};   // 本轮换条停机已提示过(boot_id 变化才重置)
     QString m_startCmd[4];              // 该工位在途 StartTest 的 command_id(放弃跟踪时要一并放开)
-    QJsonArray m_stationTasks[4];       // 各工位本轮任务列表(随 UIP1 的 StageAction 下发)
-    QJsonObject m_memoryParams[4];      // 各工位本地保存的内存参数(UIP1 下发)
-    QJsonObject m_rmtParams[4];         // 各工位本地保存的 RMT 参数(UIP1 的 run_rmt)
+    QJsonObject m_memoryParams[4];      // 各工位本地保存的内存参数(ICT1 下发)
+    QJsonObject m_rmtParams[4];         // 各工位本地保存的 RMT 参数(ICT1 的 run_rmt)
     QJsonObject m_amtParams[4];         // 各工位本地保存的 AMT 参数(AMT 节点下发)
     QJsonObject m_mtParams[4];          // 各工位本地保存的 MT 参数(UEFI Shell 节点下发)
 

+ 8 - 3
src/comanager.cpp

@@ -52,8 +52,13 @@ void ComManager::setTargetTemp(int index, int celsius)
                               Q_ARG(int, celsius));
 }
 
-void ComManager::sendTestEndCommand(int index)
+void ComManager::sendTestEndCommand(int index, bool dissipate)
 {
-    QMetaObject::invokeMethod(m_worker, "sendTestEnd", Qt::QueuedConnection,
-                              Q_ARG(int, index));
+    // 用 functor 形式的 invokeMethod:slot 刚加了 bool 参数,字符串签名一旦写错
+    // 编译期查不出来、运行时只会静默不下发帧。这样由编译器直接检查调用是否合法,
+    // 闭包仍排在 m_worker 所在线程执行(等同于原来的 QueuedConnection)。
+    ComWorker *worker = m_worker;
+    QMetaObject::invokeMethod(m_worker, [worker, index, dissipate]() {
+        worker->sendTestEnd(index, dissipate);
+    }, Qt::QueuedConnection);
 }

+ 4 - 3
src/comanager.h

@@ -30,8 +30,9 @@ public:
     // 给某个工位的 MCU 下发目标温度(AA 55 01 01 TEMP CRC8,70℃ → AA 55 01 01 46 37)
     void setTargetTemp(int index, int celsius);
 
-    // 测试结束后给该工位 MCU 下发 AA 55 08 00 2F(一次性)
-    void sendTestEndCommand(int index);
+    // 测试结束后给该工位 MCU 下发 0x08(一次性)。
+    // dissipate=true  → AA 55 08 01 00 D8 散热;false → AA 55 08 01 01 DF 不散热
+    void sendTestEndCommand(int index, bool dissipate = true);
 
 signals:
     void stateChanged(int index, int state, const QString &portName, const QString &detail);
@@ -45,7 +46,7 @@ signals:
     void targetTempReplied(int index, int status);
 
     // 测试结束命令下发结果(转发自 ComWorker)
-    void testEndSent(int index, bool ok);
+    void testEndSent(int index, bool ok, bool dissipate);
 
 private:
     QThread *m_thread;

+ 8 - 8
src/comworker.cpp

@@ -121,10 +121,10 @@ void ComWorker::poll()
         if (!slot.sp || !slot.sp->isOpen())
             continue;
 
-        // 两条读命令每 1000ms 各发一次:0x0D 取 CT7428 八路,0x02 取 24 路 BMC。
+        // 每 1000ms 只请求本板 CT7428 八路温度(0x0D)。
+        // 24 路内存温度改由后端 channels[i].temperature_c 推送,不再向 MCU 发送 0x02 请求。
         // 应答是异步回来的,由 readyRead 里的 handleReply() 处理,不等在这里。
         slot.sp->write(slt::frameRequestCt7428());
-        slot.sp->write(slt::frameRequestChannels());
     }
 }
 
@@ -148,7 +148,7 @@ void ComWorker::setTargetTemp(int index, int celsius)
     emit targetTempSent(index, celsius, true);
 }
 
-void ComWorker::sendTestEnd(int index)
+void ComWorker::sendTestEnd(int index, bool dissipate)
 {
     if (index < 0 || index >= m_slots.size())
         return;
@@ -156,16 +156,16 @@ void ComWorker::sendTestEnd(int index)
     Slot &slot = m_slots[index];
     if (!slot.sp || !slot.sp->isOpen()) {
         qInfo().noquote() << "[com]" << index << "串口未打开,测试结束命令未下发";
-        emit testEndSent(index, false);
+        emit testEndSent(index, false, dissipate);
         return;
     }
 
-    const QByteArray frame = slt::frameTestEnd();   // AA 55 08 00 2F
+    const QByteArray frame = slt::frameTestEnd(dissipate);
     slot.sp->write(frame);
     slot.sp->flush();                               // 立即把这一帧推出去,不等轮询节拍
-    qInfo().noquote() << "[com]" << index << "测试结束,下发 →"
-                      << QString::fromLatin1(frame.toHex(' ').toUpper());
-    emit testEndSent(index, true);
+    qInfo().noquote() << "[com]" << index << (dissipate ? "测试结束(散热)" : "测试结束(不散热,等待下一任务)")
+                      << "下发 →" << QString::fromLatin1(frame.toHex(' ').toUpper());
+    emit testEndSent(index, true, dissipate);
 }
 
 void ComWorker::handleReply(int index, Slot &slot)

+ 9 - 6
src/comworker.h

@@ -22,9 +22,9 @@ class QTimer;
  *   · kScanIntervalMs  —— 端口热插拔扫描(1500ms),负责「连没连上」;
  *   · kPollIntervalMs  —— 温度轮询(1000ms),只在端口已打开时下发请求帧。
  *
- * 轮询发的就是协议里的两条读命令:
+ * 温度轮询只请求本板 CT7428:
  *   0x0D → 0x8D   本板 CT7428 八路温度(8 字节)→ 取平均当「腔体温度」
- *   0x02 → 0x82   24 路 BMC 温度(24 字节)    → 一路一格填到 24 通道
+ * 24 路内存条温度由后端 channels[i].temperature_c 推送,不再请求 MCU 的 0x02/0x82。
  * 原始字节不做换算,原样发给主线程:本文件只管「字节进、帧出」。
  */
 class ComWorker : public QObject
@@ -54,8 +54,9 @@ signals:
     // 设备对 0x01 的应答:status=0x01 成功(已自动开始预加热)、0x00 被拒
     void targetTempReplied(int index, int status);
 
-    // 测试结束命令(AA 55 08 00 2F)下发结果:ok=false 表示该工位串口没打开
-    void testEndSent(int index, bool ok);
+    // 测试结束命令(0x08 + 模式载荷)下发结果:ok=false 表示该工位串口没打开
+    // dissipate=true 散热(00 D8)/ false 不散热(01 DF)
+    void testEndSent(int index, bool ok, bool dissipate);
 
 public slots:
     void configure(int index, const QString &port, const QString &serialNumber, int baud);
@@ -66,8 +67,10 @@ public slots:
     // 0x01 会连带启动预加热,所以只在「点开始测试」这种明确的时机调用,不要周期发。
     void setTargetTemp(int index, int celsius);
 
-    // 测试结束:给该工位 MCU 下发一次性命令 AA 55 08 00 2F(不轮询、不等应答)
-    void sendTestEnd(int index);
+    // 测试结束:给该工位 MCU 下发一次性 0x08 命令(不轮询、不等应答)。
+    // dissipate=true  → AA 55 08 01 00 D8(清状态 + 散热吹扫)
+    // dissipate=false → AA 55 08 01 01 DF(只清状态、不散热,后面还有任务要接着跑)
+    void sendTestEnd(int index, bool dissipate);
 
 private slots:
     void tick();          // 1500ms:端口热插拔扫描

+ 172 - 29
src/createtaskdialog.cpp

@@ -28,6 +28,7 @@
 #include <QListWidgetItem>
 #include <QMimeData>
 #include <QPushButton>
+#include <QTabWidget>
 #include <QTimer>
 #include <QToolButton>
 #include <QVBoxLayout>
@@ -173,7 +174,8 @@ public:
     }
 
     std::function<void(int)> onTaskDropped;
-    std::function<bool()> canDrop;     // 机台离线时返回 false,任务拖不进来
+    std::function<bool()> canDrop;            // 机台离线时返回 false,任务拖不进来
+    std::function<bool(int)> canDropTask;     // 这条任务本身不许拖入(例如正在执行中)
 
 protected:
     void dragEnterEvent(QDragEnterEvent *e) override
@@ -183,6 +185,15 @@ protected:
         // 这个机台显示「控制台离线」时不接收任务:直接忽略,鼠标会显示禁止图标
         if (canDrop && !canDrop())
             return;
+        // 执行中的任务不允许再添加:拖过来的 mimeData 里就是任务 id,
+        // 在 enter 阶段拒掉,鼠标直接显示禁止,不用等松手再弹提示。
+        if (canDropTask) {
+            const QByteArray b = e->mimeData()->data(QString::fromLatin1(kTaskMime));
+            bool ok = false;
+            const int taskId = b.toInt(&ok);
+            if (ok && !canDropTask(taskId))
+                return;
+        }
         e->acceptProposedAction();
         setProperty("dragOver", true);
         style()->polish(this);
@@ -210,7 +221,8 @@ protected:
 
 // 删除类操作的确认框。样式跟项目其它弹窗一致:白底圆角卡片 + 蓝色主按钮,
 // 不用系统 QMessageBox(灰底 + 系统图标,和蓝白扁平界面不搭)。
-bool confirmRemove(QWidget *parent, const QString &title, const QString &detail)
+bool confirmRemove(QWidget *parent, const QString &title, const QString &detail,
+                   bool showCancel = true)
 {
     QDialog dlg(parent);
     dlg.setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
@@ -250,31 +262,42 @@ bool confirmRemove(QWidget *parent, const QString &title, const QString &detail)
     foot->setContentsMargins(0, 0, 0, 0);
     foot->setSpacing(10);
     foot->addStretch(1);
-    QPushButton *cancel = new QPushButton(QStringLiteral("取消"), card);
-    cancel->setStyleSheet(QStringLiteral(
-        "QPushButton { color:#2f7fc1; background:#ffffff; border:1px solid #cdd7e1;"
-        " border-radius:4px; padding:5px 16px; font-size:14px; }"
-        "QPushButton:hover { background:#eef4fa; border-color:#b9cfe2; }"));
-    QPushButton *ok = new QPushButton(QStringLiteral("确定"), card);
+    QPushButton *cancel = nullptr;
+    if (showCancel) {
+        cancel = new QPushButton(QStringLiteral("取消"), card);
+        cancel->setStyleSheet(QStringLiteral(
+            "QPushButton { color:#2f7fc1; background:#ffffff; border:1px solid #cdd7e1;"
+            " border-radius:4px; padding:5px 16px; font-size:14px; }"
+            "QPushButton:hover { background:#eef4fa; border-color:#b9cfe2; }"));
+        cancel->setCursor(Qt::PointingHandCursor);
+        foot->addWidget(cancel);
+        QObject::connect(cancel, &QPushButton::clicked, &dlg, &QDialog::reject);
+    }
+    QPushButton *ok = new QPushButton(
+        showCancel ? QStringLiteral("确定") : QStringLiteral("知道了"), card);
     ok->setStyleSheet(QStringLiteral(
         "QPushButton { color:#ffffff; background:#2f7fc1; border:1px solid #2f7fc1;"
         " border-radius:4px; padding:5px 16px; font-size:14px; }"
         "QPushButton:hover { background:#2a72ad; border-color:#2a72ad; }"));
     ok->setDefault(true);
-    cancel->setCursor(Qt::PointingHandCursor);
     ok->setCursor(Qt::PointingHandCursor);
-    foot->addWidget(cancel);
     foot->addWidget(ok);
     body->addLayout(foot);
 
-    QObject::connect(cancel, &QPushButton::clicked, &dlg, &QDialog::reject);
     QObject::connect(ok, &QPushButton::clicked, &dlg, &QDialog::accept);
     return dlg.exec() == QDialog::Accepted;
 }
 
+// 只给一条说明、不需要用户做「确定/取消」的判断(例如执行中任务禁止删除)。
+void showNotice(QWidget *parent, const QString &title, const QString &detail)
+{
+    confirmRemove(parent, title, detail, false);
+}
+
 // 输入任务名字的小弹窗。样式跟 confirmRemove / ResultToast 一套:
 // 白底圆角卡片 + 蓝色主按钮,不用系统 QInputDialog 的灰底。
-bool promptTaskName(QWidget *parent, const QString &defaultName, QString *out)
+bool promptTaskName(QWidget *parent, const QString &defaultName,
+                    const QStringList &existingNames, QString *out)
 {
     QDialog dlg(parent);
     dlg.setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
@@ -317,6 +340,12 @@ bool promptTaskName(QWidget *parent, const QString &defaultName, QString *out)
     body->addWidget(title);
     body->addWidget(label);
     body->addWidget(edit);
+    QLabel *err = new QLabel(card);
+    err->setObjectName(QStringLiteral("nameError"));
+    err->setStyleSheet(QStringLiteral("QLabel#nameError { color:#c92f2f; font-size:13px; }"));
+    err->setWordWrap(true);
+    err->hide();
+    body->addWidget(err);
 
     QHBoxLayout *foot = new QHBoxLayout();
     foot->setContentsMargins(0, 0, 0, 0);
@@ -340,7 +369,23 @@ bool promptTaskName(QWidget *parent, const QString &defaultName, QString *out)
     body->addLayout(foot);
 
     QObject::connect(cancel, &QPushButton::clicked, &dlg, &QDialog::reject);
-    QObject::connect(ok, &QPushButton::clicked, &dlg, &QDialog::accept);
+    // 任务名不能重复:重名时就在输入框下方红字提示,不关窗、让用户直接改。
+    QObject::connect(ok, &QPushButton::clicked, &dlg, [&]() {
+        const QString name = edit->text().trimmed();
+        if (name.isEmpty()) {
+            dlg.reject();
+            return;
+        }
+        if (existingNames.contains(name)) {
+            err->setText(QStringLiteral("任务名「%1」已存在,请换一个名字").arg(name));
+            err->show();
+            edit->setFocus();
+            edit->selectAll();
+            return;
+        }
+        dlg.accept();
+    });
+    QObject::connect(edit, &QLineEdit::textChanged, err, &QLabel::hide);
     QObject::connect(edit, &QLineEdit::returnPressed, ok, &QPushButton::click);
     edit->setFocus();
 
@@ -444,6 +489,14 @@ CreateTaskDialog::CreateTaskDialog(QWidget *parent)
     connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &CreateTaskDialog::createTask);
     connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
 
+    // 「任务分配」页不需要底部的「创建任务 / 关闭」:只有「创建任务」页(index 0)显示。
+    // 切页时同步;分配页仍可用右上角 X(或 Esc)关窗。
+    auto syncFooter = [this](int index) {
+        ui->buttonBox->setVisible(index == 0);
+    };
+    connect(ui->taskTabs, &QTabWidget::currentChanged, this, syncFooter);
+    syncFooter(ui->taskTabs->currentIndex());
+
     ui->targetTempEdit->setValidator(new QIntValidator(40, 90, ui->targetTempEdit));
 
     // 配置页的初始值取 S1 已存配置(不再按工位分别维护一份)
@@ -561,6 +614,7 @@ void CreateTaskDialog::buildAssignTab()
         clear->setText(QStringLiteral("清空"));
         clear->setCursor(Qt::PointingHandCursor);
         clear->setProperty("role", "algoMini");
+        m_stationClearBtns.append(clear);
         head->addWidget(title);
         head->addWidget(status);
         head->addStretch(1);
@@ -579,6 +633,8 @@ void CreateTaskDialog::buildAssignTab()
         connect(clear, &QToolButton::clicked, this, [this, i]() { clearStation(i); });
         zone->onTaskDropped = [this, i](int taskId) { assignTask(i, taskId); };
         zone->canDrop = [this, i]() { return m_onlineProbe ? m_onlineProbe(i) : true; };
+        // 执行中的任务鼠标直接显示禁止图标,松手也不会被添加
+        zone->canDropTask = [this](int taskId) { return !isTaskRunning(taskId); };
         cardLay->addWidget(zone);
 
         grid->addWidget(card, i / 2, i % 2);
@@ -600,9 +656,14 @@ void CreateTaskDialog::buildAssignTab()
 // ---------------------------------------------------------------------------
 void CreateTaskDialog::createTask()
 {
-    // 先问任务名字:取消或留空都不建任务,也不占用编号
+    // 先问任务名字:取消或留空都不建任务,也不占用编号。
+    // 把已有任务名传进去,重名直接在输入框里红字提示,不生成第二条同名任务。
+    QStringList existingNames;
+    existingNames.reserve(m_tasks.size());
+    for (const SltTask &t : m_tasks)
+        existingNames.append(t.name);
     QString taskName;
-    if (!promptTaskName(this, QStringLiteral("高温标参"), &taskName))
+    if (!promptTaskName(this, QStringLiteral("高温标参"), existingNames, &taskName))
         return;
 
     SltTask t;
@@ -611,14 +672,7 @@ void CreateTaskDialog::createTask()
     t.cfg = currentConfig();
     m_tasks.append(t);
     refreshTaskList();
-    ui->taskTabs->setCurrentIndex(1);
-
-    if (QPushButton *btn = ui->buttonBox->button(QDialogButtonBox::Ok)) {
-        btn->setText(QStringLiteral("已创建"));
-        QTimer::singleShot(1200, this, [btn]() {
-            btn->setText(QStringLiteral("创建任务"));
-        });
-    }
+    ui->taskTabs->setCurrentIndex(1);   // 切到任务分配页,底部按钮随之隐藏
 }
 
 void CreateTaskDialog::refreshTaskList()
@@ -641,13 +695,20 @@ void CreateTaskDialog::deleteSelectedTask()
 {
     if (!m_taskList || !m_taskList->currentItem())
         return;
+    const int id = m_taskList->currentItem()->data(Qt::UserRole).toInt();
+    // 执行中的任务不能删:删了会让本地队列和 qt-plans.json 对不上
+    if (isTaskRunning(id)) {
+        showNotice(this, QStringLiteral("任务执行中"),
+                   QStringLiteral("「%1」正在执行中,不能删除。请等本轮结束后再操作。")
+                       .arg(taskNameOf(id)));
+        return;
+    }
     const QString name = m_taskList->currentItem()->text();
     if (!confirmRemove(this, QStringLiteral("删除任务"),
                        QStringLiteral("确定删除任务「%1」吗?\n"
                                       "已分配到机台的这条任务也会一并移除。").arg(name)))
         return;
 
-    const int id = m_taskList->currentItem()->data(Qt::UserRole).toInt();
     for (int i = 0; i < m_tasks.size(); ++i) {
         if (m_tasks.at(i).id == id) {
             m_tasks.removeAt(i);
@@ -656,8 +717,10 @@ void CreateTaskDialog::deleteSelectedTask()
     }
     // 已经挂到机台的任务也要从各机台列表里摘掉并重写该工位 JSON
     for (int s = 0; s < m_stationTaskIds.size(); ++s) {
-        if (m_stationTaskIds[s].removeAll(id) > 0)
-            saveStationTasks(s);
+        if (m_stationTaskIds[s].removeAll(id) > 0) {
+            m_saved = saveStationTasks(s);
+            emit configsSaved(m_saved, s, QStringLiteral("删除"));
+        }
     }
     refreshTaskList();
     refreshStationBoxes();
@@ -677,6 +740,17 @@ void CreateTaskDialog::refreshStationStatus()
         label->style()->unpolish(label);
         label->style()->polish(label);
     }
+
+    // 「执行中」状态随时会变(任务起跑 / 跑完),每秒同步一次「清空」按钮,
+    // 免得按钮还停留在上一次的状态。逻辑层 clearStation() 也实时兜底拦截。
+    for (int s = 0; s < m_stationClearBtns.size(); ++s) {
+        QToolButton *btn = m_stationClearBtns.at(s);
+        if (!btn)
+            continue;
+        const bool locked = stationHasRunningTask(s);
+        btn->setEnabled(!locked);
+        btn->setToolTip(locked ? QStringLiteral("有任务执行中,不能清空") : QString());
+    }
 }
 
 void CreateTaskDialog::refreshStationBoxes()
@@ -710,13 +784,19 @@ void CreateTaskDialog::refreshStationBoxes()
                 QHBoxLayout *chipLay = new QHBoxLayout(chip);
                 chipLay->setContentsMargins(8, 3, 4, 3);
                 chipLay->setSpacing(6);
+                const bool running = isTaskRunning(id);
                 QLabel *label = new QLabel(QStringLiteral("%1.  %2").arg(n + 1).arg(name), chip);
                 label->setProperty("role", "taskName");
+                if (running)
+                    label->setToolTip(QStringLiteral("任务执行中,暂不能移除"));
                 QToolButton *close = new QToolButton(chip);
                 close->setText(QStringLiteral("×"));
                 close->setCursor(Qt::PointingHandCursor);
                 close->setFocusPolicy(Qt::NoFocus);   // 同理,点完不留焦点虚框
                 close->setProperty("role", "algoMini");
+                close->setEnabled(!running);
+                close->setToolTip(running ? QStringLiteral("任务执行中,不能移除")
+                                          : QStringLiteral("从该机台移除这条任务"));
                 chipLay->addWidget(label);
                 chipLay->addStretch(1);
                 chipLay->addWidget(close);
@@ -727,6 +807,7 @@ void CreateTaskDialog::refreshStationBoxes()
         }
         lay->addStretch(1);
     }
+    refreshStationStatus();   // 重铺后立刻同步「清空」按钮的可用状态
 }
 
 // 把该机台当前的任务列表写进 qt-plans.json:
@@ -773,10 +854,48 @@ void CreateTaskDialog::setOnlineProbe(std::function<bool(int)> probe)
     m_onlineProbe = std::move(probe);
 }
 
+void CreateTaskDialog::setRunningProbe(std::function<bool(const QString &)> probe)
+{
+    m_runningProbe = std::move(probe);
+}
+
+QString CreateTaskDialog::taskNameOf(int taskId) const
+{
+    for (const SltTask &t : m_tasks)
+        if (t.id == taskId)
+            return t.name;
+    return QString();
+}
+
+bool CreateTaskDialog::isTaskRunning(int taskId) const
+{
+    // 任务名是唯一键(创建时已禁止重名),主窗口按「当前工位正在跑的那条任务名」判定。
+    const QString name = taskNameOf(taskId);
+    return !name.isEmpty() && m_runningProbe && m_runningProbe(name);
+}
+
+bool CreateTaskDialog::stationHasRunningTask(int station) const
+{
+    if (station < 0 || station >= m_stationTaskIds.size())
+        return false;
+    for (int id : m_stationTaskIds.at(station))
+        if (isTaskRunning(id))
+            return true;
+    return false;
+}
+
 void CreateTaskDialog::assignTask(int station, int taskId)
 {
     if (station < 0 || station >= m_stationTaskIds.size())
         return;
+    // 执行中的任务不能再挂到任何机台。dragEnter 已挡一层,这里再兜底:
+    // 拖拽过程中该任务可能刚好开始跑。
+    if (isTaskRunning(taskId)) {
+        showNotice(this, QStringLiteral("任务执行中"),
+                   QStringLiteral("「%1」正在执行中,不能添加到任务框。请等本轮结束后再操作。")
+                       .arg(taskNameOf(taskId)));
+        return;
+    }
     // 机台显示「控制台离线」时不接收任务(拖拽时已被 dragEnterEvent 拒了,这里双保险)
     if (m_onlineProbe && !m_onlineProbe(station))
         return;
@@ -792,7 +911,7 @@ void CreateTaskDialog::assignTask(int station, int taskId)
 
     // 不再有顶部文字反馈:拖进去之后机台框里直接出现任务条,那就是反馈。
     // 也避免连续拖多条时被弹窗 / 提示打断。
-    emit configsSaved(m_saved, station);
+    emit configsSaved(m_saved, station, QStringLiteral("分配"));
 }
 
 void CreateTaskDialog::removeTask(int station, int taskId)
@@ -801,6 +920,12 @@ void CreateTaskDialog::removeTask(int station, int taskId)
         return;
     if (!m_stationTaskIds.at(station).contains(taskId))
         return;
+    if (isTaskRunning(taskId)) {
+        showNotice(this, QStringLiteral("任务执行中"),
+                   QStringLiteral("「%1」正在执行中,不能从任务框移除。请等本轮结束后再操作。")
+                       .arg(taskNameOf(taskId)));
+        return;
+    }
 
     QString name;
     for (const SltTask &t : m_tasks)
@@ -814,6 +939,7 @@ void CreateTaskDialog::removeTask(int station, int taskId)
     m_stationTaskIds[station].removeAll(taskId);
     m_saved = saveStationTasks(station);
     refreshStationBoxes();
+    emit configsSaved(m_saved, station, QStringLiteral("移除"));
 }
 
 void CreateTaskDialog::clearStation(int station)
@@ -822,6 +948,12 @@ void CreateTaskDialog::clearStation(int station)
         return;
     if (m_stationTaskIds.at(station).isEmpty())
         return;
+    // 框里只要有一条执行中的任务就整框拒绝清空,避免连正在跑的那条一起删掉
+    if (stationHasRunningTask(station)) {
+        showNotice(this, QStringLiteral("有任务执行中"),
+                   QStringLiteral("该机台有正在执行的任务,不能清空。请等本轮结束后再操作。"));
+        return;
+    }
 
     const QString dev = QStringLiteral("SLT-HT-%1").arg(station + 1, 3, 10, QLatin1Char('0'));
     if (!confirmRemove(this, QStringLiteral("清空任务"),
@@ -832,6 +964,7 @@ void CreateTaskDialog::clearStation(int station)
     m_stationTaskIds[station].clear();
     m_saved = saveStationTasks(station);
     refreshStationBoxes();
+    emit configsSaved(m_saved, station, QStringLiteral("清空"));
 }
 
 // ---------------------------------------------------------------------------
@@ -872,7 +1005,11 @@ void CreateTaskDialog::loadUiFrom(const QJsonObject &cfg)
     auto apply = [](QListWidget *list, const QJsonObject &sec) {
         if (!sec.contains(QStringLiteral("selected")))
             return;
-        const QStringList sel = fromArray(sec.value(QStringLiteral("selected")));
+        QStringList sel = fromArray(sec.value(QStringLiteral("selected")));
+        for (QString &s : sel) {
+            if (s == QLatin1String("Adress test, walking ones, 1 CPU"))
+                s = QStringLiteral("Address test, walking ones, 1 CPU");
+        }
         const QList<QCheckBox *> cbs = algoChecks(list);
         // 存档里的名字一个都对不上当前清单 = 清单换过版,按全选处理,
         // 避免整组显示 0/N 把该阶段静默关掉。空数组是用户主动清空,照旧全不选。
@@ -917,7 +1054,13 @@ void CreateTaskDialog::refreshAll()
 
 QJsonObject CreateTaskDialog::params() const
 {
-    QJsonObject o;
+    // 保留后端 0.8.1.19 支持的扩展 ICT 目录参数(最多 224 项)。
+    // 当前表单只编辑常用快捷项,其余已从 config.json / qt-plans.json 载入的键
+    // 必须原样留在任务配置里,不能在创建任务时被空对象覆盖掉。
+    QJsonObject o = m_baseCfg.value(QStringLiteral("memory_params")).toObject();
+    if (o.isEmpty())
+        o = configMemoryParams();
+
     for (int i = 0; i < kKeyCount; ++i) {
         QLineEdit *ed = findChild<QLineEdit *>(QStringLiteral("paramEdit_%1").arg(i));
         if (!ed || ed->text().trimmed().isEmpty())

+ 13 - 2
src/createtaskdialog.h

@@ -47,14 +47,20 @@ public:
      *  返回 false 的机台,任务拖不进它的任务框。每次拖拽时实时回调,不用手动同步状态。 */
     void setOnlineProbe(std::function<bool(int)> probe);
 
+    /** 主窗口注入「任务名是否正在某个工位执行中」的判定。执行中的任务:
+     *  既不能拖进任务框,也不能从任务框移除 / 清空 / 在任务池里删除。
+     *  每次操作实时回调,任务一跑完就自动解禁。 */
+    void setRunningProbe(std::function<bool(const QString &taskName)> probe);
+
     QJsonObject params() const;                 // 当前 UI 的内存参数 + 4 个开关 + 目标温度
     QStringList algorithms() const;             // 选中的 MT 算法文本
     QStringList amtAlgorithms() const;          // 选中的 AMT 算法
     QStringList rmtAlgorithms() const;          // 选中的 RMT 命令
 
 signals:
-    /** 任务拖入某个机台、配置写入 qt-plans.json 后立即发出;窗口仍开着 */
-    void configsSaved(bool ok, int station);
+    /** 机台任务发生变更(分配 / 移除 / 清空 / 删除)、配置写入 qt-plans.json 后立即发出;
+     *  窗口仍开着。action 只用于上层日志区分是哪种变更,空值按「分配」处理。 */
+    void configsSaved(bool ok, int station, QString action = QString());
 
 private:
     void buildAssignTab();                       // 代码构造「任务分配」页
@@ -70,6 +76,9 @@ private:
     QJsonObject currentConfig() const;           // Tab1 当前 UI → 整份配置
     void loadUiFrom(const QJsonObject &cfg);
     void refreshAll();
+    QString taskNameOf(int taskId) const;        // id → 任务名(找不到返回空串)
+    bool isTaskRunning(int taskId) const;        // 该任务是否正在执行中
+    bool stationHasRunningTask(int station) const;
 
     Ui::createTaskDialog *ui;
     QJsonObject m_baseCfg;                       // Tab1 初始默认值(S1 已存配置)
@@ -79,7 +88,9 @@ private:
     QListWidget *m_taskList = nullptr;
     QVector<QVBoxLayout *> m_stationChipLays;    // 机台任务框里放任务条
     QVector<QLabel *> m_stationStatus;           // 机台标题右侧「在线 / 离线」
+    QVector<QToolButton *> m_stationClearBtns;   // 每个机台的「清空」按钮
     std::function<bool(int)> m_onlineProbe;      // 机台是否可用(离线则拒收任务)
+    std::function<bool(const QString &)> m_runningProbe;  // 任务是否执行中
     bool m_saved = false;
 };
 

+ 64 - 4
src/createtaskdialog.ui

@@ -777,7 +777,7 @@
           <item>
            <widget class="QLabel" name="mtBadge">
             <property name="text">
-             <string>14/14</string>
+             <string>26/26</string>
             </property>
             <property name="role" stdset="0">
              <string>algoBadge</string>
@@ -821,14 +821,14 @@
            </size>
           </property>
           <property name="verticalScrollBarPolicy">
-           <enum>Qt::ScrollBarAlwaysOff</enum>
+           <enum>Qt::ScrollBarAsNeeded</enum>
           </property>
           <property name="selectionMode">
            <enum>QAbstractItemView::NoSelection</enum>
           </property>
           <item>
            <property name="text">
-            <string>Adress test, walking ones, 1 CPU</string>
+            <string>Address test, walking ones, 1 CPU</string>
            </property>
           </item>
           <item>
@@ -896,12 +896,72 @@
             <string>Hammer test</string>
            </property>
           </item>
+          <item>
+           <property name="text">
+            <string>DMA test (experimental)</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>March C algorithm</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>Galloping Pattern (GALPAT)</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>Galloping Pattern (LINEAR)</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>Galloping Pattern (RANDOMADDRESS)</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>Galloping Pattern (BANKJUMP)</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>Galloping Pattern (VICTIM)</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>Galloping Pattern (MARCHIC)</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>Galloping Pattern (MARCHSSE)</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>Galloping Pattern (BUTTERFLY)</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>March SS+ algorithm</string>
+           </property>
+          </item>
+          <item>
+           <property name="text">
+            <string>Stressapp memory stress test</string>
+           </property>
+          </item>
          </widget>
         </item>
         <item>
          <widget class="QLabel" name="mtFoot">
           <property name="text">
-           <string>共 14 项 · 已选 14 项</string>
+           <string>共 26 项 · 已选 26 项</string>
           </property>
           <property name="role" stdset="0">
            <string>algoFoot</string>

+ 18 - 1
src/detailview.cpp

@@ -206,6 +206,7 @@ void DetailView::renderTasks(int station)
     const StationData &cur = m_store->station(station);
     m_lastTaskDone = cur.taskDone;
     m_lastTaskCurrent = cur.taskCurrent;
+    m_lastBackendTaskStatus = cur.taskStatus;
     m_lastAwaitingDimm = cur.awaitingDimmReplacement;
 
     if (cur.awaitingDimmReplacement) {
@@ -253,6 +254,20 @@ void DetailView::renderTasks(int station)
         if (d.taskCurrent >= 0 && i == d.taskCurrent) {
             state = QStringLiteral("running");
             stateText = QStringLiteral("执行中");
+            // 手册 9.2:后端 task_status / awaiting_dimm_replacement 比本地进度更精确,
+            // 直接用于「当前任务」这一条的显示;其余任务仍按本地队列进度。
+            if (d.awaitingDimmReplacement) {
+                state = QStringLiteral("failed");
+                stateText = QStringLiteral("等待换条");
+            } else if (d.taskStatus == QStringLiteral("queued")) {
+                stateText = QStringLiteral("排队中");
+            } else if (d.taskStatus == QStringLiteral("failed")) {
+                state = QStringLiteral("failed");
+                stateText = QStringLiteral("执行失败");
+            } else if (d.taskStatus == QStringLiteral("completed")) {
+                state = QStringLiteral("done");
+                stateText = QStringLiteral("已完成");
+            }
         } else if (i < d.taskDone) {
             state = QStringLiteral("done");
             stateText = QStringLiteral("已完成");
@@ -577,7 +592,7 @@ void DetailView::showStation(int index)
     m_ui->pageStack->setCurrentIndex(1);
 
     // 纯内存渲染,不依赖任何异步取数 —— 点开即出
-    loadParams(index);       // 参数页铺该工位已保存的 UIP + AMT 参数
+    loadParams(index);       // 参数页铺该工位已保存的 ICT + AMT + MT 任务参数
     markCurveChannel();      // 高亮当前曲线对应的通道(默认 CPU0_CHA)
     renderAll();
 
@@ -980,9 +995,11 @@ void DetailView::flushPending()
     // 没变不动,免得每秒的 state 推送都在重建控件。
     if (m_ui->detailTabStack->currentIndex() == 2) {
         if (d.taskDone != m_lastTaskDone || d.taskCurrent != m_lastTaskCurrent
+            || d.taskStatus != m_lastBackendTaskStatus
             || d.awaitingDimmReplacement != m_lastAwaitingDimm) {
             m_lastTaskDone = d.taskDone;
             m_lastTaskCurrent = d.taskCurrent;
+            m_lastBackendTaskStatus = d.taskStatus;
             m_lastAwaitingDimm = d.awaitingDimmReplacement;
             renderTasks(m_index);
         }

+ 1 - 0
src/detailview.h

@@ -80,6 +80,7 @@ private:
 
     int m_lastTaskDone = -1;        // 上次铺任务列表时的进度,用来避免每秒重铺
     int m_lastTaskCurrent = -2;
+    QString m_lastBackendTaskStatus;  // 手册 9.2:后端 task_status 变化也要重铺任务条
     bool m_lastAwaitingDimm = false;
 
     Ui::MainWindow *m_ui;

+ 417 - 315
src/localplans.cpp

@@ -1,315 +1,417 @@
-#include "localplans.h"
-
-#include "appconfig.h"
-
-#include <QCoreApplication>
-#include <QDebug>
-#include <QDir>
-#include <QFile>
-#include <QFileInfo>
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QSaveFile>
-#include <QStringList>
-
-namespace {
-
-const char *const kPlansFile = "qt-plans.json";
-
-QString plansPath()
-{
-    return QDir(appWritableDir()).filePath(QString::fromLatin1(kPlansFile));
-}
-
-QJsonObject readRoot()
-{
-    QFile f(plansPath());
-    if (!f.open(QIODevice::ReadOnly))
-        return QJsonObject();
-    return QJsonDocument::fromJson(f.readAll()).object();
-}
-
-} // namespace
-
-QJsonObject LocalPlans::defaultsFromConfig()
-{
-    const QString path = appConfigPath(QStringLiteral("config.json"));
-    QFile f(path);
-    if (!f.open(QIODevice::ReadOnly))
-        return QJsonObject();
-    return QJsonDocument::fromJson(f.readAll()).object()
-            .value(QStringLiteral("memoryParams")).toObject();
-}
-
-QJsonObject LocalPlans::stationParams(int station)
-{
-    const QString key = QStringLiteral("S%1").arg(station + 1);
-    const QJsonObject saved = readRoot()
-            .value(QStringLiteral("stations")).toObject()
-            .value(key).toObject()
-            .value(QStringLiteral("memory_params")).toObject();
-    return saved.isEmpty() ? defaultsFromConfig() : saved;
-}
-
-QJsonObject LocalPlans::amtDefaultsFromConfig()
-{
-    const QString path = appConfigPath(QStringLiteral("config.json"));
-    QFile f(path);
-    if (!f.open(QIODevice::ReadOnly))
-        return QJsonObject();
-    return QJsonDocument::fromJson(f.readAll()).object()
-            .value(QStringLiteral("amtParams")).toObject();
-}
-
-QJsonObject LocalPlans::rmtDefaultsFromConfig()
-{
-    const QString path = appConfigPath(QStringLiteral("config.json"));
-    QFile f(path);
-    if (!f.open(QIODevice::ReadOnly))
-        return QJsonObject();
-    return QJsonDocument::fromJson(f.readAll()).object()
-            .value(QStringLiteral("rmtParams")).toObject();
-}
-
-QJsonObject LocalPlans::mtDefaultsFromConfig()
-{
-    const QString path = appConfigPath(QStringLiteral("config.json"));
-    QFile f(path);
-    if (!f.open(QIODevice::ReadOnly))
-        return QJsonObject();
-    return QJsonDocument::fromJson(f.readAll()).object()
-            .value(QStringLiteral("mtParams")).toObject();
-}
-
-QJsonObject LocalPlans::stationRmt(int station)
-{
-    const QString key = QStringLiteral("S%1").arg(station + 1);
-    const QJsonObject saved = readRoot()
-            .value(QStringLiteral("stations")).toObject()
-            .value(key).toObject()
-            .value(QStringLiteral("rmt")).toObject();
-    // 没保存过就用 config.json 的 rmtParams(手册 0.8.1.9 起默认启用)
-    return saved.isEmpty() ? rmtDefaultsFromConfig() : saved;
-}
-
-QJsonObject LocalPlans::stationAmt(int station)
-{
-    const QString key = QStringLiteral("S%1").arg(station + 1);
-    const QJsonObject saved = readRoot()
-            .value(QStringLiteral("stations")).toObject()
-            .value(key).toObject()
-            .value(QStringLiteral("amt")).toObject();
-    // 没保存过就用 config.json 的 amtParams(手册 0.8.1.9 起默认启用,跑 amemdiag 1)
-    return saved.isEmpty() ? amtDefaultsFromConfig() : saved;
-}
-
-QJsonObject LocalPlans::stationMt(int station)
-{
-    const QString key = QStringLiteral("S%1").arg(station + 1);
-    const QJsonObject saved = readRoot()
-            .value(QStringLiteral("stations")).toObject()
-            .value(key).toObject()
-            .value(QStringLiteral("mt")).toObject();
-    // 没保存过就用 config.json 的 mtParams(默认启用,跑 118.efi)
-    return saved.isEmpty() ? mtDefaultsFromConfig() : saved;
-}
-
-// ---------------------------------------------------------------------------
-// MT:本地参数 → StageAction(start_mt) 的 mt 字段(手册 0.8.1.13)
-// ---------------------------------------------------------------------------
-// 后端在 UEFI Shell> 下会自动写 mt86.cfg(默认 TSTLIST=0..13、全部可用内存、
-// EXITMODE=2 退回 Shell),再启动 118.efi。这里只把用户显式配置过的可选键
-// 透传给后端;空值 / 越界值一律丢弃,避免把半成品表单写进配置。
-// ---------------------------------------------------------------------------
-QJsonObject LocalPlans::mtStagePayload(const QJsonObject &mt)
-{
-    QJsonObject out;
-
-    const QString efiPath = mt.value(QStringLiteral("efi_path")).toString().trimmed();
-    if (!efiPath.isEmpty())
-        out.insert(QStringLiteral("efi_path"), efiPath);
-
-    const QString configPath = mt.value(QStringLiteral("config_path")).toString().trimmed();
-    if (!configPath.isEmpty())
-        out.insert(QStringLiteral("config_path"), configPath);
-
-    // memory_range:只认 "all" / "custom";省略等价于后端默认 all
-    const QString memRange = mt.value(QStringLiteral("memory_range")).toString().trimmed();
-    if (memRange == QStringLiteral("all") || memRange == QStringLiteral("custom"))
-        out.insert(QStringLiteral("memory_range"), memRange);
-
-    // 自定义地址区间:按手册示例保持字符串形式(如 "0x10000000")
-    const QString addrLo = mt.value(QStringLiteral("addr_lim_lo")).toString().trimmed();
-    const QString addrHi = mt.value(QStringLiteral("addr_lim_hi")).toString().trimmed();
-    if (!addrLo.isEmpty())
-        out.insert(QStringLiteral("addr_lim_lo"), addrLo);
-    if (!addrHi.isEmpty())
-        out.insert(QStringLiteral("addr_lim_hi"), addrHi);
-
-    // exit_mode:2 退回 UEFI Shell / 1 关机 / 0 重启(手册 0.8.1.13 第 3.4 节)
-    bool exitOk = false;
-    const int exitMode = mt.value(QStringLiteral("exit_mode")).toVariant().toInt(&exitOk);
-    if (exitOk && exitMode >= 0 && exitMode <= 2)
-        out.insert(QStringLiteral("exit_mode"), exitMode);
-
-    // only_tests / skip_tests:0..13 的整数数组,过滤越界值;空数组不下发
-    const char *const kTestLists[] = {"only_tests", "skip_tests"};
-    for (const char *name : kTestLists) {
-        const QJsonArray in = mt.value(QLatin1String(name)).toArray();
-        QJsonArray filtered;
-        for (const QJsonValue &v : in) {
-            bool ok = false;
-            const int test = v.toVariant().toInt(&ok);
-            if (ok && test >= 0 && test <= 13)
-                filtered.append(test);
-        }
-        if (!filtered.isEmpty())
-            out.insert(QLatin1String(name), filtered);
-    }
-
-    return out;
-}
-
-// ---------------------------------------------------------------------------
-// 开机复位:三个可选项(RMT / AMT / MT)都回到 config.json 的默认开关
-// ---------------------------------------------------------------------------
-// 手册 0.8.1.9:run_rmt / run_amt / run_mt 默认全部开启(true)。
-// 启动时把 qt-plans.json 里各工位的 rmt.enabled / amt.enabled / mt.enabled 压回默认,
-// 本次运行里勾选并点「确定」照常写盘、当轮生效,下次启动又被复位——
-// 也就是「记住一次运行,不记住跨开机」。
-// ---------------------------------------------------------------------------
-void LocalPlans::resetOptionalStages()
-{
-    const QStringList sections = {QStringLiteral("rmt"), QStringLiteral("amt"),
-                                  QStringLiteral("mt")};
-    const QJsonObject rmtDef = rmtDefaultsFromConfig();
-    const QJsonObject amtDef = amtDefaultsFromConfig();
-    const QJsonObject mtDef = mtDefaultsFromConfig();
-    const bool want[3] = {rmtDef.value(QStringLiteral("enabled")).toBool(true),
-                          amtDef.value(QStringLiteral("enabled")).toBool(true),
-                          mtDef.value(QStringLiteral("enabled")).toBool(true)};
-
-    QJsonObject root = readRoot();
-    QJsonObject stations = root.value(QStringLiteral("stations")).toObject();
-    if (stations.isEmpty())
-        return;                     // 还没有任何工位的存档,不用建文件
-
-    bool touched = false;
-    const QStringList keys = stations.keys();
-    for (const QString &key : keys) {
-        QJsonObject one = stations.value(key).toObject();
-        bool oneTouched = false;
-
-        // 三段同构:有存档且和默认不一致才改
-        for (int i = 0; i < sections.size(); ++i) {
-            QJsonObject sec = one.value(sections.at(i)).toObject();
-            if (sec.isEmpty() || sec.value(QStringLiteral("enabled")).toBool() == want[i])
-                continue;
-
-            sec.insert(QStringLiteral("enabled"), want[i]);
-            one.insert(sections.at(i), sec);
-            oneTouched = true;
-        }
-
-        if (oneTouched) {
-            stations.insert(key, one);
-            touched = true;
-        }
-    }
-
-    if (!touched)
-        return;                     // 本来就和默认一致,不用改文件
-
-    root.insert(QStringLiteral("stations"), stations);
-
-    QSaveFile f(plansPath());
-    if (!f.open(QIODevice::WriteOnly)) {
-        qInfo().noquote() << "[plans] 开机复位打不开" << plansPath() << f.errorString();
-        return;
-    }
-    f.write(QJsonDocument(root).toJson(QJsonDocument::Indented));
-    if (!f.commit()) {
-        qInfo().noquote() << "[plans] 开机复位写入失败" << plansPath() << f.errorString();
-        return;
-    }
-
-    qInfo().noquote() << "[plans] 开机复位:RMT 开关回到" << (want[0] ? "启用" : "不启用")
-                      << "、AMT 开关回到" << (want[1] ? "启用" : "不启用")
-                      << "、MT 开关回到" << (want[2] ? "启用" : "不启用")
-                      << "→" << plansPath();
-}
-
-QJsonObject LocalPlans::stationConfig(int station)
-{
-    const QString key = QStringLiteral("S%1").arg(station + 1);
-    QJsonObject one = readRoot().value(QStringLiteral("stations")).toObject()
-                          .value(key).toObject();
-    if (one.value(QStringLiteral("memory_params")).toObject().isEmpty())
-        one.insert(QStringLiteral("memory_params"), stationParams(station));
-    if (one.value(QStringLiteral("rmt")).toObject().isEmpty())
-        one.insert(QStringLiteral("rmt"), stationRmt(station));
-    if (one.value(QStringLiteral("amt")).toObject().isEmpty())
-        one.insert(QStringLiteral("amt"), stationAmt(station));
-    if (one.value(QStringLiteral("mt")).toObject().isEmpty())
-        one.insert(QStringLiteral("mt"), stationMt(station));
-    return one;
-}
-
-bool LocalPlans::saveStations(const QJsonObject &stations)
-{
-    QJsonObject root = readRoot();
-    root.insert(QStringLiteral("version"), 2);
-
-    QJsonObject merged = root.value(QStringLiteral("stations")).toObject();
-    const QStringList keys = stations.keys();
-    for (const QString &key : keys)
-        merged.insert(key, stations.value(key).toObject());
-    root.insert(QStringLiteral("stations"), merged);
-
-    QSaveFile f(plansPath());           // 原子写:写临时文件再替换
-    if (!f.open(QIODevice::WriteOnly)) {
-        qInfo().noquote() << "[plans] 打不开" << plansPath() << f.errorString();
-        return false;
-    }
-    f.write(QJsonDocument(root).toJson(QJsonDocument::Indented));
-    if (!f.commit()) {
-        qInfo().noquote() << "[plans] 写入失败" << plansPath() << f.errorString();
-        return false;
-    }
-    qInfo().noquote() << "[plans] 已保存" << keys.size() << "个工位配置 →" << plansPath();
-    return true;
-}
-
-bool LocalPlans::saveStation(int station, const QJsonObject &memoryParams,
-                             const QJsonObject &rmt, const QJsonObject &amt,
-                             const QJsonObject &mt)
-{
-    const QString key = QStringLiteral("S%1").arg(station + 1);
-
-    QJsonObject root = readRoot();
-    root.insert(QStringLiteral("version"), 2);
-
-    QJsonObject stations = root.value(QStringLiteral("stations")).toObject();
-    QJsonObject one = stations.value(key).toObject();
-    one.insert(QStringLiteral("memory_params"), memoryParams);
-    one.insert(QStringLiteral("rmt"), rmt);
-    one.insert(QStringLiteral("amt"), amt);
-    one.insert(QStringLiteral("mt"), mt);
-    stations.insert(key, one);
-    root.insert(QStringLiteral("stations"), stations);
-
-    QSaveFile f(plansPath());           // 原子写:写临时文件再替换
-    if (!f.open(QIODevice::WriteOnly)) {
-        qInfo().noquote() << "[plans] 打不开" << plansPath() << f.errorString();
-        return false;
-    }
-    f.write(QJsonDocument(root).toJson(QJsonDocument::Indented));
-    if (!f.commit()) {
-        qInfo().noquote() << "[plans] 写入失败" << plansPath() << f.errorString();
-        return false;
-    }
-
-    qInfo().noquote() << "[plans] 已保存" << key << "内存参数 + RMT / AMT / MT 参数 →"
-                      << plansPath();
-    return true;
-}
+#include "localplans.h"
+
+#include "appconfig.h"
+
+#include <QCoreApplication>
+#include <QDebug>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QSaveFile>
+#include <QStringList>
+
+namespace {
+
+const char *const kPlansFile = "qt-plans.json";
+
+const char *const kMtCanonicalNames[26] = {
+    "address test, walking ones, 1 cpu",
+    "address test, own address, 1 cpu",
+    "address test, own address",
+    "moving inversions, ones & zeroes",
+    "moving inversions, 8-bit pattern",
+    "moving inversions, random pattern",
+    "block move, 64-byte blocks",
+    "moving inversions, 32-bit pattern",
+    "random number sequence",
+    "modulo 20, random pattern",
+    "bit fade test, 2 patterns, 1 cpu",
+    "random number sequence, 64-bit",
+    "random number sequence, 128-bit",
+    "hammer test",
+    "dma test (experimental)",
+    "march c algorithm",
+    "galloping pattern (galpat)",
+    "galloping pattern (linear)",
+    "galloping pattern (randomaddress)",
+    "galloping pattern (bankjump)",
+    "galloping pattern (victim)",
+    "galloping pattern (marchic)",
+    "galloping pattern (marchsse)",
+    "galloping pattern (butterfly)",
+    "march ss+ algorithm",
+    "stressapp memory stress test",
+};
+
+int parseMtTestValue(const QJsonValue &v)
+{
+    if (v.isDouble()) {
+        bool ok = false;
+        const int n = v.toVariant().toInt(&ok);
+        return (ok && n >= 0 && n <= 25) ? n : -1;
+    }
+    const QString raw = v.toString().trimmed();
+    if (raw.isEmpty())
+        return -1;
+
+    const QString lower = raw.toLower();
+    if (lower == QLatin1String("adress test, walking ones, 1 cpu"))
+        return 0;
+    for (int i = 0; i < 26; ++i) {
+        if (lower == QLatin1String(kMtCanonicalNames[i]))
+            return i;
+    }
+    if (lower.startsWith(QLatin1String("test "))) {
+        bool ok = false;
+        const int n = lower.mid(5).trimmed().toInt(&ok);
+        if (ok && n >= 0 && n <= 25)
+            return n;
+    }
+    int digitLen = 0;
+    while (digitLen < lower.size() && lower.at(digitLen).isDigit())
+        ++digitLen;
+    if (digitLen > 0) {
+        bool okBoundary = (digitLen == lower.size());
+        if (!okBoundary) {
+            const QChar c = lower.at(digitLen);
+            okBoundary = (c == QLatin1Char(':') || c == QLatin1Char('.')
+                          || c == QLatin1Char('-') || c == QLatin1Char(')')
+                          || c.isSpace());
+        }
+        if (okBoundary) {
+            bool ok = false;
+            const int n = lower.left(digitLen).toInt(&ok);
+            if (ok && n >= 0 && n <= 25)
+                return n;
+        }
+    }
+    return -1;
+}
+
+QString plansPath()
+{
+    return QDir(appWritableDir()).filePath(QString::fromLatin1(kPlansFile));
+}
+
+QJsonObject readRoot()
+{
+    QFile f(plansPath());
+    if (!f.open(QIODevice::ReadOnly))
+        return QJsonObject();
+    return QJsonDocument::fromJson(f.readAll()).object();
+}
+
+} // namespace
+
+QJsonObject LocalPlans::defaultsFromConfig()
+{
+    const QString path = appConfigPath(QStringLiteral("config.json"));
+    QFile f(path);
+    if (!f.open(QIODevice::ReadOnly))
+        return QJsonObject();
+    return QJsonDocument::fromJson(f.readAll()).object()
+            .value(QStringLiteral("memoryParams")).toObject();
+}
+
+QJsonObject LocalPlans::stationParams(int station)
+{
+    const QString key = QStringLiteral("S%1").arg(station + 1);
+    const QJsonObject saved = readRoot()
+            .value(QStringLiteral("stations")).toObject()
+            .value(key).toObject()
+            .value(QStringLiteral("memory_params")).toObject();
+    return saved.isEmpty() ? defaultsFromConfig() : saved;
+}
+
+QJsonObject LocalPlans::amtDefaultsFromConfig()
+{
+    const QString path = appConfigPath(QStringLiteral("config.json"));
+    QFile f(path);
+    if (!f.open(QIODevice::ReadOnly))
+        return QJsonObject();
+    return QJsonDocument::fromJson(f.readAll()).object()
+            .value(QStringLiteral("amtParams")).toObject();
+}
+
+QJsonObject LocalPlans::rmtDefaultsFromConfig()
+{
+    const QString path = appConfigPath(QStringLiteral("config.json"));
+    QFile f(path);
+    if (!f.open(QIODevice::ReadOnly))
+        return QJsonObject();
+    return QJsonDocument::fromJson(f.readAll()).object()
+            .value(QStringLiteral("rmtParams")).toObject();
+}
+
+QJsonObject LocalPlans::mtDefaultsFromConfig()
+{
+    const QString path = appConfigPath(QStringLiteral("config.json"));
+    QFile f(path);
+    if (!f.open(QIODevice::ReadOnly))
+        return QJsonObject();
+    return QJsonDocument::fromJson(f.readAll()).object()
+            .value(QStringLiteral("mtParams")).toObject();
+}
+
+QJsonObject LocalPlans::stationRmt(int station)
+{
+    const QString key = QStringLiteral("S%1").arg(station + 1);
+    const QJsonObject saved = readRoot()
+            .value(QStringLiteral("stations")).toObject()
+            .value(key).toObject()
+            .value(QStringLiteral("rmt")).toObject();
+    // 没保存过就用 config.json 的 rmtParams(手册 0.8.1.9 起默认启用)
+    return saved.isEmpty() ? rmtDefaultsFromConfig() : saved;
+}
+
+QJsonObject LocalPlans::stationAmt(int station)
+{
+    const QString key = QStringLiteral("S%1").arg(station + 1);
+    const QJsonObject saved = readRoot()
+            .value(QStringLiteral("stations")).toObject()
+            .value(key).toObject()
+            .value(QStringLiteral("amt")).toObject();
+    // 没保存过就用 config.json 的 amtParams(手册 0.8.1.9 起默认启用,跑 amemdiag 1)
+    return saved.isEmpty() ? amtDefaultsFromConfig() : saved;
+}
+
+QJsonObject LocalPlans::stationMt(int station)
+{
+    const QString key = QStringLiteral("S%1").arg(station + 1);
+    const QJsonObject saved = readRoot()
+            .value(QStringLiteral("stations")).toObject()
+            .value(key).toObject()
+            .value(QStringLiteral("mt")).toObject();
+    // 没保存过就用 config.json 的 mtParams(默认启用,跑 118.efi)
+    return saved.isEmpty() ? mtDefaultsFromConfig() : saved;
+}
+
+// ---------------------------------------------------------------------------
+// MT:本地参数 → StageAction(start_mt) / SetStageIntent(mt) 的 mt 字段
+// ---------------------------------------------------------------------------
+// 后端在 UEFI Shell> 下会自动写 mt86.cfg(默认 TSTLIST=0..25、全部可用内存、
+// EXITMODE=2 退回 Shell),再启动 118.efi。这里只把用户显式配置过的可选键
+// 透传给后端;空值 / 越界值一律丢弃,避免把半成品表单写进配置。
+// ---------------------------------------------------------------------------
+QJsonObject LocalPlans::mtStagePayload(const QJsonObject &mt)
+{
+    QJsonObject out;
+
+    const QString efiPath = mt.value(QStringLiteral("efi_path")).toString().trimmed();
+    if (!efiPath.isEmpty())
+        out.insert(QStringLiteral("efi_path"), efiPath);
+
+    const QString configPath = mt.value(QStringLiteral("config_path")).toString().trimmed();
+    if (!configPath.isEmpty())
+        out.insert(QStringLiteral("config_path"), configPath);
+
+    // memory_range:只认 "all" / "custom";省略等价于后端默认 all
+    const QString memRange = mt.value(QStringLiteral("memory_range")).toString().trimmed();
+    if (memRange == QStringLiteral("all") || memRange == QStringLiteral("custom"))
+        out.insert(QStringLiteral("memory_range"), memRange);
+
+    // 自定义地址区间:按手册示例保持字符串形式(如 "0x10000000")
+    // 兼容文档中的大写别名 ADDRLIMLO / ADDRLIMHI;
+    // JSON 保存仍统一使用小写键,避免新旧配置产生两份互相覆盖的值。
+    QString addrLo = mt.value(QStringLiteral("addr_lim_lo")).toString().trimmed();
+    QString addrHi = mt.value(QStringLiteral("addr_lim_hi")).toString().trimmed();
+    if (addrLo.isEmpty())
+        addrLo = mt.value(QStringLiteral("ADDRLIMLO")).toString().trimmed();
+    if (addrHi.isEmpty())
+        addrHi = mt.value(QStringLiteral("ADDRLIMHI")).toString().trimmed();
+    if (!addrLo.isEmpty())
+        out.insert(QStringLiteral("addr_lim_lo"), addrLo);
+    if (!addrHi.isEmpty())
+        out.insert(QStringLiteral("addr_lim_hi"), addrHi);
+
+    // exit_mode:2 退回 UEFI Shell / 1 关机 / 0 重启
+    bool exitOk = false;
+    const int exitMode = mt.value(QStringLiteral("exit_mode")).toVariant().toInt(&exitOk);
+    if (exitOk && exitMode >= 0 && exitMode <= 2)
+        out.insert(QStringLiteral("exit_mode"), exitMode);
+
+    // only_tests / skip_tests:0..25 的整数数组,过滤越界值;空数组不下发
+    const char *const kTestLists[] = {"only_tests", "skip_tests"};
+    for (const char *name : kTestLists) {
+        const QJsonArray in = mt.value(QLatin1String(name)).toArray();
+        QJsonArray filtered;
+        QList<int> seen;
+        for (const QJsonValue &v : in) {
+            const int test = parseMtTestValue(v);
+            if (test >= 0 && test <= 25 && !seen.contains(test)) {
+                seen.append(test);
+                filtered.append(test);
+            }
+        }
+        if (!filtered.isEmpty())
+            out.insert(QLatin1String(name), filtered);
+    }
+
+    // CreateTaskDialog 把用户勾选的 MT 项存在 mt.selected(字符串数组)。
+    // 若未显式指定 only_tests,但勾选了部分子项(0 < count < 26),映射成 only_tests 传给后端;
+    // 全选(26 项)时省略,由后端写默认 TSTLIST=0..25。
+    if (!out.contains(QStringLiteral("only_tests"))) {
+        const QJsonArray selArr = mt.value(QStringLiteral("selected")).toArray();
+        if (!selArr.isEmpty()) {
+            QJsonArray mapped;
+            QList<int> seen;
+            for (const QJsonValue &v : selArr) {
+                const int test = parseMtTestValue(v);
+                if (test >= 0 && test <= 25 && !seen.contains(test)) {
+                    seen.append(test);
+                    mapped.append(test);
+                }
+            }
+            if (!mapped.isEmpty() && mapped.size() < 26)
+                out.insert(QStringLiteral("only_tests"), mapped);
+        }
+    }
+
+    return out;
+}
+
+// ---------------------------------------------------------------------------
+// 开机复位:三个可选项(RMT / AMT / MT)都回到 config.json 的默认开关
+// ---------------------------------------------------------------------------
+// 手册 0.8.1.9:run_rmt / run_amt / run_mt 默认全部开启(true)。
+// 启动时把 qt-plans.json 里各工位的 rmt.enabled / amt.enabled / mt.enabled 压回默认,
+// 本次运行里勾选并点「确定」照常写盘、当轮生效,下次启动又被复位——
+// 也就是「记住一次运行,不记住跨开机」。
+// ---------------------------------------------------------------------------
+void LocalPlans::resetOptionalStages()
+{
+    const QStringList sections = {QStringLiteral("rmt"), QStringLiteral("amt"),
+                                  QStringLiteral("mt")};
+    const QJsonObject rmtDef = rmtDefaultsFromConfig();
+    const QJsonObject amtDef = amtDefaultsFromConfig();
+    const QJsonObject mtDef = mtDefaultsFromConfig();
+    const bool want[3] = {rmtDef.value(QStringLiteral("enabled")).toBool(true),
+                          amtDef.value(QStringLiteral("enabled")).toBool(true),
+                          mtDef.value(QStringLiteral("enabled")).toBool(true)};
+
+    QJsonObject root = readRoot();
+    QJsonObject stations = root.value(QStringLiteral("stations")).toObject();
+    if (stations.isEmpty())
+        return;                     // 还没有任何工位的存档,不用建文件
+
+    bool touched = false;
+    const QStringList keys = stations.keys();
+    for (const QString &key : keys) {
+        QJsonObject one = stations.value(key).toObject();
+        bool oneTouched = false;
+
+        // 三段同构:有存档且和默认不一致才改
+        for (int i = 0; i < sections.size(); ++i) {
+            QJsonObject sec = one.value(sections.at(i)).toObject();
+            if (sec.isEmpty() || sec.value(QStringLiteral("enabled")).toBool() == want[i])
+                continue;
+
+            sec.insert(QStringLiteral("enabled"), want[i]);
+            one.insert(sections.at(i), sec);
+            oneTouched = true;
+        }
+
+        if (oneTouched) {
+            stations.insert(key, one);
+            touched = true;
+        }
+    }
+
+    if (!touched)
+        return;                     // 本来就和默认一致,不用改文件
+
+    root.insert(QStringLiteral("stations"), stations);
+
+    QSaveFile f(plansPath());
+    if (!f.open(QIODevice::WriteOnly)) {
+        qInfo().noquote() << "[plans] 开机复位打不开" << plansPath() << f.errorString();
+        return;
+    }
+    f.write(QJsonDocument(root).toJson(QJsonDocument::Indented));
+    if (!f.commit()) {
+        qInfo().noquote() << "[plans] 开机复位写入失败" << plansPath() << f.errorString();
+        return;
+    }
+
+    qInfo().noquote() << "[plans] 开机复位:RMT 开关回到" << (want[0] ? "启用" : "不启用")
+                      << "、AMT 开关回到" << (want[1] ? "启用" : "不启用")
+                      << "、MT 开关回到" << (want[2] ? "启用" : "不启用")
+                      << "→" << plansPath();
+}
+
+QJsonObject LocalPlans::stationConfig(int station)
+{
+    const QString key = QStringLiteral("S%1").arg(station + 1);
+    QJsonObject one = readRoot().value(QStringLiteral("stations")).toObject()
+                          .value(key).toObject();
+    if (one.value(QStringLiteral("memory_params")).toObject().isEmpty())
+        one.insert(QStringLiteral("memory_params"), stationParams(station));
+    if (one.value(QStringLiteral("rmt")).toObject().isEmpty())
+        one.insert(QStringLiteral("rmt"), stationRmt(station));
+    if (one.value(QStringLiteral("amt")).toObject().isEmpty())
+        one.insert(QStringLiteral("amt"), stationAmt(station));
+    if (one.value(QStringLiteral("mt")).toObject().isEmpty())
+        one.insert(QStringLiteral("mt"), stationMt(station));
+    return one;
+}
+
+bool LocalPlans::saveStations(const QJsonObject &stations)
+{
+    QJsonObject root = readRoot();
+    root.insert(QStringLiteral("version"), 2);
+
+    QJsonObject merged = root.value(QStringLiteral("stations")).toObject();
+    const QStringList keys = stations.keys();
+    for (const QString &key : keys)
+        merged.insert(key, stations.value(key).toObject());
+    root.insert(QStringLiteral("stations"), merged);
+
+    QSaveFile f(plansPath());           // 原子写:写临时文件再替换
+    if (!f.open(QIODevice::WriteOnly)) {
+        qInfo().noquote() << "[plans] 打不开" << plansPath() << f.errorString();
+        return false;
+    }
+    f.write(QJsonDocument(root).toJson(QJsonDocument::Indented));
+    if (!f.commit()) {
+        qInfo().noquote() << "[plans] 写入失败" << plansPath() << f.errorString();
+        return false;
+    }
+    qInfo().noquote() << "[plans] 已保存" << keys.size() << "个工位配置 →" << plansPath();
+    return true;
+}
+
+bool LocalPlans::saveStation(int station, const QJsonObject &memoryParams,
+                             const QJsonObject &rmt, const QJsonObject &amt,
+                             const QJsonObject &mt)
+{
+    const QString key = QStringLiteral("S%1").arg(station + 1);
+
+    QJsonObject root = readRoot();
+    root.insert(QStringLiteral("version"), 2);
+
+    QJsonObject stations = root.value(QStringLiteral("stations")).toObject();
+    QJsonObject one = stations.value(key).toObject();
+    one.insert(QStringLiteral("memory_params"), memoryParams);
+    one.insert(QStringLiteral("rmt"), rmt);
+    one.insert(QStringLiteral("amt"), amt);
+    one.insert(QStringLiteral("mt"), mt);
+    stations.insert(key, one);
+    root.insert(QStringLiteral("stations"), stations);
+
+    QSaveFile f(plansPath());           // 原子写:写临时文件再替换
+    if (!f.open(QIODevice::WriteOnly)) {
+        qInfo().noquote() << "[plans] 打不开" << plansPath() << f.errorString();
+        return false;
+    }
+    f.write(QJsonDocument(root).toJson(QJsonDocument::Indented));
+    if (!f.commit()) {
+        qInfo().noquote() << "[plans] 写入失败" << plansPath() << f.errorString();
+        return false;
+    }
+
+    qInfo().noquote() << "[plans] 已保存" << key << "内存参数 + RMT / AMT / MT 参数 →"
+                      << plansPath();
+    return true;
+}

+ 72 - 72
src/localplans.h

@@ -1,72 +1,72 @@
-#ifndef LOCALPLANS_H
-#define LOCALPLANS_H
-
-#include <QJsonObject>
-#include <QString>
-
-/**
- * 本地测试计划 / 内存参数保存(qt-plans.json)
- * ------------------------------------------------------------------
- * 按《QT_CLIENT_API_ZH.md》约定:Qt 自己维护本地配置与计划,
- * 参数页点「确定」只写本机 qt-plans.json —— 不请求后端、不写 BIOS。
- * 真正下发发生在本轮每个 CPU 的 UIP1:随 StageAction(continue_uip) 的
- * memory_params 带过去,同一 CPU 只发一次;UIP2 只发空回车。
- */
-class LocalPlans
-{
-public:
-    /** config.json 里的 memoryParams(出厂默认值) */
-    static QJsonObject defaultsFromConfig();
-
-    /** config.json 里的 amtParams(AMT 的出厂默认:enabled / test_command 等) */
-    static QJsonObject amtDefaultsFromConfig();
-
-    /** config.json 里的 rmtParams(RMT 的出厂默认:enabled,手册 0.8.1.9 起默认 true) */
-    static QJsonObject rmtDefaultsFromConfig();
-
-    /** config.json 里的 mtParams(MT 的出厂默认:enabled / efi_path / config_path) */
-    static QJsonObject mtDefaultsFromConfig();
-
-    /** 某工位已保存的参数;没保存过就回落到 config.json 的默认值 */
-    static QJsonObject stationParams(int station);
-
-    /** 某工位已保存的 RMT 参数(只看 enabled,UIP1 的 run_rmt)。
-     *  没保存过就回落到 config.json 的 rmtParams;两处都没有才返回空对象。 */
-    static QJsonObject stationRmt(int station);
-
-    /** 某工位已保存的 AMT 参数(极简模式只看 enabled / test_command)。
-     *  没保存过就回落到 config.json 的 amtParams;两处都没有才返回空对象。 */
-    static QJsonObject stationAmt(int station);
-
-    /** 某工位已保存的 MT 参数(enabled / efi_path / config_path,UEFI Shell 里跑 118.efi;
-     *  手册 0.8.1.13 起还支持 memory_range / addr_lim_lo / addr_lim_hi / exit_mode /
-     *  only_tests / skip_tests 等可选扩展键) */
-    static QJsonObject stationMt(int station);
-
-    /** 把已保存的 MT 参数整理成 StageAction(start_mt) 的 mt 字段(手册 0.8.1.13)。
-     *  只带已配置的可选键:efi_path / config_path / memory_range / addr_lim_lo /
-     *  addr_lim_hi / exit_mode / only_tests / skip_tests;空值或非法值不下发,
-     *  省略的键由后端按默认处理(自动写 mt86.cfg:TSTLIST=0..13、全部可用内存、
-     *  EXITMODE=2 退回 UEFI Shell)。 */
-    static QJsonObject mtStagePayload(const QJsonObject &mt);
-
-    /** 开机复位:把 qt-plans.json 里各工位的 rmt / amt / mt 的 enabled
-     *  压回 config.json 的默认值(手册 0.8.1.9:三者默认全开)。
-     *  本次运行里勾选并点确定照常保存(只记这一次运行,不跨开机)。 */
-    static void resetOptionalStages();
-
-    /** 某工位的整份配置(memory_params / rmt / amt / mt 合在一个对象里)。
-     *  没有存档的部分回落到 config.json 默认值;不会写文件。 */
-    static QJsonObject stationConfig(int station);
-
-    /** 一次性写入多个工位配置(合并进现有 stations,保留其它键,原子写)。
-     *  stations 形如 {"S1": {...}, "S2": {...}}。 */
-    static bool saveStations(const QJsonObject &stations);
-
-    /** 原子写入某工位的参数(读-改-写整份文件,避免半截 JSON) */
-    static bool saveStation(int station, const QJsonObject &memoryParams,
-                            const QJsonObject &rmt, const QJsonObject &amt,
-                            const QJsonObject &mt);
-};
-
-#endif // LOCALPLANS_H
+#ifndef LOCALPLANS_H
+#define LOCALPLANS_H
+
+#include <QJsonObject>
+#include <QString>
+
+/**
+ * 本地测试计划 / 内存参数保存(qt-plans.json)
+ * ------------------------------------------------------------------
+ * 按《QT_CLIENT_API_ZH.md》约定:Qt 自己维护本地配置与计划,
+ * 参数页点「确定」只写本机 qt-plans.json —— 不请求后端、不写 BIOS。
+ * 真正下发发生在本轮每个 CPU 的 ICT1(protocol stage="uip1"):
+ * 随 continue_uip 的 memory_params 带过去,同一 CPU 只发一次;ICT2 只发空回车。
+ */
+class LocalPlans
+{
+public:
+    /** config.json 里的 memoryParams(出厂默认值) */
+    static QJsonObject defaultsFromConfig();
+
+    /** config.json 里的 amtParams(AMT 的出厂默认:enabled / test_command 等) */
+    static QJsonObject amtDefaultsFromConfig();
+
+    /** config.json 里的 rmtParams(RMT 的出厂默认:enabled,手册 0.8.1.9 起默认 true) */
+    static QJsonObject rmtDefaultsFromConfig();
+
+    /** config.json 里的 mtParams(MT 的出厂默认:enabled / efi_path / config_path) */
+    static QJsonObject mtDefaultsFromConfig();
+
+    /** 某工位已保存的参数;没保存过就回落到 config.json 的默认值 */
+    static QJsonObject stationParams(int station);
+
+    /** 某工位已保存的 RMT 参数(只看 enabled,ICT1 的 run_rmt)。
+     *  没保存过就回落到 config.json 的 rmtParams;两处都没有才返回空对象。 */
+    static QJsonObject stationRmt(int station);
+
+    /** 某工位已保存的 AMT 参数(极简模式只看 enabled / test_command)。
+     *  没保存过就回落到 config.json 的 amtParams;两处都没有才返回空对象。 */
+    static QJsonObject stationAmt(int station);
+
+    /** 某工位已保存的 MT 参数(enabled / efi_path / config_path,UEFI Shell 里跑 118.efi;
+     *  手册 0.8.1.19 起支持 only_tests / skip_tests(0..25)及 memory_range /
+     *  addr_lim_lo / addr_lim_hi / exit_mode 等可选扩展键) */
+    static QJsonObject stationMt(int station);
+
+    /** 把已保存的 MT 参数整理成 start_mt 的 mt 字段。
+     *  只带已配置的可选键:efi_path / config_path / memory_range / addr_lim_lo /
+     *  addr_lim_hi / exit_mode / only_tests / skip_tests;空值或非法值不下发,
+     *  省略的键由后端按默认处理(自动写 mt86.cfg:TSTLIST=0..25、全部可用内存、
+     *  EXITMODE=2 退回 UEFI Shell)。 */
+    static QJsonObject mtStagePayload(const QJsonObject &mt);
+
+    /** 开机复位:把 qt-plans.json 里各工位的 rmt / amt / mt 的 enabled
+     *  压回 config.json 的默认值(手册 0.8.1.9:三者默认全开)。
+     *  本次运行里勾选并点确定照常保存(只记这一次运行,不跨开机)。 */
+    static void resetOptionalStages();
+
+    /** 某工位的整份配置(memory_params / rmt / amt / mt 合在一个对象里)。
+     *  没有存档的部分回落到 config.json 默认值;不会写文件。 */
+    static QJsonObject stationConfig(int station);
+
+    /** 一次性写入多个工位配置(合并进现有 stations,保留其它键,原子写)。
+     *  stations 形如 {"S1": {...}, "S2": {...}}。 */
+    static bool saveStations(const QJsonObject &stations);
+
+    /** 原子写入某工位的参数(读-改-写整份文件,避免半截 JSON) */
+    static bool saveStation(int station, const QJsonObject &memoryParams,
+                            const QJsonObject &rmt, const QJsonObject &amt,
+                            const QJsonObject &mt);
+};
+
+#endif // LOCALPLANS_H

+ 2 - 2
src/main.cpp

@@ -1,4 +1,4 @@
- #include "mainwindow.h"
+#include "mainwindow.h"
 #include "appconfig.h"
 
 #include <QApplication>
@@ -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.18"));
+    app.setApplicationVersion(QStringLiteral("0.8.1.19"));
 
     applyAppFont(app);
     applyStyleSheet(app);

+ 315 - 56
src/mainwindow.cpp

@@ -25,6 +25,7 @@
 #include <QGraphicsDropShadowEffect>
 #include <QGuiApplication>
 #include <QHBoxLayout>
+#include <QIcon>
 #include <QButtonGroup>
 #include <QCheckBox>
 #include <QDialogButtonBox>
@@ -43,6 +44,7 @@
 #include <QMouseEvent>
 #include <QPainter>
 #include <QPainterPath>
+#include <QPen>
 #include <QPixmap>
 #include <QPushButton>
 #include <QResizeEvent>
@@ -59,6 +61,56 @@ namespace {
 // 协议 0x01 是 1 字节整数摄氏度,70℃ → 帧 AA 55 01 01 46 37。
 // 设备收到后会连带启动预加热,之后由自己的 PID 闭环控温。
 const int kStartTargetTempC = 70;
+// 0.8.1.19:state 进入终态后等多久仍没收到后端的 task_complete / complete=true,
+// 就按 state 终态兜底收尾(兼容不推结束事件的旧后端)。state 是 1Hz 推送,3 s 够用。
+const int kEndSignalWaitMs = 3000;
+
+// 密码输入框右端的「显示 / 隐藏」切换图标。
+// QLineEdit 的 trailing QAction 只渲染图标(文字会被压成 16x16 看不清),
+// 所以按项目自绘图标的惯例用 QPainter 画 20x20 的睁眼 / 闭眼,中文说明放在 tooltip。
+QIcon passwordEyeIcon(bool shown)
+{
+    QPixmap pm(20, 20);
+    pm.fill(Qt::transparent);
+    QPainter p(&pm);
+    p.setRenderHint(QPainter::Antialiasing, true);
+    const QColor ink(QStringLiteral("#5a6b7a"));
+    p.setPen(QPen(ink, 1.3));
+    p.setBrush(Qt::NoBrush);
+    QPainterPath eye;
+    eye.moveTo(2.0, 10.0);
+    eye.quadTo(10.0, 3.5, 18.0, 10.0);
+    eye.quadTo(10.0, 16.5, 2.0, 10.0);
+    p.drawPath(eye);
+    if (shown) {
+        p.setPen(Qt::NoPen);
+        p.setBrush(QColor(QStringLiteral("#2f7fc1")));
+        p.drawEllipse(QPointF(10.0, 10.0), 2.5, 2.5);
+    } else {
+        p.drawLine(QLineF(3.0, 16.5, 17.0, 3.5));   // 闭眼:一道斜杠
+    }
+    p.end();
+    return QIcon(pm);
+}
+
+// 给任意密码输入框挂上切换动作:默认隐藏,点一下显示明文,再点恢复圆点。
+// 用 QAction + QIcon(Qt 原生 trailing action),不用在布局里塞按钮,
+// 三个密码对话框的 fixedSize 和间距都保持原样。
+void addPasswordVisibilityToggle(QLineEdit *edit)
+{
+    edit->setEchoMode(QLineEdit::Password);
+    QAction *act = new QAction(edit);
+    act->setCheckable(true);
+    act->setIcon(passwordEyeIcon(false));
+    act->setToolTip(QStringLiteral("显示密码"));
+    act->setStatusTip(QStringLiteral("点击切换密码显示 / 隐藏"));
+    edit->addAction(act, QLineEdit::TrailingPosition);
+    QObject::connect(act, &QAction::triggered, edit, [edit, act](bool shown) {
+        edit->setEchoMode(shown ? QLineEdit::Normal : QLineEdit::Password);
+        act->setIcon(passwordEyeIcon(shown));
+        act->setToolTip(shown ? QStringLiteral("隐藏密码") : QStringLiteral("显示密码"));
+    });
+}
 
 // 目标温度的下发时机:DDR 训练(phase=training)结束的那一刻,而不是点「开始测试」时。
 // 现场口径:训练阶段本身发热在变,提前下发会让设备过早预加热、把训练结果带偏;
@@ -331,6 +383,30 @@ MainWindow::MainWindow(QWidget *parent)
             [this](int station, const QString &stage, const QString &text) {
         m_store->appendAlarm(station, stage, text);
     });
+    connect(m_backend, &BackendLink::taskCompleteArrived, this,
+            [this](int station, const QJsonObject &result) {
+        if (station < 0 || station >= m_store->count())
+            return;
+        m_store->applyTaskComplete(station, result);
+        const QString verdict = result.value(QStringLiteral("verdict")).toString();
+        const QString status = result.value(QStringLiteral("task_status")).toString();
+        m_taskCompleteVerdict[station] = verdict;
+        m_endSignalReceived[station] = true;       // 后端明确的「结束指令」已到
+        m_store->appendLog(station,
+            QStringLiteral("[backend] task_complete:%1,verdict=%2")
+                .arg(status, verdict.isEmpty() ? QStringLiteral("unknown") : verdict));
+        // task_complete 是任务终态与阶段快照的权威事件。
+        // completed 也可能带 verdict=fail(阶段已跑完但测试结论失败),必须中止队列;
+        // failed 状态同样按失败收尾。不能只在 verdict=fail 时收尾,否则正常 PASS
+        // 轮次会依赖另一条命令回执,事件先到时可能无法推进。
+        if (status == QStringLiteral("completed") || status == QStringLiteral("failed")) {
+            const bool failed = (status == QStringLiteral("failed")
+                                 || verdict == QStringLiteral("fail"));
+            finalizeRound(station, failed,
+                QStringLiteral("task_complete verdict=%1, task_status=%2")
+                    .arg(verdict.isEmpty() ? QStringLiteral("unknown") : verdict, status));
+        }
+    });
     connect(m_backend, &BackendLink::stateArrived, this, [this](int station, const QJsonObject &st) {
         m_store->applyBackendState(station, st);
 
@@ -347,25 +423,44 @@ MainWindow::MainWindow(QWidget *parent)
         // 后端运行态:见到 starting/running/waiting_input 就记住,completed/failed 才清。
         // 这样网页端 / 其他客户端发起的测试,本机也显示「执行中」;
         // 主机复位过程中短暂回到 idle 也不会让按钮闪回「开始测试」。
+        // 手册 9.2:run_state 新增 blocked(阶段 FAIL 后的换条停机挂起),
+        // 同样算本轮终态,要停表 / 复位按钮,但队列由 finishCurrentTask 决定是否中止。
         const bool terminal = (runState == QStringLiteral("completed")
-                               || runState == QStringLiteral("failed"));
+                               || runState == QStringLiteral("failed")
+                               || runState == QStringLiteral("interrupted")
+                               || runState == QStringLiteral("blocked"));
         if (running) {
             if (!m_backendRunning[station]) {
                 // 新一轮起跑:本轮「训练结束已下发目标温度」的标记清零,允许再发一次
                 m_tempSent[station] = false;
+                m_endCmdSent[station] = false; // 只在进入新一轮运行态时复位,避免每秒 state 重复放开结束命令
+                m_endSignalReceived[station] = false;
+                m_terminalSince[station].invalidate();
+                m_taskCompleteVerdict[station].clear();
             }
             m_backendRunning[station] = true;
-            m_endCmdSent[station] = false;   // 新一轮:允许结束时再发
         }
-        // 本轮由运行态进入终态:给该工位 MCU 下发测试结束命令 AA 55 08 00 2F。
-        // 只在确实见过运行态时发(软件刚打开、后端已是 completed 不补发),每轮只发一次。
-        if (terminal && m_backendRunning[station] && !m_endCmdSent[station]) {
-            m_endCmdSent[station] = true;
-            if (m_com)
-                m_com->sendTestEndCommand(station);
-            m_store->appendLog(station, QStringLiteral("[qt] 测试结束,已向 MCU 下发 AA 55 08 00 2F"));
-            // 多任务:本轮结束 → 推进到下一个任务(失败则中止整个队列)
-            advanceTask(station, runState == QStringLiteral("failed"));
+        // 0.8.1.19:0x08 只认后端明确的「结束指令」(task_complete / complete=true),
+        // 统一由 finalizeRound 下发。training / rmt / amt / mt 任一阶段 FAIL 时,
+        // 后端要先跑完当前阶段再推结束事件;若这里看到 run_state 终态就抢发,
+        // MCU 会提前结束控温,把还在跑的阶段温度带偏。
+        // 旧后端不推结束事件时,等 kEndSignalWaitMs 后按 state 终态兜底收尾。
+        if (terminal) {
+            if (!m_terminalSince[station].isValid())
+                m_terminalSince[station].start();
+            const bool roundOwnedByUs = m_backendRunning[station] || m_startClicked[station];
+            const bool endSignal = m_endSignalReceived[station];
+            const bool timedOut = m_terminalSince[station].elapsed() >= kEndSignalWaitMs;
+            if (roundOwnedByUs && (endSignal || timedOut)) {
+                const bool failed = backendRoundFailed(station, runState);
+                finalizeRound(station, failed,
+                    endSignal
+                        ? QStringLiteral("run_state=%1 + 后端结束指令").arg(runState)
+                        : QStringLiteral("run_state=%1(%2 ms 未收到 task_complete,兜底)")
+                              .arg(runState).arg(kEndSignalWaitMs));
+            }
+        } else {
+            m_terminalSince[station].invalidate();
         }
         // DDR 训练阶段结束 → 给该工位温控 MCU 下发目标温度(协议 0x01)。
         // 每轮只下一次:后端进入 RMT 后会连续推很多包 phase=rmt 的 state,靠 m_tempSent 去重。
@@ -402,10 +497,9 @@ MainWindow::MainWindow(QWidget *parent)
 
         // 后端报「本轮结束」就把计时停在这,秒数不再增长。
         // 不看 m_startClicked:网页端 / 上一次运行起的测试,本机打开软件时也该显示最终时长,
-        // 而不是一路往上走。setEndTime 只认第一次,之后的 state 推送不会把结束时刻往后拖。
-        if ((runState == QStringLiteral("completed") || runState == QStringLiteral("failed"))
-            && m_store->station(station).startTime.isValid()) {
-            m_store->setEndTime(station, QDateTime::currentDateTime());
+        // 而不是一路往上走。freezeRuntime 只认第一次,之后的 state 推送不会把时长一直往后拖。
+        if (terminal && m_store->station(station).startTime.isValid()) {
+            m_store->freezeRuntime(station);
         }
 
         if (m_startClicked[station]) {
@@ -421,6 +515,8 @@ MainWindow::MainWindow(QWidget *parent)
             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));
             // 多任务队列还没跑完(后面还有任务在等着发):按钮保持「执行中」,不要复位
@@ -441,13 +537,14 @@ MainWindow::MainWindow(QWidget *parent)
                 if (neverStarted) {
                     m_store->setStartTime(station, QDateTime());   // 根本没起跑:清回 00:00:00
                 } else {
-                    m_store->setEndTime(station, QDateTime::currentDateTime());  // 真的跑完了:停表
-                    // 兜底:后端不推 completed/failed、直接回 idle 表示本轮结束时,也补发一次
+                    m_store->freezeRuntime(station);  // 真的跑完了:停表
+                    // 兜底:后端不推 completed/failed、直接回 idle 表示本轮结束时,也补发一次。
+                    // 走到这里按钮已复位、队列已跑完或中止,按散热收尾。
                     if (!m_endCmdSent[station]) {
                         m_endCmdSent[station] = true;
                         if (m_com)
-                            m_com->sendTestEndCommand(station);
-                        m_store->appendLog(station, QStringLiteral("[qt] 测试结束,已向 MCU 下发 AA 55 08 00 2F"));
+                            m_com->sendTestEndCommand(station, true);
+                        m_store->appendLog(station, QStringLiteral("[qt] 测试结束,已向 MCU 下发 AA 55 08 01 00 D8(散热)"));
                     }
                 }
             }
@@ -467,6 +564,8 @@ 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,
@@ -482,6 +581,41 @@ MainWindow::MainWindow(QWidget *parent)
         const StationData &d = m_store->station(station);
         m_store->appendLog(station, QStringLiteral("[qt] %1 开始测试未成功:%2").arg(d.deviceId, message));
     });
+    // 手册 0.8.1.19:task_complete 主动推送与命令结果 complete=true 都可确认当前任务终态。
+    // BackendLink 按 boot_id 对两条路径去重;这里仍要求 task_status 是终态,才推进 Qt 本地队列。
+    connect(m_backend, &BackendLink::taskProgressReported, this,
+            [this](int station, bool complete, const QString &taskStatus) {
+        if (station < 0 || station >= m_store->count())
+            return;
+        const bool terminalTask = (taskStatus == QStringLiteral("completed")
+                                   || taskStatus == QStringLiteral("failed")
+                                   || taskStatus == QStringLiteral("interrupted"));
+        if (complete && terminalTask) {
+            // completed 命令回执可能先于 task_complete(其中才带 verdict / stage_completions)。
+            // 若当前还没有任何 verdict,先等权威事件;旧后端没有该事件时仍由 state 终态兜底。
+            const QString modelVerdict = m_store->station(station).verdict;
+            if (taskStatus == QStringLiteral("completed")
+                && m_taskCompleteVerdict[station].isEmpty()
+                && modelVerdict.isEmpty())
+                return;
+
+            m_endSignalReceived[station] = true;   // 后端明确的「结束指令」已到
+            const bool failed = backendRoundFailed(station, taskStatus);
+            // 命令级 complete 可能先于 run_state 终态到达:统一收尾入口完成 MCU
+            // 下发与队列推进,幂等保护避免后续 state 再触发一次。
+            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);
+            }
+        }
+    });
     // 现场口径:后端没连上就不发,也不排队、连上后不补发(startTest 直接返回并提示)。
     // 不再连上就补发:没连后端时点开始测试,那一次就作废,重连也不重放。
     // 但连接状态要同步到卡片:断链时标题右边显示「控制台离线」,不留空白。
@@ -605,11 +739,12 @@ void MainWindow::startTest(int index)
     // 没配任务时保持原来的单任务行为(用 stations.Sn 的扁平配置)。
     m_taskQueue[index] = LocalPlans::stationConfig(index).value(QStringLiteral("tasks")).toArray();
     m_taskIndex[index] = m_taskQueue[index].isEmpty() ? -1 : 0;
+    m_taskAdvanceGuard[index] = false;      // 新一轮允许再推进一次
     const int taskTotal = m_taskQueue[index].size();
     m_store->setTaskProgress(index, 0, taskTotal > 0 ? 0 : -1);
 
     // 装载当前任务(没有任务时回落到扁平配置)到后端链路。
-    // 后端没有「保存计划」接口,参数是在 UIP1 / AMT / MT 节点随 StageAction 下发的。
+    // 参数在 StartTest 后优先通过 SetStageIntent 预置(失败时回退 StageAction)下发。
     loadTaskIntoBackend(index);
     const QJsonObject plan = currentTaskConfig(index);
     const QJsonObject planMemory = plan.value(QStringLiteral("memory_params")).toObject();
@@ -619,13 +754,18 @@ void MainWindow::startTest(int index)
     // 异常记录同样按轮次走:上一轮的报错不能带进这一轮
     m_store->clearAlarms(index);
 
-    // 先让界面立即从 00:00:00 起步;后端确认后会用真实的 started_unix_ms 覆盖
-    m_store->setStartTime(index, QDateTime::currentDateTime());
+    // 先清掉上一轮计时显示 00:00:00;本轮起点完全等后端 started_unix_ms,
+    // 不再用本机时间起步。
+    m_store->setStartTime(index, QDateTime());
+    m_backendRunning[index] = false;  // 本次 StartTest 是新一轮,等待后端重新进入运行态
+    m_endCmdSent[index] = false;
+    m_endSignalReceived[index] = false;
+    m_terminalSince[index].invalidate();
+    m_taskCompleteVerdict[index].clear();
+    m_tempSent[index] = false;
     m_overview->setStartRunning(index, true);
     m_startClicked[index] = true;
     m_sawRunning[index] = false;        // 本轮还没见到运行态,等后端 transition
-    m_tempSent[index] = false;
-    m_endCmdSent[index] = false;
     m_clickTimer[index].start();        // 兜底重试计时起点
 
     const StationData &d = m_store->station(index);
@@ -671,6 +811,15 @@ void MainWindow::startTest(int index)
                                   .arg(mtOn ? QStringLiteral("启用(UEFI Shell 跑 %1)").arg(efiPath)
                                             : QStringLiteral("未启用(UEFI Shell 发 skip_mt)")));
 
+    // 手册 9.5:换条停机后的「开始测试」本身就是强制抢占并重启新一轮,
+    // 不应先并发发送 ConfirmDimmReplacement(那是另一条独立确认流程),
+    // 否则两个异步 RPC 可能竞争后端 blocked 状态。这里直接调用 StartTest。
+    if (m_store->station(index).awaitingDimmReplacement) {
+        m_store->appendLog(index,
+            QStringLiteral("[qt] %1 换条后选择强制重启:直接提交 StartTest,由后端签发新轮次")
+                .arg(m_store->station(index).deviceId));
+    }
+
     // 上面已经确认后端在线;被后端拒了会走 startTestReplied → 立刻退回「开始测试」并写明原因
     m_backend->startTest(index);
 }
@@ -704,14 +853,90 @@ void MainWindow::loadTaskIntoBackend(int station)
     m_backend->setAmtParams(station, cfg.value(QStringLiteral("amt")).toObject());
     m_backend->setMtParams(station, cfg.value(QStringLiteral("mt")).toObject());
 
-    QJsonArray one;
-    const int i = (station >= 0 && station < 4) ? m_taskIndex[station] : -1;
-    if (i >= 0 && i < m_taskQueue[station].size())
-        one.append(m_taskQueue[station].at(i));
-    m_backend->setStationTasks(station, one);
 }
 
-// 本轮结束(后端终态):推进到下一个任务,或中止/收尾整个队列。
+// MCU 协议 v1.1:0x08 带 1 字节模式载荷,0x00=散热、0x01=不散热。
+// 多任务串行时中间任务不能散温(否则下一任务要重新预热、腔体温度掉下来),
+// 只有最后一个任务 / 单任务 / 队列因失败或换条停机中止时才让 MCU 吹扫散热。
+bool MainWindow::willRunAnotherTask(int station, bool failed) const
+{
+    if (station < 0 || station >= m_store->count() || failed)
+        return false;                              // 本轮失败 → 队列中止,要散热
+    if (m_store->station(station).awaitingDimmReplacement)
+        return false;                              // 换条停机 → 队列中止,要散热
+    const int idx = m_taskIndex[station];
+    if (idx < 0)
+        return false;                              // 没在多任务队列里(单任务)
+    return idx + 1 < m_taskQueue[station].size();  // 后面还有任务要接着跑
+}
+
+bool MainWindow::backendRoundFailed(int station, const QString &stateOrStatus) const
+{
+    if (station < 0 || station >= m_store->count())
+        return false;
+    if (stateOrStatus == QStringLiteral("failed")
+        || stateOrStatus == QStringLiteral("interrupted"))
+        return true;
+    // 0.8.1.19:training / rmt / amt / mt 任一阶段 FAIL 时,后端可能把本轮
+    // task_status 报成 completed(阶段完整跑完、但结论是 fail)。这种情况同样
+    // 必须按失败收尾:散热、中止本地队列,不能继续发下一个任务。
+    // task_complete 与 state 可能交错到达:同时读取事件缓存和已落入模型的
+    // station.verdict,避免 command.complete 先到时把 completed + verdict=fail 当成功。
+    return m_taskCompleteVerdict[station] == QStringLiteral("fail")
+           || m_store->station(station).verdict == QStringLiteral("fail");
+}
+
+// 收到后端结束指令(task_complete / complete=true)后的统一收尾入口。
+// 0x08 只在这里发,state 的 run_state 终态不再抢发;m_endCmdSent 和
+// finishCurrentTask 的 guard 保证「事件 + 终态 + 兜底」三条路只生效一次。
+void MainWindow::finalizeRound(int station, bool failed, const QString &reason)
+{
+    if (station < 0 || station >= m_store->count())
+        return;
+
+    if (!m_endCmdSent[station]
+        && (m_backendRunning[station] || m_startClicked[station])) {
+        m_endCmdSent[station] = true;
+        // 必须在 finishCurrentTask 之前判断:它会改 m_taskIndex / 清空队列
+        const bool dissipate = !willRunAnotherTask(station, failed);
+        if (m_com)
+            m_com->sendTestEndCommand(station, dissipate);
+        m_store->appendLog(station, dissipate
+            ? QStringLiteral("[qt] 收到后端结束指令(%1):已向 MCU 下发 AA 55 08 01 00 D8(散热)").arg(reason)
+            : QStringLiteral("[qt] 收到后端结束指令(%1)、后面还有任务:已向 MCU 下发 AA 55 08 01 01 DF(不散热,保持腔体温度)").arg(reason));
+    }
+
+    finishCurrentTask(station, failed, reason);
+}
+
+// 本轮结束(后端终态 / 命令 complete)推进到下一个任务,或中止/收尾整个队列。
+// 手册 9.2:run_state 终态与 complete=true 会先后到达,这里统一幂等,
+// 每个任务只推进一次,避免重复发 StartTest。
+void MainWindow::finishCurrentTask(int station, bool failed, const QString &reason)
+{
+    if (station < 0 || station >= m_store->count() || m_taskAdvanceGuard[station])
+        return;
+    m_taskAdvanceGuard[station] = true;
+
+    const StationData &d = m_store->station(station);
+    // 手册 9.5 换条停机:后端把 run_state 置为 blocked 并挂起本轮,
+    // 等测试员换条确认,绝不能自动发下一轮 StartTest。
+    if (d.awaitingDimmReplacement) {
+        m_store->appendLog(station,
+            QStringLiteral("[qt] %1 换条停机(%2):队列停止自动下发,请更换异常内存条后点「开始测试」重启新一轮")
+                .arg(d.deviceId, reason));
+        if (m_taskIndex[station] >= 0)
+            m_store->setTaskProgress(station, m_taskIndex[station], -1);
+        m_taskIndex[station] = -1;
+        m_taskQueue[station] = QJsonArray();
+        return;
+    }
+
+    m_store->appendLog(station,
+        QStringLiteral("[qt] %1 本轮到达终态(%2)").arg(d.deviceId, reason));
+    advanceTask(station, failed);
+}
+
 void MainWindow::advanceTask(int station, bool failed)
 {
     if (station < 0 || station >= m_store->count())
@@ -781,13 +1006,18 @@ void MainWindow::startNextTask(int station)
     m_store->resetChannelResults(station);
 
     loadTaskIntoBackend(station);
+    m_taskAdvanceGuard[station] = false;    // 新任务允许再推进一次
 
-    // 新一轮:日志按任务清空,计时重新起步(setStartTime 会顺带清掉上一轮的 endTime)
+    // 新一轮:日志按任务清空,计时清回 00:00:00,等后端新的 started_unix_ms 起步
     m_store->clearLogs(station);
     m_store->clearAlarms(station);
-    m_store->setStartTime(station, QDateTime::currentDateTime());
+    m_store->setStartTime(station, QDateTime());
+    m_backendRunning[station] = false; // 新任务开始,重新识别运行态切换
     m_tempSent[station] = false;
     m_endCmdSent[station] = false;
+    m_endSignalReceived[station] = false;
+    m_terminalSince[station].invalidate();
+    m_taskCompleteVerdict[station].clear();
     m_sawRunning[station] = false;
     m_clickTimer[station].start();
     m_overview->setStartRunning(station, true);
@@ -863,7 +1093,7 @@ void MainWindow::showChangePassword()
     lay1->addWidget(tip1);
     QLineEdit *oldEdit = new QLineEdit(&dlg1);
     oldEdit->setProperty("role", "paramEdit");
-    oldEdit->setEchoMode(QLineEdit::Password);
+    addPasswordVisibilityToggle(oldEdit);
     oldEdit->setMinimumHeight(32);
     lay1->addWidget(oldEdit);
     QDialogButtonBox *bb1 = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dlg1);
@@ -901,7 +1131,7 @@ void MainWindow::showChangePassword()
     lay2->addWidget(tip2);
     QLineEdit *newEdit = new QLineEdit(&dlg2);
     newEdit->setProperty("role", "paramEdit");
-    newEdit->setEchoMode(QLineEdit::Password);
+    addPasswordVisibilityToggle(newEdit);
     newEdit->setMinimumHeight(32);
     lay2->addWidget(newEdit);
     QLabel *tip3 = new QLabel(QStringLiteral("再次输入新密码:"), &dlg2);
@@ -909,7 +1139,7 @@ void MainWindow::showChangePassword()
     lay2->addWidget(tip3);
     QLineEdit *againEdit = new QLineEdit(&dlg2);
     againEdit->setProperty("role", "paramEdit");
-    againEdit->setEchoMode(QLineEdit::Password);
+    addPasswordVisibilityToggle(againEdit);
     againEdit->setMinimumHeight(32);
     lay2->addWidget(againEdit);
     QDialogButtonBox *bb2 = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dlg2);
@@ -946,13 +1176,8 @@ void MainWindow::showChangePassword()
 void MainWindow::saveAdminPassword(const QString &pwd)
 {
     const QString readPath = appConfigPath(QStringLiteral("config.json"));
-    if (readPath.isEmpty()) {
-        ResultToast::popup(this, false, QStringLiteral("保存失败"),
-                           QStringLiteral("找不到 config.json"));
-        return;
-    }
     QJsonObject obj;
-    {
+    if (!readPath.isEmpty()) {
         QFile f(readPath);
         if (f.open(QIODevice::ReadOnly))
             obj = QJsonDocument::fromJson(f.readAll()).object();
@@ -1007,7 +1232,7 @@ void MainWindow::showCreateTask()
     pwdLay->addWidget(pwdTip);
     QLineEdit *pwdEdit = new QLineEdit(&pwdDlg);
     pwdEdit->setProperty("role", "paramEdit");
-    pwdEdit->setEchoMode(QLineEdit::Password);
+    addPasswordVisibilityToggle(pwdEdit);
     pwdEdit->setMinimumHeight(32);
     pwdLay->addWidget(pwdEdit);
     QDialogButtonBox *pwdBB = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &pwdDlg);
@@ -1034,37 +1259,68 @@ void MainWindow::showCreateTask()
     // 把任务拖进某个机台的任务框时才写该工位的 qt-plans.json,窗口始终不关。
     CreateTaskDialog dlg(this);
     // 机台上显示「控制台离线」时,不允许把任务拖进它的任务框。
-    // 判据跟卡片标签完全一致(链路断 / 后端报 offline / 拿不到阶段),逐台判断。
+    // 判据跟卡片标签完全一致(含手册 9.2 的 console_online:后端确认在线时不误判离线)。
     dlg.setOnlineProbe([this](int station) {
         if (!m_backend->isConnected())
             return false;
         const StationData &d = m_store->station(station);
-        return d.consoleOnline
-               || (d.connection != QLatin1String("offline")
-                   && !ui::phaseText(d.phase).isEmpty());
+        if (d.consoleOnline == 0)
+            return false;
+        if (d.consoleOnline == 1)
+            return true;
+        // 老版后端没给 console_online:沿用 connection / phase 判据
+        const bool linkLost = (d.connection == QLatin1String("offline")
+                               || d.connection == QLatin1String("error"));
+        return !linkLost && !ui::phaseText(d.phase).isEmpty();
     });
-    connect(&dlg, &CreateTaskDialog::configsSaved, this, [this](bool ok, int station) {
+    // 执行中的任务不允许在「任务分配」页被拖入任务框或被删除。
+    // 任务名是唯一键(创建时已禁止重名),这里遍历四个工位当前正在跑的那条本地队列任务。
+    dlg.setRunningProbe([this](const QString &name) {
+        if (name.isEmpty())
+            return false;
+        for (int s = 0; s < m_store->count(); ++s) {
+            const bool active = m_startClicked[s] || m_backendRunning[s]
+                                || m_store->station(s).taskStatus == QLatin1String("running");
+            if (!active)
+                continue;
+            const int idx = m_taskIndex[s];
+            if (idx < 0 || idx >= m_taskQueue[s].size())
+                continue;
+            const QString cur = m_taskQueue[s].at(idx).toObject()
+                                    .value(QStringLiteral("name")).toString();
+            if (!cur.isEmpty() && cur == name)
+                return true;
+        }
+        return false;
+    });
+    connect(&dlg, &CreateTaskDialog::configsSaved, this,
+            [this](bool ok, int station, const QString &action) {
         const QString dev = QStringLiteral("SLT-HT-%1").arg(station + 1, 3, 10, QLatin1Char('0'));
+        const QString verb = action.isEmpty() ? QStringLiteral("分配") : action;
         if (!ok) {
-            m_store->appendLog(station, QStringLiteral("[qt] %1 任务分配失败:qt-plans.json 写入失败").arg(dev));
-            ResultToast::popup(this, false, QStringLiteral("分配失败"),
+            m_store->appendLog(station,
+                QStringLiteral("[qt] %1 任务%2失败:qt-plans.json 写入失败").arg(dev).arg(verb));
+            ResultToast::popup(this, false, QStringLiteral("%1失败").arg(verb),
                                QStringLiteral("qt-plans.json 写入失败,请检查文件权限。"));
             return;
         }
 
-        // 参数页若正开着,立刻按新 JSON 重铺(RMT / AMT / MT 开关随勾选项联动)
+        // 「机台任务」页可能正开着:分配、移除、清空、删除都要立刻按新 JSON 重铺,
+        // 否则删掉任务后详情页还挂着旧任务条。
         m_detail->refreshParams();
 
         const QJsonObject cfg = LocalPlans::stationConfig(station);
+        const int taskCount = cfg.value(QStringLiteral("tasks")).toArray().size();
         const int mtCount = cfg.value(QStringLiteral("mt")).toObject()
                                .value(QStringLiteral("selected")).toArray().size();
         const int amtCount = cfg.value(QStringLiteral("amt")).toObject()
                                 .value(QStringLiteral("selected")).toArray().size();
         const int rmtCount = cfg.value(QStringLiteral("rmt")).toObject()
                                 .value(QStringLiteral("selected")).toArray().size();
-        m_store->appendLog(station, QStringLiteral("[qt] %1 已分配任务:该工位配置写入 qt-plans.json;"
-                                                   "MT %2、AMT %3、RMT %4 项已选")
-                                      .arg(dev).arg(mtCount).arg(amtCount).arg(rmtCount));
+        m_store->appendLog(station, QStringLiteral("[qt] %1 任务%2:配置已写入 qt-plans.json,"
+                                                   "当前 %3 条任务;MT %4、AMT %5、RMT %6 项已选")
+                                      .arg(dev).arg(verb).arg(taskCount)
+                                      .arg(mtCount).arg(amtCount).arg(rmtCount));
         // 不弹「任务已分配」的模态框:一个机台要连续拖好几条任务,
         // 每拖一条弹一次会把下一次拖拽的落点挡住。反馈放在对话框顶部那行提示里。
     });
@@ -1117,13 +1373,16 @@ void MainWindow::setupCom()
     });
 
     // 测试结束命令下发结果:帧发出去 / 串口没打开,都写进工位日志
-    connect(m_com, &ComManager::testEndSent, this, [this](int index, bool ok) {
+    connect(m_com, &ComManager::testEndSent, this, [this](int index, bool ok, bool dissipate) {
         if (index < 0 || index >= m_store->count())
             return;
         const StationData &d = m_store->station(index);
+        const QString frame = dissipate
+            ? QStringLiteral("AA 55 08 01 00 D8(散热)")
+            : QStringLiteral("AA 55 08 01 01 DF(不散热)");
         m_store->appendLog(index, ok
-                           ? QStringLiteral("[qt] %1 已向 MCU 下发测试结束命令 AA 55 08 00 2F").arg(d.deviceId)
-                           : QStringLiteral("[qt] %1 串口未连接,测试结束命令 AA 55 08 00 2F 未下发").arg(d.deviceId));
+            ? QStringLiteral("[qt] %1 测试结束命令 %2 已下发到 MCU").arg(d.deviceId).arg(frame)
+            : QStringLiteral("[qt] %1 串口未连接,测试结束命令 %2 未下发").arg(d.deviceId).arg(frame));
     });
 
     loadSerialConfig();

+ 21 - 1
src/mainwindow.h

@@ -106,7 +106,7 @@ private:
     bool m_startClicked[4] = {false, false, false, false};
     bool m_sawRunning[4] = {false, false, false, false};
     bool m_backendRunning[4] = {false, false, false, false};
-    // 本轮是否已给 MCU 下发了「测试结束」命令 AA 55 08 00 2F:
+    // 本轮是否已给 MCU 下发了「测试结束」命令 0x08(散热 / 不散热按队列决定):
     // 见到运行态清 false(新一轮可再发),终态只发一次,避免后端重复推状态导致重复下发。
     bool m_endCmdSent[4] = {false, false, false, false};
     // 本轮是否已给 MCU 下发目标温度(协议 0x01)。
@@ -117,7 +117,16 @@ private:
     // m_taskIndex < 0 表示不在多任务流程里(没配任务,或队列已跑完/中止)。
     QJsonArray m_taskQueue[4];
     int m_taskIndex[4] = {-1, -1, -1, -1};
+    // 手册 9.2:后端命令的 complete=true 与 state 的 run_state 终态会先后到达,
+    // 两处都可能触发队列推进。每轮任务只允许推进一次,避免重复发 StartTest。
+    bool m_taskAdvanceGuard[4] = {false, false, false, false};
     QElapsedTimer m_clickTimer[4];
+    // 0.8.1.19:本轮是否已收到后端明确的「结束指令」(task_complete 事件 /
+    // complete=true 终态)。只有它到达才给 MCU 下发 0x08;state 的 run_state
+    // 终态只做 3 s 超时兜底(兼容旧后端),避免阶段 FAIL 时前端抢发结束命令。
+    bool m_endSignalReceived[4] = {false, false, false, false};
+    QElapsedTimer m_terminalSince[4];
+    QString m_taskCompleteVerdict[4];   // 本轮 task_complete 的 verdict(pass/fail)
 
 
     // ---- 多任务串行执行 ----
@@ -127,6 +136,17 @@ private:
     void loadTaskIntoBackend(int station);              // 把当前任务装载到后端链路(只发这一个任务)
     void advanceTask(int station, bool failed);         // 本轮结束:推进到下一个 / 中止队列
     void startNextTask(int station);                    // 起下一轮(清日志、重置计时、发 StartTest)
+    // 手册 9.2/9.5:本轮终态统一入口(run_state 终态 或 命令 complete=true),
+    // 幂等;换条停机时只中止队列、不自动发下一轮。
+    void finishCurrentTask(int station, bool failed, const QString &reason);
+    // MCU 协议 v1.1 的 0x08 散热决策:本轮结束后是否还有下一个任务要接着跑。
+    // 有 → 发「不散热」帧保持腔体温度;没有 → 发「散热」帧收尾。
+    bool willRunAnotherTask(int station, bool failed) const;
+    // 本轮是否失败:除 failed/interrupted 外,0.8.1.18 的 task_complete 带 verdict,
+    // 阶段 FAIL 时后端可能仍报 task_status=completed(阶段跑完但结论失败),也按失败收尾。
+    bool backendRoundFailed(int station, const QString &stateOrStatus) const;
+    // 收到后端结束指令后的统一收尾:按队列发 0x08(幂等)+ 推进/中止本地任务队列。
+    void finalizeRound(int station, bool failed, const QString &reason);
 };
 
 #endif // MAINWINDOW_H

+ 18 - 13
src/overviewview.cpp

@@ -179,7 +179,7 @@ void OverviewView::renderInfo(int index)
     if (m_temp[index])
         m_temp[index]->setText(ui::formatTemp(d.currentTemp));
     if (m_runtime[index])
-        m_runtime[index]->setText(ui::formatElapsed(d.startTime, d.endTime));
+        m_runtime[index]->setText(ui::formatRuntimeMs(m_store->runtimeMs(index)));
 
     // 标题右侧:控制台离线时优先显示「控制台离线」(红),否则显示当前阶段。
     // 离线是 StartTest 反复 INTERNAL 的直接原因,放在标题旁最容易被看到。
@@ -190,23 +190,28 @@ void OverviewView::renderInfo(int index)
         //   以上都算「控制台离线」;只有真正拿到阶段(MT / DDR Training / 空闲…)才显示阶段。
         // 否则会出现「一台空闲、三台离线」这种看起来不一致的状态。
         QString text = ui::phaseText(d.phase);
-        if (d.awaitingDimmReplacement) {
-            text = QStringLiteral("等待更换内存条");
-        } else if (d.consoleOnline && text.isEmpty()) {
-            text = QStringLiteral("空闲");
-        }
-        const bool offline = !d.awaitingDimmReplacement
-                             && ((!d.consoleOnline && d.connection == QLatin1String("offline"))
-                                 || !m_backendOnline
-                                 || text.isEmpty());
-        if (offline)
+        // 手册 9.2 新增 console_online:后端按串口链路 + 实时字节流主动检测的控制台在线状态。
+        // 它为 true 时,connection 一次瞬时 offline 或 phase 暂时取不到都不得误报「控制台离线」;
+        // 为 false / 缺失时回落到老判据(WebSocket 断链、connection=offline/error、拿不到阶段)。
+        const bool linkLost = (d.connection == QLatin1String("offline")
+                               || d.connection == QLatin1String("error"));
+        const bool consoleConfirmed = (d.consoleOnline == 1);
+        const bool offline = !m_backendOnline
+                             || (d.consoleOnline == 0)
+                             || (!consoleConfirmed && (linkLost || text.isEmpty()));
+        if (offline) {
             text = QStringLiteral("控制台离线");
+        } else if (d.awaitingDimmReplacement) {
+            // 9.2/9.5:某阶段 FAIL 后后端挂起本轮(run_state=blocked),等测试员换条。
+            text = QStringLiteral("等待换条");
+        } else if (text.isEmpty()) {
+            text = QStringLiteral("在线");   // 控制台确认在线但阶段未知:标题右边不留空白
+        }
         m_phase[index]->setText(text);
         m_phase[index]->setVisible(!text.isEmpty());
 
         const QString st = (offline || d.awaitingDimmReplacement)
-                               ? QStringLiteral("offline")
-                               : QStringLiteral("normal");
+                               ? QStringLiteral("offline") : QStringLiteral("normal");
         if (m_phase[index]->property("state").toString() != st) {
             m_phase[index]->setProperty("state", st);
             m_phase[index]->style()->unpolish(m_phase[index]);

+ 7 - 1
src/powerbutton.cpp

@@ -33,12 +33,18 @@ void PowerButton::setRunning(bool running)
     if (m_running == running)
         return;
     m_running = running;
-    setCursor(Qt::PointingHandCursor);
+    // 执行中不当按钮用:光标回到箭头,避免「还能点」的暗示;
+    // 是否响应点击由 hitButton() 一并拦掉。
+    setCursor(running ? Qt::ArrowCursor : Qt::PointingHandCursor);
     update();
 }
 
 bool PowerButton::hitButton(const QPoint &pos) const
 {
+    // 执行中完全点不动:按下既不进入按下态,也不会发出 clicked()。
+    // 这一轮要重跑,等它自己跑完(或先在别处停掉)再点。
+    if (m_running)
+        return false;
     return QAbstractButton::hitButton(pos);
 }
 

+ 5 - 7
src/sltproto.cpp

@@ -32,19 +32,17 @@ QByteArray buildFrame(quint8 cmd, const QByteArray &payload)
     return f;
 }
 
-QByteArray frameRequestChannels()
-{
-    return buildFrame(kCmdReqChannels);
-}
-
 QByteArray frameRequestCt7428()
 {
     return buildFrame(kCmdReqCt7428);
 }
 
-QByteArray frameTestEnd()
+QByteArray frameTestEnd(bool dissipate)
 {
-    return buildFrame(kCmdTestEnd);   // AA 55 08 00 2F
+    QByteArray payload;
+    payload.append(static_cast<char>(static_cast<quint8>(dissipate ? 0x00 : 0x01)));
+    // dissipate ? AA 55 08 01 00 D8 : AA 55 08 01 01 DF
+    return buildFrame(kCmdTestEnd, payload);
 }
 
 QByteArray frameSetTargetTemp(int celsius)

+ 7 - 6
src/sltproto.h

@@ -25,9 +25,8 @@ const quint8 kHdr1 = 0x55;
 
 // PC → MCU
 const quint8 kCmdSetTargetTemp = 0x01; // 设置目标温度(会连带启动预加热)→ 0x81
-const quint8 kCmdReqChannels = 0x02;   // 请求 24 路 BMC 温度 → 0x82
 const quint8 kCmdReqCt7428   = 0x0D;   // 请求 CT7428 八路温度 → 0x8D
-const quint8 kCmdTestEnd     = 0x08;   // 测试结束通知(AA 55 08 00 2F)
+const quint8 kCmdTestEnd     = 0x08;   // 测试结束通知(0x08 + 1B 模式载荷,见 frameTestEnd)
 
 // MCU → PC
 const quint8 kRespSetTemp   = 0x81;    // 载荷 1 字节 STATUS:01 成功 / 00 失败
@@ -47,16 +46,18 @@ quint8 crc8(const QByteArray &data);
 // 组帧:AA 55 CMD LEN [Payload] CRC8
 QByteArray buildFrame(quint8 cmd, const QByteArray &payload = QByteArray());
 
-// 请求帧(CRC 已按文档算好,可直接用,运行时仍会实时计算)
-QByteArray frameRequestChannels();     // AA 55 02 00 AD
+// 请求 CT7428 八路温度(CRC 运行时实时计算)
 QByteArray frameRequestCt7428();       // AA 55 0D 00 6E
 
 // 设置目标温度:AA 55 01 01 TEMP CRC8(70℃ → AA 55 01 01 46 37)
 // 注意:0x01 会连带启动预加热;设备正在预热 / BMC 未就绪 / CPLD 失联时会回 0x81 + 00 拒绝
 QByteArray frameSetTargetTemp(int celsius);
 
-// 测试结束:AA 55 08 00 2F(CMD=0x08、无负载、CRC8=0x2F)
-QByteArray frameTestEnd();
+// 测试结束 CMD=0x08,带 1 字节模式载荷(协议 v1.1 第 12 节):
+//   dissipate=true  → AA 55 08 01 00 D8  清状态并散热(8 路风扇 100% 吹扫)
+//   dissipate=false → AA 55 08 01 01 DF  只清状态、不散热(留给下一个任务继续保温)
+// 旧格式 AA 55 08 00 2F(LEN=0)等同散热,固件仍兼容,但上位机现在一律带载荷。
+QByteArray frameTestEnd(bool dissipate = true);
 
 // 解析出来的一个完整帧(payload 不含帧头 / LEN / CRC)
 struct Frame {

Разница между файлами не показана из-за своего большого размера
+ 589 - 468
src/stationdata.cpp


+ 183 - 159
src/stationdata.h

@@ -1,159 +1,183 @@
-#ifndef STATIONDATA_H
-#define STATIONDATA_H
-
-#include <QByteArray>
-#include <QDateTime>
-#include <QJsonObject>
-#include <QObject>
-#include <QString>
-#include <QStringList>
-#include <QTimer>
-#include <QVector>
-
-/**
- * 工位实时数据模型
- * ------------------------------------------------------------------
- * 界面(总览页 / 详情页)只读这里的数据,不自己存状态:
- *   · 数据在后台线程或定时器里持续写入,与界面是否可见无关;
- *   · 详情页每次打开都直接从内存渲染,所以是"秒开",不需要等下一次采样;
- *   · 日志按行追加、完整保留(不截断、不在切换工位时清空)。
- */
-
-// 温控曲线窗口长度:保留最近 200 个温度采样(按 1s 采样 ≈ 200 秒)
-const int kTempHistorySize = 200;
-
-// 单个内存通道的状态(RUN 状态已按需求移除,只剩 PASS / FAIL / IDLE)
-struct ChannelInfo {
-    enum State { Pass = 0, Fail, Idle };
-
-    QString name;           // CPU0_CHA
-    double temperature;     // °C;Idle(未装载)为 -1
-    State state;
-
-    // 该通道自己的温度历史(点详情页上方的通道格子,曲线就切到它)
-    QVector<double> history;
-    int historyStart = 0;   // history[0] 对应的全局采样序号
-
-    ChannelInfo() : temperature(-1.0), state(Idle) {}
-    ChannelInfo(const QString &n, double t, State s) : name(n), temperature(t), state(s) {}
-};
-
-// 一条异常记录(详情页「异常记录」页):来自后端 stage_errors 与 verdict=fail
-struct AlarmInfo {
-    QDateTime time;
-    QString stage;      // training / rmt / amt / mt;空 = 未分类(整体判定)
-    QString text;       // 可读描述
-
-    AlarmInfo() {}
-    AlarmInfo(const QDateTime &t, const QString &s, const QString &x)
-        : time(t), stage(s), text(x) {}
-};
-
-// 一个工位的全部实时数据
-struct StationData {
-    QString deviceId;       // SLT-HT-001
-    QString port;           // 串口名 COM3
-
-    double currentTemp = -1.0;     // <0 表示还没采到温度,界面显示 --℃
-
-    // 后端 phase:boot / uip / training / rmt / amt / post / uefi / mt / unknown / powered_off
-    // 卡片标题右侧显示当前阶段;空或 unknown 时不显示
-    QString phase;
-
-    // 后端 BIOS 控制台连接状态:online / connecting / offline / error。
-    // offline 时卡片标题右侧直接显示「控制台离线」(红色)——这正是不点不行的根因
-    QString connection;
-    bool consoleOnline = false;
-    bool awaitingDimmReplacement = false;
-    int offlineDebounceTicks = 0;
-
-    QVector<double> tempHistory;   // 最近 kTempHistorySize 个腔体温度,最老的在前
-
-    QDateTime startTime;           // 无效 = 还没点过「开始测试」,界面显示 00:00:00
-    QDateTime endTime;             // 无效 = 本轮还在跑;有效 = 后端报完成/失败的时刻,计时停在这里
-
-    // 多任务执行进度(由主窗口维护):
-    //   taskDone    本轮队列里已经跑完的任务数
-    //   taskCurrent 当前正在跑的任务下标,-1 = 不在多任务流程里
-    int taskDone = 0;
-    int taskCurrent = -1;
-
-    QVector<ChannelInfo> channels;      // 24 个
-    QStringList logs;                   // 完整日志,只增不减
-    QVector<AlarmInfo> alarms;          // 本轮异常记录(点「开始测试」时清空)
-};
-
-// 24 通道命名(CPU0_CHA..CHL / CPU1_CHA..CHL):数据源、总览卡、详情页共用同一份顺序
-QStringList channelNames();
-
-class StationStore : public QObject
-{    Q_OBJECT
-
-public:
-    explicit StationStore(int stationCount, QObject *parent = nullptr);
-
-    int count() const { return m_stations.size(); }
-    const StationData &station(int index) const;
-
-    // ---- 写入(数据源调用) ----
-    void initStation(int index, const StationData &data);
-    void appendLog(int index, const QString &line);
-    // 清空该工位的日志(点「开始测试」时用:新一轮只留本轮的 BIOS 日志)
-    void clearLogs(int index);
-
-    // ---- 异常记录(详情页第二个标签页) ----
-    // 来源:后端 stage_errors(training/rmt/amt/mt)与 verdict=fail。
-    // 同一条内容只记一次(state 每秒推送一次,不去重会刷屏)。
-    void appendAlarm(int index, const QString &stage, const QString &text);
-    void clearAlarms(int index);
-    void setCurrentTemp(int index, double temperature);
-    void setPort(int index, const QString &port);
-
-    // 点「开始测试」时把计时起点写进来;传无效 QDateTime 可以把它清回 00:00:00
-    // 顺带清掉上一轮的结束时刻,让计时重新走起来
-    void setStartTime(int index, const QDateTime &start);
-    // 后端报「本轮结束」(completed / failed)时调用:把计时停在 end 上,秒数不再增长。
-    // 已经停过的不会被后面的 state 推送反复改写(只认第一次)
-    void setEndTime(int index, const QDateTime &end);
-    // 多任务进度:done = 已完成任务数,current = 当前任务下标(-1 表示没有在跑的任务)
-    void setTaskProgress(int index, int done, int current);
-    // 新一轮测试开始时清空 24 路内存通道的状态、当前温度和历史曲线;不影响 CT7428 腔体温度采集。
-    void resetChannelResults(int index);
-    // 只通知界面「这个工位的运行时间该重画了」,不改任何数据(给每秒走表的定时器用)
-    void touchRuntime(int index);
-
-    // ---- 真实设备数据入口(串口线程把原始字节送上来,换算规则全在这里) ----
-    // CT7428 八路(0x8D 的 8 字节):跳过 0xFF 后取平均 → 腔体温度;全无效 → -1(显示 --℃)
-    void applyCtTemperatures(int index, const QByteArray &raw8);
-    // 24 路 BMC(0x82 的 24 字节):只写温度(0xFF → -1,界面 --℃)并追加到曲线。
-    // 通道状态灯一律不动——PASS / FAIL / IDLE 只认后端 state 推送
-    void applyChannelTemperatures(int index, const QByteArray &raw24);
-
-    // 串口掉线:腔体温度 + 24 路温度作废(--℃),状态灯与曲线历史保留
-    void clearTemperatures(int index);
-
-    // ---- 后端状态入口(Qt 纯净接口 state 推送里的单个工位对象) ----
-    // 映射通道状态灯(idle/pass/fail)、本轮启动时间,以及 24 通道内存条温度
-    // (channels[i].temperature_c,取代原 MCU 串口 0x82 来源);
-    // 腔体温度(currentTemp)仍由本地 MCU 温控串口采集,后端不下发该字段
-    void applyBackendState(int index, const QJsonObject &station);
-
-
-signals:
-    void logAppended(int index, const QString &line);
-    void logsCleared(int index);
-    void alarmsChanged(int index);      // 异常记录有增删:详情页整列表重铺
-    void channelsChanged(int index);
-    void temperatureChanged(int index);
-    void infoChanged(int index);        // 设备编号/任务/串口等静态信息变化
-
-private slots:
-    // 每秒推动一次已开始测试工位的「运行时间」走表(只发 infoChanged,不改数据)
-    void runtimeTick();
-
-private:
-    QVector<StationData> m_stations;
-    QTimer m_runtimeTimer;
-};
-
-#endif // STATIONDATA_H
+#ifndef STATIONDATA_H
+#define STATIONDATA_H
+
+#include <QByteArray>
+#include <QDateTime>
+#include <QElapsedTimer>
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QObject>
+#include <QString>
+#include <QStringList>
+#include <QTimer>
+#include <QVector>
+
+/**
+ * 工位实时数据模型
+ * ------------------------------------------------------------------
+ * 界面(总览页 / 详情页)只读这里的数据,不自己存状态:
+ *   · 数据在后台线程或定时器里持续写入,与界面是否可见无关;
+ *   · 详情页每次打开都直接从内存渲染,所以是"秒开",不需要等下一次采样;
+ *   · 日志按行追加、完整保留(不截断、不在切换工位时清空)。
+ */
+
+// 温控曲线窗口长度:保留最近 200 个温度采样(按 1s 采样 ≈ 200 秒)
+const int kTempHistorySize = 200;
+
+// 单个内存通道的状态(RUN 状态已按需求移除,只剩 PASS / FAIL / IDLE)
+struct ChannelInfo {
+    enum State { Pass = 0, Fail, Idle };
+
+    QString name;           // CPU0_CHA
+    double temperature;     // °C;Idle(未装载)为 -1
+    State state;
+
+    // 该通道自己的温度历史(点详情页上方的通道格子,曲线就切到它)
+    QVector<double> history;
+    int historyStart = 0;   // history[0] 对应的全局采样序号
+
+    ChannelInfo() : temperature(-1.0), state(Idle) {}
+    ChannelInfo(const QString &n, double t, State s) : name(n), temperature(t), state(s) {}
+};
+
+// 一条异常记录(详情页「异常记录」页):来自后端 stage_errors 与 verdict=fail
+struct AlarmInfo {
+    QDateTime time;
+    QString stage;      // training / rmt / amt / mt;空 = 未分类(整体判定)
+    QString text;       // 可读描述
+
+    AlarmInfo() {}
+    AlarmInfo(const QDateTime &t, const QString &s, const QString &x)
+        : time(t), stage(s), text(x) {}
+};
+
+// 一个工位的全部实时数据
+struct StationData {
+    QString deviceId;       // SLT-HT-001
+    QString port;           // 串口名 COM3
+
+    double currentTemp = -1.0;     // <0 表示还没采到温度,界面显示 --℃
+
+    // 后端 phase:boot / uip(界面显示 ICT) / training / rmt / amt / post / uefi / mt / unknown / powered_off
+    // 卡片标题右侧显示当前阶段;空或 unknown 时不显示
+    QString phase;
+
+    // 后端 BIOS 控制台连接状态:online / connecting / offline / error。
+    // offline 时卡片标题右侧直接显示「控制台离线」(红色)
+    QString connection;
+    int offlineDebounceTicks = 0;         // connection=offline 防抖计数(2 拍确认)
+    QString bootId;                       // 当前 BIOS 启动轮次,切换时清空 24 路旧结果
+
+    // 后端工位级测试结论与固件族(0.8.1.19)
+    QString verdict;
+    QString verdictScope;
+    QString firmwareFamily;
+    QJsonObject stageCompletions;          // ICT1 / Training / RMT / AMT / ICT2 / UEFI / MT 七个独立完成标志
+
+    // ---- 手册 9.2:GetState / state 推送新增的工位状态字段 ----
+    // console_online 是后端按串口链路 + 实时字节流主动检测的控制台在线状态:
+    // 为 true 时,connection 一次瞬时 offline 或 phase 暂时取不到都不能误报「控制台离线」。
+    // -1 = 后端未提供该字段(旧版),界面回落到 connection / phase 的老判据。
+    int consoleOnline = -1;                // 1 在线 / 0 离线 / -1 未知
+    bool awaitingDimmReplacement = false;  // 换条停机挂起(后端把 run_state 置为 blocked)
+    QString taskStatus;                    // not_started / queued / running / completed / failed
+    QJsonObject taskBatch;                 // 后端托管批次队列快照(前端自维护队列时仅留档)
+    QJsonArray taskHistory;                // 已完成轮次归档摘要
+
+    QVector<double> tempHistory;   // 最近 kTempHistorySize 个腔体温度,最老的在前
+
+    // 运行时间:起点只认后端 started_unix_ms(这里存转换值,仅作「本轮是否起跑」标记),
+    // 走表用单调计时器,终态冻结;计时链路不再使用本机墙钟 currentDateTime()。
+    QDateTime startTime;           // 无效 = 后端还没确认本轮启动,界面显示 00:00:00
+    QElapsedTimer runtimeClock;    // 单调时钟:收到后端起点时 start()
+    qint64 frozenMs = -1;          // 终态冻结的时长(ms);-1 = 未冻结
+
+    // 多任务执行进度(由主窗口维护):
+    //   taskDone    本轮队列里已经跑完的任务数
+    //   taskCurrent 当前正在跑的任务下标,-1 = 不在多任务流程里
+    int taskDone = 0;
+    int taskCurrent = -1;
+
+    QVector<ChannelInfo> channels;      // 24 个
+    QStringList logs;                   // 完整日志,只增不减
+    QVector<AlarmInfo> alarms;          // 本轮异常记录(点「开始测试」时清空)
+};
+
+// 24 通道命名(CPU0_CHA..CHL / CPU1_CHA..CHL):数据源、总览卡、详情页共用同一份顺序
+QStringList channelNames();
+
+class StationStore : public QObject
+{
+    Q_OBJECT
+
+public:
+    explicit StationStore(int stationCount, QObject *parent = nullptr);
+
+    int count() const { return m_stations.size(); }
+    const StationData &station(int index) const;
+
+    // ---- 写入(数据源调用) ----
+    void initStation(int index, const StationData &data);
+    void appendLog(int index, const QString &line);
+    // 清空该工位的日志(点「开始测试」时用:新一轮只留本轮的 BIOS 日志)
+    void clearLogs(int index);
+
+    // ---- 异常记录(详情页第二个标签页) ----
+    // 来源:后端 stage_errors(training/rmt/amt/mt)与 verdict=fail。
+    // 同一条内容只记一次(state 每秒推送一次,不去重会刷屏)。
+    void appendAlarm(int index, const QString &stage, const QString &text);
+    void clearAlarms(int index);
+    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 = 未起跑。起点来自后端,增量来自单调时钟。
+    qint64 runtimeMs(int index) const;
+    // 多任务进度:done = 已完成任务数,current = 当前任务下标(-1 表示没有在跑的任务)
+    void setTaskProgress(int index, int done, int current);
+    // 新一轮测试开始时清空 24 路内存通道的状态、当前温度和历史曲线;不影响 CT7428 腔体温度采集。
+    void resetChannelResults(int index);
+    // 只通知界面「这个工位的运行时间该重画了」,不改任何数据(给每秒走表的定时器用)
+    void touchRuntime(int index);
+
+    // ---- 真实设备数据入口(串口线程把原始字节送上来,换算规则全在这里) ----
+    // CT7428 八路(0x8D 的 8 字节):跳过 0xFF 后取平均 → 腔体温度;全无效 → -1(显示 --℃)
+    void applyCtTemperatures(int index, const QByteArray &raw8);
+    // 24 路 BMC(0x82 的 24 字节):只写温度(0xFF → -1,界面 --℃)并追加到曲线。
+    // 通道状态灯一律不动——PASS / FAIL / IDLE 只认后端 state 推送
+    void applyChannelTemperatures(int index, const QByteArray &raw24);
+
+    // 串口掉线:腔体温度 + 24 路温度作废(--℃),状态灯与曲线历史保留
+    void clearTemperatures(int index);
+
+    // ---- 后端状态入口(Qt 纯净接口 state 推送里的单个工位对象) ----
+    // 映射通道状态灯(idle/pass/fail)、本轮启动时间,以及 24 通道内存条温度
+    // (channels[i].temperature_c,取代原 MCU 串口 0x82 来源);
+    // 腔体温度(currentTemp)仍由本地 MCU 温控串口采集,后端不下发该字段
+    void applyBackendState(int index, const QJsonObject &station);
+    // 0.8.1.19:处理独立 task_complete 推送(终态、verdict 与七阶段完成快照)。
+    void applyTaskComplete(int index, const QJsonObject &result);
+
+
+signals:
+    void logAppended(int index, const QString &line);
+    void logsCleared(int index);
+    void alarmsChanged(int index);      // 异常记录有增删:详情页整列表重铺
+    void channelsChanged(int index);
+    void temperatureChanged(int index);
+    void infoChanged(int index);        // 设备编号/任务/串口等静态信息变化
+
+private slots:
+    // 每秒推动一次已开始测试工位的「运行时间」走表(只发 infoChanged,不改数据)
+    void runtimeTick();
+
+private:
+    QVector<StationData> m_stations;
+    QTimer m_runtimeTimer;
+};
+
+#endif // STATIONDATA_H

Разница между файлами не показана из-за своего большого размера
+ 850 - 832
src/style/app.qss


+ 19 - 11
src/uiformat.h

@@ -1,7 +1,7 @@
 #ifndef UIFORMAT_H
 #define UIFORMAT_H
 
-#include <QDateTime>
+#include <QtGlobal>
 #include <QLatin1Char>
 #include <QString>
 
@@ -11,17 +11,12 @@
  */
 namespace ui {
 
-// 运行时长 HH:mm:ss
-// start 无效 = 这个工位还没点过「开始测试」,统一显示 00:00:00
-// end 有效 = 本轮已结束(后端报 completed / failed),按 end 算并停住;
-// end 无效 = 还在跑,按当前时刻算(每秒重画一次自然就"走表"了)
-inline QString formatElapsed(const QDateTime &start, const QDateTime &end = QDateTime())
+// 运行时长 HH:mm:ss。入参是「本轮已运行毫秒」,由 StationStore 按后端
+// started_unix_ms 起点 + 单调计时器算出;<0 表示本轮还没起跑,显示 00:00:00。
+// 这里不读本机墙钟,避免本机时间被修改 / 与后端时钟不同步时显示错乱。
+inline QString formatRuntimeMs(qint64 ms)
 {
-    if (!start.isValid())
-        return QStringLiteral("00:00:00");
-
-    const QDateTime stop = end.isValid() ? end : QDateTime::currentDateTime();
-    qint64 secs = qMax<qint64>(0, start.secsTo(stop));
+    qint64 secs = qMax<qint64>(0, ms) / 1000;
     const qint64 h = secs / 3600;
     secs %= 3600;
     const qint64 m = secs / 60;
@@ -48,6 +43,8 @@ inline QString phaseText(const QString &phase)
         return QString();
     if (phase == QLatin1String("idle"))        return QStringLiteral("空闲");
     if (phase == QLatin1String("boot"))        return QStringLiteral("Boot");
+    // 手册第 9.1 节:界面统一显示 ICT(IMC Config Tool);底层协议 phase 仍是 "uip",
+    // input.stage 仍是 uip1/uip2、action 仍是 continue_uip/apply_uip,一个字都不能跟着改。
     if (phase == QLatin1String("uip"))         return QStringLiteral("ICT");
     if (phase == QLatin1String("uip1"))        return QStringLiteral("ICT1");
     if (phase == QLatin1String("uip2"))        return QStringLiteral("ICT2");
@@ -61,6 +58,17 @@ inline QString phaseText(const QString &phase)
     return phase;   // 未知但非空:原样显示,便于现场排查
 }
 
+// input.stage → 界面 / 日志里的阶段名(手册 9.1:UIP1/UIP2 显示为 ICT1/ICT2)。
+// 注意这里只做「显示文案」转换:对比、请求里的 stage 值必须继续用原始 uip1/uip2。
+inline QString inputStageText(const QString &stage)
+{
+    if (stage == QLatin1String("uip1"))     return QStringLiteral("ICT1");
+    if (stage == QLatin1String("uip2"))     return QStringLiteral("ICT2");
+    if (stage == QLatin1String("amt"))      return QStringLiteral("AMT");
+    if (stage == QLatin1String("uefi"))     return QStringLiteral("UEFI");
+    return stage;
+}
+
 // 24 通道格子里「名称」和「状态/温度」两行之间额外拉开的间隙(px)
 // 0 = 贴着;调大两行分得更开。概览卡片和详情页共用这一个值,
 // 改这一处两边一起变(两个视图在 cache 控件时都拿它去设格子布局的 spacing)。

+ 1 - 68
tools/validate_qt_clean.py

@@ -85,8 +85,7 @@ class Evidence:
             "schema": "qt-clean-validation-v1", "started_utc": timestamp(),
             "endpoint": safe_url(args.url), "station_id": args.station,
             "requested": {"start": args.start, "drive_default_plan": args.drive_default_plan,
-                          "check_unconfigured": args.check_unconfigured,
-                          "grpc": bool(args.grpc_address)},
+                          "check_unconfigured": args.check_unconfigured},
             "checks": [], "commands": [], "state_transitions": [], "logs": [],
             "protocol_verdict": "RUNNING", "memory_verdict": "NOT_TESTED",
             "memory_verdict_reason": "This driver does not run AMT or MT; reaching UEFI is not memory PASS.",
@@ -315,69 +314,6 @@ async def readonly_checks(client, evidence, args, session, token):
     evidence.check("first_client_survives_second_disconnect", (await client.get_state()).get("server_id") == state.get("server_id"))
 
 
-async def grpc_check(args, evidence, token):
-    if not args.grpc_address:
-        return
-    try:
-        import grpc
-        metadata = (("authorization", "Bearer " + token),) if token else ()
-        async with grpc.aio.insecure_channel(args.grpc_address) as channel:
-            raw_info = await channel.unary_unary(
-                "/stl.v1.BenchService/GetSystemInfo",
-                request_serializer=lambda b: b,
-                response_deserializer=lambda b: b,
-            )(b"", timeout=15, metadata=metadata)
-            raw_stations = await channel.unary_unary(
-                "/stl.v1.BenchService/ListStations",
-                request_serializer=lambda b: b,
-                response_deserializer=lambda b: b,
-            )(b"", timeout=15, metadata=metadata)
-
-        def decode_pb_fields(buf):
-            idx, out = 0, {}
-            while idx < len(buf):
-                tag, shift = 0, 0
-                while True:
-                    b = buf[idx]; idx += 1
-                    tag |= (b & 0x7F) << shift
-                    if not (b & 0x80):
-                        break
-                    shift += 7
-                fn, wt = tag >> 3, tag & 7
-                if wt == 0:
-                    val, shift = 0, 0
-                    while True:
-                        b = buf[idx]; idx += 1
-                        val |= (b & 0x7F) << shift
-                        if not (b & 0x80):
-                            break
-                        shift += 7
-                    out.setdefault(fn, []).append(val)
-                elif wt == 2:
-                    ln, shift = 0, 0
-                    while True:
-                        b = buf[idx]; idx += 1
-                        ln |= (b & 0x7F) << shift
-                        if not (b & 0x80):
-                            break
-                        shift += 7
-                    out.setdefault(fn, []).append(buf[idx:idx + ln])
-                    idx += ln
-                else:
-                    break
-            return out
-
-        info_f = decode_pb_fields(raw_info)
-        st_f = decode_pb_fields(raw_stations)
-        ver = info_f.get(1, [b""])[0].decode("utf-8", "replace")
-        mode = info_f.get(4, [b""])[0].decode("utf-8", "replace")
-        st_cnt = len(st_f.get(1, []))
-        evidence.check("native_grpc_readonly_compatibility", bool(ver) and st_cnt > 0,
-                       {"version": ver, "mode": mode, "station_count": st_cnt})
-    except Exception as exc:
-        evidence.check("native_grpc_readonly_compatibility", False, {"error": type(exc).__name__, "message": str(exc)[:500]})
-
-
 async def unconfigured_check(client, evidence, args):
     if not args.check_unconfigured:
         return
@@ -493,7 +429,6 @@ async def run(args, evidence):
     async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30)) as session:
         async with WsClient(session, args.url, evidence, token) as client:
             await readonly_checks(client, evidence, args, session, token)
-            await grpc_check(args, evidence, token)
             if evidence.fail_count():
                 raise RuntimeError("Read-only contract checks failed; no hardware actions submitted")
             await unconfigured_check(client, evidence, args)
@@ -516,8 +451,6 @@ def main():
     parser.add_argument("--start", action="store_true", help="Actually start/reset the server host once")
     parser.add_argument("--drive-default-plan", action="store_true", help="With --start: CR at UIP; exit AMT; stop at UEFI")
     parser.add_argument("--check-unconfigured", metavar="STATION", help="Explicitly try StartTest on a station with bmc_power=false")
-    parser.add_argument("--grpc-address", help="Optional native gRPC HOST:PORT read-only smoke test")
-    parser.add_argument("--backend-source", help="Backend project root for generated gRPC modules")
     parser.add_argument("--token-env", help="Environment variable containing API bearer token; never written to evidence")
     args = parser.parse_args()
     if args.drive_default_plan and not args.start:

+ 2 - 2
web/boot-plan-controls.js

@@ -42,7 +42,7 @@
           </select></label>
           <label>MT (118.efi) 快捷覆盖<select id="tb-profile-mt-mode">
             <option value="current">沿用第 4 页已保存的 PXE/MT 详细配置</option>
-            <option value="fast64m">短地址极速验证 (TSTLIST=0..13 · 仅测 64MB 区间)</option>
+            <option value="fast64m">短地址极速验证 (TSTLIST=0..25 · 仅测 64MB 区间)</option>
             <option value="test0_64m">仅测 Test 0 + 64MB 短地址 (10秒极速)</option>
             <option value="test0_all">仅测 Test 0 (全内存)</option>
             <option value="skip">本 Profile 跳过 MT (到 UEFI Shell 即完成)</option>
@@ -360,7 +360,7 @@
       if (mtMode === 'skip') {
         runMt = false;
       } else if (mtMode === 'fast64m') {
-        mt.tstlist = '0,1,2,3,4,5,6,7,8,9,10,11,12,13';
+        mt.tstlist = '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25';
         mt.memory_range = 'custom';
         mt.addr_lim_lo = '0x10000000';
         mt.addr_lim_hi = '0x14000000';

+ 27 - 12
web/firmware-controls.js

@@ -349,7 +349,7 @@
     $('phase-action-context').textContent = `${firmware.live === false ? '上次观测:' : prompt.ready ? '当前输入:' : ''}${title}${detail ? ' · ' + detail : ''}${firmware.observed_unix_ms ? ' · ' + api.time(firmware.observed_unix_ms) : ''}`;
     $('btn-send-enter').title = prompt.ready && prompt.kind === 'uip' ? '只发送 CR:继续当前 ICT,不自动应用页面参数' : '只发送一个回车字符,不附带页面配置';
     const last = control.last_phase_action || {}, name = {ContinueUip:'ICT 发送 exit 继续',SkipAmt:'退出 AMT'}[last.action] || last.action || '';
-    const confirmation = {submitted:last.output_observed ? '已发送,等待后续节点确认' : '已发送,尚无回显',queued_intent:'已存入待消费阶段意图 (到阶段自动执行)',transition_observed:'已观察到后续节点',rejected:'固件返回错误'}[last.confirmation] || last.confirmation || '待确认';
+    const confirmation = {submitted:last.output_observed ? '已发送,等待后续节点确认' : '已发送,尚无回显',staged:'已存入待消费阶段意图 (到阶段自动执行)',queued_intent:'已存入待消费阶段意图 (到阶段自动执行)',transition_observed:'已观察到后续节点',rejected:'固件返回错误'}[last.confirmation] || last.confirmation || '待确认';
     $('phase-action-last-summary').textContent = last.observed_unix_ms ? `${name} · ${confirmation} · ${last.confirmed_unix_ms ? '确认于 ' + api.time(last.confirmed_unix_ms) : api.time(last.observed_unix_ms)}` : '尚无记录';
     const followup = last.confirmation === 'submitted' ? ' 后端继续观察,后续回显到达后自动更新,无需重复点击。' : '';
     const prior = last.action === 'SkipAmt' && last.prior_amt_execution_observed ? ' 此前的算法执行记录保留,本次退出不启动新测试。' : '';
@@ -358,7 +358,7 @@
   }
   function renderResponses() {
     const value = snapshot(), applied = value.last_uip_apply || {}, mt = value.last_mt_launch || {};
-    $('uip-last-apply-summary').textContent = applied.observed_unix_ms ? `${{submitted:'已发送,按回显核对',queued_intent:'已存入待消费阶段意图',rejected:'固件返回错误',unchanged:'未发送覆盖'}[applied.confirmation] || applied.confirmation} · ${api.time(applied.observed_unix_ms)}` : '尚无记录';
+    $('uip-last-apply-summary').textContent = applied.observed_unix_ms ? `${{submitted:'已发送,按回显核对',staged:'已存入待消费阶段意图',queued_intent:'已存入待消费阶段意图',rejected:'固件返回错误',unchanged:'未发送覆盖'}[applied.confirmation] || applied.confirmation} · ${api.time(applied.observed_unix_ms)}` : '尚无记录';
     $('uip-last-apply-responses').innerHTML = (applied.responses || []).map(row => `<section><strong>${esc(row.command)}</strong><span>${row.prompt_observed ? '已回到提示符' : '尚未观察到提示符'}</span><pre>${esc(api.terminalText(row.output) || '没有返回文本')}</pre></section>`).join('') || '尚未发送参数。';
     const mtStatus = mt.confirmation === 'rejected' ? '固件拒绝启动' : mt.confirmation === 'submitted' ? mt.output_observed === false ? '已发送,尚无回显' : '已发送,按输出确认' : '启动状态待确认';
     $('mt-last-launch-summary').textContent = mt.observed_unix_ms ? `${mtStatus} · ${api.time(mt.observed_unix_ms)}` : '尚无记录';
@@ -394,7 +394,7 @@
     $('pxe-stage1-preview').textContent = stage1On
       ? ['errhandle disable','admt disable','pxe umemdiag 118.efi','pxe umemdiagcfg mt86.cfg','pxe clientip 192.168.0.160','pxe subnetmaskip 255.255.255.0','pxe gatewayip 192.168.0.10','pxe serverip 192.168.0.10','exit'].join('\n')
       : '(默认标准 PXE 模式:不在 ICT Stage 1 发送 pxe 命令,由 UEFI PXE / DHCP 直接引导 118.efi)';
-    const tst = ($('pxe-cfg-tstlist')?.value || '0,1,2').trim();
+    const tst = ($('pxe-cfg-tstlist')?.value || '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25').trim();
     const cpusel = $('pxe-cfg-cpusel')?.value || 'PARALLEL';
     const cpunum = $('pxe-cfg-cpunum')?.value || '384';
     const maxcpus = $('pxe-cfg-maxcpus')?.value || '384';
@@ -403,6 +403,7 @@
     const memrange = $('pxe-cfg-memrange')?.value || 'all';
     const addrlo = ($('pxe-cfg-addrlo')?.value || '').trim();
     const addrhi = ($('pxe-cfg-addrhi')?.value || '').trim();
+    const tftpIp = snapshot()?.pxe_control?.pxe_server_ip || '192.168.0.10';
     if ($('pxe-cfg-addrlo')) $('pxe-cfg-addrlo').disabled = memrange !== 'custom';
     if ($('pxe-cfg-addrhi')) $('pxe-cfg-addrhi').disabled = memrange !== 'custom';
     const cfgLines = [
@@ -417,6 +418,10 @@
       `AUTOMODE=1`,
       `EXITMODE=2`,
       `SKIPSPLASH=1`,
+      `AUTOREPORT=1`,
+      `AUTOREPORTFMT=HTML`,
+      `REPORTNUMERRS=100`,
+      `TFTPSERVERIP=${tftpIp}`,
     ];
     if (memrange === 'custom' && addrlo) cfgLines.push(`ADDRLIMLO=${addrlo}`);
     if (memrange === 'custom' && addrhi) cfgLines.push(`ADDRLIMHI=${addrhi}`);
@@ -427,8 +432,8 @@
     const control = snapshot();
     const pxe = control.pxe_control || {};
     if ($('pxe-control-panel') && pxe.variants) {
-      if (!selectedPxeVariant) selectedPxeVariant = pxe.active_variant || '118_orig.efi';
-      $('pxe-active-badge').textContent = `当前使用: ${pxe.active_variant || '118_orig.efi'}`;
+      if (!selectedPxeVariant) selectedPxeVariant = pxe.active_variant || '118_serial.efi';
+      $('pxe-active-badge').textContent = `当前使用: ${pxe.active_variant || '118_serial.efi'}`;
       if ($('pxe-sha-note')) $('pxe-sha-note').textContent = pxe.active_sha256 ? `SHA256: ${pxe.active_sha256.slice(0,12)}…` : '';
       const cardsEl = $('pxe-variant-cards');
       if (cardsEl) {
@@ -449,7 +454,7 @@
       }
       if (!pxeFormInitialized && pxe.mt86_cfg) {
         pxeFormInitialized = true;
-        selectedPxeVariant = pxe.active_variant || '118_orig.efi';
+        selectedPxeVariant = pxe.active_variant || '118_serial.efi';
         if ($('pxe-stage1-enabled')) $('pxe-stage1-enabled').checked = !!pxe.stage1_pxe_enabled;
         if ($('pxe-cfg-tstlist')) $('pxe-cfg-tstlist').value = pxe.mt86_cfg.tstlist ?? '0,1,2';
         if ($('pxe-cfg-cpusel')) $('pxe-cfg-cpusel').value = pxe.mt86_cfg.cpusel ?? 'PARALLEL';
@@ -465,7 +470,7 @@
       if ($('pxe-reports-bar')) {
         const rpts = pxe.recent_reports || [];
         $('pxe-reports-bar').innerHTML = `<strong>已回传测试报告 (${rpts.length}):</strong>` + (rpts.length
-          ? rpts.map(r => `<span class="pxe-report-chip">✓ ${esc(r.filename)} · ${esc(r.verdict)}</span>`).join('')
+          ? rpts.map(r => `<span class="pxe-report-chip">${r.verdict === 'pass' ? '✓' : '✗'} ${esc(r.filename)} · ${esc(r.verdict)}${r.errors !== undefined ? ` (${esc(r.errors)} errs)` : ''}</span>`).join('')
           : '<span>暂无报告</span>') + (pxe.remote_sync_note ? `<span class="field-note" style="margin-left:auto">${esc(pxe.remote_sync_note)}</span>` : '');
       }
     }
@@ -628,7 +633,14 @@
     api.bind('btn-save-mt-selection',saveSettings);
     const mtBox = $('mt-test-checkboxes');
     if (mtBox) {
-      const mtNames = ['0:Walking 1s','1:Own Addr','2:MovInv 1&0','3:MovInv 8b','4:MovInv Rand','5:Block Move','6:MovInv 32b','7:Rand Seq','8:Modulo 20','9:Bit Fade','10:Test 10','11:Test 11','12:Test 12','13:Test 13'];
+      const mtNames = [
+        '0:Walking 1s 1CPU','1:Own Addr 1CPU','2:Own Addr','3:MovInv 1&0','4:MovInv 8b',
+        '5:MovInv Rand','6:Block Move','7:MovInv 32b','8:Rand Seq','9:Modulo 20',
+        '10:Bit Fade 2pat','11:Rand 64-bit','12:Rand 128-bit','13:Hammer test','14:DMA test',
+        '15:March C','16:GALPAT','17:GALPAT Linear','18:GALPAT RandAddr','19:GALPAT BankJump',
+        '20:GALPAT Victim','21:GALPAT MarchIC','22:GALPAT MarchSSE','23:GALPAT Butterfly',
+        '24:March SS+','25:Stressapp'
+      ];
       mtBox.innerHTML = mtNames.map((lb,i) => `<label class="check-label"><input type="checkbox" class="mt-test-cb" data-tid="${i}" checked>${lb}</label>`).join('');
       mtBox.querySelectorAll('.mt-test-cb').forEach(cb => cb.addEventListener('change', () => { readMtFields(); if (draft()) draft().modified = true; renderPreviews(); }));
       $('btn-mt-test-all').onclick = () => {
@@ -674,7 +686,7 @@
       });
     }
     if ($('btn-pxe-preset-fast64m')) $('btn-pxe-preset-fast64m').onclick = () => {
-      $('pxe-cfg-tstlist').value = '0,1,2,3,4,5,6,7,8,9,10,11,12,13';
+      $('pxe-cfg-tstlist').value = '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25';
       $('pxe-cfg-cpusel').value = 'PARALLEL'; $('pxe-cfg-cpunum').value = '384'; $('pxe-cfg-maxcpus').value = '384';
       $('pxe-cfg-enableht').value = '1'; $('pxe-cfg-numpass').value = '1';
       if ($('pxe-cfg-memrange')) $('pxe-cfg-memrange').value = 'custom';
@@ -693,7 +705,7 @@
       renderPxePreviewFromDom();
     };
     if ($('btn-pxe-preset-all')) $('btn-pxe-preset-all').onclick = () => {
-      $('pxe-cfg-tstlist').value = '0,1,2,3,4,5,6,7,8,9,10,11,12,13'; $('pxe-cfg-cpusel').value = 'PARALLEL'; $('pxe-cfg-cpunum').value = '384'; $('pxe-cfg-maxcpus').value = '384'; $('pxe-cfg-enableht').value = '1'; $('pxe-cfg-numpass').value = '1';
+      $('pxe-cfg-tstlist').value = '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25'; $('pxe-cfg-cpusel').value = 'PARALLEL'; $('pxe-cfg-cpunum').value = '384'; $('pxe-cfg-maxcpus').value = '384'; $('pxe-cfg-enableht').value = '1'; $('pxe-cfg-numpass').value = '1';
       if ($('pxe-cfg-memrange')) $('pxe-cfg-memrange').value = 'all';
       renderPxePreviewFromDom();
     };
@@ -703,12 +715,12 @@
         const addrLo = ($('pxe-cfg-addrlo')?.value || '').trim();
         const addrHi = ($('pxe-cfg-addrhi')?.value || '').trim();
         const payload = {
-          variant: selectedPxeVariant || '118_orig.efi',
+          variant: selectedPxeVariant || '118_serial.efi',
           stage1_pxe_enabled: !!$('pxe-stage1-enabled')?.checked,
           apply_to_uip: $('pxe-apply-uip')?.checked !== false,
           sync_remote: !!$('pxe-sync-remote')?.checked,
           mt86_cfg: {
-            tstlist: ($('pxe-cfg-tstlist')?.value || '0,1,2').trim(),
+            tstlist: ($('pxe-cfg-tstlist')?.value || '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25').trim(),
             cpusel: $('pxe-cfg-cpusel')?.value || 'PARALLEL',
             cpunum: Number($('pxe-cfg-cpunum')?.value || 384),
             maxcpus: Number($('pxe-cfg-maxcpus')?.value || 384),
@@ -722,6 +734,9 @@
             automode: 1,
             exitmode: 2,
             skipsplash: 1,
+            autoreport: 1,
+            autoreportfmt: 'HTML',
+            reportnumerrs: 100,
           },
         };
         await api.command('ConfigurePxe', payload, `切换 PXE 为 ${payload.variant} 并同步 mt86.cfg`);

+ 15 - 15
web/index.html

@@ -5,7 +5,7 @@
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta name="theme-color" content="#f4f7fa">
   <title>内存高温测试工作台 · 新见科技</title>
-  <link rel="stylesheet" href="style.css?v=0.8.1.18">
+  <link rel="stylesheet" href="style.css?v=0.8.1.19">
 </head>
 <body>
   <header class="app-header">
@@ -231,18 +231,18 @@
             <div class="panel-heading">
               <div>
                 <h3 id="pxe-panel-title">PXE 网络引导与 MemTest86 (118.efi) 配置</h3>
-                <p>上位机 192.168.2.63 有线网口 (192.168.0.10/24) 独立提供标准 PXE 服务,直连被测服务器网口。</p>
+                <p>控制后端内置 UDP :69 TFTP 服务 (192.168.0.10) 并支持同步外部 PXE 主机 (192.168.2.63),自动下发 mt86.cfg 并接收 HTML 报告。</p>
               </div>
-              <span class="badge" id="pxe-active-badge">当前使用: 118_orig.efi</span>
+              <span class="badge" id="pxe-active-badge">当前使用: 118_serial.efi</span>
             </div>
             <div class="pxe-variant-grid" id="pxe-variant-cards" role="radiogroup" aria-label="118.efi 版本选择"></div>
             <div class="pxe-options-row">
               <label class="check-label"><input type="checkbox" id="pxe-stage1-enabled"><strong>启用 ICT Stage 1 静态 PXE 命令注入(可选 · 默认不勾选,直接走标准 DHCP PXE)</strong></label>
               <label class="check-label"><input type="checkbox" id="pxe-apply-uip" checked>保存时同步更新 ICT 附加命令列表</label>
-              <label class="check-label"><input type="checkbox" id="pxe-sync-remote" checked>同步到 192.168.2.63 PXE 容器</label>
+              <label class="check-label"><input type="checkbox" id="pxe-sync-remote" checked>同步到外部 PXE 主机 (192.168.2.63)</label>
             </div>
             <div class="pxe-cfg-grid">
-              <label>测试项 (TSTLIST)<input id="pxe-cfg-tstlist" value="0,1,2" placeholder="如 0 或 0,1,2" spellcheck="false"></label>
+              <label>测试项 (TSTLIST)<input id="pxe-cfg-tstlist" value="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25" placeholder="如 0 或 0..25" spellcheck="false"></label>
               <label>多核模式 (CPUSEL)<select id="pxe-cfg-cpusel"><option value="PARALLEL">PARALLEL (多核并发)</option><option value="SINGLE">SINGLE (单核)</option><option value="RROBIN">RROBIN (轮转)</option><option value="SEQ">SEQ (顺序)</option></select></label>
               <label>启用线程数 (CPUNUM)<input id="pxe-cfg-cpunum" type="number" min="1" max="512" value="384"></label>
               <label>最大线程数 (MAXCPUS)<input id="pxe-cfg-maxcpus" type="number" min="1" max="512" value="384"></label>
@@ -253,10 +253,10 @@
               <label>结束地址 (ADDRLIMHI)<input id="pxe-cfg-addrhi" placeholder="如 0x14000000" spellcheck="false"></label>
             </div>
             <div class="form-actions" style="margin:6px 0">
-              <button type="button" class="btn btn-quiet btn-xs" id="btn-pxe-preset-fast64m">快捷:短地址极速验证 (Test 0..13 · 仅测 64MB)</button>
+              <button type="button" class="btn btn-quiet btn-xs" id="btn-pxe-preset-fast64m">快捷:短地址极速验证 (Test 0..25 · 仅测 64MB)</button>
               <button type="button" class="btn btn-quiet btn-xs" id="btn-pxe-preset-test0">快捷:仅测 Test 0 (全内存)</button>
               <button type="button" class="btn btn-quiet btn-xs" id="btn-pxe-preset-test012">快捷:测 Test 0, 1, 2 (384 线程)</button>
-              <button type="button" class="btn btn-quiet btn-xs" id="btn-pxe-preset-all">快捷:全量 Test 0..13 (全内存 · 384 线程)</button>
+              <button type="button" class="btn btn-quiet btn-xs" id="btn-pxe-preset-all">快捷:全量 Test 0..25 (全内存 · 384 线程)</button>
             </div>
             <div class="pxe-preview-grid">
               <div class="command-preview"><div class="subpanel-title"><strong>PXE 引导方式说明</strong><span id="pxe-stage1-mode-note"></span></div><pre id="pxe-stage1-preview"></pre></div>
@@ -336,13 +336,13 @@
 
     <footer class="app-footer">新见科技 · 内存测试工作台</footer>
   </main>
-  <script src="transport.js?v=0.8.1.18"></script>
-  <script src="boot-plan-controls.js?v=0.8.1.18"></script>
-  <script src="amt-controls.js?v=0.8.1.18"></script>
-  <script src="dimm-overview.js?v=0.8.1.18"></script>
-  <script src="ui-navigation.js?v=0.8.1.18"></script>
-  <script src="firmware-controls.js?v=0.8.1.18"></script>
-  <script src="stage-progress.js?v=0.8.1.18"></script>
-  <script src="app.js?v=0.8.1.18"></script>
+  <script src="transport.js?v=0.8.1.19"></script>
+  <script src="boot-plan-controls.js?v=0.8.1.19"></script>
+  <script src="amt-controls.js?v=0.8.1.19"></script>
+  <script src="dimm-overview.js?v=0.8.1.19"></script>
+  <script src="ui-navigation.js?v=0.8.1.19"></script>
+  <script src="firmware-controls.js?v=0.8.1.19"></script>
+  <script src="stage-progress.js?v=0.8.1.19"></script>
+  <script src="app.js?v=0.8.1.19"></script>
 </body>
 </html>