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

feat: consolidate Qt clean 0.8.1.1.dev0 on dev

XJKJ-STL Dev Automation 1 месяц назад
Родитель
Сommit
e58afe5220
100 измененных файлов с 72050 добавлено и 4915 удалено
  1. 4 0
      .gitattributes
  2. 0 55
      AUDIT.md
  3. 0 63
      BASELINE.md
  4. 0 32
      CHANGELOG.md
  5. 0 38
      CURRENT_TASK.md
  6. 1 1
      Dockerfile
  7. 0 179
      LOCAL_AGENT_TASK.txt
  8. 21 157
      README.md
  9. 1 1
      VERSION
  10. 9 5
      config/hardware.example.json
  11. 14 8
      config/profiles/cxmt-live-gnr.json
  12. 98 0
      config/serial-net.example.json
  13. 4 21
      config/simulated.json
  14. 11 7
      config/station0-live.json
  15. 15 0
      deploy/Dockerfile.qt-runtime
  16. 0 4
      docker-compose.yml
  17. 0 153
      docs/ARCHITECTURE.md
  18. 0 113
      docs/DEPLOYMENT.md
  19. 0 162
      docs/DEVICE_ADAPTERS.md
  20. 0 43
      docs/EVIDENCE_20261023.json
  21. 0 171
      docs/FRONTEND_MAPPING.md
  22. 1096 0
      docs/GRPC_API_ZH.md
  23. 0 225
      docs/GRPC_CLIENT.md
  24. 0 189
      docs/LOG_FORMATS.md
  25. 362 0
      docs/QT_CLIENT_API_ZH.md
  26. 0 93
      docs/REVIEW_20261023.md
  27. 0 114
      docs/TEST_REPORT.md
  28. 1107 0
      docs/WEBSOCKET_API_ZH.md
  29. 0 24
      docs/firmware-commands.csv
  30. 0 10
      docs/hardware-evidence/ipmi_channel_authcap.txt
  31. 0 23
      docs/hardware-evidence/ipmi_lan_print.txt
  32. 0 0
      docs/hardware-evidence/serial_capture_1125200.bin
  33. 0 1
      docs/hardware-evidence/serial_capture_1125200.hex
  34. 0 1
      docs/hardware-evidence/sol_capture.bin
  35. 0 1
      docs/hardware-evidence/sol_capture.hex
  36. 0 16
      docs/hardware-evidence/test_suite_83_passed.log
  37. 25 0
      examples/qt-clean/config.json
  38. 9 0
      examples/qt-websocket/CMakeLists.txt
  39. 105 0
      examples/qt-websocket/main.cpp
  40. 168 0
      native/stl_ssh_console_bridge.py
  41. 138 4
      proto/stl/v1/bench.proto
  42. 4 4
      pyproject.toml
  43. 60 0
      qt-client/DDR5_SLT_Monitor.pro
  44. 129 0
      qt-client/QT_CLEAN_CLIENT_ZH.md
  45. 38 0
      qt-client/config.json
  46. 21 0
      qt-client/live-config-off/config.json
  47. 24 0
      qt-client/live-config-off/port.json
  48. 19 0
      qt-client/live-config-on/config.json
  49. 24 0
      qt-client/live-config-on/port.json
  50. 9 0
      qt-client/port.json
  51. 674 0
      qt-client/src/3rdparty/qcustomplot/GPL.txt
  52. 35529 0
      qt-client/src/3rdparty/qcustomplot/qcustomplot.cpp
  53. 7774 0
      qt-client/src/3rdparty/qcustomplot/qcustomplot.h
  54. 37 0
      qt-client/src/appconfig.h
  55. BIN
      qt-client/src/assets/logo-mark.png
  56. 417 0
      qt-client/src/backendlink.cpp
  57. 89 0
      qt-client/src/backendlink.h
  58. 49 0
      qt-client/src/comanager.cpp
  59. 43 0
      qt-client/src/comanager.h
  60. 231 0
      qt-client/src/comworker.cpp
  61. 84 0
      qt-client/src/comworker.h
  62. 116 0
      qt-client/src/demofeed.cpp
  63. 657 0
      qt-client/src/detailview.cpp
  64. 94 0
      qt-client/src/detailview.h
  65. 75 0
      qt-client/src/localplans.cpp
  66. 24 0
      qt-client/src/localplans.h
  67. 65 0
      qt-client/src/main.cpp
  68. 409 0
      qt-client/src/mainwindow.cpp
  69. 93 0
      qt-client/src/mainwindow.h
  70. 18026 0
      qt-client/src/mainwindow.ui
  71. 196 0
      qt-client/src/overviewview.cpp
  72. 61 0
      qt-client/src/overviewview.h
  73. 103 0
      qt-client/src/powerbutton.cpp
  74. 32 0
      qt-client/src/powerbutton.h
  75. 6 0
      qt-client/src/resources.qrc
  76. 100 0
      qt-client/src/sltproto.cpp
  77. 75 0
      qt-client/src/sltproto.h
  78. 291 0
      qt-client/src/stationdata.cpp
  79. 122 0
      qt-client/src/stationdata.h
  80. 413 0
      qt-client/src/style/app.qss
  81. 52 0
      qt-client/src/uiformat.h
  82. 432 0
      qt-client/tests/qt_clean_probe.cpp
  83. 10 0
      qt-client/tests/qt_clean_probe.pro
  84. 0 2868
      reference/original-archive-manifest.json
  85. 95 0
      scripts/collect_live_evidence.py
  86. 86 0
      scripts/deploy_qt_release.py
  87. 0 89
      scripts/explore_firmware_uip.py
  88. 299 0
      scripts/generate_api_reference.py
  89. 2 2
      scripts/package_delivery.py
  90. 44 0
      scripts/probe_bmc.py
  91. 74 0
      scripts/probe_ipmi_sol.py
  92. 33 0
      scripts/run_qt_fixtures.py
  93. 703 37
      scripts/test_web_browser.mjs
  94. 112 0
      scripts/test_web_command_recovery.mjs
  95. 97 0
      scripts/test_web_transport.mjs
  96. 105 0
      scripts/validate_live_actions.py
  97. 503 0
      scripts/validate_qt_clean.py
  98. 1 1
      src/stl_backend/__init__.py
  99. 1 0
      src/stl_backend/application/__init__.py
  100. 0 0
      src/stl_backend/application/acquisition.py

+ 4 - 0
.gitattributes

@@ -0,0 +1,4 @@
+# Preserve captured console bytes across Git checkouts and source archives.
+tests/fixtures/live_*.log binary
+# The command catalogue is a standard CRLF CSV; retain its recorded bytes.
+docs/LIVE_COMMANDS_20261023.csv -text

+ 0 - 55
AUDIT.md

@@ -1,55 +0,0 @@
-# XJKJ-STL 审阅记录与事实更正
-
-更新日期:2026-10-23。目标版本:0.1.2;工作和交付分支:`dev`。
-
-本文件替换 0.1.1 中证据不足的审阅结论。旧文档仍保存在原 Git 历史和 `v0.1.1` 标签中,未改写历史。
-
-## 1. 输入和覆盖范围
-
-输入包括后端基线 ZIP 和 `hongxinyu_wanrun_xjkj_stl.zip`。`reference/original-archive-manifest.json` 保存原 ZIP 的路径、大小和哈希清单,但清单不等于逐文件阅读记录。
-
-本轮重点复核 v0.1.0 到本地 agent 提交的代码差异、网页和后端控制路径、固件 profile、PTY 桥、打包脚本及实际设备证据。**尚无足够记录证明两个包的全部源码、第三方内容、文档和大日志已完成逐行审阅。** 不继续沿用“全量审阅完成”“100%覆盖”或未经核对的逐行行号。
-
-| 范围 | 本轮处理方式 | 可以得出的结论 |
-| --- | --- | --- |
-| Git 差异及版本记录 | 核对真实分支、提交、标签和差异 | 修改规模和运行版本可核实;提交不等于部署 |
-| 网页、网关、流程、设备及解析路径 | 按模块审阅并针对发现的问题修改、验证 | 具体结果见本轮复核报告及测试证据 |
-| `scripts/package_delivery.py` | 全文件阅读并改写导出与证据收集逻辑 | 源码来自明确提交,日志包覆盖实际采集目录 |
-| `docs/firmware-commands.csv` | 全文件核对已知来源及缺少的证据 | 删除猜测的合法范围、默认值、错误和恢复方式;不称实机验证 |
-| `docs/hardware-evidence/` | 逐个检查 7 个原证据文件的字节和内容 | 空串口文件和 SOL busy 提示无法证明控制台可用 |
-| `data/evidence/` | 根执行会话重新采集,打包时完整列出实际文件及哈希 | 本轮网络、UART、SOL、复位结果以原始记录为准 |
-| 原 Qt、自带第三方库、文档和全部原始大日志 | 已有来源和历史分析仍保留;本轮未逐文件重新完成全部阅读 | 保留后续审阅项,不伪造全量完成率 |
-
-## 2. 对 0.1.1 声明的更正
-
-| 原声明 | 已核实事实 | 处置 |
-| --- | --- | --- |
-| engine 已重写为更简单的线性协程,service 已合并精简 | 截至 `a47e66b` 的基线差异约为 2774 行新增、11 行删除;`service.py`、`artifacts.py`、`store.py` 没有相应重构 | 撤回“大量精简已完成”;按具体修改说明收益 |
-| 删除了原工程的临时目录,已完成所有文件阅读 | 没有完整逐文件处置记录证明这些操作和阅读覆盖 | 不据此删除原材料;原 ZIP 保留 |
-| `/dev/ttyUSB0` 已确认为 CPLD 遥测 | 旧二进制捕获为 0 字节;本轮 1125200、无流控只读采集仅得 2 个 NUL | 串口角色未确定,不能声称识别成功 |
-| SOL 双向回显、掉线恢复已验证 | 旧 53 字节捕获就是 `SOL payload already active on another session`;本轮仍被占用 | 未完成 BIOS 控制台验证,不宣称 PTY 方案已解决现场问题 |
-| 两根 DIMM 在位,其余 22 槽为空 | 只有两个 SDR 温度读数;其他槽 `No Reading` | 保留未知状态;读不到温度不能判定空槽 |
-| 230 V / 35.7 A 等于整机 428 W | 这些数值没有足够同源、同时间和单位关系说明 | 不组合为可信实时功率结论 |
-| 已容器部署运行 | 接手时 Linux79 为裸 Python 进程提供 8080/50051,`docker ps` 为空 | 容器构建、容器运行、网页访问分别验证 |
-| 测试 83 项、耗时 35.05 秒或 34.51 秒 | 已保存的日志是 `83 passed in 34.41s` | 引用原日志;本轮新测试另行记录 |
-| 可用命令全量目录 | 目录主要来自旧源码/profile 和旧报告,合法范围、默认值及若干错误没有对应证据 | 改为命令线索目录,字段未知就写未知 |
-
-## 3. 本轮删改原则
-
-保留一个 Python 后端、本地 SQLite、四工位上下文和现有 gRPC 契约。先修复正常操作路径中已发现的错误,不为完整重构而重写底层通信。
-
-- 网页应真实调用并展示后端,不能把缺失数据、未配置工位或未完成阶段显示为成功。
-- 未实测的 profile 不能直接自动发送成组的时序/电压设置、退出 AMT 或假定测试完成。
-- SOL 占用应明确报告,不能把持续重连或抢占视作已经获得独占权。
-- 历史日志解析与当前设备读数区分来源、采集时间和有效性。
-- 打包仅导出已提交源码;原始日志保留目录结构、字节及 SHA-256,不把固定旧文件列表当作全部现场记录。
-
-## 4. 后续仍需取得的证据
-
-1. 现场 SOL 所有者及可用的 BIOS 输入输出链路。
-2. 当前固件的 UIP/RMT/AMT 开关、读回、完成标记和恢复方式。
-3. 温控板实际协议、有效温度来源及整套供电执行器与反馈。
-4. 一个真实工位的完整开始、测试、停止/结束、全断电及结果导入流程。
-5. 原输入包逐文件审阅的剩余覆盖,不用现有清单代替阅读。
-
-本轮现场事实、已知限制和证据位置见 `docs/REVIEW_20261023.md`。最终部署、测试、提交和包路径以该记录的实测更新及交付清单为准。

+ 0 - 63
BASELINE.md

@@ -1,63 +0,0 @@
-> 历史说明:此文件保存 v0.1.0 的初始任务/基线。继续当前版本请先读 CURRENT_TASK.md、README.md 和 docs/DEPLOYMENT.md,不要重新导入旧基线、回退版本或覆盖已有 tag。当前已提供内置网页网关;新源码包不附完整历史 bundle。
-
-# v0.1.0 基线和本地执行入口
-
-本项目的工作分支和量产交付分支都为 `dev`。这是第一份可继续开发的基线,不代表已经通过量产实机验收。
-
-## 先做什么
-
-完整任务在 `LOCAL_AGENT_TASK.txt`。它包含最新的简化要求、全文件审阅、设备探索、网页、版本、打包和 Windows 回传工作;与旧文档的后续规划有冲突时,以这个任务为准。
-
-需要同时交给本地 agent 两个 ZIP:本基线包,以及原始的 `hongxinyu_wanrun_xjkj_stl.zip`。本包不包含原 Qt 工程和全部原始附件。`reference/original-archive-manifest.json` 是原 ZIP 的 486 条目清单,不能代替实际文件,也不代表逐行审阅已经完成。
-
-包内 `source/` 是基线提交的源码快照;`history/xjkj-stl-v0.1.0.bundle` 可恢复完整的当前 Git 历史、`dev` 和 `v0.1.0`。在解压包的根目录,用一个尚不存在的目标目录执行:
-
-```bash
-git clone -b dev history/xjkj-stl-v0.1.0.bundle XJKJ-STL-work
-cd XJKJ-STL-work
-git remote remove origin
-python3 scripts/version.py check
-```
-
-此处移除的是 clone 自动建立的本地 bundle 文件 origin;本地 bundle 不能作为真实推送地址。若已有项目仓库,先检查并整合,勿覆盖原工作。
-
-## 当前交付的范围
-
-- 后端业务代码、协议、配置、原生 SOL helper 和测试与上轮 0.1.0 保持一致。
-- 本轮新增版本入口、版本脚本、Git 提交与离线历史、完整任务说明和附件清单。
-- 历史验证:78 项测试和 12 个子测试通过。详细原记录在 `docs/TEST_REPORT.md`,不是本轮实机结果。
-- 当前没有新网页,没有连接现场 Linux / BMC / UART / Windows,也没有远端推送。
-- 完整源码审阅、真正精简、UIP / AMT 实测、网页部署和现场回传由本地 agent 按任务书执行,并用真实结果更新记录。
-
-## 简单版本流程
-
-`VERSION` 是手工版本入口;现有 Python 包和 gRPC 系统信息通过 `__version__` 返回同一版本。不要只改其中一个版本字段。
-
-```bash
-python3 scripts/version.py set 0.1.1
-python3 scripts/version.py check
-```
-
-在 `CHANGELOG.md` 写几行真实改动,完成与本次修改有关的验证后提交到 `dev`。可交付版本再打 `v0.1.1` tag;普通小提交不必都改版本。发布包还应记录 commit 和是否实机验证,不用分支名代替验证结果。
-
-```bash
-git add VERSION CHANGELOG.md pyproject.toml src/stl_backend/__init__.py
-# 再明确添加本轮实际修改的源码、测试、配置模板和文档。
-git commit -m 'feat: deliver v0.1.1 memory test station iteration'
-git tag -a v0.1.1 -m 'v0.1.1'
-```
-
-只有真实项目远端已经确定时才执行:
-
-```bash
-git push origin dev
-git push origin v0.1.1
-```
-
-当前未提供远端 URL,状态为 `pending_push`。本地提交、tag、bundle、容器调试和打包可以先完成。
-
-## 现场参数
-
-Linux 主机是 `user@192.168.2.79`;目标 BMC 地址需要核实;物理串口是 `/dev/ttyUSB0`、`1125200`、无流控;回传 Windows 是 `administrator@192.168.2.24`。密码通过本次会话的一次性参数交给本地 agent,不放入本 Git 基线或回传包。
-
-容器、网页和实机接入方式按任务书落实。不要把 `1125200` 自行纠正成常见波特率,不把 BMC 调试 UART 与主机 BIOS SOL 混为同一个控制台。

+ 0 - 32
CHANGELOG.md

@@ -1,32 +0,0 @@
-# 版本记录
-
-版本入口为 `VERSION`,工作和交付分支均为 `dev`。标签不代替实机验收。
-
-## 0.1.2 — 2026-10-23
-
-- 修复网页实际命令参数、gRPC-Web 分帧和错误码、按运行隔离日志、SN登记/历史/结果导入;支持人工接管与单CR输入。
-- 新增低频空闲BMC读取,标注SDR来源和未知测量时间;SOL只在真实激活后ready,占用/断线明确报错。
-- 修复固件inventory覆盖登记SN造成历史索引不一致;统一当前硬件模板为人工核对流程。
-- 完成容器构建和现场部署,保留旧数据;版本/commit由运行服务返回。
-- 最终94项回归及12个子测试通过,Windows Edge模拟交互与现场只读检查通过,详见实际证据。
-
-- 复核 0.1.1 代码、运行部署和原始证据,更正“全量逐行审阅”“大量重构精简”“串口识别完成”“SOL 已可用”等缺乏证据的声明。
-- 固件命令表改为有来源的探索线索,删除猜测的参数范围、默认值、错误和恢复方法,明确尚未完成当前固件实机验证。
-- 打包脚本从干净 dev 提交导出源码,递归收集实际 `data/evidence`、运行 SOL 和结果文件,记录逐文件校验,不再硬编码测试通过或硬件角色。
-- 保留旧标签和历史证据;完整 Git bundle 暂不放入新包,因为早期提交包含运行凭据。当前源码和新包须排除凭据。
-- 本轮 BMC 网络及复位结果已有现场记录;1125200 UART 未识别、SOL 仍 busy、UIP/AMT 未实测。其他代码修复、测试与部署结果见本轮复核报告。
-
-## 0.1.1 — 2026-10-23(事实说明已于 0.1.2 更正)
-
-- 新增网页、HTTP/gRPC-Web 网关、Docker 配置、GNR profile、PTY SOL 桥和探索/打包脚本。
-- 新增 `[HD_RMTSensor]` 日志解析相关代码。历史日志中的输出格式不能单独证明当前固件阶段和实时读温链路。
-- 新增审阅文档和命令表;其审阅覆盖、参数范围、串口角色及实机完成情况存在证据不足的问题,详见 `AUDIT.md`。
-- 已保存的历史测试日志为 `83 passed in 34.41s`。该结果不等于完整硬件流程验收,也不自动适用于后续修改。
-- 接手时开发 HEAD 为 `a47e66b`,Linux79 实际部署为 `f9e960f`;两者并非同一提交。旧 tag 不移动。
-
-## 0.1.0 — 2026-10-23
-
-- 将已有 Python / gRPC 四工位后端固化为第一个 Git 基线,包含模拟器、CLI、IPMI / SOL 适配、协议和测试。
-- 增加简单的版本同步检查脚本、完整本地 agent 执行提示词及原始附件清单。
-- 业务代码沿用上一轮交付;78 项测试和 12 个子测试通过属于 2026-10-22 的历史验证。
-- 本版本未完成现场实机联调、网页前端、新一轮全文件审阅及精简。

+ 0 - 38
CURRENT_TASK.md

@@ -1,38 +0,0 @@
-# XJKJ-STL 当前任务
-
-日期:2026-10-23。工作分支:`dev`。目标版本:`0.1.2`。
-
-## 已接手的状态
-
-- 开发目录:`/workspace/XJKJ-STL-dev`;接手时 HEAD 为 `a47e66b`,旧标签 `v0.1.1` 指向此提交。
-- Linux79 部署目录:`/home/user/XJKJ-STL`;接手时为 `f9e960f`,由裸 Python 进程提供 `http://192.168.2.79:8080/` 和 gRPC 50051,未运行项目容器。
-- 无真实 Git 远端,状态 `pending_push`。无需等待远端 URL 才能开发、调试或本地提交。
-- 已有 Windows SSH key 可访问 `administrator@192.168.2.24`。新包仍须实际传输并核对,不能沿用旧包的回传结论。
-
-## 本轮现场核验
-
-- BMC 地址 `192.168.0.100`,IPMI 网络查询可用;Linux79 的专用有线地址为 `192.168.0.101`。
-- SDR 读取到 CPU0_A 约 34°C、CPU1_A 约 35.2°C。这是采集时的读数;其他 `No Reading` 不能判定为空槽。
-- `/dev/ttyUSB0` 按 `1125200`、无流控只读采集 8 秒,仅有 2 个 NUL。尚不能识别为 BMC、主机 BIOS 或 CPLD 控制台。
-- SOL 激活返回 `already active on another session`。会话信息出现 `192.168.0.10` 和 `192.168.0.101`;没有证据表明本 agent 独占 SOL。
-- BMC warm reset 返回 `Invalid command`;cold reset 成功,约 134 秒后 IPMI 恢复,主板仍为 on。恢复后 SOL 仍 busy,未获得 BIOS 回显。
-- 本轮未发送 BIOS 参数,也未发主板电源开关命令。未完成 UIP/AMT 实机配置验证。
-- 原始记录保留在 `data/evidence/`,本轮采集在其 `review-20261023/` 子目录;旧证据未删除。
-
-## 本轮已完成
-
-- 0.1.2 的网页/协议/控制请求、日志游标、人工接管与结果导入已修复;Windows Edge 对独立模拟实例的实际操作验证通过。
-- 全套最终回归:94 passed、12 subtests passed,30.73 秒。
-- Linux79 已由裸 Python 迁移为 xjkj-stl-backend 单容器,旧数据已备份。运行服务可返回真实版本/commit。
-- S1 每15秒空闲读取 BMC 电源与 SDR;数值标为采样时间未知的 BMC 报告值。温控接口缺失时开始前明确拒绝,不创建运行或进行电源操作。
-- 实机与通用硬件模板使用人工核对 profile,未验证命令不自动发送。固件 SN 不覆盖测试开始时登记的身份。
-- 当前 Git 提交/tag 与源码/调试包以 COMMIT、MANIFEST 和实际传输回执为准;无远端仓库,推送仍待配置。
-- 实际审阅范围和证据见 docs/REVIEW_20261023.md;没有启动远端本机 AI agent。
-
-## 继续工作的入口
-
-1. 识别 BMC 会话表中 192.168.0.10 的连接者或固件占用状态;SOL busy 解除前,不把连接尝试称作 BIOS 联调完成。
-2. 取得真实 BIOS 控制台后,先采集帮助和只读值,再逐条验证 UIP/RMT/AMT 配置、返回值和错误;每条命令保留原始证据。
-3. 接入温控板 SET/温度读取协议和总供电执行方式;当前不会把IPMI主板off当作整套断电。
-4. 确认 UEFI 程序路径/配置、完成和落盘标记,再做完整的实际高温轮次验证。
-5. 后续改动继续用 dev 提交、递增 VERSION、打包并同步 Windows;不要恢复旧版本或移动旧 tag。

+ 1 - 1
Dockerfile

@@ -5,7 +5,7 @@ ENV PYTHONUNBUFFERED=1 \
 WORKDIR /app
 
 RUN apt-get update && \
-    apt-get install -y --no-install-recommends ipmitool freeipmi-tools && \
+    apt-get install -y --no-install-recommends ipmitool freeipmi-tools openssh-client sshpass && \
     rm -rf /var/lib/apt/lists/*
 
 COPY pyproject.toml README.md ./

Разница между файлами не показана из-за своего большого размера
+ 0 - 179
LOCAL_AGENT_TASK.txt


Разница между файлами не показана из-за своего большого размера
+ 21 - 157
README.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-0.1.2
+0.8.1.1.dev0

+ 9 - 5
config/hardware.example.json

@@ -26,7 +26,8 @@
         "sol_helper_argv": [
           "python3",
           "native/stl_sol_bridge.py"
-        ]
+        ],
+        "console_transport": "ipmi_sol"
       },
       "bridge": {
         "argv": [
@@ -56,7 +57,8 @@
         "sol_helper_argv": [
           "python3",
           "native/stl_sol_bridge.py"
-        ]
+        ],
+        "console_transport": "ipmi_sol"
       },
       "bridge": {
         "argv": [
@@ -86,7 +88,8 @@
         "sol_helper_argv": [
           "python3",
           "native/stl_sol_bridge.py"
-        ]
+        ],
+        "console_transport": "ipmi_sol"
       },
       "bridge": {
         "argv": [
@@ -116,7 +119,8 @@
         "sol_helper_argv": [
           "python3",
           "native/stl_sol_bridge.py"
-        ]
+        ],
+        "console_transport": "ipmi_sol"
       },
       "bridge": {
         "argv": [
@@ -148,7 +152,7 @@
       "required_artifact_kinds": [
         "memtest_html"
       ],
-      "notes": "未实机验证的硬件接入模板。BIOS与UEFI配置均人工核对;旧17条参数保留在模拟配置和历史命令目录,不会自动发送。",
+      "notes": "硬件接入模板。BIOS 与 UEFI 参数由操作员核对;未显式配置的参数不会自动发送。",
       "stop_on_test_error": true,
       "metadata": {}
     }

+ 14 - 8
config/profiles/cxmt-live-gnr.json

@@ -1,19 +1,25 @@
 {
   "profile_id": "cxmt-live-gnr",
   "mode": "hardware",
-  "description": "现场辅助流程。当前没有成功SOL回显验证,所有配置/测试完成/UEFI启动均人工确认,不自动重放原Qt设置。",
+  "description": "现场辅助流程。已通过SSH 2200实测双路UIP、Training、RMT和UEFI入口,并采集双CPU AMEMDIAG真实算法输出;整体结果按每轮完整证据判定。UEFI外部测试程序及温控板闭环未验证。步骤仍按实际证据人工确认,不自动重放旧Qt参数。",
   "steps": [
     {
       "id": "cpu0_configuration",
       "phase": "bios_config",
       "manual": true,
-      "instruction": "观察真实 CPU0 UIP,按本轮工艺核对内存参数及 RMT/AMT 启停,保存前后值。未验证命令不要直接重放。完成 CPU0 配置后确认。"
+      "instruction": "观察真实 CPU0 UIP 阶段号和提示符。默认不发送覆盖;要修改时在 UIP 页面显式应用并检查回显。当前固件用 rmt enable/disable 和 admt enable/disable 选择 RMT、AMEMDIAG。完成后点击空回车继续(ContinueUip,仅 CR),再独立确认本流程步骤;不自动应用保存项。"
     },
     {
       "id": "cpu1_configuration",
       "phase": "bios_config",
       "manual": true,
-      "instruction": "观察真实 CPU1 UIP,按本轮工艺核对内存参数及 RMT/AMT 启停。完成 CPU1 配置后确认。"
+      "instruction": "观察真实 CPU1 UIP 输入点,分别核对本 CPU 参数;需要修改时显式应用并检查回显。完成后点击空回车继续(ContinueUip,仅 CR),再独立确认本流程步骤。CPU0 已处理不代表 CPU1 已配置;设置 ACK 不等于测试已运行。"
+    },
+    {
+      "id": "training_confirmation",
+      "phase": "training",
+      "manual": true,
+      "instruction": "完成各 CPU 的 UIP 输入并空回车继续,观察 DDR Training 实际输出及明确 DIMM/通道状态。空回车只跳过参数输入,不跳过训练。无明确槽位结果保持未知;确认本阶段结束后继续。"
     },
     {
       "id": "rmt_completion",
@@ -21,7 +27,7 @@
       "when": "rmt",
       "test": "rmt",
       "manual": true,
-      "instruction": "确认本轮 RMT 实际执行完毕并保留 SOL 证据;测温输出不等于 RMT 完成。失败请报告失败。"
+      "instruction": "核对本轮各 CPU 的 RMT 实际执行、裕量行与结束标记并保留原始日志;测温或极短步骤结束不等于完整裕量扫描,没有工艺阈值不自行判裕量 PASS。确认执行结束后继续,实际失败请报告失败。"
     },
     {
       "id": "amt_completion",
@@ -29,21 +35,21 @@
       "when": "amt",
       "test": "amt",
       "manual": true,
-      "instruction": "确认本轮 AMT 实际执行完毕并保留结果;进入 AMT 提示符或执行 exit 不代表测试通过。失败请报告失败。"
+      "instruction": "核对当前是否为 AMT/AMEMDIAG 菜单或算法执行。若本次不做测试,在各 CPU 菜单分别点退出 AMT(SkipAmt,仅 exit+CR);不是运行中止命令。退出后仍需独立确认流程,已请求跳过/已跳过不会因此改为完成或 PASS。若需要执行,保留实际算法及结果;菜单和 BIOS MemTest 完成不代替算法通过。"
     },
     {
       "id": "uefi_confirmation",
       "phase": "uefi_ready",
       "manual": true,
       "uefi_ready": true,
-      "instruction": "确认已进入真实 UEFI Shell。核实 U 盘映射、用户程序 memtest.efi 的实际路径和配置文件,不猜测 fs0 或 -r 参数。"
+      "instruction": "观察后续 MRC、UIP stage2、DXE/BDS,新的 UIP 提示符可空回车继续。仅在真实 UEFI Shell 就绪后确认;用 map 和目录核对实际测试介质、EFI 程序与配置。当前 FS0 是 NVMe、EFI 下仅 BOOT/redhat,不默认 FS0 是 U 盘,也不使用无关启动文件代替测试程序。"
     },
     {
       "id": "mt_launch",
       "phase": "mt",
       "when": "mt",
       "manual": true,
-      "instruction": "在 SOL 手动输入已核实的 memtest.efi 启动命令及配置,记录实际命令。确认程序已开始本轮测试。"
+      "instruction": "在启动与测试页读取真实 UEFI 目录,选择已核实路径/版本的 EFI 与配置,填写该程序支持的调用模板并预览后启动。保存实际命令及程序启动输出;仅发送成功不表示 MT 已运行,确认真实程序开始本轮测试后再确认流程。"
     },
     {
       "id": "mt_completion",
@@ -51,7 +57,7 @@
       "when": "mt",
       "test": "mt",
       "manual": true,
-      "instruction": "确认 MT 已结束并完成 USB 结果落盘,保留结论及结束证据。收尾后导入本轮实际 HTML 报告及其他日志。失败请报告失败。"
+      "instruction": "确认 MT 已结束并完成 USB/PXE 结果保存,保留实际结论及结束证据。收尾后导入本轮真实报告和日志;缺文件、未执行或证据不足不记 PASS,实际失败请报告失败。"
     }
   ],
   "stop_commands": []

+ 98 - 0
config/serial-net.example.json

@@ -0,0 +1,98 @@
+{
+  "mode": "hardware",
+  "listen": "127.0.0.1:50051",
+  "data_dir": "../var/serial-net",
+  "telemetry_interval_s": 1.0,
+  "idle_poll_interval_s": 15,
+  "profile_files": [
+    "profiles/cxmt-live-gnr.json"
+  ],
+  "stations": [
+    {
+      "station_id": "S1",
+      "frontend_index": 0,
+      "name": "工位 001(串口转网待配置)",
+      "mode": "hardware",
+      "cpu_count": 2,
+      "channels_per_cpu": 12,
+      "supply_mode": "manual",
+      "console": {
+        "enabled": false,
+        "transport": "tcp_serial",
+        "host": "",
+        "port": 0,
+        "connect_timeout_s": 5,
+        "write_timeout_s": 15
+      },
+      "bmc": {
+        "enabled": false,
+        "host": "",
+        "user": "ADMIN",
+        "password_env": "STL_BMC_S1_PASSWORD",
+        "cipher_suite": 17,
+        "timeout_s": 15
+      }
+    },
+    {
+      "station_id": "S2",
+      "frontend_index": 1,
+      "name": "工位 002(串口转网待配置)",
+      "mode": "hardware",
+      "cpu_count": 2,
+      "channels_per_cpu": 12,
+      "supply_mode": "manual",
+      "console": {
+        "enabled": false,
+        "transport": "tcp_serial",
+        "host": "",
+        "port": 0,
+        "connect_timeout_s": 5,
+        "write_timeout_s": 15
+      },
+      "bmc": {
+        "enabled": false
+      }
+    },
+    {
+      "station_id": "S3",
+      "frontend_index": 2,
+      "name": "工位 003(串口转网待配置)",
+      "mode": "hardware",
+      "cpu_count": 2,
+      "channels_per_cpu": 12,
+      "supply_mode": "manual",
+      "console": {
+        "enabled": false,
+        "transport": "tcp_serial",
+        "host": "",
+        "port": 0,
+        "connect_timeout_s": 5,
+        "write_timeout_s": 15
+      },
+      "bmc": {
+        "enabled": false
+      }
+    },
+    {
+      "station_id": "S4",
+      "frontend_index": 3,
+      "name": "工位 004(串口转网待配置)",
+      "mode": "hardware",
+      "cpu_count": 2,
+      "channels_per_cpu": 12,
+      "supply_mode": "manual",
+      "console": {
+        "enabled": false,
+        "transport": "tcp_serial",
+        "host": "",
+        "port": 0,
+        "connect_timeout_s": 5,
+        "write_timeout_s": 15
+      },
+      "bmc": {
+        "enabled": false
+      }
+    }
+  ],
+  "recipes": []
+}

+ 4 - 21
config/simulated.json

@@ -69,7 +69,7 @@
   "recipes": [
     {
       "recipe_id": "DEMO-80",
-      "name": "四工位模拟:80℃(仅示例数值)",
+      "name": "四工位模拟:默认 UIP 参数(80℃为示例)",
       "revision": 1,
       "profile_id": "sim-cxmt",
       "dimm_target_c": 80.0,
@@ -81,30 +81,13 @@
       "run_rmt": true,
       "run_amt": true,
       "run_mt": true,
-      "stage1_commands": [
-        "errhandle disable",
-        "vol mem vdd 1070",
-        "vol mem vddq 1070",
-        "actm tCL 44",
-        "actm tRCD 43",
-        "actm tRP 43",
-        "actm tRAS 86",
-        "actm tWR 80",
-        "actm tRFC 425",
-        "actm tRTP 20",
-        "actm trrd_l 13",
-        "actm twTR_S 7",
-        "actm tWTR_L 27",
-        "actm tCCD_L 13",
-        "actm trefi 23046",
-        "actm tRFCsb 123",
-        "ap disable"
-      ],
+      "stage1_commands": [],
+      "firmware_settings": {"uip_overrides": [], "mt_selection": {}},
       "mt_command": "memtest.efi {run_id}",
       "required_artifact_kinds": [
         "result_json"
       ],
-      "notes": "参数清单来自上传 Qt 工程,用于演示。温度和时序均不是通用测试推荐值。",
+      "notes": "默认不发送 UIP 参数覆盖;在 UIP 页面明确选择后保存或应用。温度数值仅用于模拟演示。",
       "stop_on_test_error": true,
       "metadata": {}
     }

+ 11 - 7
config/station0-live.json

@@ -27,8 +27,11 @@
         "timeout_s": 15,
         "sol_helper_argv": [
           "python3",
-          "native/stl_sol_bridge.py"
-        ]
+          "native/stl_ssh_console_bridge.py"
+        ],
+        "console_transport": "ssh_console",
+        "ssh_console_port": 2200,
+        "ssh_known_hosts": "data/ssh_known_hosts"
       }
     },
     {
@@ -81,16 +84,17 @@
       "run_amt": true,
       "run_mt": true,
       "stage1_commands": [],
-      "mt_command": "memtest.efi",
+      "mt_command": "MemTest86SiteX64.efi",
       "required_artifact_kinds": [
         "memtest_html"
       ],
-      "notes": "温控与总供电接入方式待现场核实。UIP/RMT/AMT及UEFI启动路径/参数未经本机SOL验证,保持人工操作与确认;memtest.efi仅为用户给出的程序名,不自动执行。",
+      "notes": "现场辅助流程:已实测当前UIP的rmt enable/disable与admt enable/disable确认,以及CPU0/CPU1交互;完整RMT/AMEMDIAG执行尚未验证。当前UEFI只映射NVMe,EFI目录只有BOOT/redhat,未发现测试U盘。MemTest86SiteX64.efi来自历史文件名线索,profile保持人工启动。温控板和自动总供电尚未接入。",
       "stop_on_test_error": true,
       "metadata": {
-        "firmware_verified": "false",
-        "mt_launch": "manual",
-        "dimm_temperature": "UEFI后有效;BMC SDR只作为采样时间未知的诊断报告值"
+        "firmware_verified": "partial_uip_ack_and_uefi_shell",
+        "mt_launch": "manual_path_unverified",
+        "dimm_temperature": "UEFI后有效;BMC SDR只作为采样时间未知的诊断报告值",
+        "console_transport": "ssh_console_port_2200"
       }
     }
   ],

+ 15 - 0
deploy/Dockerfile.qt-runtime

@@ -0,0 +1,15 @@
+# Reuse the site's installed, verified dependency image for an offline upgrade.
+# For a fresh installation use the project-root Dockerfile instead.
+ARG BASE_IMAGE=xjkj-stl:0.6.1-b66cfd7
+FROM ${BASE_IMAGE}
+WORKDIR /app
+COPY src/ /app/src/
+COPY native/ /app/native/
+COPY VERSION pyproject.toml README.md /app/
+ARG QT_BUILD_COMMIT=unknown
+ARG QT_BUILD_VERSION=0.8.0
+ENV PYTHONPATH=/app/src \
+    PYTHONUNBUFFERED=1 \
+    STL_BUILD_COMMIT=${QT_BUILD_COMMIT}
+LABEL org.opencontainers.image.version=${QT_BUILD_VERSION} \
+      org.opencontainers.image.revision=${QT_BUILD_COMMIT}

+ 0 - 4
docker-compose.yml

@@ -1,5 +1,3 @@
-version: '3.8'
-
 services:
   stl-backend:
     build:
@@ -12,8 +10,6 @@ services:
     restart: unless-stopped
     stop_grace_period: 120s
     network_mode: host
-    devices:
-      - /dev/ttyUSB0:/dev/ttyUSB0
     volumes:
       - ./data:/app/data
       - ./config:/app/config:ro

+ 0 - 153
docs/ARCHITECTURE.md

@@ -1,153 +0,0 @@
-# 业务状态、流程与持久化约定
-
-## 1. 主机承担的职责
-
-后端是机台运行的唯一调度者,管理四个工位;每个工位拥有自己的设备适配器、SOL 读取者、增量解析器、流程任务、停止事件和本轮上下文。Qt 或未来 HTML 仅提交动作和读取结果。
-
-前端可暂时离线,查询可以比设备实际状态慢几秒;后端推进预热、下发参数、测试阶段和断电使用自己的设备采集与流程条件,不等待 UI 刷新。温控闭环仍在温控板中,主机不会每几百毫秒替板计算加热输出。
-
-流程状态在 SQLite 与内存快照中维护。读工位页面不触发新的 BMC 或温控板操作;多个客户端同时查询不会增加对应次数的设备读写。操作请求持久化后由后台任务执行。
-
-## 2. 三类电源状态
-
-| 字段/动作 | 对象 | 不能代替的含义 |
-| --- | --- | --- |
-| `server_power`、`bmc_power` | 服务器主板,由 BMC/IPMI 管理 | 主板 off 不证明 BMC、温控板和其他供电已关闭 |
-| `supply_state`、`supply_set` | 该工位服务器、BMC、温控板的整套供电 | 需要独立执行器反馈或有来源标记的人工确认 |
-| `bmc_state` / `sol_state` | 后端观测的通信状态 | BMC 不可达不能推导整套电源 off |
-
-`supply_confirmation` 明确区分 `controller_feedback`、`operator_confirmed`、`simulated`、`unavailable`。未知状态不会升级为已断电。
-
-正常完成、明确测试失败、流程错误和人工停止都走同一个收尾入口。先尝试配置中明确允许的程序停止序列,再尽力关闭主板,随后独立尝试总断电;主板操作失败不会跳过总断电。没有获知的固件退出协议不会通过猜测 Ctrl-C、exit 或任意串口按键实现。
-
-停止会取消正在进行的运行中目标修改/手工 SOL 写入,释放本工位 I/O 锁,再执行收尾。等待锁的时间不消耗总供电控制器自己的超时预算。控制器失联仍可能无法确认断电,此时保存 `recovery_required` 并保持工位占用。
-
-物理断电/换料依据 `supply_state` 及其确认来源。后端没有把“测试 PASS”用作物理断电证明。
-
-## 3. 正常流程与结束分支
-
-```mermaid
-flowchart TD
-    A["登记本轮与装料"] --> B["总供电接通;主板保持关闭"]
-    B --> C["环境温度满足预热条件"]
-    C --> D["SOL 建链;主板开机"]
-    D --> E["CPU0/CPU1 UIP;所选 RMT/AMT"]
-    E --> F["进入 UEFI;执行所选 MT"]
-    F --> G["有界收尾;整套断电"]
-    X["停止、失败或流程错误"] --> G
-    G --> H{"断电已确认?"}
-    H -->|是| I["释放工位;旧轮次可继续导入文件"]
-    H -->|否| J["保留占用;等待核对或再次收尾"]
-```
-
-1. `StartRun` 校验工位、配方和装料清单,将新轮次、DIMM 位置和命令一起提交事务。
-2. 接通整套供电,等 BMC 可读;确认主板仍为 off。如果来电自动开机导致主板已经 on,停止本轮并收尾,避免在预热前已经错过 UIP。
-3. 设置本轮 DIMM 目标并核对板上确认值。初始设置完成前不接受运行中的目标修改。
-4. 依据环境测点的有效性、新鲜度、温度阈值和连续保持时间,判定预热条件。
-5. 在主板开机前建立 SOL,以记录早期 BIOS 输出。按 profile 执行 CPU0/1 设置与测试。
-6. 识别 UEFI 后才允许实时 DIMM 温度进入有效数据路径;读不到就继续显示缺失。
-7. MT 启动命令包含现场需要的程序及配置参数。正常完成依据 profile 的结束/落盘标记,或明确人工确认。
-8. 收尾并总断电。关电后的 U 盘结果可以后补,仍绑定原 `run_id`。
-
-示例 profile 即使关闭 MT 也会走到 UEFI 入口;它不会启动 MT。配方中的 `run_rmt/run_amt/run_mt` 表达本轮要求,实际固件开关仍需 profile 的命令或人工步骤正确应用。
-
-## 4. 四个独立判断维度
-
-| 维度 | 代表值 | 解释 |
-| --- | --- | --- |
-| 执行状态 `Run.state` | accepted / running / stopping / completed / stopped / failed / recovery_required | 主机流程是否执行、终止或需要核对 |
-| 总供电 `supply_state` | on / off / unknown | 物理供电的已知状态及来源 |
-| 资料状态 `artifact_state` | not_started / pending_import / complete / partial | 本轮要求的文件是否存在并能支持结论 |
-| 测试结论 `verdict` | pending / pass / fail / inconclusive | 基于当前可用证据的结论 |
-
-例如:
-
-- `completed + off + pending_import + pending`:流程已正常结束,工位断电,等待 U 盘报告。
-- `completed + off + complete + pass`:流程完整、要求的结果齐备且提供 PASS,没有明确失败或 SOL 采集缺口。
-- `failed + off + pending_import + fail`:SOL 已出现明确测试失败,已收尾断电,还可补录原始文件。
-- `stopped + off + complete + inconclusive`:操作员中止,当前资料没有明确失败,不能据此宣告 PASS。
-- `recovery_required + unknown`:供电未能确认或后端在过程中重启,工位不能开始新轮次。
-
-选定测试各自保留 `pending/running/completed/failed/interrupted/not_run_due_to_stop`。未选测试为 `skipped_by_recipe`,不会写成“执行通过”。
-
-PASS 的业务规则是:要求的流程完成;选定测试均完成;不存在明确失败;未记录 SOL 缺口;若进入 MT,则要求的结果种类均存在且有完整 PASS 证据。RMT 裕量阈值没有在附件中被定义,本包不把负数或星号解释成故障,也不自动实施额外的工艺阈值。硬件 profile 的人工完成确认属于有操作者和证据文本的完成来源。
-
-存在明确失败时保留 FAIL,即便报告不完整。不同来源可能描述相同错误,不能用 SOL 数量加 USB LOG 数量再加 HTML 数量作为“总错误次数”。
-
-## 5. 温度和进度
-
-- `Recipe.dimm_target_c` 是温控板的 DIMM 目标,`preheat_air_c` 是主机判断预热的环境阈值,两者分别存储。
-- `requested_target_c` 表示主机请求;`applied_target_c` 表示板确认值;它们不是实际温度已经达到的证明。
-- `hood_air` 与 `dimms[]` 分开;每个读数带来源、观测时间与 quality。
-- UEFI 前,DIMM 温度为 `unavailable_in_phase`;不能把上轮读数或默认 0 ℃当作本轮实测。
-- 读数错误后可保留最后数值,但 quality 变为 `stale`;断电后变为 `powered_off`。
-- 采样时间是主机本次获取该测量的时间。现场 bridge 对缓存/过期读数必须返回相应质量;文件导入的历史测量不覆盖实时温度。
-- `progress_percent` 是 optional。只有解析到明确百分比才存在,它描述来源当前测试的进度;阶段推进不自动转换为整轮完成百分比。
-- 示例硬件采样周期为 2 秒,UI 可约 2~3 秒查询概况。默认模拟模式的短周期仅用于迅速演示。
-
-## 6. 固件 profile
-
-Profile 是机型/BIOS 版本相关的执行定义,配方是本轮参数与选项。启动时两者均冻结进本轮,运行中编辑配方不影响已运行的任务。
-
-| step 字段 | 语义 |
-| --- | --- |
-| `id` | 本 profile 中唯一的步骤编号,也是人工确认的目标 |
-| `phase` | 对外显示的当前阶段 |
-| `when` | always / rmt / amt / mt / not_rmt / not_amt / not_mt |
-| `test` | rmt / amt / mt;步骤成功时将该项执行标为 completed |
-| `expect` | 进入此步骤前要观察到的正则标记 |
-| `expect_from_start` | 本轮一次性入口标记可提前被观察;已见标记保留到该步骤消费 |
-| `manual` / `instruction` | 等待操作者明确完成确认;SOL 保持可读并允许手工输入 |
-| `send` | 按顺序发送的一行命令数组 |
-| `use_stage1_commands` | 发送本轮配方的 stage1_commands |
-| `use_mt_command` | 发送本轮 mt_command;可将 `{run_id}` 替换为当前编号 |
-| `initial_delay_s` / `interval_s` | 初始等待和命令间隔 |
-| `ack_template` | 每条命令后的回显匹配;`{command}` 自动正则转义 |
-| `append_enter` | 此命令组后附加一个空回车 |
-| `expect_after` | 命令组结束后所需标记 |
-| `uefi_ready` | 此步骤已确认进入 UEFI;开启有效 DIMM 采样路径 |
-| `timeout_s` | 覆盖本轮默认阶段超时 |
-
-`expect_from_start` 仅用于在本轮内唯一且允许提前出现的入口,例如 CPU1 UIP 标记。普通 ACK 和结束匹配继续使用向前的 SOL 游标,不能因为之前出现过某个通用词就确认当前命令成功。每轮重置全部观察状态。
-
-手工 SOL 模式只暂停自动输入,后台日志与采样继续。恢复自动流程前,操作者应把控制台留在 profile 能继续识别的位置;后端不会猜测任意按键操作后固件当前在哪个菜单。
-
-当前实机配置与通用硬件模板均使用人工核对 profile;UIP 参数、RMT/AMT 设置与完成、UEFI 程序启动和结果落盘须根据实际控制台确认。旧17条参数保留在模拟配方与历史命令目录,当前入口不自动发送。取得本机型可靠命令、读回及完成标记后再逐步启用自动步骤。
-
-## 7. 命令与失败恢复
-
-控制操作使用稳定 `command_id`,服务端保存动作、参数哈希和结果。同 ID 同参数返回同一命令;同 ID 不同参数返回 `ALREADY_EXISTS`。运行相关操作绑定 `run_id`,旧轮次的停止、写 SOL 或改温度请求不会作用到新轮次。
-
-gRPC 写请求即使因为 deadline 或断线没有把响应传回,已开始的接受/持久化过程仍完成;客户端用相同 ID 查询或重试。`Command.succeeded` 对 StartRun 表示运行已启动,对 StopRun 表示已确认本次收尾的总断电;测试是否 PASS 要读 `Run.verdict`。
-
-后端异常退出后:
-
-1. 尚未终结的命令改为 interrupted,不自动重新发送;
-2. 未结束轮次改为 recovery_required,供电状态回到 unknown;
-3. 不因为数据库之前写过“准备开机”或“命令已接受”就重发开机/BIOS 输入;
-4. 核对现场后,对该 run 调用 StopRun 完成收尾;人工供电模式再通过 ConfirmPower 确认;
-5. 若断电无法确认,保留工位占用。
-
-正常服务退出(SIGTERM/SIGINT)会主动停止正在执行的轮次并尽力收尾。宿主机断电、进程被强制杀死或网络失联时,主机软件无法继续执行断电操作;按已知硬件行为,温控板可能继续独立运行。本版本没有把主机心跳失联改造成温控板的停机协议。
-
-## 8. 装料、日志和结果归属
-
-每轮存储工单号、批号、操作员、SN 与 CPU/通道/插槽清单。相同 slot 文本可以出现在不同 CPU 上,完整物理位置不能重复;同一轮同一 SN 不能装在两处。通道格是聚合视图,并不意味着一通道仅有一根 DIMM。
-
-当日志明确给出 CPU 和通道时,通道显示相应错误;只有 slot/CPU/通道组合唯一匹配本轮清单时才补充对应 SN。没有位置的错误保持轮次级别,不把所有 DIMM 同时判为失败。
-
-`Run.error_count` 是实时 SOL 中明确失败事件的计数,包括整体 FAIL 等确认事件,并非去重后的物理故障次数。`evidence.sol_channel_error_counts` 只统计可明确定位的错误行;导入文件各自保留原始统计。通道显示的 `error_count` 取来源间的最大可归属记录数,保留 `channel_error_counts_by_source` 供审查。这是证据计数,可能少于报告给出的总错误数。
-
-上传文件始终绑定具体 run_id。带 `stl.test-result.v1` 的 JSON 必须声明匹配的 run_id;老版 LOG/HTML 不一定包含该编号,绑定关系来自操作员导入,SHA-256 证明文件传输完整,不证明它一定取自那台服务器。原文件、来源名称、导入人和时间均保存。
-
-未来 PXE 负责启动文件与配置分发;结果回传仍可复用相同的分块导入 API。当前交付没有安装 DHCP/TFTP/PXE 服务,也没有假设启用 PXE 就自动获得完整测试报告。
-
-## 9. 存储与资源
-
-数据目录包括 `bench.sqlite3`、`backend.lock`、`runs/<run_id>/sol.raw`、`uploads/` 和 `artifacts/`。客户端文件名只作为元数据,不直接拼接为服务器路径。
-
-SQLite 事务保存运行和上传进度,使用 FULL 同步;原始 SOL 直接按字节追加到文件,终止采集后 fsync。进程在运行中被强制终止时,末尾数据能否落盘仍取决于操作系统与存储,恢复时不能声明记录完整。
-
-SOL 的流程匹配窗口限制为约1 MiB字符,原始文件不因此截断;等待标记被窗口越过会明确失败。文件解析限制见日志文档,完整解析只允许一个并行任务,避免四份大报告同时占用低频主机。事件、温度、历史运行和文件读取都分页。
-
-本版本没有自动删除历史或轮转原始结果。部署时应给数据目录配置足够容量,按留存要求做整体归档;不能只备份 SQLite 而遗漏它引用的原始文件。推荐在没有活动轮次、停止服务后备份整个数据目录。目标主机的 CPU、磁盘同步延迟、日志峰值仍需现场测量,不能把模拟测试耗时当作产线吞吐量。

+ 0 - 113
docs/DEPLOYMENT.md

@@ -1,113 +0,0 @@
-# Linux 主机部署(0.1.2)
-
-现场使用一个 Docker 容器,里面运行 Python 后端、原生 gRPC 端口与网页/gRPC-Web 端口。SQLite 和日志留在宿主机 `data/`。不额外部署数据库、消息队列或代理服务。
-
-## 1. 当前目录和入口
-
-| 项目 | 位置 |
-| --- | --- |
-| 开发仓库 | 调试容器 `/workspace/XJKJ-STL-dev`,分支 `dev` |
-| 运行代码 | Linux `192.168.2.79:/home/user/XJKJ-STL` |
-| 持久记录 | 运行目录 `data/`,映射为容器 `/app/data` |
-| 现场配置 | `config/station0-live.json`、`config/profiles/cxmt-live-gnr.json` |
-| 本地口令 | 运行目录 `local.env`,不提交、不打包 |
-| 网页 | `http://192.168.2.79:8080/` |
-| 原生 gRPC | `192.168.2.79:50051` |
-| 源码/调试交付 | Windows `C:\Users\Administrator\delivery` |
-
-现场部署的实际 commit 和验收结果见 `REVIEW_20261023.md` 与交付清单;本文件是操作步骤,不以“文件已经存在”代替部署成功。页面版本来自后端 `GetSystemInfo`,构建 commit 来自镜像环境标记。
-
-## 2. 构建与运行
-
-需要 Linux、Docker,以及 Docker Compose v2 或 `docker-compose` v1.29。在项目根目录创建 `local.env`,只填现场值,例如:
-
-```text
-STL_BMC_S1_PASSWORD=填写现场密码
-```
-
-本文件不要复制进源码,也不要放进调试包。启动脚本只读取版本信息;Compose 从 `local.env` 读取口令。
-
-```bash
-chmod 600 local.env
-sh scripts/run_container.sh build
-sh scripts/run_container.sh up -d
-sh scripts/run_container.sh ps
-sh scripts/run_container.sh logs --tail=60
-```
-
-如果构建机器需要现有局域网代理,可仅给本次构建传入,不必改 Docker 的全局网络配置:
-
-```bash
-sh scripts/run_container.sh build \
-  --build-arg http_proxy=http://192.168.2.24:10889 \
-  --build-arg https_proxy=http://192.168.2.24:10889
-```
-
-镜像包含固定 Python 依赖、网页静态资源、ipmitool、FreeIPMI 工具及 `native/` helper。应用代码编入镜像,不挂载宿主源码;`config/` 只读挂载以便现场改配置。版本从 `VERSION` 获取,commit 从 Git 获取;源码 ZIP 无 `.git` 时读取包中的 `COMMIT`。
-
-现场 Compose 使用 host 网络并映射 `/dev/ttyUSB0`。当前 BMC 走 LAN;该串口尚未识别出有效数据,不将它当成温控板。用户给定串口参数是 **1125200、无流控**,不要擅自改为 115200 或 1152000。
-
-## 3. 初次迁移与更新
-
-同一数据目录只能有一个后端进程。首次从宿主 Python 进程迁移时,先确认没有活动测试,正常停止旧进程并备份完整 `data/`,再启动容器。不要同时用旧 Qt 的直连 BMC 功能控制这个工位。
-
-更新已提交代码后:
-
-```bash
-sh scripts/run_container.sh build
-sh scripts/run_container.sh up -d
-```
-
-Compose 给正常退出保留 120 秒;后端退出时会收尾活动任务。更新应在没有活动测试时进行。不要用强杀来替代正常停止。
-
-容器内检查:
-
-```bash
-docker exec xjkj-stl-backend stl-client --target 127.0.0.1:50051 system
-docker exec xjkj-stl-backend stl-client --target 127.0.0.1:50051 stations
-docker inspect --format '{{.Config.Image}} {{.State.Status}}' xjkj-stl-backend
-```
-
-数据包含 `runs/`、`artifacts/`、`uploads/` 和 SQLite。数据库内附件路径为绝对路径;移动数据根目录时应核对这些路径。当前容器固定使用 `/app/data`,备份恢复继续使用这个容器内路径。不要仅复制 `.db` 而丢失日志或结果文件。
-
-配置文件中的配方只在数据库没有同名 ID 时导入,重启不覆盖用户已编辑的配方。0.1.2 现场配方使用新的 `GNR-DDR5-ASSISTED` ID;旧配方继续保留用于历史记录。历史运行使用开始时冻结的配置快照,不随新版 profile 重写。
-
-## 4. 现场配置的实际含义
-
-S1 使用 BMC `192.168.0.100`、cipher 17、环境变量 `STL_BMC_S1_PASSWORD`。S2~S4 未配置。空闲状态默认每 15 秒读取一次主板电源与 BMC SDR;网页查询只取缓存,不因为页面刷新就重复连接设备。
-
-BMC SDR 没有本次传感器测量时间。其 DIMM 值标为 `source=bmc_sdr`、`quality=unverified`、`observed_unix_ms=0`,不当成 UEFI 实时读数,也不用于罩内预热判定。`No Reading` 表示不可读,不能据此判断 DIMM 空槽。
-
-温控板协议和总电源控制器还需现场资料。没有温控 `bridge` 时,开始测试会在创建运行和设备写操作之前拒绝。`supply_mode=manual` 表示整套通断电由操作员执行并明确确认;IPMI 的 chassis off 只关闭主板电源,不代表 BMC、高温罩和温控板都已断电。
-
-现场 `cxmt-live-gnr` profile 保持人工确认;未验证的 UIP 电压、时序、RMT/AMT 设置、AMT exit 和 UEFI 程序路径不会自动下发。网页人工模式允许明确的 SOL 输入,恢复自动模式也必须显式操作。
-
-SOL helper 用 ipmitool 建立一次会话,看到真实激活成功提示才报告 ready。占用时报错,不自动抢占;连接断开不静默重连、不重放 BIOS 输入。当前观察到另一个来源 `192.168.0.10` 的会话,解除占用后才能继续获取本机型 BIOS 帮助和命令回显。
-
-## 5. 模拟器与现场必须使用不同数据目录
-
-在开发机上可直接运行:
-
-```bash
-python3 -m venv .venv
-. .venv/bin/activate
-python -m pip install -e '.[dev]'
-stl-server --config config/simulated.json --data-dir /tmp/xjkj-stl-demo \
-  --listen 127.0.0.1:50061 --web-listen 0.0.0.0:18080
-```
-
-打开 `http://127.0.0.1:18080/`。模拟器不连接真实 BMC,也不使用现场数据库;它可验证四工位开始、停止、人工模式、日志、文件导入与历史查看。网页仅负责输入和显示,流程推进与记录始终由后端执行。
-
-## 6. 被动 SOL 证据与版本交付
-
-设置 BMC 密码环境变量后,从已安装项目目录运行:
-
-```bash
-python scripts/explore_firmware_uip.py --duration 30
-```
-
-脚本保存原始字节与 `capture.json`。它不发送 BIOS 命令、不切换电源、不解除别人的 SOL 会话;占用和连接失败会返回非零,不会写成“验证成功”。
-
-发布前完成测试、提交 `dev`、建立版本标签,再运行 `python scripts/package_delivery.py`。源码来自精确的 Git commit;调试包包含实际证据、文件大小和 SHA-256。没有远端仓库地址时,保持本地提交和标签,记录 Git 推送待配置,不伪造推送完成。
-
-保留的 `deploy/stl-backend.service` 为非容器部署模板。现场已经选择容器时,无需同时注册它,避免第二个进程占用同一端口和设备。

+ 0 - 162
docs/DEVICE_ADAPTERS.md

@@ -1,162 +0,0 @@
-# 设备适配与真实机台接入
-
-本包默认运行 `simulated`。模拟器不建立 BMC 网络连接,所有模拟输出均包含 `STL_SIM` 标记或 `simulated: true`。真实连接由部署配置显式选择 `hardware`。
-
-## 1. 设备接口
-
-每个工位有一个 `StationDevice`,四工位分别持有自己的设备对象。除 `sol_read()` 返回异步迭代器外,下表方法均需 `await`。
-
-| 方法 | 返回值与作用 |
-| --- | --- |
-| `configure_run(recipe, dimms)` | 为本轮初始化模拟上下文;真实硬件配置由流程逐项应用 |
-| `supply_set(on)` | 操作该工位全部供电,返回反馈 `on/off/unknown` |
-| `supply_read()` | 读取总供电状态 |
-| `confirm_supply(on)` | 仅人工供电模式使用;上层必须记录操作者、本轮编号与确认时间 |
-| `bmc_power("on"/"off")` | 操作服务器主板电源,并额外查询 BMC 主板状态 |
-| `bmc_read()` | 查询服务器主板状态;不能据此证明 BMC/温控板全部断电 |
-| `set_target(c)` | 给温控板设置 DIMM 目标,返回板上确认值 |
-| `read_telemetry()` | 环境温度、可用 DIMM 温度、质量和板状态 |
-| `sol_start()` | 等待 SOL 真正建链就绪 |
-| `sol_read()` | 取得原始 SOL 字节;只应有一个后台读取者 |
-| `sol_write(bytes)` | 写原始串口字节,例如命令加 `\r` |
-| `sol_close()` / `close()` | 关闭通信资源;关闭连接本身不执行设备断电 |
-
-设备操作报错使用 `DeviceError`。人工供电步骤通过 `ManualActionRequired(on)` 告诉流程等待确认,不能把“等待人工操作”当作已经完成。
-
-## 2. 真实设备配置
-
-以下是设备配置片段,外层工位、配方、服务监听配置参见主 README。
-
-```json
-{
-  "mode": "hardware",
-  "supply_mode": "bridge",
-  "bridge": {
-    "argv": ["/opt/stl/board-bridge", "--port", "/dev/ttyUSB0"],
-    "timeout_s": 5
-  },
-  "supply_bridge": {
-    "argv": ["/opt/stl/power-bridge", "--channel", "1"],
-    "timeout_s": 5
-  },
-  "bmc": {
-    "host": "192.0.2.10",
-    "user": "operator",
-    "password_env": "STL_S1_BMC_PASSWORD",
-    "cipher_suite": 17,
-    "timeout_s": 15,
-    "sol_timeout_s": 15,
-    "ipmitool_argv": ["ipmitool"],
-    "sol_helper_argv": ["/opt/stl/native/stl-sol-helper"]
-  }
-}
-```
-
-上面 `/dev/ttyUSB0` 是 bridge 参数占位示例,不能据此认定现场串口属于温控板。当前现场串口角色尚未确认,实际参数为用户给定的 1125200、无流控。
-
-`192.0.2.10` 是文档地址,必须替换为现场地址。密码只读取指定的环境变量,不复制原前端源文件中的密码。ipmitool 子进程使用 `-E`;SOL helper 通过环境读取密码,两者都不把密码放进参数或 gRPC 返回值。
-
-`bridge` 是温控板接口。若总电源与温控板由同一个桥接程序控制,可不写 `supply_bridge`,两类操作会共用一个序列化连接。若现在人工开关总电源,使用 `supply_mode: "manual"`,无需电源 bridge。人工确认只表达操作员确认,不能冒充硬件回读。
-
-`cipher_suite` 根据现场 BMC 支持选择。当前现场及模板使用 17;192.168.0.100 的 BMC 查询已实测支持该配置。模板地址是占位值,其他机器仍需实际核对。
-
-## 3. 温控板和总电源 bridge 协议
-
-附件中没有可确认的温控板串口帧格式、地址、校验方式或总电源协议。因此这里定义进程边界,不猜测硬件报文。将现场驱动封装成长期运行的进程,即可保持主流程和 gRPC 不变。
-
-后端通过 argv 数组启动进程,不经过 shell。stdin 每行一个 UTF-8 JSON 请求;stdout 每行一个 JSON 响应;诊断日志写 stderr。禁止在 stdout 打印启动说明,否则会破坏协议。
-
-请求示例:
-
-```json
-{"id":"唯一请求编号","operation":"set_target","arguments":{"target_c":80.0}}
-```
-
-响应示例:
-
-```json
-{"id":"同一请求编号","ok":true,"result":{"confirmed_target_c":80.0}}
-```
-
-| operation | arguments | result |
-| --- | --- | --- |
-| `supply_set` | `{"on":true}` / `{"on":false}` | `{"accepted":true}`;表示收到操作 |
-| `supply_read` | `{}` | `{"state":"on"}`;或 `off/unknown`,来自实际反馈 |
-| `set_target` | `{"target_c":80.0}` | `{"confirmed_target_c":80.0}`;板上确认或读回 |
-| `read_telemetry` | `{}` | 见下方样本 |
-
-```json
-{
-  "id": "同一请求编号",
-  "ok": true,
-  "result": {
-    "air_c": 73.4,
-    "dimms": [
-      {"cpu":0,"channel":"A","slot":"A1","value_c":79.8,"quality":"valid"}
-    ],
-    "quality": "valid",
-    "dimm_quality": "valid",
-    "board_state": "running"
-  }
-}
-```
-
-数值只是格式例子,不是推荐工艺温度。UEFI 前 DIMM 不可读时返回 `dimms: []`、`dimm_quality: "unavailable_in_phase"`。未知环境温度用 `air_c: null` 并给出相应质量,不能填 0 或重复旧值却标记为有效。若板返回缓存读数,应同时返回其采样时间/年龄与 `stale` 状态。
-
-操作失败:
-
-```json
-{"id":"同一请求编号","ok":false,"error":"driver_timeout"}
-```
-
-后端每个 bridge 同时只发一个请求,响应需匹配请求 ID,最大响应行 1 MiB。超时、取消或响应无效时关闭该进程,下一次操作重新建链,避免旧响应错配到新请求。bridge 应把响应发送在实际串口/设备事务完成之后,而不是启动内部后台线程后立即宣告成功。
-
-总供电写入后,适配器会独立执行 `supply_read`。回读 `unknown` 保持未知;不能通过 BMC ping 不通推断为 `off`。电源执行器失去供电后如何重新上电必须由实际硬件提供。
-
-`native/example_json_bridge.py --simulate` 是可运行的协议示范,没有真实设备 I/O。替换其中各 operation 的处理体即可接入现场协议;不能把这个示范作为真实机台驱动使用。
-
-## 4. SOL 原生 helper
-
-保留原工程的 FreeIPMI/libipmiconsole 技术路径,去掉 Qt 依赖并放入独立进程。helper 不负责判断 BIOS 阶段;原始字节交给 Python 后端保存和解析。这样单个 BMC/本地库故障不会在同一进程内破坏其余工位。
-
-在 Debian/Ubuntu 类环境,安装对应发行版的构建工具、`libipmiconsole-dev` 和 `ipmitool` 后:
-
-```bash
-python3 native/build_sol_helper.py
-native/stl-sol-helper --help
-```
-
-源码同时适配三参数和四参数 `ipmiconsole_ctx_create`;本次对附件实际携带的四参数头文件/共享库进行了编译和 `--help` 运行验证。其他 FreeIPMI 版本需要在部署机重新构建验证。不要混用不匹配的头文件和库。
-
-使用单独安装的匹配库时可指定:
-
-```bash
-python3 native/build_sol_helper.py \
-  --include-dir /opt/freeipmi/include \
-  --library-dir /opt/freeipmi/lib \
-  --output ./native/stl-sol-helper
-```
-
-helper 协议:stdin/stdout 原始字节;stderr 发送 `connecting`、`ready`、`error`、`closed` JSON 事件。收到 `ready` 后,Python 才认为 SOL 建链完成。原生 SOL fd 非阻塞,检测 EOF/连接错误,退出时释放上下文及库引擎;Python 管理超时、终止和回收。
-
-四参数版本显式要求占用中的 SOL 报错,避免接管其他程序正在使用的会话。三参数旧 API 使用该版本库的行为。部署后,需要停用原 Qt 程序中的 `SolManager` 直连和 stage1 自动发送逻辑,再由 gRPC 客户端操作唯一的后台会话。
-
-以上 C++ / libipmiconsole helper 是保留的可选实现。当前现场配置和硬件模板使用 `native/stl_sol_bridge.py`(Python PTY + ipmitool);收到真正的 SOL 激活成功提示后才 ready,占用或断线直接报告,不自动抢占或重连。BMC LAN 查询已经实测;当前 SOL 仍被占用,UIP 命令回显、BIOS 全流程、温控协议与总供电执行器尚未完成实机验证。
-
-## 5. 模拟器行为
-
-`SimulatedDevice` 完全在内存中工作。可配置:
-
-```json
-{"mode":"simulated","simulation":{"step_delay_s":0.15,"mt_duration_s":2,"fail_mt":false}}
-```
-
-主板开机后输出附件中的 CPU0 stage1 标记;空回车推进到 CPU1;CPU1 空回车后按配方输出 RMT/AMT 的模拟开始和结束标记,再进入 `Shell>`。包含 `memtest` 的命令启动模拟 MT,输出进度、结果及 `RESULTS_FLUSHED`。
-
-仅到达模拟 UEFI 后才提供 DIMM 温度。全工位断电会取消模拟测试任务并关闭 SOL。模拟测试结果只验证主机流程,不能作为内存质量判断。
-
-设备层测试使用本地子进程桩,不访问真实设备:
-
-```bash
-PYTHONPATH=src python3 -m unittest discover -s tests -p test_devices.py -v
-```

+ 0 - 43
docs/EVIDENCE_20261023.json

@@ -1,43 +0,0 @@
-{
-  "review_date": "2026-10-23",
-  "scope": "Historical evidence bytes inspected locally; current live collection remains in data/evidence and is indexed by the delivery manifest",
-  "historical_files": [
-    {
-      "path": "docs/hardware-evidence/ipmi_channel_authcap.txt",
-      "bytes": 347,
-      "sha256": "8e3bb19d2ffbf18d36596f6067237257f872f43cc4ab02661c1fe1c2ea8a4f43"
-    },
-    {
-      "path": "docs/hardware-evidence/ipmi_lan_print.txt",
-      "bytes": 894,
-      "sha256": "c6181becbccf946d3229e0762f9f25d2b01b718453761fcc81f42a9b8cca7849"
-    },
-    {
-      "path": "docs/hardware-evidence/serial_capture_1125200.bin",
-      "bytes": 0,
-      "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
-    },
-    {
-      "path": "docs/hardware-evidence/serial_capture_1125200.hex",
-      "bytes": 1,
-      "sha256": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b"
-    },
-    {
-      "path": "docs/hardware-evidence/sol_capture.bin",
-      "bytes": 53,
-      "sha256": "9128edc66090ba17c9d46b9fb50e1e5fb689ca56ad6a2e509dc119bda28abe28"
-    },
-    {
-      "path": "docs/hardware-evidence/sol_capture.hex",
-      "bytes": 159,
-      "sha256": "9608b3c274e37bd518d5d5b305189a31de6facbf60c435e2b5be6f886abbc591"
-    },
-    {
-      "path": "docs/hardware-evidence/test_suite_83_passed.log",
-      "bytes": 926,
-      "sha256": "545147d6a94e37afd6d5d79434ea7c74714c142ce5442704c7e72cfff806c01f"
-    }
-  ],
-  "live_collection_directory": "data/evidence/review-20261023",
-  "live_file_hashes": "not copied here; compute from actual files when packaging"
-}

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


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


+ 0 - 225
docs/GRPC_CLIENT.md

@@ -1,225 +0,0 @@
-# gRPC 协议与操作客户端
-
-本后端使用 `stl.v1.BenchService`,协议源文件为 `proto/stl/v1/bench.proto`。所有 RPC 都是 unary:查询轮询、控制返回命令、SOL 按字节游标读取、结果文件分块上传。无需为一次测试保持一条长时间 RPC,也无需前端持续在线。
-
-当前 Qt 工程为 Qt 5 / C++11;本交付未修改 `.ui`、`.cpp`、`.h`、`.pro` 或样式。`stl-client` 是用于操作与验证后端的命令行工具,没有 GUI。
-
-## 1. 安装与快速连通
-
-在项目目录安装后,得到 `stl-server` 和 `stl-client` 两个入口:
-
-```bash
-python3 -m venv .venv
-. .venv/bin/activate
-python -m pip install -e '.[dev]'
-stl-client --help
-stl-client system
-stl-client stations
-stl-client recipes
-```
-
-未安装 entry point 时,也可用 `PYTHONPATH=src python -m stl_backend.cli` 调用相同客户端。服务启动方式见根目录 README。
-
-默认连接 `127.0.0.1:50051`。全局选项放在子命令之前:
-
-```bash
-stl-client --target 192.0.2.10:50051 --timeout 15 stations
-stl-client --target bench.example:50051 --tls stations
-stl-client --target bench.example:50051 --tls-root ./ca.pem stations
-stl-client --token-env STL_API_TOKEN stations
-```
-
-`--token-env` 读取已有环境变量并发送 `authorization: Bearer ...`。不要将令牌内容填入文件名或命令 ID。`--tls` 使用系统信任根;`--tls-root` 使用指定 PEM 根证书并启用 TLS。服务端必须配置匹配的 TLS/令牌;客户端不能通过选项替服务端开启这些能力。
-
-默认每次 RPC deadline 为 15 秒,上传结束的分析步骤至少给 60 秒。`--timeout` 可调高这两者。RPC 超时仅表示客户端未拿到响应,不能据此判断操作未执行。
-
-## 2. 现有界面与实际 RPC 对照
-
-| 功能 | RPC | 主要响应 |
-| --- | --- | --- |
-| 后端身份和模式 | `GetSystemInfo` | 版本、server_id、simulated/hardware、工位数量 |
-| 四工位概况 | `ListStations` | `StationSnapshot[]`,含前端索引、温度、阶段、电源、通道 |
-| 一个工位详情 | `GetStation` | `StationSnapshot` |
-| 配方列表和读取 | `ListRecipes` / `GetRecipe` | 带 revision 的 `Recipe` |
-| 创建或修订配方 | `PutRecipe` | 以 expected_revision 保护编辑,运行中的配方快照不变 |
-| 开始/停止测试 | `StartRun` / `StopRun` | `Command`;实际过程继续在后端执行 |
-| 修改本轮 DIMM 目标 | `SetTargetTemperature` | `Command`;应用后的读回在工位温度快照中 |
-| 人工步骤确认 | `ConfirmStage` | 绑定 run_id、step_id、operator 和 evidence |
-| 人工确认整套供电 | `ConfirmPower` | 标明人工来源,绑定 expected_run_id |
-| 空闲工位电源操作 | `StationPower` | supply_on/off 与 host_on/off 分开 |
-| 人工接管 SOL | `SetSolMode` / `WriteSol` | 后端保持设备连接和记录;人工模式暂停自动输入 |
-| 操作状态 | `GetCommand` | accepted/running/succeeded/failed/interrupted |
-| 本轮与历史 | `GetRun` / `ListRuns` | 运行状态、结论、资料完整度、装料和配置快照 |
-| 事件和异常 | `ListEvents` / `AcknowledgeEvent` | 原始来源、时间、等级、确认人;确认不删除证据 |
-| 温度曲线数据 | `QueryTemperatures` | 时间与测点质量明确的分页采样 |
-| SOL 原始文本 | `ReadSol` | bytes、next_offset、eof、total_bytes |
-| U 盘文件导入 | `BeginArtifact` → `UploadArtifactChunk` → `FinishArtifact` | 可恢复上传及 SHA-256 校验后的原始文件登记 |
-| 文件列表与读取 | `ListArtifacts` / `ReadArtifact` | 元数据与原始字节 |
-| 测试报告数据 | `GetRunReport` | 运行快照、文件清单、缺少的结果种类和解释 |
-
-没有定义“清空服务器日志”RPC。前端的清空按钮只清本地显示缓存。没有单独的“按前端百分比推动测试”RPC;真实测试流程由后端执行。
-
-## 3. 创建本轮测试
-
-先准备装料清单,例如 `dimms.json`:
-
-```json
-[
-  {"sn": "EXAMPLE-SN-001", "cpu": 0, "channel": "0", "slot": "A1", "part_number": "EXAMPLE-PN"},
-  {"sn": "EXAMPLE-SN-002", "cpu": 1, "channel": "0", "slot": "A1", "part_number": "EXAMPLE-PN"}
-]
-```
-
-SN 示例需要替换为真实值;通道编号用 0~11,CPU 用 0/1,slot 以实际主板标识为准。一个通道可以存在多根 DIMM,`cpu + channel + slot` 和 SN 应保持明确对应。
-
-```bash
-stl-client start --station S1 --recipe DEMO-80 --work-order WO-001 \
-  --batch BATCH-001 --operator operator-a --dimms ./dimms.json \
-  --command-id start-WO001-S1-001
-```
-
-`DEMO-80` 是模拟配置使用的配方。接真机时须使用该硬件配置文件中的已验证配方;示例温度不代表工艺建议。
-
-响应含 `run_id`。后续命令示例先设定该值:
-
-```bash
-RUN_ID='替换为实际返回的 run_id'
-stl-client run "$RUN_ID"
-stl-client report "$RUN_ID"
-stl-client command start-WO001-S1-001
-```
-
-客户端未指定 `--command-id` 时会生成 ID,并在发送前打印到 stderr。网络超时后,重新发送相同操作时应携带相同 ID、完全相同参数。不同操作必须换 ID。
-
-```bash
-stl-client target "$RUN_ID" 80 --operator operator-a --command-id settemp-001
-stl-client stop "$RUN_ID" --reason operator_requested --operator operator-a --command-id stop-001
-```
-
-目标温度命令的成功表示设置动作结果,达到目标温度需要后续有效测量。后端先完成本轮初始配方目标的应用,进入预热及后续阶段才接受运行中目标修改;初始化期间与收尾期间拒绝修改,避免成功的人工设置又被启动流程覆盖。修改保存在本轮 `evidence.target_changes`,原始配方快照保持不变。
-
-停止命令绑定运行编号,即使工位已经开始下一轮,也不能把旧运行的停止请求作用到新运行。客户端超时、关闭连接之后,已经接受的写操作继续由后端执行。若服务进程本身重启,未结束轮次进入 `recovery_required`,不会重放开机或 BIOS 输入;核对现场后通过本轮 `StopRun` 收尾。
-
-## 4. 查询与游标
-
-```bash
-stl-client stations S1
-stl-client runs --batch BATCH-001 --limit 50
-stl-client runs --sn EXAMPLE-SN-001 --limit 50
-stl-client events "$RUN_ID" --after 0 --limit 100
-stl-client temps "$RUN_ID" --after 0 --limit 100
-stl-client logs "$RUN_ID" --offset 0
-stl-client logs "$RUN_ID" --offset 0 --follow --interval 1 --follow-seconds 300
-```
-
-- `ListRuns` 使用 `before_sequence` 向更早的记录翻页,响应提供 `next_before_sequence`。
-- `ListEvents` 使用 `after_event_id` 向更新的事件读取。
-- `QueryTemperatures` 使用 `after_sample_id`。
-- `ReadSol` 使用字节 offset;offset 不是字符数、行数或时间戳。
-- `logs` 默认仅读取一个最大 256 KiB 的块,原始字节写到 stdout,`next_offset` 打印到 stderr;`--follow` 连续读取,等待新数据时轮询,默认最多跟随 300 秒,已完成运行读到末尾时退出。
-- 对正在执行的运行,SOL 的 `eof=true` 表示“本次读到了当前文件末尾”,后续仍可能出现新字节。
-- CLI 查询 JSON 遵循 Protobuf JSON 映射,64 位整数字段可能表现为字符串;原生客户端按 `.proto` 中的类型处理。
-
-温度缺失时 `Measurement.value_c` 没有 presence。前端要同时查看 quality,不可把默认数值 0 当作真实的 0 ℃。`progress_percent` 同样是 optional,没有时展示阶段或时长即可。
-
-## 5. 结果文件上传、恢复与下载
-
-```bash
-stl-client upload "$RUN_ID" ./MemTest86-example.log --kind memtest_log --operator operator-a
-stl-client upload "$RUN_ID" ./MemTest86-report.html --kind memtest_html --operator operator-a
-stl-client upload "$RUN_ID" ./result.json --kind result_json --operator operator-a
-stl-client artifacts "$RUN_ID"
-```
-
-`--kind auto` 为默认值,适用于识别已有文件格式;需要满足配方规定的结果种类时,显式指定一致的 kind。现有解析格式见 `LOG_FORMATS.md`。
-
-上传过程:
-
-1. 流式计算本地文件 SHA-256;
-2. 从 run_id、文件名、kind、operator、SHA-256 生成稳定 upload_id;
-3. `BeginArtifact` 获得服务端 `next_offset`;
-4. 按 256 KiB 分块上传,每次响应确认新的 offset;
-5. `FinishArtifact` 发送完整 SHA-256,校验后登记原文件并分析。
-
-同一条上传命令在断线后重跑,会复用稳定 ID 和服务端进度。若改变 `--operator`、kind 或文件内容,会产生不同 ID。也可显式指定 `--upload-id`,但同一 ID 不能用于不同文件。
-
-```bash
-ARTIFACT_ID='替换为实际 artifact_id'
-stl-client download "$ARTIFACT_ID" ./downloaded-result.log
-stl-client download "$ARTIFACT_ID" ./downloaded-result.log --force --sha256 '替换为64位十六进制摘要'
-```
-
-下载写入同目录临时文件,收到全部字节后再替换目标文件。默认拒绝覆盖已有文件。提供 `--sha256` 时额外核对摘要;未提供时仍返回实际下载摘要,但不会声称已与服务端元数据比对。
-
-运行已断电并不妨碍导入本轮 U 盘文件。文件总是关联指定 `run_id`,不按工位“最新一轮”隐式分配。
-
-## 6. 人工阶段和供电确认
-
-在硬件 profile 的人工步骤中,`GetStation` 返回 `pending_step_id` 与 `pending_instruction`。只有完成了该动作并取得证据后才确认:
-
-```bash
-stl-client confirm-stage "$RUN_ID" --step uefi-start \
-  --evidence '实际完成依据或观察结果' --success --operator operator-a
-```
-
-无法完成时使用 `--failed`,不要用成功确认掩盖未执行动作。具体 step ID 以当前工位快照为准。同一步骤的确认由第一个有效请求认领;两个操作员不能以不同命令 ID 覆盖彼此的确认。需要重试已发送请求时,保留相同 `--command-id` 与全部参数。
-
-人工供电确认:
-
-```bash
-stl-client confirm-power S1 --run "$RUN_ID" --on --operator operator-a
-stl-client confirm-power S1 --run "$RUN_ID" --off --operator operator-a
-```
-
-这条 RPC 记录操作人员确认的状态,不会让物理开关自己动作。全自动供电必须接入实际硬件适配器。空闲工位的实际控制命令是:
-
-```bash
-stl-client power S1 supply_on --operator operator-a
-stl-client power S1 host_on --operator operator-a
-stl-client power S1 host_off --operator operator-a
-stl-client power S1 supply_off --operator operator-a
-```
-
-运行中的测试通过本轮流程控制电源,不能用空闲工位接口绕过运行归属。
-
-## 7. 手工 SOL 操作
-
-```bash
-stl-client sol-mode "$RUN_ID" manual --operator operator-a
-stl-client sol-write "$RUN_ID" --text 'help' --operator operator-a
-stl-client sol-write "$RUN_ID" --file ./keys.bin --operator operator-a
-stl-client sol-mode "$RUN_ID" auto --operator operator-a
-```
-
-`--text` 按 UTF-8 编码并附加 `\r`;`--no-cr` 禁止追加。`--file` 发送原始字节,适合 ESC 等非文本按键。每次最多 4 KiB。接管后自动输入暂停,采集和日志仍继续;回到 auto 前应确认控制台已处于流程能够识别的阶段。
-
-## 8. 四工位模拟演示
-
-在 simulated 配置启动服务之后:
-
-```bash
-stl-client demo
-```
-
-该命令先核对后端及所有工位均为 `simulated`,随后:
-
-- 对四个空闲模拟工位创建独立运行和带 SIM 前缀的 24 条 DIMM 身份;
-- 等待各轮完成;
-- 仅为工作流完成、无错误的模拟运行生成 `stl.test-result.v1` 格式结果,文件显式带有 simulated 标记;
-- 分块导入该文件,再查询最终报告与断电状态。
-
-`demo` 不调用真实设备,也不能在 hardware 配置上执行。模拟结果不代表任何真实内存测试结论。可用 `--count 1` 只演示一个工位,`--wait-seconds 180` 调整等待上限。
-
-Ctrl-C 或客户端退出不会停止已经被后端接受的运行。需要停止时,使用打印出的 run_id 执行 `stop`。
-
-## 9. Qt 5 和浏览器接入
-
-Qt 5 可使用同一 proto 生成原生 gRPC C++ stub。需要的生成工具是 C++ Protobuf 编译器及 `grpc_cpp_plugin`;本项目 Python 的 `grpcio-tools` 用于 Python 生成,不代替 C++ 插件。将 RPC 放到工作线程/异步调用环境中,通过 Qt 信号槽更新 UI,避免主线程等待网络。
-
-当前版本已提供浏览器页面与内嵌 gRPC-Web 网关,默认位于 8080;原生 gRPC 位于 50051。网页使用带消息帧与状态尾帧的 gRPC-Web JSON,控制、轮询与文件分块共用同一 BenchService。原 Qt 尚未改造成 gRPC 客户端,接入方式仍按上段实施。
-
-官方技术参考:
-
-- [gRPC C++ 基础与代码生成](https://grpc.io/docs/languages/cpp/basics/)
-- [gRPC-Web 官方协议客户端与代理要求](https://github.com/grpc/grpc-web)
-- 交付协议:`proto/stl/v1/bench.proto`

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


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


+ 0 - 93
docs/REVIEW_20261023.md

@@ -1,93 +0,0 @@
-# 2026-10-23 直接复核记录
-
-本记录区分实际观测、旧报告和未完成工作。原始文件保留;包内 manifest 为实际收集的文件提供大小和 SHA-256。日期采用用户时区 Asia/Jerusalem,采集脚本和包时间若标为 UTC 则按各自字段解释。
-
-## 1. 接手时的差异
-
-开发目录在 `dev` / `a47e66b`,旧 `v0.1.1` 标签指向此提交;Linux79 部署目录是 `f9e960f`。网页与 gRPC 由裸 Python 服务运行,接手时 `docker ps` 为空。
-
-从 v0.1.0 到 a47e66b 的差异约为 2774 行新增、11 行删除。`service.py`、`artifacts.py` 和 `store.py` 没有旧审计报告所称的精简重构。因此本轮依据具体缺陷修复,不将上轮增添网页和设备工具描述为已完成整体精简。
-
-## 2. 证据能够支持什么
-
-| 证据 | 实际内容 | 结论 |
-| --- | --- | --- |
-| `docs/hardware-evidence/ipmi_lan_print.txt` | 静态地址 192.168.0.100、LAN 配置及列出的 cipher 17 | 支持历史网络配置记录,不是整机全功能验收 |
-| `docs/hardware-evidence/ipmi_channel_authcap.txt` | channel 1 支持 IPMI 2.0 | 仅为认证能力查询 |
-| `docs/hardware-evidence/serial_capture_1125200.bin` | 0 字节 | 无法证明串口角色 |
-| `docs/hardware-evidence/serial_capture_1125200.hex` | 单个换行 | 无额外遥测内容 |
-| `docs/hardware-evidence/sol_capture.bin` | 53 字节:`Info: SOL payload already active on another session` | 没有 BIOS 回显或双向控制证据 |
-| `docs/hardware-evidence/sol_capture.hex` | 上述 53 字节的十六进制表示 | 与原字节是同一证据 |
-| `docs/hardware-evidence/test_suite_83_passed.log` | `83 passed in 34.41s` | 历史代码测试记录,不是当前全部修改或实机通过 |
-| `data/evidence/` | 包含探索超时、原始串口和命令记录 | 打包时递归保留,不只选择旧的 7 个文件 |
-| `data/evidence/review-20261023/` | 本轮直接采集的查询、UART、SOL 和 BMC 复位过程 | 文件列表和哈希由实际打包生成,不在此捏造 |
-
-## 3. 本轮设备观测
-
-IPMI 可读 BMC `192.168.0.100`。Linux79 的专用有线地址为 `192.168.0.101`。读取时 CPU0_A 约 34°C、CPU1_A 约 35.2°C,其余温度不可读;这些值不能证明只有两根 DIMM 在位,亦不能将多个传感器的电压、电流、功率直接拼成同一测量结果。
-
-1125200、无流控 UART 只读采集 8 秒得到 2 个 NUL,当前无法识别串口角色。没有将其解释为 CPLD 遥测。
-
-SOL 返回被另一会话占用。会话查询出现 `192.168.0.10` 和 `192.168.0.101`;前者需继续核实归属。BMC warm reset 返回 `Invalid command`,cold reset 成功,约 134 秒后 IPMI 恢复,主板仍为 on;之后 SOL 仍 busy。本轮没有获得 BIOS 回显、没有发送 UIP/AMT 参数,也没有发送主板电源开关命令。
-
-## 4. 已完成的代码和交付修正
-
-- 审阅文档只记录已核实的范围和事实,原始输入及旧证据不删除。
-- 命令目录区分旧源码/profile 线索和当前固件实测;未知范围、默认值、错误和恢复方式保持未知。
-- 源码包使用 `git archive HEAD`,要求干净 dev 工作区。版本读取同一提交中的 `VERSION`;只有 HEAD 上确有对应标签才记录 tag。
-- 源码包根目录及项目 `source/COMMIT` 保存完整提交号,便于没有 `.git` 的解压目录显示实际构建版本。
-- 日志包收集 `docs/hardware-evidence`、`data/evidence`、`data/runs`、`data/artifacts` 和 data 顶层 `.log`;可通过 `--evidence-dir` 增加现场服务日志目录。保持子目录以避免重名覆盖。
-- 包含运行凭据的文件不应进入新包。默认排除运行环境文件/私钥路径;设置 `STL_BMC_S1_PASSWORD` 等运行变量或 `--secret-env NAME` 时,若文件含对应值则终止打包。原始证据不会被静默改写。
-- 旧 Git 历史包含明文默认密码,因此新包不自动附完整 bundle;保留本机 Git 历史及旧标签。源码包仍对应确切提交。
-- Windows SSH key 连通已核实。包生成、实际传输和远端哈希核对分别记录,不由打包脚本自动宣称回传成功。
-
-在干净提交后使用:
-
-```bash
-python3 scripts/package_delivery.py --mode mixed --session review-20261023
-```
-
-若现场数据不在项目 `data` 下,显式提供 `--data-dir`;额外证据目录通过 `--evidence-dir` 添加。活动 SQLite 库不直接复制进日志包,避免把不一致的数据库副本当作完整业务归档。
-
-## 5. 已执行的验收与部署
-
-| 验证 | 实际结果 | 证据 |
-| --- | --- | --- |
-| Python 全套回归 | 最终 94 passed、12 subtests passed,30.73 秒 | `unit-tests.txt`;使用模拟设备、本地进程桩及临时 SQLite |
-| 三份配置 | simulated、hardware.example、station0-live 均通过配置和配方验证,各四工位 | `configuration-check.txt` |
-| 容器镜像 | Python 3.11,grpcio 1.84.0,protobuf 7.36.2;实际完成构建 | `container-build.log` |
-| 运行迁移 | 停止原裸 Python PID 86013,备份完整 data,启动 xjkj-stl-backend | `deployment.json`、`container-start.log` |
-| 迁移前数据核对 | runs=0、artifacts=0、uploads=0;没有旧绝对附件路径需要转换 | 本轮数据库只读核对 |
-| 原生 gRPC 实机查询 | 0.1.2/hardware,四工位,S1 BMC online、主板 on | `live-api-check.json` |
-| 缺温控配置时开始 | FAILED_PRECONDITION,明确缺少 thermal bridge;前后无活动轮次 | 同上 |
-| Windows Edge 网页 | 独立模拟实例实际完成输入 SN、开始、人工接管、SOL 单 CR、空 CR、目标 78.5℃读回、停止/模拟总断电、文件导入、报告下载 | `browser-simulated-dynamic.txt`、`browser/simulated/` |
-| 现场网页 | 只读核对版本、commit、四工位、24 通道及工位切换 | `browser-hardware.txt`、`browser/hardware/` |
-
-全套自动测试最初为 93 项;补查发现 SN 身份一致性问题,增加回归并修正后为 94 项。测试不是硬件认证,模拟的 off/pass 不作为实机供电或内存质量结论。
-
-浏览器测试最初因固定调试端口被 Windows VS Code 转发占用而失败,失败日志保留。随后使用浏览器自己分配的临时端口,通过实际操作验证;没有修改 VS Code 或系统网络设置。
-
-### 本轮具体修复
-
-- 网页请求补齐 command_id、run_id、operator 和 DIMM 身份,接受命令后继续读取执行结果;总供电确认与阶段确认分别使用正确接口。
-- gRPC-Web JSON/proto 均采用真实数据帧和状态尾帧;正确处理 metadata、异步 abort、错误码和未知字段。
-- SOL 和事件游标按 run_id 隔离;支持人工接管/恢复、一个 CR 的手工输入、历史、原始日志/报告下载及分块导入。
-- 空闲工位按 15 秒间隔读 BMC 电源与 SDR。SDR 的来源和未知测量时间单独标注,No Reading 不等于空槽。
-- SOL helper 看到实际激活成功提示才 ready;占用报错、不自动抢占、不隐式重连。被动探索脚本不再改电源、猜命令或伪报验证成功。
-- 现场及通用硬件入口均使用人工核对流程。旧自动 profile 只保留历史兼容说明,不在当前模板入口启用。
-- 固件 inventory 只作为事件保存,不静默覆盖人工登记 SN;GetRun、通道显示和按 SN 查询历史保持同一身份。
-- 镜像正确安装 Python 包,包含网页资源/native helper;服务直接显示后端版本及镜像 commit。
-
-补审实际阅读 service/store/artifacts/config/cli/base/simulator/proto 共 2032 行,并交叉检查收尾与结果聚合;原生 C++ helper 与构建脚本另行阅读。`AUDIT.md` 记录实际审阅范围,不将文件清单冒充全部逐行分析。
-
-运行目录保留两份旧的未跟踪现场文件,未覆盖或删除。旧数据库配方 GNR-DDR5-LIVE 保留并标为未验证参考,新默认现场配方为 GNR-DDR5-ASSISTED。
-
-空闲单次容器观测约 21.27 MiB、CPU 0.04%;这仅是当时 S1 监视状态的一个采样,不是四工位满负荷性能验收。
-
-## 6. 交付与尚未完成的工作
-
-发布代码在 dev 提交并建立 v0.1.2 标签,最终提交号读取包中 COMMIT / MANIFEST,运行实例可通过 GetSystemInfo 核对。没有 Git 远端 URL,推送状态保持 pending_push。
-
-源码分析包、原始调试包与交付清单发往 Windows `C:\Users\Administrator\delivery`。文件名、实际传输时间和远端 SHA-256 以生成后的交付回执为准;不会将打包动作本身等同于上传成功。
-
-尚未完成的实机工作是:解除/识别 SOL 占用、取得 UIP/RMT/AMT 帮助及读回、确认 UEFI 程序/配置与结果落盘标记、接入温控板协议和总电源反馈,最后执行真实完整高温测试。BMC 会话表出现的 192.168.0.10 只是待核实线索,不能仅据此确定具体进程。当前没有 BIOS 回显证据,也没有自动验证这些命令。

+ 0 - 114
docs/TEST_REPORT.md

@@ -1,114 +0,0 @@
-# 本次交付验证记录
-
-日期:2026-10-22。对象:本包 `XJKJ-STL-backend` 0.1.0。
-
-## 1. 完整测试结果
-
-在本项目根目录执行:
-
-```bash
-python -m pytest -q
-```
-
-最终整体运行结果:
-
-```text
-78 passed, 12 subtests passed in 30.79s
-```
-
-| 测试文件 | 测试数 | 实际验证内容 |
-| --- | ---: | --- |
-| `test_devices.py` | 11 | 设备模拟、JSONL bridge、超时/取消、请求匹配、BMC 子进程、总供电写后回读、SOL helper 生命周期 |
-| `test_engine.py` | 12 | 四工位隔离、每轮重置、提前 CPU1 标记、预热停止、失败关电、跳过测试、手工模式、供电确认竞态、慢目标写入期间停止、真实进程终止恢复 |
-| `test_grpc_integration.py` | 14 | 实际 localhost gRPC、四工位并行、断电后导入、请求去重、deadline、客户端断线、历史、认证、配方快照、CLI 文件往返及完整 demo |
-| `test_parsers.py` | 20 | 附件日志摘录、跨包编码/换行、AMT 位置、RMT 原值、UTF-16 HTML、不完整报告、BMC 缺失值、计数与返回上限 |
-| `test_artifacts.py` | 21 | 上传幂等/冲突、续传、SHA-256、跨轮拒绝、重命名后中断恢复、取消一致性、标准类型别名、内容识别、逐字节下载 |
-
-测试使用临时数据目录、模拟设备和本地子进程桩。gRPC 集成测试使用真正的 TCP loopback 连接,不是直接调用服务方法代替网络通信。
-
-## 2. 与现场流程直接有关的验证
-
-### 四工位与前端生命周期
-
-- 四个工位同时创建独立运行;一个在预热期间停止,另外三个继续完成。
-- 同一工位连续两轮都分别发送 CPU0 和 CPU1 的参数;上轮阶段标记不污染下轮。
-- CPU1 的 UIP 标记在 CPU0 参数回显期间提前出现,仍能正确触发后续 CPU1 配置。
-- 客户端断开后已接受运行继续执行。
-- 原生 CLI 的 `demo` 在独立子进程中连接服务,四轮执行、关电、导入结果后全部 PASS。
-
-### 控制与停止
-
-- 旧 run 的停止请求不能停止同工位下一轮。
-- 相同 command_id 和参数并发提交只建立一次运行;相同 ID 的不同参数被拒绝。
-- 在数据库已经提交、运行任务尚未启动的确定时点令客户端 deadline 到期:持久请求仍完成启动;使用相同命令 ID 重试只有一个运行。
-- 首个手工阶段确认的事件写入被暂停时,第二个相反确认不能抢占/覆盖。
-- 初始配方温度设置尚未完成时,运行中的改温度请求被拒绝;初始化完成后可修改,并保持原配方快照不变。
-- 运行中慢目标写入被停止请求取消;总电源 off 操作仍被实际调用。
-- 总电源反馈 unknown 时,工位保留占用,不允许开始新轮次。
-- 人工断电确认分别在 SOL 尾部收集期间、最终待核对状态之后到达,都能正确处理。
-
-### 数据与恢复
-
-- 正常结束先得到 completed / off / pending_import / pending;导入本轮完整结果后变为 PASS。
-- 终态首次持久发布已经包含本轮完整的资料状态与结论,不出现已完成但资料仍是 not_started 的短暂记录。
-- 错误通道仅影响有明确位置的 CPU/通道;另一个 CPU 的同名插槽不被误判。
-- 结果 JSON 的 run_id 与目标不一致时被拒绝。
-- 上传重复块、错误 SHA、断点恢复、重复 Finish 均按契约处理,重复 Finish 不重复插入事件。
-- 真实杀死测试后端子进程,再重新打开持久库:原活动运行进入 recovery_required,设备开机、供电或串口写入均未重放。
-- 正常完成后的运行、SN 查询、温度、SOL、文件、命令身份在后端重启后仍可读取。
-
-## 3. 上传原始文件解析验证
-
-以下是本次对实际输入文件的解析结果,不是模拟器生成的硬件测试结论。各文件来自不同采集内容,统计不能相互叠加。
-
-| 文件 | 识别结果 |
-| --- | --- |
-| `MemTest86-20261008-140219_489355.log` | 501 条明确 MEM ERROR;CPU0/通道5明确归属500条,1条位置不明 |
-| `MemTest86-Report-20261008-140403_588551.html` | UTF-16;INCOMPLETE PASS;17/56 项完成;报告 ECC corrected 为1208;尾部只有10条可明确归属的通道明细 |
-| `minicom_20261008_04.log` | 24条内存身份、192行 RMT 数据;保留负值与星号缺失值,没有配置阈值时不推导 RMT PASS |
-| `minicom_20261009_17.log` | 5458条 AMT 明确失败记录;CPU0/通道2;上下文续行不重复计数 |
-| `bmc_dimmInfo.json` | 24个位置、360项历史测量;null 保持不可用 |
-| `01_dimm_pmic_inventory.csv` | 24条导入清单,保留原始字段和来源 |
-
-HTML 报告的1208个总错误不会全部分摊给仅在尾部明细出现的通道。`INCOMPLETE PASS` 不会被解释为已完成通过,CSS 中的 PASS 字样也不作为测试结论。
-
-## 4. 原生 SOL 与依赖
-
-原生 `sol_helper.cpp` 使用上传工程中的匹配 FreeIPMI 头文件和库实际编译,编译成功,并执行了 `--help`。构建脚本支持系统库与显式 include/library 目录。
-
-该验证不包含真实 SOL 建链、BMC 认证或实际 BIOS 输入确认。交付源码,不附带链接到临时验证目录的编译二进制;现场应在目标 Linux 环境按部署文档构建。
-
-验证环境:
-
-| 项目 | 版本 |
-| --- | --- |
-| Python | 3.12.14 |
-| grpcio / grpcio-tools | 1.84.0 |
-| protobuf | 7.36.2 |
-| pytest | 9.1.1 |
-| pytest-asyncio | 1.4.0 |
-| Protobuf 服务方法数 | 27,全部 unary |
-
-## 5. 前端保持原状的检查
-
-把本地解压的输入文件与原上传 ZIP 的对应条目逐一计算 SHA-256 比较:
-
-```text
-extracted_files_compared: 410
-frontend_tree_files_compared: 323
-changed_files: []
-```
-
-比较范围是实际解压的普通文件,解压时排除了版本控制元数据及 Python 缓存。`XJKJ-STL` 前端树中的323个已解压文件均与 ZIP 内容一致。
-
-## 6. 没有经过本次验证的项目
-
-- 现场 BMC 网络、认证和真实电源动作;
-- 温控板/总电源控制器的物理协议与回读;
-- 具体 BIOS 版本中 RMT/AMT 开关和完整自动流程;
-- 具体 UEFI 程序的配置参数、正常退出和文件落盘行为;
-- 原 Qt 界面的 gRPC 改造,HTML 界面和 gRPC-Web 网关部署;
-- 目标低频 Linux 主机的性能、长期运行与存储容量;
-- PXE 启动服务与实际网络结果回传。
-
-这些边界已在配置和说明中明确,不以模拟测试通过代替实机验收。

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


+ 0 - 24
docs/firmware-commands.csv

@@ -1,24 +0,0 @@
-command,console,stage,cpu_context,firmware_version,read_write,observed_literal_value,unit,legal_range,current_or_default,advances_flow,raw_error,recovery_method,verification_status,evidence_location,notes
-errhandle disable,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,disable,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-vol mem vdd 1070,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,1070,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-vol mem vddq 1070,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,1070,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm tCL 44,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,44,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm tRCD 43,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,43,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm tRP 43,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,43,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm tRAS 86,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,86,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm tWR 80,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,80,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm tRFC 425,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,425,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm tRTP 20,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,20,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm trrd_l 13,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,13,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm twTR_S 7,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,7,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm tWTR_L 27,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,27,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm tCCD_L 13,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,13,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm trefi 23046,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,23046,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-actm tRFCsb 123,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,123,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-ap disable,host BIOS via SOL,UIP stage1,0/1 in legacy profile,unknown,write_candidate,disable,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/hardware.example.json: recipes[].stage1_commands,Literal migrated from legacy Qt configuration; not validated on current firmware; do not infer legal range/default/restore value
-\r,host BIOS/UEFI via SOL,UIP stage1,stage dependent,unknown,control_candidate,unknown,unknown,unknown,unknown,yes_in_legacy_flow,unknown,unknown,untested,v0.1.1:config/profiles/cxmt-live-assisted.json: append_enter,Empty input may advance training; not a passive probe
-exit,host BIOS/UEFI via SOL,AMT,stage dependent,unknown,control_candidate,unknown,unknown,unknown,unknown,unknown,unknown,unknown,untested,v0.1.1:config/profiles/cxmt-live-gnr.json: amt_wait_cpu0/amt_wait_cpu1,Legacy auto-exit is not evidence that AMT ran or passed
-fs0:,host BIOS/UEFI via SOL,UEFI Shell,stage dependent,unknown,control_candidate,unknown,unknown,unknown,unknown,changes_shell_context,unknown,unknown,untested,v0.1.1:config/profiles/cxmt-live-gnr.json: uefi_shell_wait,Filesystem number must be confirmed on current machine; replaces unsupported legacy table spelling fso 0:
-cd EFI,host BIOS/UEFI via SOL,UEFI Shell,stage dependent,unknown,control_candidate,unknown,unknown,unknown,unknown,changes_shell_context,unknown,unknown,untested,v0.1.1:config/profiles/cxmt-live-gnr.json: uefi_shell_wait,Directory must be confirmed; unsupported old table spelling cd EFIEFI removed
-MemTest86SiteX64.efi,host BIOS/UEFI via SOL,UEFI Shell,stage dependent,unknown,control_candidate,unknown,unknown,unknown,unknown,starts_program_if_present,unknown,unknown,untested,v0.1.1:config/profiles/cxmt-live-gnr.json: uefi_shell_wait,"Path, config, program revision and completion markers require current media evidence"
-memtest.efi,host BIOS/UEFI via SOL,UEFI Shell,stage dependent,unknown,control_candidate,unknown,unknown,unknown,unknown,starts_program_if_present,unknown,unknown,untested,config/hardware.example.json: recipes[].mt_command,Example launch command only; actual USB program and configuration must be confirmed

+ 0 - 10
docs/hardware-evidence/ipmi_channel_authcap.txt

@@ -1,10 +0,0 @@
-Channel number             : 1
-IPMI v1.5  auth types      : 
-KG status                  : default (all zeroes)
-Per message authentication : enabled
-User level authentication  : enabled
-Non-null user names exist  : yes
-Null user names exist      : no
-Anonymous login enabled    : no
-Channel supports IPMI v1.5 : no
-Channel supports IPMI v2.0 : yes

+ 0 - 23
docs/hardware-evidence/ipmi_lan_print.txt

@@ -1,23 +0,0 @@
-Set in Progress         : Set Complete
-Auth Type Support       : 
-Auth Type Enable        : Callback : 
-                        : User     : 
-                        : Operator : 
-                        : Admin    : 
-                        : OEM      : 
-IP Address Source       : Static Address
-IP Address              : 192.168.0.100
-Subnet Mask             : 255.255.255.0
-MAC Address             : 30:43:d7:3b:ae:7b
-Default Gateway IP      : 192.168.0.1
-Default Gateway MAC     : 00:00:00:00:00:00
-802.1q VLAN ID          : Disabled
-RMCP+ Cipher Suites     : 17
-Cipher Suite Priv Max   : aaaaaaaaaaaaaaa
-                        :     X=Cipher Suite Unused
-                        :     c=CALLBACK
-                        :     u=USER
-                        :     o=OPERATOR
-                        :     a=ADMIN
-                        :     O=OEM
-Bad Password Threshold  : Not Available

+ 0 - 0
docs/hardware-evidence/serial_capture_1125200.bin


+ 0 - 1
docs/hardware-evidence/serial_capture_1125200.hex

@@ -1 +0,0 @@
-

+ 0 - 1
docs/hardware-evidence/sol_capture.bin

@@ -1 +0,0 @@
-Info: SOL payload already active on another session

+ 0 - 1
docs/hardware-evidence/sol_capture.hex

@@ -1 +0,0 @@
-49 6e 66 6f 3a 20 53 4f 4c 20 70 61 79 6c 6f 61 64 20 61 6c 72 65 61 64 79 20 61 63 74 69 76 65 20 6f 6e 20 61 6e 6f 74 68 65 72 20 73 65 73 73 69 6f 6e 0d 0a

+ 0 - 16
docs/hardware-evidence/test_suite_83_passed.log

@@ -1,16 +0,0 @@
-============================= test session starts ==============================
-platform linux -- Python 3.13.5, pytest-8.4.1, pluggy-1.6.0
-rootdir: /workspace/XJKJ-STL-dev
-configfile: pyproject.toml
-plugins: asyncio-1.4.0
-asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=None, asyncio_default_test_loop_scope=function
-collected 83 items
-
-tests/test_artifacts.py .....................                            [ 25%]
-tests/test_devices.py ...........                                        [ 38%]
-tests/test_engine.py ............                                        [ 53%]
-tests/test_grpc_integration.py ..............                            [ 69%]
-tests/test_parsers.py ......................                             [ 96%]
-tests/test_web_gateway.py ...                                            [100%]
-
-============================= 83 passed in 34.41s ==============================

+ 25 - 0
examples/qt-clean/config.json

@@ -0,0 +1,25 @@
+{
+  "_comment": "内存参数配置:详情页「内存参数设置」页签从这里加载默认值,键名与界面控件一一对应。errhandle / ap 为开关(true=enable,false=disable),其余为数值(mem vdd / mem vddq 单位 mV,时序参数单位 tCK)。",
+  "memoryParams": {
+    "mem vdd": 1070,
+    "mem vddq": 1070,
+    "tCL": 44,
+    "tRCD": 43,
+    "tRP": 43,
+    "tRAS": 86,
+    "tRFC": 425,
+    "tRTP": 20,
+    "trrd_l": 13,
+    "tWTR_S": 7,
+    "tWTR_L": 27,
+    "tWR": 80,
+    "tCCD_L": 13,
+    "trefi": 23046,
+    "tRFCsb": 123,
+    "errhandle": false,
+    "ap": false
+  },
+  "backend": {
+    "url": "ws://192.168.2.79:8080/ws?view=qt"
+  }
+}

+ 9 - 0
examples/qt-websocket/CMakeLists.txt

@@ -0,0 +1,9 @@
+cmake_minimum_required(VERSION 3.16)
+project(stl_ws_sample LANGUAGES CXX)
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core Network WebSockets)
+find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core Network WebSockets)
+add_executable(stl_ws_sample main.cpp)
+target_link_libraries(stl_ws_sample PRIVATE
+    Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Network Qt${QT_VERSION_MAJOR}::WebSockets)

+ 105 - 0
examples/qt-websocket/main.cpp

@@ -0,0 +1,105 @@
+// Read-only Qt 5.15 / Qt 6 example: two concurrent calls on one WebSocket.
+// No protobuf, gRPC client, or hardware commands are required.
+#include <QCoreApplication>
+#include <QDebug>
+#include <QHash>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QNetworkRequest>
+#include <QStringList>
+#include <QTimer>
+#include <QUrl>
+#include <QUuid>
+#include <QWebSocket>
+
+int main(int argc, char **argv)
+{
+    QCoreApplication app(argc, argv);
+    const auto args = app.arguments();
+    const QUrl url(args.value(1, QStringLiteral("ws://127.0.0.1:8080/ws")));
+    const QString station = args.value(2, QStringLiteral("S1"));
+    QWebSocket socket;
+    QHash<QString, QString> pending; // request id -> method, never assume reply order
+    bool done = false;
+    int failures = 0;
+
+    auto finish = [&](int code) {
+        if (done) return;
+        done = true;
+        socket.close();
+        app.exit(code);
+    };
+    auto call = [&](const QString &method, const QJsonObject &params) {
+        const QString id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+        pending.insert(id, method);
+        const QJsonObject frame{{"v", 1}, {"id", id}, {"method", method}, {"params", params}};
+        socket.sendTextMessage(QString::fromUtf8(QJsonDocument(frame).toJson(QJsonDocument::Compact)));
+    };
+
+    QObject::connect(&socket, &QWebSocket::connected, &app, [&] {
+        call(QStringLiteral("GetSystemInfo"), {});
+        call(QStringLiteral("GetStationControl"), {{"station_id", station}});
+    });
+    QObject::connect(&socket, &QWebSocket::textMessageReceived, &app, [&](const QString &text) {
+        QJsonParseError parse;
+        const auto doc = QJsonDocument::fromJson(text.toUtf8(), &parse);
+        if (parse.error != QJsonParseError::NoError || !doc.isObject()) {
+            qWarning() << "Invalid JSON reply";
+            finish(1);
+            return;
+        }
+        const auto frame = doc.object();
+        if (frame.value("v").toInt() != 1 || !frame.value("id").isString()
+            || !frame.value("ok").isBool()) {
+            qWarning() << "Invalid JSON v1 response envelope";
+            finish(1);
+            return;
+        }
+        const QString id = frame.value("id").toString();
+        if (!pending.contains(id)) return;
+        const QString method = pending.take(id);
+        if (!frame.value("ok").toBool()) {
+            qWarning().noquote() << method << QJsonDocument(frame.value("error").toObject()).toJson(QJsonDocument::Compact);
+            ++failures;
+        } else {
+            const auto result = frame.value("result").toObject();
+            if (method == QStringLiteral("GetSystemInfo")) {
+                qInfo() << "version" << result.value("version").toString()
+                        << "commit" << result.value("commit").toString();
+            } else {
+                const auto firmware = result.value("firmware").toObject();
+                const auto mainStage = firmware.value("stage_progress").toObject().value("main").toObject();
+                qInfo() << "station" << station << "main stage" << mainStage.value("id").toString()
+                        << "DIMM slots" << result.value("dimms").toArray().size();
+                qInfo().noquote() << "prompt:" << QJsonDocument(firmware.value("console_prompt").toObject()).toJson(QJsonDocument::Compact);
+            }
+        }
+        if (pending.isEmpty()) finish(failures ? 1 : 0);
+    });
+    QObject::connect(&socket, &QWebSocket::disconnected, &app, [&] {
+        if (!done) {
+            qWarning() << "Disconnected; requests are not replayed" << pending.keys();
+            finish(1);
+        }
+    });
+    auto socketError = [&](QAbstractSocket::SocketError) {
+        qWarning().noquote() << socket.errorString();
+        finish(1);
+    };
+#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
+    QObject::connect(&socket, &QWebSocket::errorOccurred, &app, socketError);
+#else
+    QObject::connect(&socket, static_cast<void (QWebSocket::*)(QAbstractSocket::SocketError)>(&QWebSocket::error), &app, socketError);
+#endif
+    QTimer::singleShot(15000, &app, [&] {
+        if (!done) { qWarning() << "Reply timeout"; finish(1); }
+    });
+    QNetworkRequest request(url);
+    const auto token = qgetenv("STL_API_TOKEN");
+    if (!token.isEmpty()) request.setRawHeader("Authorization", "Bearer " + token);
+    // Open after exec() starts: an immediate connection error must be able to
+    // exit the event loop, rather than calling exit() before it is running.
+    QTimer::singleShot(0, &app, [&socket, request] { socket.open(request); });
+    return app.exec();
+}

+ 168 - 0
native/stl_ssh_console_bridge.py

@@ -0,0 +1,168 @@
+#!/usr/bin/env python3
+"""OpenBMC host console over SSH: raw stdin/stdout, JSON status on stderr.
+
+This connects to the configured host-console SSH port, not the BMC Linux shell.
+It never sends a CR, changes BIOS settings, reconnects, or replays input by itself.
+"""
+import contextlib
+import json
+import os
+from pathlib import Path
+import pty
+import select
+import signal
+import subprocess
+import sys
+import time
+import tty
+
+
+def status(event, code=0):
+    print(json.dumps({"event": event, "code": code}), file=sys.stderr, flush=True)
+
+
+class SshStatus:
+    """Interpret only SSH's independent diagnostic stream, never console bytes."""
+    def __init__(self):
+        self.buffer = b""
+        self.authenticated = False
+        self.shell_accepted = False
+        self.error = 0
+
+    @property
+    def ready(self):
+        return self.authenticated and self.shell_accepted and not self.error
+
+    def feed(self, data):
+        self.buffer = (self.buffer + data)[-65536:]
+        text = self.buffer.lower()
+        self.authenticated = self.authenticated or b"authenticated to " in text
+        self.shell_accepted = self.shell_accepted or b"shell request accepted on channel " in text
+        if b"remote host identification has changed" in text or b"host key verification failed" in text:
+            self.error = 1011
+        elif b"permission denied" in text or b"authentication failed" in text:
+            self.error = 1010
+        elif b"shell request failed" in text or b"pty allocation request failed" in text:
+            self.error = 1012
+
+
+def main():
+    if sys.argv[1:] == ["--help"]:
+        print("STL_SOL_HOST, STL_SOL_USER, STL_SOL_PASSWORD; optional STL_SSH_PORT=2200, "
+              "STL_SSH_KNOWN_HOSTS=data/ssh_known_hosts", file=sys.stderr)
+        return 0
+    host, user, secret = (os.environ.get(k) for k in ("STL_SOL_HOST", "STL_SOL_USER", "STL_SOL_PASSWORD"))
+    try:
+        port = int(os.environ.get("STL_SSH_PORT", "2200"))
+        if not all((host, user, secret)) or host.startswith("-") or not 1 <= port <= 65535:
+            raise ValueError("Invalid SSH console settings")
+        known_hosts = Path(os.environ.get("STL_SSH_KNOWN_HOSTS", "data/ssh_known_hosts")).resolve()
+        known_hosts.parent.mkdir(parents=True, exist_ok=True)
+    except (ValueError, OSError):
+        status("error", 1002)
+        return 2
+
+    stopped = False
+    def stop(signum, frame):
+        nonlocal stopped
+        stopped = True
+    signal.signal(signal.SIGTERM, stop)
+    signal.signal(signal.SIGINT, stop)
+
+    env = os.environ.copy()
+    env["SSHPASS"] = secret
+    # The child only needs sshpass's environment name; never place secrets in argv.
+    env.pop("STL_SOL_PASSWORD", None)
+    env["LC_ALL"] = "C"
+    command = ["sshpass", "-e", "ssh", "-tt", "-vv", "-p", str(port), "-l", user,
+               "-o", "StrictHostKeyChecking=accept-new",
+               "-o", "UserKnownHostsFile=" + str(known_hosts),
+               "-o", "NumberOfPasswordPrompts=1",
+               "-o", "PreferredAuthentications=password,keyboard-interactive",
+               "-o", "PubkeyAuthentication=no", "-o", "ConnectTimeout=8",
+               "-o", "ConnectionAttempts=1", "-o", "ServerAliveInterval=10",
+               "-o", "ServerAliveCountMax=2", "-o", "EscapeChar=none", host]
+
+    master, slave = pty.openpty()
+    tty.setraw(slave)
+    proc = None
+    try:
+        proc = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=subprocess.PIPE,
+                                env=env, close_fds=True, start_new_session=True)
+        os.close(slave)
+        slave = None
+        status("connecting")
+        parsed = SshStatus()
+        ready = False
+        master_open = True
+        stderr_open = True
+        deadline = time.monotonic() + 20
+        while not stopped:
+            if not ready and time.monotonic() >= deadline:
+                status("error", 1007)
+                return 2
+            sources = ([master] if master_open else []) + ([proc.stderr.fileno()] if stderr_open else [])
+            if ready:
+                sources.append(sys.stdin.fileno())
+            readable, _, _ = select.select(sources, [], [], 0.2)
+            if stderr_open and proc.stderr.fileno() in readable:
+                data = os.read(proc.stderr.fileno(), 8192)
+                if not data:
+                    stderr_open = False
+                else:
+                    parsed.feed(data)
+                    if parsed.error:
+                        status("error", parsed.error)
+                        return 2
+                    if not ready and parsed.ready:
+                        ready = True
+                        status("ready")
+            if master_open and master in readable:
+                try:
+                    data = os.read(master, 8192)
+                except OSError:
+                    data = b""
+                if not data:
+                    master_open = False
+                else:
+                    # Raw remote console output is evidence even if it precedes
+                    # the local SSH acknowledgement by a few scheduling ticks.
+                    sys.stdout.buffer.write(data)
+                    sys.stdout.buffer.flush()
+            if ready and sys.stdin.fileno() in readable:
+                data = os.read(sys.stdin.fileno(), 65536)
+                if not data:
+                    break
+                while data:
+                    size = os.write(master, data)
+                    data = data[size:]
+            if proc.poll() is not None and not master_open and not stderr_open:
+                status("error", 1008 if ready else parsed.error or 1010)
+                return 2
+        status("closed")
+        return 0
+    except OSError:
+        status("error", 1005)
+        return 2
+    finally:
+        if slave is not None:
+            os.close(slave)
+        if proc:
+            # sshpass and SSH share this private process group. Releasing the
+            # network connection does not send exit/Ctrl-C to the BIOS program.
+            with contextlib.suppress(ProcessLookupError):
+                os.killpg(proc.pid, signal.SIGTERM)
+            try:
+                proc.wait(timeout=1)
+            except subprocess.TimeoutExpired:
+                with contextlib.suppress(ProcessLookupError):
+                    os.killpg(proc.pid, signal.SIGKILL)
+                proc.wait()
+            if proc.stderr:
+                proc.stderr.close()
+        with contextlib.suppress(OSError):
+            os.close(master)
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 138 - 4
proto/stl/v1/bench.proto

@@ -4,13 +4,22 @@ package stl.v1;
 import "google/protobuf/empty.proto";
 import "google/protobuf/struct.proto";
 
-// Native gRPC for Qt 5's C++ gRPC client. All operations are unary so the same
-// contract also works through a gRPC-Web proxy. UI polls; hardware acquisition
-// and workflows never depend on the presence of a connected UI.
+// 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);
@@ -22,6 +31,12 @@ service BenchService {
   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);
@@ -41,6 +56,59 @@ 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;
@@ -77,6 +145,12 @@ message Recipe {
   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 {
@@ -125,7 +199,8 @@ message ConfirmPowerRequest {
 message StationPowerRequest {
   string command_id = 1;
   string station_id = 2;
-  // supply_on, supply_off, host_on, host_off. Idle stations only.
+  // 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;
 }
@@ -142,6 +217,61 @@ message WriteSolRequest {
   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;
@@ -206,6 +336,10 @@ message StationSnapshot {
   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 {

+ 4 - 4
pyproject.toml

@@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta"
 
 [project]
 name = "xjkj-stl-backend"
-version = "0.1.2"
-description = "Four-station memory thermal test backend with native gRPC"
+version = "0.8.1.1.dev0"
+description = "Four-station memory thermal test backend with WebSocket and gRPC"
 readme = "README.md"
 requires-python = ">=3.11"
-dependencies = ["grpcio==1.84.0", "protobuf==7.36.2"]
+dependencies = ["grpcio==1.84.0", "protobuf==7.36.2", "aiohttp==3.14.5"]
 
 [project.optional-dependencies]
 dev = ["grpcio-tools==1.84.0", "pytest>=8,<10", "pytest-asyncio>=1,<2"]
@@ -21,7 +21,7 @@ stl-client = "stl_backend.cli:main"
 where = ["src"]
 
 [tool.setuptools.package-data]
-stl_backend = ["web/*.html", "web/*.css", "web/*.js"]
+stl_backend = ["web/*.html", "web/*.css", "web/*.js", "domain/*.json"]
 
 [tool.pytest.ini_options]
 asyncio_mode = "auto"

+ 60 - 0
qt-client/DDR5_SLT_Monitor.pro

@@ -0,0 +1,60 @@
+#-------------------------------------------------------------------------------
+# DDR5 RDIMM SLT 上位机监控平台 —— 多工位测试监控
+# Qt 5 / C++11 / Linux + Windows(MinGW)
+#
+# 编译:
+#   qmake DDR5_SLT_Monitor.pro
+#   make -j4
+#-------------------------------------------------------------------------------
+
+QT       += core gui serialport websockets
+greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+
+# QCustomPlot 2.1.1(GPLv3,src/3rdparty/qcustomplot/GPL.txt):温控曲线用
+QT       += printsupport
+
+TARGET    = DDR5_SLT_Monitor
+TEMPLATE  = app
+CONFIG   += c++11
+
+# 界面代码全部由 src/mainwindow.ui 生成
+INCLUDEPATH += $$PWD/src
+INCLUDEPATH += $$PWD/src/3rdparty/qcustomplot
+DEPENDPATH  += $$PWD/src
+
+SOURCES += \
+    src/main.cpp \
+    src/mainwindow.cpp \
+    src/overviewview.cpp \
+    src/detailview.cpp \
+    src/powerbutton.cpp \
+    src/stationdata.cpp \
+    src/localplans.cpp \
+    src/backendlink.cpp \
+    src/comworker.cpp \
+    src/sltproto.cpp \
+    src/comanager.cpp \
+    src/3rdparty/qcustomplot/qcustomplot.cpp
+
+HEADERS += \
+    src/appconfig.h \
+    src/mainwindow.h \
+    src/overviewview.h \
+    src/detailview.h \
+    src/powerbutton.h \
+    src/stationdata.h \
+    src/localplans.h \
+    src/backendlink.h \
+    src/uiformat.h \
+    src/comworker.h \
+    src/sltproto.h \
+    src/comanager.h \
+    src/3rdparty/qcustomplot/qcustomplot.h
+
+FORMS += \
+    src/mainwindow.ui
+
+RESOURCES += \
+    src/resources.qrc
+
+# 源码/样式统一按 UTF-8 处理(Linux g++ 默认即 UTF-8)

+ 129 - 0
qt-client/QT_CLEAN_CLIENT_ZH.md

@@ -0,0 +1,129 @@
+# Qt 纯净版临时客户端 0.8.1.1.dev0
+
+本目录基于上传的 XJKJ-STL Qt 工程制作;原始工程另存,界面布局沿用原来的 `.ui`。它只连接独立接口 `/ws?view=qt-clean`。
+
+## 用户操作
+
+1. **参数确定**:保存到本机 `qt-plans.json` 的当前工位,不调用后端保存计划/保存固件配置接口,也不重启设备。
+2. **开始测试**:读取本机该工位计划,发送 `StartTest`。后端按主机当前电源状态开机或复位,等待新 BIOS 及实际可交互输入窗口;冷启动的固件预初始化重启由后端正确等待,Qt 不额外发主机重启。
+3. **阶段推进**:客户端根据后端明确给出的可输入阶段和 `input.id`,发送一次对应的 `StageAction`;窗口代码不解析串口、不识别 BIOS 提示词、不转换固件参数名。
+4. **状态与日志**:后端自动推送状态与 BIOS UART 原始字节;界面只打印 BIOS UART 原文,不再显示事件摘要或后端时间戳。DDR Training 明确成功后,对应 CPU 的 12 路先显示健康绿灯;遇到对应训练/内存错误则显示红灯。
+
+默认配置采用:UIP 不修改内存参数并继续,AMT 输入退出,UEFI 停留等待。到达 UEFI 表示启动和阶段推进完成,不代表内存测试 PASS。点击参数页“确定”后,该工位计划才启用参数应用。这样初始配置中的电压、时序样例不会在第一次连接时自动应用。
+
+## 本地计划
+
+`config.json` 提供默认参数和默认行为。第一次保存参数时创建 `qt-plans.json`,各工位分别保存,原 `config.json` 不改。例:
+
+```json
+{
+  "version": 1,
+  "stations": {
+    "S1": {
+      "memory_params": {"errhandle": false},
+      "uip": {"action": "continue_uip", "apply_memory_params": true},
+      "amt": {"action": "skip_amt"},
+      "uefi": {"action": "hold"}
+    }
+  }
+}
+```
+
+内存参数使用原 UI 的键名,如 `mem vdd`、`mem vddq`、`tCL`、`tRCD`、`errhandle`。映射与校验在后端。UIP1 会向对应 CPU 的有效输入窗口提交;UIP2 是独立的后续阶段,不重复应用 UIP1 的电压/时序参数。
+
+如需选择 AMT 或 MT,把对应行为改为 `start_amt` 或 `start_mt`,详细参数保存在该段的 `settings` 中,由客户端原样提交给后端:
+
+```json
+{
+  "amt": {"action": "start_amt", "exit_after": true, "settings": {}},
+  "uefi": {
+    "action": "start_mt",
+    "settings": {"efi_path": "FS0:/EFI/memtest.efi", "config_path": "", "arguments": ""}
+  }
+}
+```
+
+AMT 参数键、MT 路径/参数的实际要求以随包后端接口文档为准。`hold` 会结束本轮自动提交,保留当前设备状态,允许检查后再次开始。计划在点击开始时读取;执行期间保存的新参数用于下一轮,不改变当前轮已经选定的动作。
+
+## 分层
+
+| 文件 | 职责 |
+| --- | --- |
+| `localplans.h/.cpp` | Qt 本地计划的读取、按工位保存、原子写入 |
+| `backendlink.h/.cpp` | WebSocket 封装、清洁状态/日志接收、当前轮阶段动作提交与命令查询 |
+| `stationdata.h/.cpp` | 界面数据模型;温度和测试结果独立 |
+| `mainwindow.cpp` | 开始按钮调用一次 `startTest()`;参数确定调用一次本地保存;接收模型更新 |
+| `overviewview.cpp`、`detailview.cpp` | 使用模型刷新原有控件 |
+| `tests/qt_clean_probe.cpp` | 实际 MainWindow 与 QWebSocket 联调程序,直接点击原界面的按钮 |
+
+没有使用后端计划 CRUD。UI 不再发送 `EnqueueCommand(SaveFirmwareSettings)`,也不再每秒对四工位轮询日志。
+
+## 已处理的原版问题
+
+- 开始按钮原来只保存固件参数;现在是独立的主机启动/复位流程。
+- 原版即使后端断开也开始本地计时;现在只有后端确认的新 BIOS 启动时间才能开始计时。
+- 原版开始过一次便永久禁止再次开始;现在依据当前操作状态恢复按钮。
+- 参数页修改原来不落盘,下一次开始重新读旧值;现在按工位保存到 Qt 本地计划。
+- 有效温度原来直接把通道变成 PASS;现在温度只更新温度,PASS/FAIL 必须来自明确测试结果。
+- 温度无效不再覆盖已经确认的 FAIL。
+- 同一个提示窗口只提交一次,两个 CPU 的不同窗口分别处理。
+- 连接中断后查询原命令,绝不因为重连自动重放主机重启;后端实例变化时停止旧的客户端自动执行。
+- 连上后若连续 20 秒收不到后端任何消息,或新连接 10 秒仍卡在连接中,客户端会主动重新建立链路;每 3 秒尝试一次,不要求 UI 增加额外逻辑。
+- 开始响应先到而旧快照尚未更新时继续等待;当前轮出现明确失败或意外再次启动时立即停止,不会一直显示执行中。
+- 重连后按原始 BIOS UART 会话和字节游标补齐缺失文本、丢弃重放的重复字节;不显示事件日志。
+
+## 编译
+
+需要 Qt 5 开发环境:Core、Gui、Widgets、WebSockets、SerialPort、PrintSupport,另需 qmake、g++、make。
+
+```bash
+mkdir -p build
+cd build
+env -u LD_LIBRARY_PATH qmake ../DDR5_SLT_Monitor.pro
+make -j4
+```
+
+客户端可执行文件名仍为 `DDR5_SLT_Monitor`,放在本临时目录下,与原程序隔离。
+
+## 配置覆盖
+
+| 环境变量 | 用途 |
+| --- | --- |
+| `STL_QT_BACKEND_URL` | 覆盖 WebSocket 地址;联调使用 `ws://127.0.0.1:8080/ws?view=qt-clean` |
+| `STL_QT_CONFIG_DIR` | 指定本次运行的配置目录,包含 `config.json` / `port.json` |
+| `STL_QT_PLANS_FILE` | 指定 Qt 本地计划文件,便于每个测试独立保存 |
+| `STL_QT_DISABLE_SERIAL=1` | 临时联调不打开温控串口,避免与后端或现场工具抢占 |
+| `QT_QPA_PLATFORM=offscreen` | 无桌面环境运行真实 Qt 控件并导出截图 |
+
+## 联调程序
+
+```bash
+mkdir -p build-probe
+cd build-probe
+env -u LD_LIBRARY_PATH qmake ../tests/qt_clean_probe.pro
+make -j4
+```
+
+模式明确区分:
+
+| 模式 | 行为 |
+| --- | --- |
+| `--mode fixture` | 在同一进程建立本机 WebSocket 协议夹具,运行真实窗口及按钮,验证双 CPU 阶段、断线重连、保存参数和去重;不连接实机 |
+| `--mode fixture-amt` | 夹具执行双 CPU AMT 启动、等待真实结果标志、返回菜单后退出;验证每颗 CPU 只启动一次 |
+| `--mode fixture-fail` | 负向夹具:在 UEFI 注入固件执行失败,预期返回非零并报告 `pass: false` |
+| `--mode fixture-unexpected-boot` | 负向夹具:阶段命令仍在执行时注入新的 BIOS 启动与本轮失败,验证及时退出,不能等到超时才报失败 |
+| `--mode fixture-silent` | 只读夹具:服务器连接保持建立但不再发送状态,检查 20 秒静默检测会主动重连;不触发真实主机动作 |
+| `--mode read-only` | 连接指定真实后端,接收状态/日志、检查界面模型,导出截图;不发主机控制命令 |
+| `--mode start` | 点击实际工位开始按钮,启动/复位真实主机,按指定本地计划推进,等待新 BIOS 和目标阶段 |
+
+```bash
+QT_QPA_PLATFORM=offscreen ./QtCleanProbe --mode fixture --report /tmp/qt-fixture.json --screenshot /tmp/qt-fixture.png --timeout 45
+
+QT_QPA_PLATFORM=offscreen ./QtCleanProbe --mode read-only --url 'ws://127.0.0.1:8080/ws?view=qt-clean' --report /tmp/qt-readonly.json --screenshot /tmp/qt-readonly.png
+
+STL_QT_PLANS_FILE=/path/to/test-plan.json QT_QPA_PLATFORM=offscreen ./QtCleanProbe --mode start --url 'ws://127.0.0.1:8080/ws?view=qt-clean' --station 1 --expect-phase uefi --timeout 900 --report /tmp/qt-start.json --screenshot /tmp/qt-start.png
+```
+
+AMT 的 `exit_after` 由 Qt 计划执行器处理;只有后端当前 CPU 的 `input.test_complete=true`,才自动退出菜单,提交命令和测试完成严格分开。
+
+程序用进程退出码与 JSON 报告标明验证结果;真实启动模式只有确认新 BIOS、到达目标阶段、客户端本轮动作结束、未发生命令错误,才返回 0。到达 UEFI 的验证名称是启动/阶段链路验证,报告不会把它标为内存测试 PASS。最终实机结果应查看随交付提供的实际报告。

+ 38 - 0
qt-client/config.json

@@ -0,0 +1,38 @@
+{
+  "_comment": "内存参数配置:详情页「内存参数设置」页签从这里加载默认值,键名与界面控件一一对应。errhandle / ap 为开关(true=enable,false=disable),其余为数值(mem vdd / mem vddq 单位 mV,时序参数单位 tCK)。",
+  "memoryParams": {
+    "mem vdd": 1070,
+    "mem vddq": 1070,
+    "tCL": 44,
+    "tRCD": 43,
+    "tRP": 43,
+    "tRAS": 86,
+    "tRFC": 425,
+    "tRTP": 20,
+    "trrd_l": 13,
+    "tWTR_S": 7,
+    "tWTR_L": 27,
+    "tWR": 80,
+    "tCCD_L": 13,
+    "trefi": 23046,
+    "tRFCsb": 123,
+    "errhandle": false,
+    "ap": false
+  },
+  "backend": {
+    "url": "ws://192.168.2.79:8080/ws?view=qt-clean"
+  },
+  "qtPlan": {
+    "uip": {
+      "action": "continue_uip",
+      "apply_memory_params": false
+    },
+    "amt": {
+      "action": "skip_amt"
+    },
+    "uefi": {
+      "action": "hold"
+    }
+  },
+  "_qt_note": "Qt 纯净临时版:计划保存在本机 qt-plans.json。默认跳过 UIP 参数修改、退出 AMT、停在 UEFI;点击参数确定后才为该工位开启参数应用。开始测试重启/启动主机并等待新 BIOS,不重启 BMC。"
+}

+ 21 - 0
qt-client/live-config-off/config.json

@@ -0,0 +1,21 @@
+{
+  "backend": {
+    "url": "ws://127.0.0.1:8080/ws?view=qt-clean"
+  },
+  "memoryParams": {
+    "errhandle": false
+  },
+  "qtPlan": {
+    "uip": {
+      "action": "continue_uip",
+      "apply_memory_params": true
+    },
+    "amt": {
+      "action": "skip_amt",
+      "exit_after": true
+    },
+    "uefi": {
+      "action": "hold"
+    }
+  }
+}

+ 24 - 0
qt-client/live-config-off/port.json

@@ -0,0 +1,24 @@
+{
+  "serialPorts": [
+    {
+      "port": "",
+      "serialNumber": "",
+      "baud": 115200
+    },
+    {
+      "port": "",
+      "serialNumber": "",
+      "baud": 115200
+    },
+    {
+      "port": "",
+      "serialNumber": "",
+      "baud": 115200
+    },
+    {
+      "port": "",
+      "serialNumber": "",
+      "baud": 115200
+    }
+  ]
+}

+ 19 - 0
qt-client/live-config-on/config.json

@@ -0,0 +1,19 @@
+{
+  "backend": {
+    "url": "ws://127.0.0.1:8080/ws?view=qt-clean"
+  },
+  "memoryParams": {},
+  "qtPlan": {
+    "uip": {
+      "action": "continue_uip",
+      "apply_memory_params": false
+    },
+    "amt": {
+      "action": "skip_amt",
+      "exit_after": true
+    },
+    "uefi": {
+      "action": "hold"
+    }
+  }
+}

+ 24 - 0
qt-client/live-config-on/port.json

@@ -0,0 +1,24 @@
+{
+  "serialPorts": [
+    {
+      "port": "",
+      "serialNumber": "",
+      "baud": 115200
+    },
+    {
+      "port": "",
+      "serialNumber": "",
+      "baud": 115200
+    },
+    {
+      "port": "",
+      "serialNumber": "",
+      "baud": 115200
+    },
+    {
+      "port": "",
+      "serialNumber": "",
+      "baud": 115200
+    }
+  ]
+}

+ 9 - 0
qt-client/port.json

@@ -0,0 +1,9 @@
+{
+  "_comment": "工位串口配置:数组第 1 个对应 001 工位,依次到 004。port 支持 ttyUSB0、COM1 或 /dev/ttyUSB0;serialNumber 非空时优先按 USB 序列号匹配(插拔也不怕换名);baud 缺省 115200。当前为联调临时配置:001 接 com0com 虚拟串口 COM1(另一端 COM2 由 tools/mcusim 应答),002~004 暂未配置。",
+  "serialPorts": [
+    { "port": "COM18", "serialNumber": "", "baud": 115200 },
+    { "port": "", "serialNumber": "", "baud": 115200 },
+    { "port": "", "serialNumber": "", "baud": 115200 },
+    { "port": "", "serialNumber": "", "baud": 115200 }
+  ]
+}

+ 674 - 0
qt-client/src/3rdparty/qcustomplot/GPL.txt

@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.

Разница между файлами не показана из-за своего большого размера
+ 35529 - 0
qt-client/src/3rdparty/qcustomplot/qcustomplot.cpp


Разница между файлами не показана из-за своего большого размера
+ 7774 - 0
qt-client/src/3rdparty/qcustomplot/qcustomplot.h


+ 37 - 0
qt-client/src/appconfig.h

@@ -0,0 +1,37 @@
+#ifndef APPCONFIG_H
+#define APPCONFIG_H
+
+#include <QCoreApplication>
+#include <QDir>
+#include <QFileInfo>
+#include <QString>
+
+/**
+ * 运行期配置文件定位(config.json / port.json)
+ * ------------------------------------------------------------------
+ * 从 exe 所在目录开始,逐级向上找,命中即返回;都没命中再看当前工作目录。
+ * 这样三种放法都能找到:
+ *   · 部署目录:exe 与 json 同级(推荐)
+ *   · 开发期:exe 在 build-win/debug,json 在源码根,向上几级即可碰到
+ *   · 从命令行启动:工作目录里放 json
+ * 越靠近 exe 的文件优先级越高,方便临时用一份配置覆盖默认值。
+ */
+inline QString appConfigPath(const QString &fileName)
+{
+    // A deployment or test may select its own configuration directory.
+    const QString explicitDir = qEnvironmentVariable("STL_QT_CONFIG_DIR");
+    if (!explicitDir.isEmpty())
+        return QDir(explicitDir).filePath(fileName);
+    QDir dir(QCoreApplication::applicationDirPath());
+    for (int i = 0; i < 6; ++i) {          // exe 同级算第 0 层,最多再向上 5 层
+        const QString candidate = dir.filePath(fileName);
+        if (QFileInfo::exists(candidate))
+            return candidate;
+        if (!dir.cdUp())
+            break;
+    }
+    const QString inCwd = QDir::current().filePath(fileName);
+    return QFileInfo::exists(inCwd) ? inCwd : QString();
+}
+
+#endif // APPCONFIG_H

BIN
qt-client/src/assets/logo-mark.png


+ 417 - 0
qt-client/src/backendlink.cpp

@@ -0,0 +1,417 @@
+#include "backendlink.h"
+
+#include "appconfig.h"
+#include "localplans.h"
+#include <QDateTime>
+#include <QDebug>
+#include <QFile>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QUrl>
+#include <QUuid>
+
+namespace {
+QString stationId(int index) { return QStringLiteral("S%1").arg(index + 1); }
+int stationIndex(const QJsonObject &object)
+{
+    const QString id = object.value(QStringLiteral("station_id")).toString();
+    for (int i = 0; i < 4; ++i)
+        if (id == stationId(i)) return i;
+    return -1;
+}
+QString errorMessage(const QJsonValue &value)
+{
+    return value.isObject() ? value.toObject().value(QStringLiteral("message")).toString()
+                            : value.toString();
+}
+}
+
+BackendLink::BackendLink(QObject *parent) : QObject(parent)
+{
+    connect(&m_ws, &QWebSocket::connected, this, &BackendLink::onConnected);
+    connect(&m_ws, &QWebSocket::disconnected, this, &BackendLink::onDisconnected);
+    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();
+        if (m_ws.state() == QAbstractSocket::UnconnectedState && !m_reconnect.isActive())
+            m_reconnect.start();
+    });
+    m_reconnect.setSingleShot(true);
+    m_reconnect.setInterval(3000);
+    connect(&m_reconnect, &QTimer::timeout, this, &BackendLink::openSocket);
+    m_pendingTimer.setInterval(1000);
+    connect(&m_pendingTimer, &QTimer::timeout, this, &BackendLink::checkPending);
+}
+
+BackendLink::~BackendLink()
+{
+    // QWebSocket emits disconnect-related signals while being destroyed. Stop
+    // those callbacks before Run/request members (declared after it) are gone.
+    m_reconnect.stop();
+    m_pendingTimer.stop();
+    disconnect(&m_ws, nullptr, this, nullptr);
+    disconnect(this, nullptr, nullptr, nullptr);
+    m_ws.abort();
+    m_requests.clear();
+}
+
+void BackendLink::start()
+{
+    m_url = QStringLiteral("ws://192.168.2.79:8080/ws?view=qt-clean");
+    QFile file(appConfigPath(QStringLiteral("config.json")));
+    if (file.open(QIODevice::ReadOnly)) {
+        const QString configured = QJsonDocument::fromJson(file.readAll()).object()
+            .value(QStringLiteral("backend")).toObject().value(QStringLiteral("url")).toString();
+        if (!configured.isEmpty()) m_url = configured;
+    }
+    const QString overrideUrl = qEnvironmentVariable("STL_QT_BACKEND_URL");
+    if (!overrideUrl.isEmpty()) m_url = overrideUrl;
+    openSocket();
+    m_pendingTimer.start();
+}
+
+void BackendLink::openSocket()
+{
+    if (m_ws.state() != QAbstractSocket::UnconnectedState) return;
+    m_connectStartedMs = QDateTime::currentMSecsSinceEpoch();
+    m_ws.open(QUrl(m_url));
+}
+
+void BackendLink::onConnected()
+{
+    m_reconnect.stop();
+    m_connectStartedMs = 0;
+    m_lastReceivedMs = QDateTime::currentMSecsSinceEpoch();
+    emit connectionChanged(true);
+    qInfo().noquote() << "[backend] Qt clean connected";
+    sendRequest(QStringLiteral("GetState"), {}, -1, [this](const QJsonObject &state) { applyState(state); });
+    // Pending controls are queried, never blindly replayed after reconnect.
+    for (Run &run : m_runs) run.queried = 0;
+    checkPending();
+}
+
+void BackendLink::onDisconnected()
+{
+    emit connectionChanged(false);
+    m_requests.clear();
+    for (int i = 0; i < 4; ++i) {
+        if (m_runs[i].active)
+            qWarning().noquote() << "[backend] connection lost, pending command will only be queried" << i;
+    }
+    m_reconnect.start();
+}
+
+void BackendLink::sendRequest(const QString &method, const QJsonObject &params, int station,
+                             const std::function<void(const QJsonObject &)> &onOk,
+                             const std::function<void(const QString &)> &onError)
+{
+    if (!isConnected()) return;
+    const QString id = QStringLiteral("qt-%1").arg(++m_idCounter);
+    Request request;
+    request.method = method;
+    request.station = station;
+    request.sent = QDateTime::currentMSecsSinceEpoch();
+    request.onOk = onOk;
+    request.onError = onError;
+    m_requests.insert(id, request);
+    const QJsonObject frame{{QStringLiteral("v"), 1}, {QStringLiteral("id"), id},
+                            {QStringLiteral("method"), method}, {QStringLiteral("params"), params}};
+    m_ws.sendTextMessage(QString::fromUtf8(QJsonDocument(frame).toJson(QJsonDocument::Compact)));
+}
+
+void BackendLink::onTextMessage(const QString &json)
+{
+    m_lastReceivedMs = QDateTime::currentMSecsSinceEpoch();
+    const QJsonObject frame = QJsonDocument::fromJson(json.toUtf8()).object();
+    const QString event = frame.value(QStringLiteral("event")).toString();
+    if (event == QStringLiteral("state")) {
+        applyState(frame.value(QStringLiteral("result")).toObject());
+        return;
+    }
+    if (event == QStringLiteral("logs")) {
+        // Qt's test log contains only captured BIOS UART, never event summaries.
+        return;
+    }
+    if (event == QStringLiteral("bios_uart")) {
+        applyBiosUart(frame.value(QStringLiteral("result")).toObject());
+        return;
+    }
+    const QString id = frame.value(QStringLiteral("id")).toString();
+    if (!m_requests.contains(id)) return;
+    const Request request = m_requests.take(id);
+    if (frame.value(QStringLiteral("ok")).toBool()) {
+        if (request.onOk) request.onOk(frame.value(QStringLiteral("result")).toObject());
+    } else {
+        const QString message = errorMessage(frame.value(QStringLiteral("error")));
+        if (request.onError) request.onError(message);
+        else if (request.station >= 0) failRun(request.station, message);
+        else qWarning().noquote() << "[backend]" << message;
+    }
+}
+
+bool BackendLink::isBusy(int station) const
+{
+    return station >= 0 && station < 4 && m_runs[station].active;
+}
+
+bool BackendLink::startTest(int station)
+{
+    if (station < 0 || station >= 4) return false;
+    if (!isConnected()) {
+        qWarning() << "[backend] cannot start: disconnected" << station;
+        return false;
+    }
+    if (isBusy(station)) {
+        qInfo() << "[backend] duplicate start ignored" << station;
+        return false;
+    }
+    Run &run = m_runs[station];
+    run.active = true;
+    run.bootConfirmed = false;
+    run.bootId.clear();
+    run.startedUnixMs = 0;
+    run.sawMatchingBoot = false;
+    run.inputs.clear();
+    run.amtStartedCpus.clear();
+    run.plan = LocalPlans().plan(station);
+    qInfo() << "[backend] local plan started, waiting for BIOS" << station;
+    return sendControl(station, QStringLiteral("StartTest"), {});
+}
+
+bool BackendLink::sendControl(int station, const QString &method, QJsonObject params)
+{
+    Run &run = m_runs[station];
+    if (!isConnected() || !run.commandId.isEmpty()) return false;
+    run.commandId = QStringLiteral("qt-%1").arg(QUuid::createUuid().toString(QUuid::WithoutBraces));
+    run.commandMethod = method;
+    run.queried = QDateTime::currentMSecsSinceEpoch();
+    params.insert(QStringLiteral("command_id"), run.commandId);
+    params.insert(QStringLiteral("station_id"), stationId(station));
+    sendRequest(method, params, station, [this, station](const QJsonObject &command) {
+        observeCommand(station, command);
+    });
+    return true;
+}
+
+void BackendLink::applyState(const QJsonObject &result)
+{
+    const QString serverId = result.value(QStringLiteral("server_id")).toString();
+    if (!serverId.isEmpty() && serverId != m_serverId) {
+        const bool restarted = !m_serverId.isEmpty();
+        m_serverId = serverId;
+        for (int i = 0; i < 4; ++i) {
+            if (restarted && m_runs[i].active)
+                failRun(i, QStringLiteral("后端已重启,旧操作不自动重放;请检查当前状态后重新开始"));
+        }
+    }
+    for (const QJsonValue &value : result.value(QStringLiteral("stations")).toArray()) {
+        const QJsonObject state = value.toObject();
+        const int station = stationIndex(state);
+        if (station < 0) continue;
+        m_runs[station].latest = state;
+        observeCommand(station, state.value(QStringLiteral("command")).toObject());
+        advancePlan(station);
+        emit stationState(station, state);
+    }
+}
+
+void BackendLink::observeCommand(int station, const QJsonObject &command)
+{
+    Run &run = m_runs[station];
+    if (run.commandId.isEmpty() || command.value(QStringLiteral("command_id")).toString() != run.commandId)
+        return;
+    const QString state = command.value(QStringLiteral("state")).toString().toLower();
+    if (state != QStringLiteral("succeeded") && state != QStringLiteral("failed")
+        && state != QStringLiteral("interrupted")) return;
+    const QString method = run.commandMethod;
+    run.commandId.clear();
+    run.commandMethod.clear();
+    if (state != QStringLiteral("succeeded")) {
+        const QString message = errorMessage(command.value(QStringLiteral("error")));
+        run.active = false;
+        emit commandFinished(station, method, false, message);
+        qWarning().noquote() << "[backend] operation failed" << station << (message.isEmpty() ? state : message);
+        return;
+    }
+    if (method == QStringLiteral("StartTest")) {
+        run.bootId = command.value(QStringLiteral("result")).toObject()
+            .value(QStringLiteral("boot_id")).toVariant().toString();
+        run.startedUnixMs = command.value(QStringLiteral("result")).toObject()
+            .value(QStringLiteral("started_unix_ms")).toVariant().toLongLong();
+        if (run.bootId.isEmpty()) {
+            failRun(station, QStringLiteral("开始响应缺少新启动编号,未执行后续阶段动作"));
+            return;
+        }
+        run.bootConfirmed = true;
+        qInfo() << "[backend] new BIOS boot confirmed" << station;
+        if (run.latest.value(QStringLiteral("boot_id")).toVariant().toString() != run.bootId)
+            sendRequest(QStringLiteral("GetState"), {}, -1, [this](const QJsonObject &state) { applyState(state); });
+    }
+    emit commandFinished(station, method, true, {});
+    advancePlan(station);
+    emit stationState(station, run.latest);
+}
+
+void BackendLink::advancePlan(int station)
+{
+    Run &run = m_runs[station];
+    if (!run.active || !run.bootConfirmed || !isConnected()) return;
+    const QString observedBoot = run.latest.value(QStringLiteral("boot_id")).toVariant().toString();
+    const qint64 observedStarted = run.latest.value(QStringLiteral("started_unix_ms")).toVariant().toLongLong();
+    const bool matchingBoot = !run.bootId.isEmpty() && observedBoot == run.bootId;
+    const bool currentRun = matchingBoot || (run.startedUnixMs > 0 && observedStarted >= run.startedUnixMs);
+    const QString runState = run.latest.value(QStringLiteral("run_state")).toString();
+    // A Start reply can precede its new snapshot. An older UEFI/failed snapshot
+    // is ignored, but an explicit failure belonging to this run must not hide
+    // behind a changed boot id or a still-pending stage command.
+    if (currentRun && runState == QStringLiteral("failed")) {
+        failRun(station, matchingBoot ? QStringLiteral("本轮固件执行失败,已停止后续阶段动作")
+                                     : QStringLiteral("本轮 BIOS 启动已变化且后端报告失败,已停止后续阶段动作"));
+        return;
+    }
+    if (!matchingBoot) {
+        if (run.sawMatchingBoot && currentRun && !observedBoot.isEmpty())
+            failRun(station, QStringLiteral("本轮 BIOS 意外再次启动,已停止后续阶段动作"));
+        return;
+    }
+    run.sawMatchingBoot = true;
+    if (!run.commandId.isEmpty()) return;
+    if (runState == QStringLiteral("completed")) {
+        run.active = false;
+        return;
+    }
+    const QJsonObject input = run.latest.value(QStringLiteral("input")).toObject();
+    const QString id = input.value(QStringLiteral("id")).toString();
+    if (!input.value(QStringLiteral("ready")).toBool() || id.isEmpty() || run.inputs.contains(id)) return;
+    const QString stage = input.value(QStringLiteral("stage")).toString();
+    QJsonObject params{{QStringLiteral("input_id"), id}};
+    QString action;
+    if (stage == QStringLiteral("uip1") || stage == QStringLiteral("uip2") || stage == QStringLiteral("uip")) {
+        const QJsonObject uip = run.plan.value(QStringLiteral("uip")).toObject();
+        action = uip.value(QStringLiteral("action")).toString(QStringLiteral("continue_uip"));
+        if (stage != QStringLiteral("uip2") && uip.value(QStringLiteral("apply_memory_params")).toBool(false))
+            params.insert(QStringLiteral("memory_params"), run.plan.value(QStringLiteral("memory_params")).toObject());
+    } else if (stage == QStringLiteral("amt")) {
+        const QJsonObject amt = run.plan.value(QStringLiteral("amt")).toObject();
+        action = amt.value(QStringLiteral("action")).toString(QStringLiteral("skip_amt"));
+        if (action == QStringLiteral("start_amt") && run.amtStartedCpus.contains(input.value(QStringLiteral("cpu")).toInt())) {
+            if (!input.value(QStringLiteral("test_complete")).toBool(false)) return;
+            action = amt.value(QStringLiteral("exit_after")).toBool(true)
+                ? QStringLiteral("skip_amt") : QStringLiteral("hold");
+        }
+        if (action == QStringLiteral("start_amt")) params.insert(QStringLiteral("amt"), amt.value(QStringLiteral("settings")).toObject());
+    } else if (stage == QStringLiteral("uefi")) {
+        const QJsonObject uefi = run.plan.value(QStringLiteral("uefi")).toObject();
+        action = uefi.value(QStringLiteral("action")).toString(QStringLiteral("hold"));
+        if (action == QStringLiteral("start_mt")) params.insert(QStringLiteral("mt"), uefi.value(QStringLiteral("settings")).toObject());
+    } else return;
+    if (action == QStringLiteral("hold")) {
+        run.inputs.insert(id);
+        run.active = false;
+        qInfo() << "[backend] waiting for operator at" << stage << station;
+        return;
+    }
+    const QJsonArray actions = input.value(QStringLiteral("actions")).toArray();
+    if (!actions.contains(action)) return;
+    params.insert(QStringLiteral("action"), action);
+    run.inputs.insert(id);
+    if (!sendControl(station, QStringLiteral("StageAction"), params)) run.inputs.remove(id);
+    else if (action == QStringLiteral("start_amt")) run.amtStartedCpus.insert(input.value(QStringLiteral("cpu")).toInt());
+}
+
+void BackendLink::applyBiosUart(const QJsonObject &result)
+{
+    const int station = stationIndex(result);
+    if (station < 0) return;
+    const QString session = result.value(QStringLiteral("session_id")).toString();
+    if (session.isEmpty()) return;
+    if (m_uartSession[station] != session) {
+        m_uartSession[station] = session;
+        m_uartOffset[station] = 0;
+        m_uartPending[station].clear();
+    }
+    const quint64 first = result.value(QStringLiteral("offset")).toVariant().toULongLong();
+    QByteArray bytes = QByteArray::fromBase64(result.value(QStringLiteral("data_base64")).toString().toLatin1());
+    const quint64 end = first + static_cast<quint64>(bytes.size());
+    if (end <= m_uartOffset[station]) return; // Reconnect replay: already displayed.
+    if (first > m_uartOffset[station]) {
+        qWarning() << "[backend] BIOS UART stream gap" << station << first << m_uartOffset[station];
+        // The next reconnect replays from offset zero; never invent a missing line.
+        return;
+    }
+    bytes.remove(0, static_cast<int>(m_uartOffset[station] - first));
+    m_uartOffset[station] = end;
+    m_uartPending[station].append(bytes);
+    int newline = -1;
+    while ((newline = m_uartPending[station].indexOf('\n')) >= 0) {
+        QByteArray line = m_uartPending[station].left(newline);
+        m_uartPending[station].remove(0, newline + 1);
+        if (line.endsWith('\r')) line.chop(1); // Normalize CRLF for QPlainTextEdit only.
+        emit logLine(station, QString::fromUtf8(line));
+    }
+    // BIOS prompts often omit the final newline. Do not withhold a long raw
+    // prompt indefinitely, while preserving the ordinary line-by-line display.
+    if (m_uartPending[station].size() > 16384) {
+        emit logLine(station, QString::fromUtf8(m_uartPending[station]));
+        m_uartPending[station].clear();
+    }
+}
+
+void BackendLink::failRun(int station, const QString &message)
+{
+    Run &run = m_runs[station];
+    const QString method = run.commandMethod;
+    run.active = false;
+    run.commandId.clear();
+    run.commandMethod.clear();
+    qWarning().noquote() << "[backend]" << station << message;
+    emit commandFinished(station, method, false, message);
+}
+
+void BackendLink::checkPending()
+{
+    const qint64 now = QDateTime::currentMSecsSinceEpoch();
+    if (!isConnected()) {
+        // Qt can remain in ConnectingState after an unreachable network hop.
+        if (m_connectStartedMs > 0 && now - m_connectStartedMs > 10000) {
+            qWarning() << "[backend] connection attempt timed out; retrying";
+            m_connectStartedMs = 0;
+            m_ws.abort();
+            if (!m_reconnect.isActive()) m_reconnect.start();
+        }
+        return;
+    }
+    // The clean backend sends a state every second. A silent TCP half-open
+    // must not leave the Qt UI showing a misleading connected indicator.
+    if (m_lastReceivedMs > 0 && now - m_lastReceivedMs > 20000) {
+        qWarning() << "[backend] state stream silent for 20 seconds; reconnecting";
+        m_lastReceivedMs = 0;
+        m_ws.abort();
+        if (!m_reconnect.isActive()) m_reconnect.start();
+        return;
+    }
+    const auto keys = m_requests.keys();
+    for (const QString &id : keys) {
+        const Request request = m_requests.value(id);
+        if (now - request.sent < 10000) continue;
+        m_requests.remove(id);
+        if (request.onError) request.onError(QStringLiteral("响应超时"));
+        else if (request.station >= 0)
+            qWarning() << "[backend] awaiting command state" << request.station;
+    }
+    for (int i = 0; i < 4; ++i) {
+        Run &run = m_runs[i];
+        if (now - run.queried < 3000) continue;
+        if (run.commandId.isEmpty()) {
+            if (run.active && run.bootConfirmed && run.latest.value(QStringLiteral("boot_id")).toVariant().toString() != run.bootId) {
+                run.queried = now;
+                sendRequest(QStringLiteral("GetState"), {}, -1, [this](const QJsonObject &state) { applyState(state); });
+            }
+            continue;
+        }
+        run.queried = now;
+        const QJsonObject params{{QStringLiteral("command_id"), run.commandId}};
+        sendRequest(QStringLiteral("GetCommand"), params, i, [this, i](const QJsonObject &command) { observeCommand(i, command); });
+    }
+}

+ 89 - 0
qt-client/src/backendlink.h

@@ -0,0 +1,89 @@
+#ifndef BACKENDLINK_H
+#define BACKENDLINK_H
+
+#include <functional>
+#include <QByteArray>
+#include <QHash>
+#include <QJsonObject>
+#include <QJsonArray>
+#include <QObject>
+#include <QSet>
+#include <QString>
+#include <QTimer>
+#include <QWebSocket>
+
+// Qt clean client. Widgets only start a local plan and consume clean snapshots.
+// Parameter names, BIOS parsing and hardware actions are owned by the backend.
+class BackendLink : public QObject
+{
+    Q_OBJECT
+public:
+    explicit BackendLink(QObject *parent = nullptr);
+    ~BackendLink() override;
+    void start();
+    bool isConnected() const { return m_ws.state() == QAbstractSocket::ConnectedState; }
+    bool startTest(int station);
+    bool isBusy(int station) const;
+    QString bootId(int station) const { return station >= 0 && station < 4 ? m_runs[station].bootId : QString(); }
+    QString url() const { return m_url; }
+
+signals:
+    void connectionChanged(bool connected);
+    void logLine(int station, const QString &line);
+    void stationState(int station, const QJsonObject &state);
+    void commandFinished(int station, const QString &method, bool success, const QString &error);
+
+private slots:
+    void onConnected();
+    void onDisconnected();
+    void onTextMessage(const QString &json);
+    void checkPending();
+
+private:
+    struct Request {
+        QString method;
+        int station = -1;
+        qint64 sent = 0;
+        std::function<void(const QJsonObject &)> onOk;
+        std::function<void(const QString &)> onError;
+    };
+    struct Run {
+        bool active = false;
+        bool bootConfirmed = false;
+        QString bootId;
+        qint64 startedUnixMs = 0;
+        bool sawMatchingBoot = false;
+        QJsonObject plan;
+        QJsonObject latest;
+        QSet<QString> inputs;
+        QSet<int> amtStartedCpus;
+        QString commandId;
+        QString commandMethod;
+        qint64 queried = 0;
+    };
+    void openSocket();
+    void sendRequest(const QString &method, const QJsonObject &params, int station = -1,
+                     const std::function<void(const QJsonObject &)> &onOk = {},
+                     const std::function<void(const QString &)> &onError = {});
+    void applyState(const QJsonObject &result);
+    void applyBiosUart(const QJsonObject &result);
+    void observeCommand(int station, const QJsonObject &command);
+    void advancePlan(int station);
+    bool sendControl(int station, const QString &method, QJsonObject params);
+    void failRun(int station, const QString &message);
+
+    QWebSocket m_ws;
+    QTimer m_reconnect;
+    QTimer m_pendingTimer;
+    QString m_url;
+    int m_idCounter = 0;
+    qint64 m_connectStartedMs = 0;
+    qint64 m_lastReceivedMs = 0;
+    QHash<QString, Request> m_requests;
+    Run m_runs[4];
+    quint64 m_uartOffset[4] = {0, 0, 0, 0};
+    QString m_uartSession[4];
+    QByteArray m_uartPending[4];
+    QString m_serverId;
+};
+#endif

+ 49 - 0
qt-client/src/comanager.cpp

@@ -0,0 +1,49 @@
+#include "comanager.h"
+
+#include "comworker.h"
+
+#include <QMetaObject>
+#include <QThread>
+
+ComManager::ComManager(QObject *parent)
+    : QObject(parent)
+    , m_thread(new QThread(this))
+    , m_worker(new ComWorker)          // 不带 parent,moveToThread 后才能被线程接管
+{
+    m_worker->moveToThread(m_thread);
+    connect(m_worker, &ComWorker::stateChanged, this, &ComManager::stateChanged);
+    // 温度原始字节:跨线程自动走 QueuedConnection,QByteArray 已注册元类型
+    connect(m_worker, &ComWorker::ctRawArrived, this, &ComManager::ctRawArrived);
+    connect(m_worker, &ComWorker::channelRawArrived, this, &ComManager::channelRawArrived);
+    m_thread->start();
+}
+
+ComManager::~ComManager()
+{
+    if (m_thread->isRunning()) {
+        QMetaObject::invokeMethod(m_worker, "stop", Qt::BlockingQueuedConnection);
+        m_thread->quit();
+        m_thread->wait(3000);
+    }
+    delete m_worker;
+}
+
+void ComManager::configure(int index, const QString &port, const QString &serialNumber, int baud)
+{
+    QMetaObject::invokeMethod(m_worker, "configure", Qt::QueuedConnection,
+                              Q_ARG(int, index),
+                              Q_ARG(QString, port),
+                              Q_ARG(QString, serialNumber),
+                              Q_ARG(int, baud));
+}
+
+void ComManager::start()
+{
+    QMetaObject::invokeMethod(m_worker, "start", Qt::QueuedConnection);
+}
+
+void ComManager::stopAll()
+{
+    if (m_thread->isRunning())
+        QMetaObject::invokeMethod(m_worker, "stop", Qt::QueuedConnection);
+}

+ 43 - 0
qt-client/src/comanager.h

@@ -0,0 +1,43 @@
+#ifndef COMANAGER_H
+#define COMANAGER_H
+
+#include <QByteArray>
+#include <QObject>
+#include <QString>
+
+class ComWorker;
+class QThread;
+
+/**
+ * 工位串口管理器(主线程侧)
+ * ------------------------------------------------------------------
+ * 真正的串口操作放在工作线程的 ComWorker 里,
+ * 主线程只通过信号槽收状态;四个工位共用这一个扫描线程(串口流量很小)。
+ *
+ * 通信链路:MainWindow ⇄ ComManager ⇄ ComWorker(QThread)⇄ QSerialPort
+ */
+class ComManager : public QObject
+{
+    Q_OBJECT
+
+public:
+    explicit ComManager(QObject *parent = nullptr);
+    ~ComManager() override;
+
+    void configure(int index, const QString &port, const QString &serialNumber, int baud);
+    void start();
+    void stopAll();
+
+signals:
+    void stateChanged(int index, int state, const QString &portName, const QString &detail);
+
+    // 转发 ComWorker 收到的原始温度字节(0xFF = 该路无效),换算交给 StationStore
+    void ctRawArrived(int index, const QByteArray &raw);        // CT7428 八路
+    void channelRawArrived(int index, const QByteArray &raw);   // 24 路 BMC
+
+private:
+    QThread *m_thread;
+    ComWorker *m_worker;
+};
+
+#endif // COMANAGER_H

+ 231 - 0
qt-client/src/comworker.cpp

@@ -0,0 +1,231 @@
+#include "comworker.h"
+
+#include <QDateTime>
+#include <QDebug>
+#include <QFileInfo>
+#include <QSerialPort>
+#include <QSerialPortInfo>
+#include <QTimer>
+
+namespace {
+const int kScanIntervalMs = 1500;   // 端口热插拔扫描间隔
+const int kPollIntervalMs = 1000;   // 温度轮询间隔(协议建议值为准,和设备同一拍)
+
+// 界面显示用的短名:/dev/ttyUSB0 -> ttyUSB0,ttyUSB1 -> ttyUSB1
+QString shortName(const QString &path)
+{
+    QString p = path;
+    if (p.startsWith(QLatin1String("/dev/")))
+        p = p.mid(5);
+    return p;
+}
+
+// 设备节点是否存在
+//   Linux:ttyUSB0 或 /dev/ttyUSB0(前者靠下面的枚举同样能查到)
+//   Windows:串口不是文件节点(没有 /dev/COM3),只能靠 QSerialPortInfo 枚举
+bool deviceExists(const QString &port)
+{
+    if (port.startsWith(QLatin1Char('/')))
+        return QFileInfo::exists(port);
+
+    const QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();
+    for (const QSerialPortInfo &info : ports) {
+        if (info.portName().compare(port, Qt::CaseInsensitive) == 0)
+            return true;
+    }
+    return QFileInfo::exists(QStringLiteral("/dev/") + port);   // Linux 兜底
+}
+}
+
+ComWorker::ComWorker(QObject *parent)
+    : QObject(parent)
+    , m_timer(nullptr)
+    , m_pollTimer(nullptr)
+{
+}
+
+ComWorker::~ComWorker()
+{
+    for (int i = 0; i < m_slots.size(); ++i)
+        closeSlot(m_slots[i]);
+}
+
+void ComWorker::configure(int index, const QString &port, const QString &serialNumber, int baud)
+{
+    if (index < 0)
+        return;
+
+    while (m_slots.size() <= index)
+        m_slots.append(Slot());
+
+    Slot &slot = m_slots[index];
+    const bool changed = (slot.port != port
+                          || slot.serialNumber != serialNumber
+                          || slot.baud != baud);
+
+    if (changed) {
+        closeSlot(slot);            // 配置变了:先放开旧端口,下一轮按新配置重开
+        slot.port = port;
+        slot.serialNumber = serialNumber;
+        slot.baud = baud > 0 ? baud : 115200;
+        slot.lastState = -1;        // 强制重新上报
+    }
+}
+
+void ComWorker::start()
+{
+    if (!m_timer) {
+        m_timer = new QTimer(this);   // 定时器必须在工作线程里创建
+        m_timer->setInterval(kScanIntervalMs);
+        connect(m_timer, &QTimer::timeout, this, &ComWorker::tick);
+    }
+    if (!m_pollTimer) {
+        m_pollTimer = new QTimer(this);
+        m_pollTimer->setInterval(kPollIntervalMs);
+        connect(m_pollTimer, &QTimer::timeout, this, &ComWorker::poll);
+    }
+    if (!m_timer->isActive())
+        m_timer->start();
+    if (!m_pollTimer->isActive())
+        m_pollTimer->start();
+    tick();                           // 不用等满 1.5s,先扫一次
+}
+
+void ComWorker::stop()
+{
+    if (m_timer)
+        m_timer->stop();
+    if (m_pollTimer)
+        m_pollTimer->stop();
+    for (int i = 0; i < m_slots.size(); ++i)
+        closeSlot(m_slots[i]);
+}
+
+void ComWorker::poll()
+{
+    // 只有真正打开了的串口才轮询:轮询 disabled 的端口没有意义,还会刷一堆写失败日志
+    for (int index = 0; index < m_slots.size(); ++index) {
+        Slot &slot = m_slots[index];
+        if (!slot.sp || !slot.sp->isOpen())
+            continue;
+
+        // 两条读命令每 1000ms 各发一次:0x0D 取 CT7428 八路,0x02 取 24 路 BMC。
+        // 应答是异步回来的,由 readyRead 里的 handleReply() 处理,不等在这里。
+        slot.sp->write(slt::frameRequestCt7428());
+        slot.sp->write(slt::frameRequestChannels());
+    }
+}
+
+void ComWorker::handleReply(int index, Slot &slot)
+{
+    if (!slot.sp)
+        return;
+
+    const QByteArray chunk = slot.sp->readAll();
+    if (chunk.isEmpty())
+        return;
+
+    const QVector<slt::Frame> frames = slot.parser.feed(chunk);
+    for (const slt::Frame &f : frames) {
+        if (f.cmd == slt::kRespCt7428 && f.payload.size() == slt::kRespCt7428Len)
+            emit ctRawArrived(index, f.payload);
+        else if (f.cmd == slt::kRespChannels && f.payload.size() == slt::kRespChannelsLen)
+            emit channelRawArrived(index, f.payload);
+    }
+}
+
+void ComWorker::tick()
+{
+    for (int index = 0; index < m_slots.size(); ++index) {
+        Slot &slot = m_slots[index];
+
+        // ---- 1. 没配置:始终按“未配置”显示 ----
+        if (slot.port.isEmpty() && slot.serialNumber.isEmpty()) {
+            closeSlot(slot);
+            report(index, slot, Unconfigured, QStringLiteral("COM"),
+                   QStringLiteral("port.json 未配置该工位串口"));
+            continue;
+        }
+
+        // ---- 2. 找到真正要打开的端口 ----
+        QString target;
+        QString shown = slot.port.isEmpty() ? QStringLiteral("COM") : shortName(slot.port);
+        if (!slot.serialNumber.isEmpty()) {
+            const QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();
+            for (const QSerialPortInfo &info : ports) {
+                if (info.serialNumber().compare(slot.serialNumber, Qt::CaseInsensitive) == 0) {
+                    target = info.portName();
+                    shown = target;
+                    break;
+                }
+            }
+        } else {
+            target = slot.port;
+            if (!deviceExists(target))
+                target.clear();     // 设备不在(拔了 / 没插)
+        }
+
+        if (target.isEmpty()) {
+            closeSlot(slot);
+            report(index, slot, Offline, shown, QStringLiteral("未检测到串口设备"));
+            continue;
+        }
+
+        // ---- 3. 已打开:保持(设备被拔掉时 isOpen() 会变 false,走下面重开分支)----
+        if (slot.sp && slot.sp->isOpen()) {
+            report(index, slot, Online, shown,
+                   QStringLiteral("已打开 %1 @%2").arg(shortName(target)).arg(slot.baud));
+            continue;
+        }
+
+        // ---- 4. 打开(只在必要时建对象,打开失败下一轮继续试)----
+        if (!slot.sp) {
+            slot.sp = new QSerialPort(this);
+            connect(slot.sp, &QSerialPort::readyRead, this, [this, index]() {
+                // 收到数据就解帧:0x8D / 0x82 的温度数据从这里往上送
+                if (index < m_slots.size())
+                    handleReply(index, m_slots[index]);
+            });
+        }
+
+        slot.sp->setPortName(target);
+        slot.sp->setBaudRate(slot.baud);
+        slot.sp->setDataBits(QSerialPort::Data8);
+        slot.sp->setParity(QSerialPort::NoParity);
+        slot.sp->setStopBits(QSerialPort::OneStop);
+        slot.sp->setFlowControl(QSerialPort::NoFlowControl);
+
+        if (slot.sp->open(QIODevice::ReadWrite)) {
+            report(index, slot, Online, shown,
+                   QStringLiteral("已打开 %1 @%2").arg(shortName(target)).arg(slot.baud));
+        } else {
+            report(index, slot, Offline, shown,
+                   QStringLiteral("打开 %1 失败:%2").arg(shortName(target), slot.sp->errorString()));
+        }
+    }
+}
+
+void ComWorker::closeSlot(Slot &slot)
+{
+    if (slot.sp) {
+        if (slot.sp->isOpen())
+            slot.sp->close();
+        slot.parser.reset();    // 端口重开时清掉半帧残数据,别把新会话的头一帧拼错
+        delete slot.sp;         // 和本对象同一个线程,直接删
+        slot.sp = nullptr;
+    }
+}
+
+void ComWorker::report(int index, Slot &slot, int state, const QString &shown, const QString &detail)
+{
+    if (slot.lastState == state && slot.lastShown == shown && slot.lastDetail == detail)
+        return;                     // 状态没变不重复刷界面、不刷日志
+
+    slot.lastState = state;
+    slot.lastShown = shown;
+    slot.lastDetail = detail;
+
+    qInfo().noquote() << QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz"))
+                      << "[com]" << index << state << shown << detail;
+    emit stateChanged(index, state, shown, detail);
+}

+ 84 - 0
qt-client/src/comworker.h

@@ -0,0 +1,84 @@
+#ifndef COMWORKER_H
+#define COMWORKER_H
+
+#include "sltproto.h"
+
+#include <QObject>
+#include <QString>
+#include <QVector>
+
+class QSerialPort;
+class QTimer;
+
+/**
+ * 工位串口巡检 + 温度轮询(跑在独立工作线程里)
+ * ------------------------------------------------------------------
+ * 每个工位一个 USB 转串口,端口与工位的对应关系写在 port.json:
+ *   · port         —— 设备名(如 ttyUSB0)或绝对路径(/dev/ttyUSB0)
+ *   · serialNumber —— 非空时优先按 USB 序列号匹配(换设备名也不会错位)
+ *   · baud         —— 波特率,缺省 115200
+ *
+ * 两条节拍,各管各的(互不牵制):
+ *   · kScanIntervalMs  —— 端口热插拔扫描(1500ms),负责「连没连上」;
+ *   · kPollIntervalMs  —— 温度轮询(1000ms),只在端口已打开时下发请求帧。
+ *
+ * 轮询发的就是协议里的两条读命令:
+ *   0x0D → 0x8D   本板 CT7428 八路温度(8 字节)→ 取平均当「腔体温度」
+ *   0x02 → 0x82   24 路 BMC 温度(24 字节)    → 一路一格填到 24 通道
+ * 原始字节不做换算,原样发给主线程:本文件只管「字节进、帧出」。
+ */
+class ComWorker : public QObject
+{
+    Q_OBJECT
+
+public:
+    // 与界面芯片状态一一对应
+    enum State {
+        Unconfigured = 0,   // port.json 里没配这个工位
+        Offline,            // 配了端口,但设备不在 / 打不开
+        Online              // 端口已打开
+    };
+
+    explicit ComWorker(QObject *parent = nullptr);
+    ~ComWorker() override;
+
+signals:
+    void stateChanged(int index, int state, const QString &portName, const QString &detail);
+
+    // 收到的原始温度字节(未经换算):0xFF 表示该路无效,换算规则归 StationStore
+    void ctRawArrived(int index, const QByteArray &raw);        // 0x8D,8 字节
+    void channelRawArrived(int index, const QByteArray &raw);   // 0x82,24 字节
+
+public slots:
+    void configure(int index, const QString &port, const QString &serialNumber, int baud);
+    void start();
+    void stop();
+
+private slots:
+    void tick();          // 1500ms:端口热插拔扫描
+    void poll();          // 1000ms:给已打开的串口下发温度请求帧
+
+private:
+    struct Slot {
+        QString port;           // 配置的端口名(原样保存,界面显示会去掉 /dev/ 前缀)
+        QString serialNumber;   // 非空时按 USB 序列号找端口
+        int baud;
+        QSerialPort *sp;
+        slt::FrameParser parser; // 这个端口自己的收帧缓冲(多个串口的字节不能混)
+        int lastState;          // -1 = 还没上报过,强制下一轮上报
+        QString lastShown;
+        QString lastDetail;
+
+        Slot() : baud(115200), sp(nullptr), lastState(-1) {}
+    };
+
+    void closeSlot(Slot &slot);
+    void report(int index, Slot &slot, int state, const QString &shown, const QString &detail);
+    void handleReply(int index, Slot &slot);
+
+    QVector<Slot> m_slots;
+    QTimer *m_timer;      // 端口扫描
+    QTimer *m_pollTimer;  // 温度轮询
+};
+
+#endif // COMWORKER_H

+ 116 - 0
qt-client/src/demofeed.cpp

@@ -0,0 +1,116 @@
+#include "demofeed.h"
+
+#include "stationdata.h"
+
+#include <QDateTime>
+#include <QRandomGenerator>
+#include <QtGlobal>
+
+#include <cmath>
+
+namespace {
+
+// 走表周期:1000ms 一次,跟真实设备的采样节奏一致。
+// 现在只用来刷新「运行时间」,温度 / 状态都保持空态。
+const int kSampleIntervalMs = 1000;
+
+} // namespace
+
+DemoDataSource::DemoDataSource(StationStore *store, QObject *parent)
+    : QObject(parent)
+    , m_store(store)
+{
+    m_timer.setInterval(kSampleIntervalMs);
+    connect(&m_timer, &QTimer::timeout, this, &DemoDataSource::tick);
+}
+
+void DemoDataSource::start()
+{
+    seed();
+    m_timer.start();
+}
+
+void DemoDataSource::seed()
+{
+    const QStringList names = channelNames();
+    const QStringList devices = {QStringLiteral("SLT-HT-001"), QStringLiteral("SLT-HT-002"),
+                                 QStringLiteral("SLT-HT-003"), QStringLiteral("SLT-HT-004")};
+    const QStringList tasks = {QStringLiteral("TASK-20261021-001"), QStringLiteral("TASK-20261019-019"),
+                               QStringLiteral("TASK-20261019-020"), QStringLiteral("TASK-20261019-021")};
+    const QStringList ports = {QStringLiteral("COM3"), QStringLiteral("COM4"),
+                               QStringLiteral("COM5"), QStringLiteral("COM6")};
+
+    for (int i = 0; i < m_store->count() && i < devices.size(); ++i) {
+        StationData d;
+        d.deviceId = devices.at(i);
+        d.taskId = tasks.at(i);
+        d.product = QStringLiteral("DDR5 RDIMM");
+        d.mode = QStringLiteral("高温模式");
+        d.port = ports.at(i);
+        d.targetTemp = 70.0;
+
+        // 空态:还没开始测试 —— 温度无数据(界面 --℃)、运行时间从 00:00:00 起步
+        d.currentTemp = -1.0;
+        d.startTime = QDateTime();
+
+        // 24 个通道一律未装载(IDLE),不预置任何 PASS / FAIL
+        for (const QString &name : names)
+            d.channels.append(ChannelInfo(name, -1.0, ChannelInfo::Idle));
+
+        // 日志不再预置假数据:等后端 / 串口报文接入后由 StationStore::appendLog() 实时写入
+
+        m_store->initStation(i, d);
+    }
+}
+
+void DemoDataSource::tick()
+{
+    ++m_tick;
+
+    if (m_simulate)
+        pushSimulatedTemperatures();
+
+    // 演示数据(温度抖动 / PASS-FAIL 随机)已按要求停掉,界面保持空态:
+    // 现在 tick 只做一件事 —— 让已经点过「开始测试」的工位,运行时间每秒往下走。
+    for (int i = 0; i < m_store->count(); ++i) {
+        if (m_store->station(i).startTime.isValid())
+            m_store->touchRuntime(i);
+    }
+}
+
+void DemoDataSource::pushSimulatedTemperatures()
+{
+    // 造一组「像设备回的」字节:温度在 68~72℃ 之间缓慢起伏,
+    // 并故意留几个 0xFF,好让界面上同时出现「蓝色已装载」和「灰色 --℃」两种格子。
+    // 四个工位的相位错开一点,看起来不像同一条曲线在复制。
+    for (int i = 0; i < m_store->count(); ++i) {
+        const double phase = m_tick / 9.0 + i * 1.7;
+
+        QByteArray ct;                        // CT7428 八路
+        for (int c = 0; c < 8; ++c) {
+            // 第 3 路固定无效:验证「跳过 0xFF 再取平均」
+            if (c == 2) {
+                ct.append(char(0xFF));
+                continue;
+            }
+            const double t = 69.0 + std::sin(phase + c * 0.35) * 2.0
+                           + (QRandomGenerator::global()->generateDouble() - 0.5) * 0.6;
+            ct.append(char(qRound(qBound(0.0, t, 254.0))));
+        }
+        m_store->applyCtTemperatures(i, ct);
+
+        QByteArray ch;                        // 24 路 BMC
+        for (int c = 0; c < 24; ++c) {
+            // 最后 4 路固定无效:模拟没插条的通道
+            if (c >= 20) {
+                ch.append(char(0xFF));
+                continue;
+            }
+            const double t = 70.0 + std::sin(phase + c * 0.22) * 1.6
+                           + (QRandomGenerator::global()->generateDouble() - 0.5) * 0.5;
+            ch.append(char(qRound(qBound(0.0, t, 254.0))));
+        }
+        m_store->applyChannelTemperatures(i, ch);
+    }
+}
+

+ 657 - 0
qt-client/src/detailview.cpp

@@ -0,0 +1,657 @@
+#include "detailview.h"
+
+#include "appconfig.h"
+#include "localplans.h"
+#include "stationdata.h"
+
+#include "qcustomplot.h"
+#include "ui_mainwindow.h"
+
+#include <QCheckBox>
+#include <QCoreApplication>
+#include <QDateTime>
+#include <QDebug>
+#include <QDir>
+#include <QFile>
+#include <QFontMetrics>
+#include <QFileInfo>
+#include <QHBoxLayout>
+#include <QFrame>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QIntValidator>
+#include <QJsonValue>
+#include <QLabel>
+#include <QLineEdit>
+#include <QMouseEvent>
+#include <QPlainTextEdit>
+#include <QPushButton>
+#include <QScrollBar>
+#include <QStyle>
+
+namespace {
+
+const int kTabCount = 3;   // 温控曲线 / 异常记录 / 内存参数设置
+
+// 顺序必须与 tools/gen_ui.py 的 PARAM_COLS / PARAM_CHECKS 保持一致
+const char *const kParamKeys[] = {
+    "mem vdd", "mem vddq", "tCL", "tRCD", "tRP", "tRAS",
+    "tRFC", "tRTP", "trrd_l", "tWTR_S", "tWTR_L", "tWR",
+    "tCCD_L", "trefi", "tRFCsb",
+};
+const int kParamKeyCount = int(sizeof(kParamKeys) / sizeof(kParamKeys[0]));
+
+const char *const kParamChecks[] = {"errhandle", "ap"};
+const int kParamCheckCount = int(sizeof(kParamChecks) / sizeof(kParamChecks[0]));
+
+// 图例前面那个小色块的画法。
+// QCustomPlot 默认是照抄曲线画笔(1.6px)画一条细线,右端还会多画 5px,
+// 缩到 18×8 的图标框里就成了「一根毛边小横杠」。这里自己画:
+//   Pill = 3px 圆头短棒(默认)、Dot = 小圆点、None = 只要文字
+enum LegendSwatch { SwatchPill, SwatchDot, SwatchNone };
+const LegendSwatch kSwatch = SwatchPill;
+
+// 色块的尺寸由 setupCurvePlot() 按图例字体算好,画的时候直接用:
+//   g_swatchH   = 大写字母高度(色块要和字一样高)
+//   g_swatchTop = ascent - capHeight(图标框里色块该往下挪多少才和字对齐)
+int g_swatchH = 10;
+int g_swatchTop = 3;
+
+class CurveGraph : public QCPGraph
+{
+public:
+    CurveGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
+        : QCPGraph(keyAxis, valueAxis)
+    {
+    }
+
+protected:
+    // 只在图例里生效:曲线本身仍然用 setPen() 设的 1.6px 细线
+    void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const override
+    {
+        if (kSwatch == SwatchNone)
+            return;
+
+        const QColor color("#2f7fc1");
+        painter->setRenderHint(QPainter::Antialiasing, true);
+
+        if (kSwatch == SwatchDot) {
+            painter->setPen(Qt::NoPen);
+            painter->setBrush(color);
+            const qreal r = qMin(rect.height() / 2.0 - 0.5, 4.0);
+            painter->drawEllipse(rect.center(), r, r);
+            return;
+        }
+
+        // 直角矩形,高度 = 大写字母高度,垂直位置和文字的大写字母对齐(不要圆角)
+        const QRectF bar(rect.left(), rect.top() + g_swatchTop, rect.width(), g_swatchH);
+        painter->setPen(Qt::NoPen);
+        painter->setBrush(color);
+        painter->drawRect(bar);
+    }
+};
+
+} // namespace
+
+DetailView::DetailView(Ui::MainWindow *ui, StationStore *store, QObject *parent)
+    : QObject(parent)
+    , m_ui(ui)
+    , m_store(store)
+{
+    // 布局伸缩比例(.ui 里写 stretch 会被 uic 拒绝)
+    m_ui->detailCols->setStretch(0, 56);
+    m_ui->detailCols->setStretch(1, 44);
+    m_ui->detailLeftCol->setStretch(0, 4);
+    m_ui->detailLeftCol->setStretch(1, 5);
+
+    // 内存参数表单:三列等宽(索引 0/2/4 是三列,1/3 是列间分隔线);
+    // 表单本身吃满页面高度,列里的 Expanding spacer 把行距均分,下方不再留大片空白
+    m_ui->paramForm->setStretch(0, 1);
+    m_ui->paramForm->setStretch(2, 1);
+    m_ui->paramForm->setStretch(4, 1);
+    m_ui->tabPageParamLayout->setStretch(0, 1);
+
+    // 行内让输入框优先吃富余宽度(涨到 160 就停),剩下的才给行尾的弹性空隙。
+    // 不给 stretch 的话,富余宽度会被行尾 spacer 全吃掉,输入框反而停在 sizeHint(≈124)上。
+    // 开关行(第 2 个是 QCheckBox)不参与,免得复选框被拉宽。
+    const QList<QHBoxLayout *> paramRows = m_ui->tabPageParam->findChildren<QHBoxLayout *>();
+    for (QHBoxLayout *row : paramRows) {
+        if (!row->objectName().startsWith(QStringLiteral("paramRow_")) || row->count() < 2)
+            continue;
+        if (qobject_cast<QLineEdit *>(row->itemAt(1)->widget()))
+            row->setStretch(1, 1);
+    }
+
+    cacheChannelWidgets();
+
+    // 内存参数只接受非负整数:挡住小数点、正负号、字母和粘贴进来的脏数据
+    const QList<QLineEdit *> paramEdits = m_ui->tabPageParam->findChildren<QLineEdit *>();
+    for (QLineEdit *e : paramEdits)
+        e->setValidator(new QIntValidator(0, 99999999, e));
+
+    loadParamConfig();
+
+    m_flush.setSingleShot(true);
+    m_flush.setInterval(120);
+    connect(&m_flush, &QTimer::timeout, this, &DetailView::flushPending);
+
+    connect(m_ui->btnBackMonitor, &QPushButton::clicked, this, &DetailView::backRequested);
+    connect(m_ui->btnParamSubmit, &QPushButton::clicked, this, &DetailView::submitParams);
+    QPushButton *tabs[kTabCount] = {m_ui->detailTab_0, m_ui->detailTab_1, m_ui->detailTab_2};
+    for (int i = 0; i < kTabCount; ++i)
+        connect(tabs[i], &QPushButton::clicked, this, [this, i] { selectTab(i); });
+
+    connect(m_store, &StationStore::logAppended, this, &DetailView::onLogAppended);
+    connect(m_store, &StationStore::channelsChanged, this, &DetailView::onChannelsChanged);
+    connect(m_store, &StationStore::infoChanged, this, &DetailView::onInfoChanged);
+    connect(m_store, &StationStore::temperatureChanged, this, &DetailView::onTemperatureChanged);
+
+    setupCurvePlot();
+}
+
+// ---------------------------------------------------------------------------
+// 参数先读当前工位 Qt 本地计划,未保存的工位读 config.json 默认值。
+// ---------------------------------------------------------------------------
+void DetailView::loadParamConfig()
+{
+    const LocalPlans plans;
+    const QJsonObject params = plans.memoryParams(qMax(0, m_index));
+
+    int filled = 0;
+    for (int i = 0; i < kParamKeyCount; ++i) {
+        // 行号规则与 gen_ui.py 一致:前 6 个在第一列,接着 6 个第二列,最后 3 个第三列
+        const int col = (i < 6) ? 0 : (i < 12 ? 1 : 2);
+        const int row = (i < 6) ? i : (i < 12 ? i - 6 : i - 12);
+
+        const QJsonValue v = params.value(QLatin1String(kParamKeys[i]));
+        QLineEdit *edit = m_ui->tabPageParam->findChild<QLineEdit *>(
+            QStringLiteral("paramEdit_%1_%2").arg(col).arg(row));
+        if (!edit)
+            continue;
+        edit->clear();
+        if (v.isUndefined() || v.isNull())
+            continue;
+
+        edit->setText(v.isDouble() ? QString::number(v.toDouble(), 'g', 12)
+                                   : v.toVariant().toString());
+        ++filled;
+    }
+
+    for (int i = 0; i < kParamCheckCount; ++i) {
+        const QJsonValue v = params.value(QLatin1String(kParamChecks[i]));
+        QCheckBox *chk = m_ui->tabPageParam->findChild<QCheckBox *>(
+            QStringLiteral("paramCheck_2_%1").arg(3 + i)); // 第三列第 4、5 行,接在 3 个输入框后面
+        if (!chk)
+            continue;
+        chk->setChecked(false);
+        if (v.isUndefined() || v.isNull())
+            continue;
+
+        chk->setChecked(v.isBool() ? v.toBool() : v.toInt() != 0);
+        ++filled;
+    }
+
+    qInfo().noquote() << "[param] 从 Qt 本地计划加载工位" << qMax(0, m_index) + 1
+                      << filled << "项参数";
+}
+
+// ---------------------------------------------------------------------------
+// 内存参数页:界面输入框 / 开关 → memoryParams 同构 JSON(确定按钮用)
+// 只收集;上层原子保存到 Qt 的 qt-plans.json,config.json 默认值不改。
+// ---------------------------------------------------------------------------
+QJsonObject DetailView::collectParams(bool *valid)
+{
+    *valid = true;
+    QJsonObject params;
+
+    for (int i = 0; i < kParamKeyCount; ++i) {
+        const int col = (i < 6) ? 0 : (i < 12 ? 1 : 2);
+        const int row = (i < 6) ? i : (i < 12 ? i - 6 : i - 12);
+
+        const QLineEdit *edit = m_ui->tabPageParam->findChild<QLineEdit *>(
+            QStringLiteral("paramEdit_%1_%2").arg(col).arg(row));
+        if (!edit || edit->text().trimmed().isEmpty())
+            continue;
+
+        bool ok = false;
+        const qlonglong value = edit->text().trimmed().toLongLong(&ok);
+        if (!ok || !edit->hasAcceptableInput() || value < 0 || value > 99999999) {
+            *valid = false;
+            m_store->appendLog(m_index, QStringLiteral("[参数] %1 必须为非负整数,未保存任何修改")
+                .arg(QLatin1String(kParamKeys[i])));
+            return QJsonObject();
+        }
+        params.insert(QLatin1String(kParamKeys[i]), static_cast<double>(value));
+    }
+
+    for (int i = 0; i < kParamCheckCount; ++i) {
+        const QCheckBox *chk = m_ui->tabPageParam->findChild<QCheckBox *>(
+            QStringLiteral("paramCheck_2_%1").arg(3 + i));
+        if (chk)
+            params.insert(QLatin1String(kParamChecks[i]), chk->isChecked());
+    }
+
+    return params;
+}
+
+void DetailView::submitParams()
+{
+    if (m_index < 0)
+        return;
+
+    bool valid = false;
+    const QJsonObject params = collectParams(&valid);
+    if (!valid) return;
+    qInfo().noquote() << "[param] 工位" << m_index + 1 << "点确定,收集到"
+                      << params.count() << "项内存参数,保存到 Qt 本地计划";
+    emit paramsSubmitted(m_index, params);
+}
+
+// ---------------------------------------------------------------------------
+// 通道切换:点 24 通道卡片里的任意格子,曲线切到该通道
+// ---------------------------------------------------------------------------
+bool DetailView::eventFilter(QObject *watched, QEvent *event)
+{
+    if (event->type() == QEvent::MouseButtonRelease) {
+        QMouseEvent *me = static_cast<QMouseEvent *>(event);
+        if (me->button() == Qt::LeftButton) {
+            const QString name = watched->objectName();
+            if (name.startsWith(QLatin1String("chCell_")))
+                selectCurveChannel(name.mid(7));   // 去掉 "chCell_" 前缀
+        }
+    }
+    return QObject::eventFilter(watched, event);
+}
+
+void DetailView::selectCurveChannel(const QString &name)
+{
+    if (m_curveChannel == name || name.isEmpty())
+        return;
+
+    m_curveChannel = name;
+    markCurveChannel();
+    renderCurve();
+}
+
+void DetailView::markCurveChannel()
+{
+    const QString want = QStringLiteral("chCell_") + m_curveChannel;
+    for (QFrame *f : m_cellFrames) {
+        const bool on = (f->objectName() == want);
+        if (f->property("selected").toBool() == on)
+            continue;
+        f->setProperty("selected", on);
+        f->style()->unpolish(f);
+        f->style()->polish(f);
+    }
+}
+
+// ---------------------------------------------------------------------------
+// 温控曲线:QCustomPlot,横轴最近 200 个采样点,纵轴 20~90 °C
+// 样式全部在这里设,.ui 里只有控件本体
+// ---------------------------------------------------------------------------
+void DetailView::setupCurvePlot()
+{
+    QCustomPlot *p = m_ui->curvePlot;
+    if (!p)
+        return;
+
+    p->setBackground(QBrush(QColor("#ffffff")));
+    p->setNoAntialiasingOnDrag(true);
+
+    QFont font = p->font();
+    font.setPointSize(9);
+    p->setFont(font);
+
+    const QColor axisColor("#c6d2df");
+    const QColor subTickColor("#dde5ee");
+    const QColor labelColor("#6b7d90");
+    const QColor gridColor("#eef2f7");
+
+    for (QCPAxis *ax : {p->xAxis, p->yAxis}) {
+        ax->setBasePen(QPen(axisColor, 1));
+        ax->setTickPen(QPen(axisColor, 1));
+        ax->setSubTickPen(QPen(subTickColor, 1));
+        ax->setTickLabelColor(labelColor);
+        ax->setLabelColor(labelColor);
+        ax->setTickLength(0, 4);
+        ax->grid()->setPen(QPen(gridColor, 1, Qt::DotLine));
+        ax->grid()->setSubGridVisible(false);
+        ax->grid()->setZeroLinePen(Qt::NoPen);
+    }
+
+    p->xAxis->setLabel(QStringLiteral("采样点"));
+    p->yAxis->setLabel(QStringLiteral("温度 (°C)"));
+    p->xAxis->setRange(0, kTempHistorySize);
+    p->yAxis->setRange(20, 90);
+    p->xAxis->ticker()->setTickCount(6);      // 0 / 40 / 80 / 120 / 160 / 200
+    p->yAxis->ticker()->setTickCount(8);      // 20 ~ 90,每 10 一格
+    p->xAxis->setSubTicks(false);
+    p->yAxis->setSubTicks(false);
+
+    // 用 CurveGraph 代替 addGraph():曲线画法不变,只是把图例里的小色块换成圆头短棒
+    QCPGraph *g = new CurveGraph(p->xAxis, p->yAxis);
+    g->setPen(QPen(QColor("#2f7fc1"), 1.6));
+    g->setLineStyle(QCPGraph::lsLine);
+    g->setScatterStyle(QCPScatterStyle::ssNone);
+    g->setAntialiased(true);
+    g->setName(QStringLiteral("腔体温度"));       // 曲线名,进详情页后会换成「工位号 · 腔体温度」
+
+    // 图例:右上角白色小框,曲线名由 renderCurve() 随工位更新
+    QCPLegend *lg = p->legend;
+    lg->setVisible(true);
+    lg->setBrush(QBrush(QColor(255, 255, 255, 225)));
+    lg->setBorderPen(QPen(QColor("#dde5ee")));
+    lg->setTextColor(QColor("#5d7086"));
+    lg->setFont(font);
+    // 图标框取整行高(这样它在图例行里就是垂直居中的),
+    // 色块本身再按字体度量放进去:高度 = 大写字母高度,顶边 = ascent - capHeight
+    const QFontMetrics lgFm(font);
+    g_swatchH = qMax(8, lgFm.capHeight());
+    g_swatchTop = qMax(0, lgFm.ascent() - lgFm.capHeight());
+    lg->setIconSize(20, lgFm.height());
+    lg->setIconTextPadding(6);
+    lg->setRowSpacing(0);
+    p->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight);
+
+    // 最新点:一个白底蓝边的小圆点 + 下面的温度数值(跟着数据一起走,见 renderCurve)
+    m_lastDot = new QCPItemTracer(p);
+    m_lastDot->setGraph(g);
+    m_lastDot->setStyle(QCPItemTracer::tsCircle);
+    m_lastDot->setSize(5);
+    m_lastDot->setPen(QPen(QColor("#2f7fc1"), 1.6));
+    m_lastDot->setBrush(QBrush(Qt::white));
+    m_lastDot->setSelectable(false);
+    m_lastDot->setClipToAxisRect(false);
+
+    m_lastLabel = new QCPItemText(p);
+    m_lastLabel->setSelectable(false);
+    m_lastLabel->setClipToAxisRect(false);
+    m_lastLabel->setPositionAlignment(Qt::AlignTop | Qt::AlignHCenter);
+    m_lastLabel->position->setType(QCPItemPosition::ptPlotCoords);
+    m_lastLabel->setPadding(QMargins(2, 6, 2, 1));   // 上边多留点,让标签离开圆点
+    m_lastLabel->setPen(Qt::NoPen);
+    m_lastLabel->setBrush(Qt::NoBrush);              // 不要底色块,只留文字
+    m_lastLabel->setColor(QColor("#2f7fc1"));
+    {
+        QFont lf = font;
+        lf.setPointSizeF(8.5);
+        lf.setBold(true);
+        m_lastLabel->setFont(lf);
+    }
+
+    p->replot();
+}
+
+void DetailView::renderCurve()
+{
+    if (m_index < 0 || m_index >= m_store->count())
+        return;
+
+    QCustomPlot *p = m_ui->curvePlot;
+    if (!p || p->graphCount() == 0)
+        return;
+
+    const StationData &d = m_store->station(m_index);
+
+    // 找当前选中的通道;工位换了但通道名还在(24 个通道各工位同名),所以直接按名字找
+    const ChannelInfo *sel = nullptr;
+    for (const ChannelInfo &c : d.channels) {
+        if (c.name == m_curveChannel) {
+            sel = &c;
+            break;
+        }
+    }
+    if (!sel && !d.channels.isEmpty())
+        sel = &d.channels.first();
+    if (!sel)
+        return;
+
+    const int n = sel->history.size();
+    const int start = sel->historyStart;
+
+    QVector<double> keys(n);
+    QVector<double> values(n);
+    for (int i = 0; i < n; ++i) {
+        keys[i] = start + i;             // 全局采样序号,不回绕
+        values[i] = sel->history.at(i);
+    }
+
+    QCPGraph *g = p->graph(0);
+    g->setData(keys, values, true);
+
+    // 图例显示通道名:CPU0_CHA
+    if (g->name() != sel->name)
+        g->setName(sel->name);
+
+    // 横轴滚动:可见宽度恒为 kTempHistorySize 点,起点跟着最新数据走(刻度数字会一起滚)
+    double lo = start;
+    if (n < kTempHistorySize)
+        lo = 0;                          // 还没满 200 点时从 0 开始铺,不从负数起
+    p->xAxis->setRange(lo, lo + kTempHistorySize);
+
+    // 最新点标记 + 数值标签:贴在最后一个采样点下方
+    if (m_lastDot && m_lastLabel && n > 0) {
+        const double k = keys.last();
+        const double v = values.last();
+
+        m_lastDot->setGraphKey(k);
+        m_lastDot->setVisible(true);
+
+        m_lastLabel->setText(QStringLiteral("%1°C").arg(QString::number(v, 'f', 1)));
+        m_lastLabel->position->setCoords(k, v);
+        m_lastLabel->setVisible(true);
+
+        // 点贴近轴的右边缘时改成右对齐,否则标签会甩到图外
+        const double px = p->xAxis->coordToPixel(k);
+        const QRect rect = p->axisRect()->rect();
+        if (px > rect.right() - 40)
+            m_lastLabel->setPositionAlignment(Qt::AlignTop | Qt::AlignRight);
+        else if (px < rect.left() + 40)
+            m_lastLabel->setPositionAlignment(Qt::AlignTop | Qt::AlignLeft);
+        else
+            m_lastLabel->setPositionAlignment(Qt::AlignTop | Qt::AlignHCenter);
+    } else if (m_lastDot && m_lastLabel) {
+        m_lastDot->setVisible(false);
+        m_lastLabel->setVisible(false);
+    }
+
+    p->replot(QCustomPlot::rpQueuedReplot);
+}
+
+void DetailView::onTemperatureChanged(int index)
+{
+    if (index != m_index)
+        return; // 不在当前工位:数据留在模型里,切回来整体重铺
+    if (m_ui->detailTabStack->currentIndex() != 0)
+        return; // 曲线页没显示,画了也看不见
+
+    renderCurve();
+}
+
+void DetailView::cacheChannelWidgets()
+{
+    m_cellFrames.clear();
+    m_cellValues.clear();
+
+    const QStringList names = channelNames();
+    for (const QString &name : names) {
+        QFrame *frame = m_ui->detailPage->findChild<QFrame *>(QStringLiteral("chCell_") + name);
+        QLabel *value = m_ui->detailPage->findChild<QLabel *>(QStringLiteral("chCellValue_") + name);
+        if (!frame || !value)
+            continue;
+
+        // 点通道格子 → 曲线切到该通道
+        frame->installEventFilter(this);
+        frame->setCursor(Qt::PointingHandCursor);
+        m_cellFrames.append(frame);
+        m_cellValues.append(value);
+    }
+}
+
+// ---------------------------------------------------------------------------
+// 打开 / 关闭
+// ---------------------------------------------------------------------------
+void DetailView::showStation(int index)
+{
+    if (index < 0 || index >= m_store->count())
+        return;
+
+    m_index = index;
+    loadParamConfig();
+    m_ui->pageStack->setCurrentIndex(1);
+
+    // 纯内存渲染,不依赖任何异步取数 —— 点开即出
+    markCurveChannel();      // 高亮当前曲线对应的通道(默认 CPU0_CHA)
+    renderAll();
+}
+
+void DetailView::leave()
+{
+    m_index = -1;
+    m_flush.stop();
+    m_needTitle = m_needChannels = false;
+}
+
+// ---------------------------------------------------------------------------
+// 全量渲染(首次进入 / 切换工位)
+// ---------------------------------------------------------------------------
+void DetailView::renderAll()
+{
+    renderTitle();
+    renderChannels();
+    renderCurve();
+    renderLogs();
+}
+
+void DetailView::renderTitle()
+{
+    // 标题栏的“设备详情页 ·”是静态控件,代码只填工位号
+    const StationData &d = m_store->station(m_index);
+    m_ui->detailDevice->setText(d.deviceId.isEmpty() ? QStringLiteral("—") : d.deviceId);
+}
+
+void DetailView::renderChannels()
+{
+    const StationData &d = m_store->station(m_index);
+    const int n = qMin(m_cellFrames.size(), d.channels.size());
+    for (int i = 0; i < n; ++i) {
+        const ChannelInfo &ch = d.channels.at(i);
+
+        // 未装载不显示温度,用 --℃ 占位;已装载只显示温度,不区分 PASS / FAIL
+        m_cellValues[i]->setText(ch.temperature < 0.0
+                                     ? QStringLiteral("--℃")
+                                     : QStringLiteral("%1 ℃").arg(QString::number(ch.temperature, 'f', 1)));
+
+        QFrame *frame = m_cellFrames[i];
+        const QString state = (ch.temperature < 0.0) ? QStringLiteral("idle")
+                                                             : QStringLiteral("loaded");
+        if (frame->property("state").toString() == state)
+            continue;
+
+        frame->setProperty("state", state);
+        // 兜底重刷:QSS 里值文字的颜色挂在父框的 state 上
+        frame->style()->unpolish(frame);
+        frame->style()->polish(frame);
+        m_cellValues[i]->style()->unpolish(m_cellValues[i]);
+        m_cellValues[i]->style()->polish(m_cellValues[i]);
+    }
+}
+
+void DetailView::renderLogs()
+{
+    const StationData &d = m_store->station(m_index);
+    QPlainTextEdit *log = m_ui->detailLog;
+    const int total = d.logs.size();
+
+    if (m_logStation == m_index && total >= m_logLines) {
+        // 同一工位:只把新增的尾巴整块追加进去。
+        // 实测 7.5 万行:整块 append 约 0.2s,逐行 append 会退化到 13s 以上,
+        // 所以这里必须一次性插入,绝不能 for 循环 appendPlainText。
+        if (total > m_logLines) {
+            log->appendPlainText(d.logs.mid(m_logLines).join(QLatin1Char('\n')));
+            m_logLines = total;
+        }
+    } else {
+        // 换工位:整篇重铺(7.5 万行约 0.4s,属可接受的一次性开销)
+        log->setPlainText(d.logs.join(QLatin1Char('\n')));
+        m_logStation = m_index;
+        m_logLines = total;
+    }
+
+    log->verticalScrollBar()->setValue(log->verticalScrollBar()->maximum());
+}
+
+void DetailView::selectTab(int index)
+{
+    QPushButton *tabs[kTabCount] = {m_ui->detailTab_0, m_ui->detailTab_1, m_ui->detailTab_2};
+    for (int i = 0; i < kTabCount; ++i) {
+        tabs[i]->setProperty("active", i == index ? QStringLiteral("true") : QStringLiteral("false"));
+        tabs[i]->style()->unpolish(tabs[i]);
+        tabs[i]->style()->polish(tabs[i]);
+    }
+    m_ui->detailTabStack->setCurrentIndex(index);
+
+    if (index == 0)      // 切回曲线页时补画一次,避免看到离开期间的旧曲线
+        renderCurve();
+}
+
+// ---------------------------------------------------------------------------
+// 实时刷新:日志走快路径,其余 120ms 合并
+// ---------------------------------------------------------------------------
+void DetailView::onLogAppended(int index, const QString &line)
+{
+    if (index != m_index)
+        return; // 不在当前工位:只留在模型里,切回来时一次性铺全
+
+    QPlainTextEdit *log = m_ui->detailLog;
+    QScrollBar *bar = log->verticalScrollBar();
+    const bool follow = (bar->value() >= bar->maximum() - 4); // 用户往上翻就不抢滚动条
+
+    log->appendPlainText(line);
+    m_logStation = index;
+    m_logLines = m_store->station(index).logs.size();
+
+    if (follow)
+        bar->setValue(bar->maximum());
+}
+
+void DetailView::onChannelsChanged(int index)
+{
+    if (index != m_index)
+        return;
+    m_needChannels = true;
+    requestFlush();
+}
+
+void DetailView::onInfoChanged(int index)
+{
+    if (index != m_index)
+        return;
+    m_needTitle = true;   // 标题栏的工位号跟着任务信息一起变
+    requestFlush();
+}
+
+void DetailView::requestFlush()
+{
+    if (!m_flush.isActive())
+        m_flush.start();
+}
+
+void DetailView::flushPending()
+{
+    if (m_index < 0)
+        return;
+
+    if (m_needTitle) {
+        m_needTitle = false;
+        renderTitle();
+    }
+    if (m_needChannels) {
+        m_needChannels = false;
+        renderChannels();
+        // 曲线看的是通道温度,所以通道数据一变也要重画(只在曲线页可见时做)
+        if (m_ui->detailTabStack->currentIndex() == 0)
+            renderCurve();
+    }
+}

+ 94 - 0
qt-client/src/detailview.h

@@ -0,0 +1,94 @@
+#ifndef DETAILVIEW_H
+#define DETAILVIEW_H
+
+#include <QObject>
+#include <QJsonObject>
+#include <QString>
+#include <QTimer>
+#include <QVector>
+
+class QFrame;
+class QLabel;
+class QCPItemText;
+class QCPItemTracer;
+class StationStore;
+
+namespace Ui {
+class MainWindow;
+}
+
+/**
+ * 设备详情页视图
+ * ------------------------------------------------------------------
+ * 只做两件事:
+ *   1. showStation(i) 时**同步**把模型里的数据铺到界面上(纯内存操作,点开即出);
+ *   2. 之后订阅 StationStore 的信号做增量刷新,高频信号用 120ms 合并,
+ *      日志走快路径直接 append,保证不丢行、不重建文档。
+ * 页面隐藏期间数据照常在模型里累积,再次打开直接把完整历史重新铺一遍。
+ */
+class DetailView : public QObject
+{
+    Q_OBJECT
+
+public:
+    DetailView(Ui::MainWindow *ui, StationStore *store, QObject *parent = nullptr);
+
+public slots:
+    void showStation(int index);     // 立即渲染当前工位并订阅实时刷新
+    void leave();                    // 离开详情页:只停止刷新,数据仍继续累积
+
+signals:
+    void backRequested();
+    /** 内存参数页点「确定」:携带界面上当前的参数值(键与 config.json 一致),
+     *  由上层保存到该工位的 Qt 本地计划;config.json 默认值不动 */
+    void paramsSubmitted(int station, const QJsonObject &params);
+
+protected:
+    bool eventFilter(QObject *watched, QEvent *event) override;
+
+private slots:
+    void onLogAppended(int index, const QString &line);
+    void onChannelsChanged(int index);
+    void onInfoChanged(int index);
+    void onTemperatureChanged(int index);
+    void flushPending();
+    void submitParams();             // 内存参数页「确定」:收集界面值 → paramsSubmitted
+
+private:
+    void cacheChannelWidgets();
+    void loadParamConfig();          // 内存参数:从 config.json 读默认值填进参数页
+    QJsonObject collectParams(bool *valid); // Invalid input never silently becomes zero.
+    void setupCurvePlot();           // 温控曲线:坐标轴范围、网格、曲线样式
+    void renderCurve();              // 把当前选中通道的温度历史铺到曲线上
+    void selectCurveChannel(const QString &name);   // 点通道格子切换曲线数据源
+    void markCurveChannel();                        // 给选中的格子打 selected 属性
+    void renderAll();
+    void renderTitle();
+    void renderChannels();
+    void renderLogs();
+    void selectTab(int index);
+    void requestFlush();
+
+    Ui::MainWindow *m_ui;
+    StationStore *m_store;
+    int m_index = -1;                // 当前展示的工位,-1 表示不在详情页
+
+    QTimer m_flush;                  // 高频信号合并定时器
+    bool m_needTitle = false;
+    bool m_needChannels = false;
+
+    QVector<QFrame *> m_cellFrames;
+    QVector<QLabel *> m_cellValues;
+
+    // 日志区增量渲染:记住当前铺的是哪个工位、已铺多少行,重复打开只追加新增部分
+    int m_logStation = -1;
+    int m_logLines = 0;
+
+    // 温控曲线当前看的是哪个通道,默认 CPU0_CHA
+    QString m_curveChannel = QStringLiteral("CPU0_CHA");
+
+    QCPItemText *m_lastLabel = nullptr;    // 最新点下方的数值标签
+    QCPItemTracer *m_lastDot = nullptr;    // 最新点的小圆点
+};
+
+#endif // DETAILVIEW_H

+ 75 - 0
qt-client/src/localplans.cpp

@@ -0,0 +1,75 @@
+#include "localplans.h"
+
+#include "appconfig.h"
+
+#include <QCoreApplication>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QJsonDocument>
+#include <QSaveFile>
+
+LocalPlans::LocalPlans()
+{
+    const QString configPath = appConfigPath(QStringLiteral("config.json"));
+    QFile config(configPath);
+    if (config.open(QIODevice::ReadOnly))
+        m_defaults = QJsonDocument::fromJson(config.readAll()).object();
+    m_path = qEnvironmentVariable("STL_QT_PLANS_FILE");
+    if (m_path.isEmpty()) {
+        const QDir dir(configPath.isEmpty() ? QCoreApplication::applicationDirPath()
+                                          : QFileInfo(configPath).absolutePath());
+        m_path = dir.filePath(QStringLiteral("qt-plans.json"));
+    }
+}
+
+QJsonObject LocalPlans::read() const
+{
+    QFile file(m_path);
+    return file.open(QIODevice::ReadOnly)
+        ? QJsonDocument::fromJson(file.readAll()).object() : QJsonObject();
+}
+
+QJsonObject LocalPlans::plan(int station) const
+{
+    QJsonObject result = m_defaults.value(QStringLiteral("qtPlan")).toObject();
+    if (!result.contains(QStringLiteral("memory_params")))
+        result.insert(QStringLiteral("memory_params"), m_defaults.value(QStringLiteral("memoryParams")));
+    const QJsonObject saved = read().value(QStringLiteral("stations")).toObject()
+                                  .value(QStringLiteral("S%1").arg(station + 1)).toObject();
+    for (auto it = saved.constBegin(); it != saved.constEnd(); ++it)
+        result.insert(it.key(), it.value());
+    return result;
+}
+
+QJsonObject LocalPlans::memoryParams(int station) const
+{
+    return plan(station).value(QStringLiteral("memory_params")).toObject();
+}
+
+bool LocalPlans::saveMemoryParams(int station, const QJsonObject &params, QString *error)
+{
+    if (station < 0 || station >= 4) {
+        if (error) *error = QStringLiteral("工位编号无效");
+        return false;
+    }
+    QJsonObject root = read();
+    QJsonObject stations = root.value(QStringLiteral("stations")).toObject();
+    QJsonObject value = plan(station);
+    value.insert(QStringLiteral("memory_params"), params);
+    QJsonObject uip = value.value(QStringLiteral("uip")).toObject();
+    uip.insert(QStringLiteral("action"), QStringLiteral("continue_uip"));
+    uip.insert(QStringLiteral("apply_memory_params"), true);
+    value.insert(QStringLiteral("uip"), uip);
+    stations.insert(QStringLiteral("S%1").arg(station + 1), value);
+    root.insert(QStringLiteral("version"), 1);
+    root.insert(QStringLiteral("stations"), stations);
+
+    QSaveFile file(m_path);
+    const QByteArray bytes = QJsonDocument(root).toJson(QJsonDocument::Indented);
+    if (!file.open(QIODevice::WriteOnly) || file.write(bytes) != bytes.size() || !file.commit()) {
+        if (error) *error = file.errorString();
+        return false;
+    }
+    return true;
+}

+ 24 - 0
qt-client/src/localplans.h

@@ -0,0 +1,24 @@
+#ifndef LOCALPLANS_H
+#define LOCALPLANS_H
+
+#include <QJsonObject>
+#include <QString>
+
+// Qt owns these plans. No backend plan CRUD is used.
+// Saving the parameter form changes only this local file; Start reads it afresh.
+class LocalPlans
+{
+public:
+    LocalPlans();
+    QJsonObject plan(int station) const;
+    QJsonObject memoryParams(int station) const;
+    bool saveMemoryParams(int station, const QJsonObject &params, QString *error = nullptr);
+    QString path() const { return m_path; }
+
+private:
+    QJsonObject read() const;
+    QString m_path;
+    QJsonObject m_defaults;
+};
+
+#endif

+ 65 - 0
qt-client/src/main.cpp

@@ -0,0 +1,65 @@
+#include "mainwindow.h"
+
+#include <QApplication>
+#include <QDebug>
+#include <QFile>
+#include <QFont>
+#include <QFontDatabase>
+#include <QStringList>
+
+/* 跨平台中文字体回退:按优先级挑选系统上实际存在的字体 */
+static void applyAppFont(QApplication &app)
+{
+    const QStringList prefer = QStringList()
+        << QStringLiteral("Microsoft YaHei UI")
+        << QStringLiteral("Microsoft YaHei")
+        << QStringLiteral("PingFang SC")
+        << QStringLiteral("Noto Sans CJK SC")
+        << QStringLiteral("Source Han Sans SC")
+        << QStringLiteral("WenQuanYi Micro Hei")
+        << QStringLiteral("Segoe UI");
+
+    QFontDatabase db;
+    const QStringList installed = db.families();
+
+    QFont f = app.font();
+    for (int i = 0; i < prefer.size(); ++i) {
+        if (installed.contains(prefer.at(i))) {
+            f.setFamily(prefer.at(i));
+            break;
+        }
+    }
+    f.setPointSize(9);
+    f.setStyleStrategy(QFont::PreferAntialias);
+    app.setFont(f);
+}
+
+/* 从 Qt 资源中加载全局样式表(src/style/app.qss) */
+static void applyStyleSheet(QApplication &app)
+{
+    QFile f(QStringLiteral(":/style/app.qss"));
+    if (f.open(QIODevice::ReadOnly | QIODevice::Text))
+        app.setStyleSheet(QString::fromUtf8(f.readAll()));
+}
+
+int main(int argc, char *argv[])
+{
+#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
+    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
+    QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
+#endif
+
+    QApplication app(argc, argv);
+    app.setApplicationName(QStringLiteral("HOVSE SLT Pro"));
+    app.setApplicationVersion(QStringLiteral("0.8.1.1.dev0"));
+    app.setOrganizationName(QStringLiteral("XJKJ"));
+
+    applyAppFont(app);
+    applyStyleSheet(app);
+
+    MainWindow w;
+
+    w.showMaximizedArea(); // 启动即铺满屏幕可用区域,右上角 ❐ 可还原
+
+    return app.exec();
+}

+ 409 - 0
qt-client/src/mainwindow.cpp

@@ -0,0 +1,409 @@
+#include "mainwindow.h"
+
+#include "ui_mainwindow.h"
+#include "appconfig.h"
+#include "backendlink.h"
+#include "localplans.h"
+#include "comanager.h"
+#include "comworker.h"
+#include "detailview.h"
+#include "overviewview.h"
+#include "stationdata.h"
+
+#include <QAbstractButton>
+#include <QCoreApplication>
+#include <QDateTime>
+#include <QDebug>
+#include <QDir>
+#include <QEvent>
+#include <QFile>
+#include <QFileInfo>
+#include <QGuiApplication>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QLabel>
+#include <QMouseEvent>
+#include <QPushButton>
+#include <QResizeEvent>
+#include <QScreen>
+#include <QSizeGrip>
+#include <QStyle>
+
+MainWindow::MainWindow(QWidget *parent)
+    : QMainWindow(parent)
+    , ui(new Ui::MainWindow)
+    , m_grip(nullptr)
+    , m_dragging(false)
+    , m_maximized(false)
+    , m_store(nullptr)
+    , m_backend(nullptr)
+    , m_overview(nullptr)
+    , m_detail(nullptr)
+    , m_com(nullptr)
+{
+    ui->setupUi(this);
+
+    // 让工位卡网格占满内容区剩余高度
+    ui->contentBody->setStretch(1, 1);
+
+    // 无边框窗口:标题栏由 .ui 中的 header 绘制,窗口按钮自己实现
+    setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
+    setWindowTitle(QStringLiteral("HOVSE SLT Pro"));
+
+    connect(ui->btnWinMin, &QPushButton::clicked, this, &MainWindow::onMinimize);
+    connect(ui->btnWinMax, &QPushButton::clicked, this, &MainWindow::onMaximize);
+    connect(ui->btnWinClose, &QPushButton::clicked, this, &MainWindow::onClose);
+
+    // 按住标题栏任意空白处可拖动窗口(按钮区域除外),双击最大化/还原
+    watchDrag(ui->header);
+
+    // 右下角缩放手柄(无边框窗口需要自己提供)
+    m_grip = new QSizeGrip(ui->centralwidget);
+    m_grip->setFixedSize(16, 16);
+    m_grip->raise();
+
+    // 数据层:模型在后台持续累积,详情页只负责展示
+    // 数据来源:温度走串口协议(ComWorker),通道测试状态(PASS/IDLE)等由后端下发
+    m_store = new StationStore(4, this);
+    m_overview = new OverviewView(ui, m_store, this);
+    // 整卡点击进详情页已移除:只保留卡头「查看详情 >」按钮(见 setupDetail)
+    connect(m_overview, &OverviewView::startTestRequested, this, &MainWindow::startTest);
+    m_detail = new DetailView(ui, m_store, this);
+    connect(m_detail, &DetailView::backRequested, this, &MainWindow::backToMonitor);
+
+    // Qt owns its local plans; the backend pushes curated state and log events.
+    m_backend = new BackendLink(this);
+    connect(m_backend, &BackendLink::logLine, this, [this](int station, const QString &line) {
+        m_store->appendLog(station, line);
+    });
+    connect(m_backend, &BackendLink::stationState, this, [this](int station, const QJsonObject &state) {
+        m_store->applyBackendState(station, state);
+        m_store->setBackendLink(station, m_backend->isConnected(), m_backend->isBusy(station));
+    });
+    connect(m_backend, &BackendLink::connectionChanged, this, [this](bool connected) {
+        for (int i = 0; i < m_store->count(); ++i)
+            m_store->setBackendLink(i, connected, m_backend->isBusy(i));
+    });
+    connect(m_backend, &BackendLink::commandFinished, this, [this](int station, const QString &, bool, const QString &) {
+        m_store->setBackendLink(station, m_backend->isConnected(), m_backend->isBusy(station));
+    });
+    connect(m_detail, &DetailView::paramsSubmitted, this, &MainWindow::saveLocalParams);
+
+    setupDetail();
+    setupCom();
+    m_backend->start();
+
+    // 空态初始化:工位号固定 SLT-HT-001~004;24 个通道一律 IDLE,
+    // 任务号 / 产品 / 模式等留空,等后端接入后填充
+    const QStringList deviceIds = {QStringLiteral("SLT-HT-001"), QStringLiteral("SLT-HT-002"),
+                                   QStringLiteral("SLT-HT-003"), QStringLiteral("SLT-HT-004")};
+    for (int i = 0; i < m_store->count(); ++i) {
+        StationData d;
+        if (i < deviceIds.size())
+            d.deviceId = deviceIds.at(i);
+        for (const QString &name : channelNames())
+            d.channels.append(ChannelInfo(name, -1.0, ChannelInfo::Idle));
+        m_store->initStation(i, d);
+    }
+
+    centerOnScreen();
+}
+
+MainWindow::~MainWindow()
+{
+    // Close the socket while all UI/model objects are still alive. QObject's
+    // automatic child destruction happens after this body and after delete ui.
+    delete m_backend;
+    m_backend = nullptr;
+    // ComManager 析构里会停扫描、关串口、退线程
+    delete m_com;
+    m_com = nullptr;
+
+    delete ui;
+}
+
+// ---------------------------------------------------------------------------
+// 多机监控 ⇄ 设备详情页
+// ---------------------------------------------------------------------------
+void MainWindow::setupDetail()
+{
+    QPushButton *detailButtons[4] = {ui->cardDetail_0, ui->cardDetail_1, ui->cardDetail_2,
+                                     ui->cardDetail_3};
+    for (int i = 0; i < 4; ++i) {
+        connect(detailButtons[i], &QPushButton::clicked, this, [this, i] { openDetail(i); });
+    }
+
+    ui->pageStack->setCurrentIndex(0);
+}
+
+void MainWindow::openDetail(int index)
+{
+    // 详情页用模型里的缓存数据同步渲染,点开即出,不等下一次采样
+    m_detail->showStation(index);
+}
+
+void MainWindow::backToMonitor()
+{
+    m_detail->leave();
+    ui->pageStack->setCurrentIndex(0);
+}
+
+void MainWindow::startTest(int index)
+{
+    if (index < 0 || index >= m_store->count()) return;
+    m_backend->startTest(index);
+    m_store->setBackendLink(index, m_backend->isConnected(), m_backend->isBusy(index));
+}
+
+void MainWindow::saveLocalParams(int index, const QJsonObject &params)
+{
+    if (index < 0 || index >= m_store->count()) return;
+    LocalPlans plans;
+    QString error;
+    const bool saved = plans.saveMemoryParams(index, params, &error);
+    m_store->appendLog(index, saved
+        ? QStringLiteral("[参数] 已保存到本工位 Qt 本地计划;下次开始测试在 UIP 阶段应用")
+        : QStringLiteral("[参数] 保存失败:%1").arg(error));
+}
+
+// ---------------------------------------------------------------------------
+// COM:四工位 USB 转串口连接状态(端口来自 port.json,扫描在 ComWorker 线程)
+// ---------------------------------------------------------------------------
+void MainWindow::setupCom()
+{
+    m_com = new ComManager(this);
+    connect(m_com, &ComManager::stateChanged, this, &MainWindow::onComStateChanged);
+
+    // 温度:串口线程只认字节,换算(取平均 / 0xFF → --℃)全部在 StationStore 里,
+    // 界面不用管数据来源是演示还是真设备,照吃 signals 就行
+    connect(m_com, &ComManager::ctRawArrived, this, [this](int index, const QByteArray &raw) {
+        m_store->applyCtTemperatures(index, raw);
+    });
+    connect(m_com, &ComManager::channelRawArrived, this, [this](int index, const QByteArray &raw) {
+        m_store->applyChannelTemperatures(index, raw);
+    });
+
+    if (qEnvironmentVariable("STL_QT_DISABLE_SERIAL") != QStringLiteral("1"))
+        loadSerialConfig();
+
+    // 先摆上初始状态,等第一次扫描结果回来再刷新
+    for (int i = 0; i < 4; ++i)
+        setComChip(i, ComWorker::Unconfigured, QStringLiteral("COM"), QStringLiteral("等待扫描"));
+
+    m_com->start();
+}
+
+void MainWindow::loadSerialConfig()
+{
+    // 文件名是 port.json(串口专配);config.json 留给内存参数,由 DetailView 读取
+    // 查找规则见 appconfig.h:exe 同级优先,逐级向上找,最后看当前工作目录
+    const QString path = appConfigPath(QStringLiteral("port.json"));
+    if (path.isEmpty()) {
+        qInfo().noquote() << "[com] 未找到 port.json,四个工位串口按未配置处理";
+        return;
+    }
+
+    QFile f(path);
+    if (!f.open(QIODevice::ReadOnly)) {
+        qInfo().noquote() << "[com] 打不开串口配置" << path << f.errorString();
+        return;
+    }
+
+    QJsonParseError err;
+    const QJsonDocument doc = QJsonDocument::fromJson(f.readAll(), &err);
+    if (err.error != QJsonParseError::NoError || !doc.isObject()) {
+        qInfo().noquote() << "[com] 串口配置解析失败" << path << err.errorString();
+        return;
+    }
+
+    const QJsonArray arr = doc.object().value(QStringLiteral("serialPorts")).toArray();
+    qInfo().noquote() << "[com] 配置" << path << "工位串口" << arr.size() << "条";
+
+    for (int i = 0; i < arr.size() && i < 4; ++i) {
+        const QJsonObject o = arr.at(i).toObject();
+        m_com->configure(i,
+                         o.value(QStringLiteral("port")).toString(),
+                         o.value(QStringLiteral("serialNumber")).toString(),
+                         o.value(QStringLiteral("baud")).toInt(115200));
+    }
+}
+
+void MainWindow::onComStateChanged(int index, int state, const QString &portName, const QString &detail)
+{
+    setComChip(index, state, portName, detail);
+}
+
+void MainWindow::setComChip(int index, int state, const QString &portName, const QString &detail)
+{
+    // 每张卡的串口名 / 状态芯片固定为 cardComName_N、cardCom_N,按 index 取
+    QLabel *nameChip = findChild<QLabel *>(QStringLiteral("cardComName_%1").arg(index));
+    QLabel *chip = findChild<QLabel *>(QStringLiteral("cardCom_%1").arg(index));
+    if (!nameChip || !chip) {
+        qInfo().noquote() << "[com] 界面缺少芯片 cardComName_" << index << "/ cardCom_" << index;
+        return;
+    }
+
+    QString prop, text, nameText;
+    switch (state) {
+    case ComWorker::Online:
+        prop = QStringLiteral("online");
+        text = QStringLiteral("● 已连接");
+        nameText = portName;
+        break;
+    case ComWorker::Offline:
+        prop = QStringLiteral("offline");
+        text = QStringLiteral("● 未连接");
+        nameText = portName;    // 配了端口但没插 / 打不开,仍然显示端口名
+        break;
+    default:
+        prop = QStringLiteral("offline");
+        text = QStringLiteral("● 未配置");
+        nameText = QStringLiteral("—");
+        break;
+    }
+
+    nameChip->setText(nameText);
+    chip->setText(text);
+    chip->setProperty("state", prop);
+    // 卡片上不再挂 hover 提示(鼠标扫过卡片会弹框),连接失败原因仍走日志
+    Q_UNUSED(detail);
+    chip->style()->unpolish(chip);
+    chip->style()->polish(chip);
+
+    // 详情页的串口信息跟着实际连接状态走
+    if (m_store && index >= 0 && index < m_store->count() && state != ComWorker::Unconfigured
+        && !portName.isEmpty()) {
+        m_store->setPort(index, portName);
+    }
+}
+
+// ---------------------------------------------------------------------------
+// 窗口外壳
+// ---------------------------------------------------------------------------
+void MainWindow::showMaximizedArea()
+{
+    show();
+    setMaximized(true);
+}
+
+void MainWindow::centerOnScreen()
+{
+    QScreen *screen = QGuiApplication::primaryScreen();
+    if (!screen)
+        return;
+
+    const QRect avail = screen->availableGeometry();
+    const QSize sz = size().boundedTo(avail.size());
+    resize(sz);
+    move(avail.x() + (avail.width() - sz.width()) / 2,
+         avail.y() + (avail.height() - sz.height()) / 2);
+}
+
+void MainWindow::setMaximized(bool on)
+{
+    if (m_maximized == on)
+        return;
+
+    if (on) {
+        m_normalGeometry = geometry();
+
+        QScreen *screen = QGuiApplication::screenAt(frameGeometry().center());
+        if (!screen)
+            screen = QGuiApplication::primaryScreen();
+        if (screen) {
+            const QRect avail = screen->availableGeometry();
+            setGeometry(avail); // 已排除任务栏 / Dock
+        }
+        m_maximized = true;
+    } else {
+        m_maximized = false;
+        setGeometry(m_normalGeometry);
+    }
+
+    if (m_grip)
+        m_grip->setVisible(!m_maximized);
+    ui->btnWinMax->setText(m_maximized ? QStringLiteral("❒") : QStringLiteral("❐"));
+}
+
+void MainWindow::watchDrag(QWidget *root)
+{
+    if (!root)
+        return;
+
+    root->installEventFilter(this);
+    const QList<QWidget *> children = root->findChildren<QWidget *>();
+    for (QWidget *w : children) {
+        if (qobject_cast<QAbstractButton *>(w))
+            continue; // 按钮自行处理鼠标事件
+        w->installEventFilter(this);
+    }
+}
+
+bool MainWindow::eventFilter(QObject *watched, QEvent *event)
+{
+    switch (event->type()) {
+    case QEvent::MouseButtonPress: {
+        QMouseEvent *me = static_cast<QMouseEvent *>(event);
+        if (me->button() == Qt::LeftButton) {
+            m_dragging = true;
+            m_offset = me->globalPos() - frameGeometry().topLeft();
+        }
+        break;
+    }
+    case QEvent::MouseMove: {
+        QMouseEvent *me = static_cast<QMouseEvent *>(event);
+        if (m_dragging && (me->buttons() & Qt::LeftButton)) {
+            if (m_maximized) {
+                // 最大化状态下拖动标题栏:先还原,再让窗口继续跟随鼠标
+                const QPoint global = me->globalPos();
+                setMaximized(false);
+                m_offset = global - frameGeometry().topLeft();
+            }
+            move(me->globalPos() - m_offset);
+            return true;
+        }
+        break;
+    }
+    case QEvent::MouseButtonRelease:
+        m_dragging = false;
+        break;
+    case QEvent::MouseButtonDblClick:
+        toggleMaximized();
+        return true;
+    default:
+        break;
+    }
+
+    return QMainWindow::eventFilter(watched, event);
+}
+
+void MainWindow::resizeEvent(QResizeEvent *event)
+{
+    QMainWindow::resizeEvent(event);
+    if (m_grip) {
+        m_grip->move(ui->centralwidget->width() - m_grip->width(),
+                     ui->centralwidget->height() - m_grip->height());
+        m_grip->raise();
+    }
+}
+
+void MainWindow::toggleMaximized()
+{
+    setMaximized(!m_maximized);
+}
+
+void MainWindow::onMinimize()
+{
+    showMinimized();
+}
+
+void MainWindow::onMaximize()
+{
+    toggleMaximized();
+}
+
+void MainWindow::onClose()
+{
+    close();
+}

+ 93 - 0
qt-client/src/mainwindow.h

@@ -0,0 +1,93 @@
+#ifndef MAINWINDOW_H
+#define MAINWINDOW_H
+
+#include <QJsonObject>
+#include <QMainWindow>
+#include <QPoint>
+#include <QRect>
+#include <QString>
+
+class QSizeGrip;
+class BackendLink;
+class ComManager;
+class StationStore;
+class DetailView;
+class OverviewView;
+
+namespace Ui {
+class MainWindow;
+}
+
+/**
+ * 主窗口(主线程)
+ * ------------------------------------------------------------------
+ * 窗口外壳 + 界面刷新 + 工位串口状态:
+ *   · 无边框窗口拖动、最小化/最大化/关闭、右下角缩放
+ *   · 四工位 USB 转串口连接状态,按 index 刷新对应工位卡
+ *   · 多机监控 ⇄ 设备详情页切换(详情页数据由 StationStore 提供)
+ * 通信链路:MainWindow ⇄ ComManager ⇄ ComWorker(QThread)⇄ QSerialPort
+ * 数据链路:串口协议 / 后端下发 → StationStore → DetailView → 界面
+ */
+class MainWindow : public QMainWindow
+{
+    Q_OBJECT
+
+public:
+    explicit MainWindow(QWidget *parent = nullptr);
+    ~MainWindow() override;
+
+    /** 启动时铺满屏幕可用区域(避开任务栏 / Dock) */
+    void showMaximizedArea();
+
+    /** 数据源只读入口:联调 / 压测时直接灌数据用,界面刷新仍走信号 */
+    StationStore *store() const { return m_store; }
+
+protected:
+    bool eventFilter(QObject *watched, QEvent *event) override;
+    void resizeEvent(QResizeEvent *event) override;
+
+private slots:
+    void onMinimize();
+    void onMaximize();
+    void onClose();
+
+    // ---- 多机监控 ⇄ 设备详情页 ----
+    void openDetail(int index);
+    void backToMonitor();
+
+    // ---- 工位卡右下角「开始测试」圆钮 ----
+    void startTest(int index);
+
+    // ---- COM 串口相关(index = 工位序号 0..3) ----
+    void onComStateChanged(int index, int state, const QString &portName, const QString &detail);
+
+private:
+    void watchDrag(QWidget *root);
+    void toggleMaximized();
+    void setMaximized(bool on);
+    void centerOnScreen();
+
+    void setupCom();
+    void loadSerialConfig();
+    void setComChip(int index, int state, const QString &portName, const QString &detail);
+
+    void setupDetail();
+
+    // Saving the form updates only the Qt-owned per-station plan.
+    void saveLocalParams(int index, const QJsonObject &params);
+
+    Ui::MainWindow *ui;
+    QSizeGrip *m_grip;
+    bool m_dragging;
+    bool m_maximized;
+    QPoint m_offset;
+    QRect m_normalGeometry;
+
+    StationStore *m_store;      // 四工位实时数据(界面只读)
+    BackendLink *m_backend;     // 后端 WebSocket 链路(发参数 / 拉 BIOS 日志)
+    OverviewView *m_overview;   // 多机监控总览视图
+    DetailView *m_detail;       // 设备详情页视图
+    ComManager *m_com;          // 四工位 USB 转串口状态
+};
+
+#endif // MAINWINDOW_H

Разница между файлами не показана из-за своего большого размера
+ 18026 - 0
qt-client/src/mainwindow.ui


+ 196 - 0
qt-client/src/overviewview.cpp

@@ -0,0 +1,196 @@
+#include "overviewview.h"
+
+#include "powerbutton.h"
+#include "stationdata.h"
+#include "uiformat.h"
+#include "ui_mainwindow.h"
+
+#include <QFrame>
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QStyle>
+
+namespace {
+
+const char *stateName(ChannelInfo::State state)
+{
+    switch (state) {
+    case ChannelInfo::Pass:
+        return "pass";
+    case ChannelInfo::Fail:
+        return "fail";
+    default:
+        return "idle";
+    }
+}
+
+// 格子第二行显示的状态字(与图例同一套说法)
+const char *stateWord(ChannelInfo::State state)
+{
+    switch (state) {
+    case ChannelInfo::Pass:
+        return "PASS";
+    case ChannelInfo::Fail:
+        return "FAIL";
+    default:
+        return "IDLE";
+    }
+}
+
+} // namespace
+
+OverviewView::OverviewView(Ui::MainWindow *ui, StationStore *store, QObject *parent)
+    : QObject(parent)
+    , m_ui(ui)
+    , m_store(store)
+{
+    cacheWidgets();
+
+    m_flush.setSingleShot(true);
+    m_flush.setInterval(200);
+    connect(&m_flush, &QTimer::timeout, this, &OverviewView::flushPending);
+
+    connect(m_store, &StationStore::channelsChanged, this, &OverviewView::onChannelsChanged);
+    connect(m_store, &StationStore::temperatureChanged, this, &OverviewView::onTemperatureChanged);
+    connect(m_store, &StationStore::infoChanged, this, &OverviewView::onInfoChanged);
+
+    // 先把已有数据铺一遍,首屏就是实时值而不是 .ui 里的占位
+    for (int i = 0; i < m_store->count(); ++i)
+        renderStation(i);
+}
+
+void OverviewView::cacheWidgets()
+{
+    const int count = m_store->count();
+    const QStringList names = channelNames();
+
+    m_dirty = QVector<bool>(count, false);
+    m_cells = QVector<QVector<QFrame *>>(count);
+    m_cellValues = QVector<QVector<QLabel *>>(count);
+    m_temp = QVector<QLabel *>(count, nullptr);
+    m_runtime = QVector<QLabel *>(count, nullptr);
+    m_start = QVector<PowerButton *>(count, nullptr);
+
+    for (int i = 0; i < count; ++i) {
+        // 整卡点击进详情页的行为已按需求移除,只有「查看详情 >」按钮还能跳转
+        for (const QString &nm : names) {
+            QFrame *cell = m_ui->contentArea->findChild<QFrame *>(
+                QStringLiteral("ovChCell_%1_%2").arg(i).arg(nm));
+            QLabel *value = m_ui->contentArea->findChild<QLabel *>(
+                QStringLiteral("ovChCellValue_%1_%2").arg(i).arg(nm));
+            m_cells[i].append(cell);
+            m_cellValues[i].append(value);
+        }
+        m_temp[i] = m_ui->contentArea->findChild<QLabel *>(QStringLiteral("infoValue_%1_temp").arg(i));
+        m_runtime[i] = m_ui->contentArea->findChild<QLabel *>(QStringLiteral("infoValue_%1_runtime").arg(i));
+
+        // 开始测试圆钮:点它发信号,不再冒泡到卡片(否则会顺带跳进详情页)
+        m_start[i] = m_ui->contentArea->findChild<PowerButton *>(QStringLiteral("startTest_%1").arg(i));
+        if (m_start[i]) {
+            PowerButton *btn = m_start[i];
+            connect(btn, &QAbstractButton::clicked, this, [this, i] { emit startTestRequested(i); });
+        }
+
+        // 信息行等比例分布:温度 / 运行时间 / 串口 / 开始测试 四块各吃 1/4 富余宽度,
+        // 中间三条竖分界线是固定 1px,不参与均分(uic 不认 rowStretch,只能在 C++ 设)
+        QWidget *rowW = m_ui->contentArea->findChild<QWidget *>(QStringLiteral("infoRow_%1").arg(i));
+        QHBoxLayout *row = rowW ? qobject_cast<QHBoxLayout *>(rowW->layout()) : nullptr;
+        if (row) {
+            for (int k : {0, 2, 4, 6})
+                if (k < row->count())
+                    row->setStretch(k, 1);
+        }
+    }
+}
+
+void OverviewView::renderStation(int index)
+{
+    renderInfo(index);
+    renderChannels(index);
+}
+
+void OverviewView::renderInfo(int index)
+{
+    if (index < 0 || index >= m_temp.size())
+        return;
+
+    const StationData &d = m_store->station(index);
+
+    // 没有温度数据时显示 --℃(currentTemp < 0 表示还没采到数)
+    if (m_temp[index])
+        m_temp[index]->setText(ui::formatTemp(d.currentTemp));
+    if (m_runtime[index])
+        m_runtime[index]->setText(ui::formatElapsed(d.startTime));
+    if (m_start[index]) {
+        m_start[index]->setEnabled(d.backendConnected && d.canStart && !d.backendBusy);
+        m_start[index]->setText(d.backendBusy ? QStringLiteral("执行中") : QStringLiteral("开始测试"));
+    }
+    if (QLabel *name = m_ui->contentArea->findChild<QLabel *>(QStringLiteral("cardName_%1").arg(index)))
+        name->setText(d.deviceId + (d.phase.isEmpty() ? QString() : QStringLiteral(" · ") + d.phase.toUpper()));
+}
+
+void OverviewView::renderChannels(int index)
+{
+    if (index < 0 || index >= m_cells.size())
+        return;
+
+    const StationData &d = m_store->station(index);
+    const int n = qMin(m_cells[index].size(), d.channels.size());
+
+    for (int c = 0; c < n; ++c) {
+        QFrame *cell = m_cells[index].at(c);
+        QLabel *value = m_cellValues[index].at(c);
+        if (!cell || !value)
+            continue;
+
+        const ChannelInfo &ch = d.channels.at(c);
+        // 第二行显示状态字:绿字 PASS / 红字 FAIL / 灰字 IDLE(配色仍由 QSS 按 state 决定)
+        // 概览卡片不放 hover 提示:鼠标划过 24 个格子会不停弹框,干扰观察
+        value->setText(QString::fromLatin1(stateWord(ch.state)));
+
+        const QString state = QString::fromLatin1(stateName(ch.state));
+        if (cell->property("state").toString() == state)
+            continue;
+
+        cell->setProperty("state", state);
+        // 值文字的颜色挂在父框的 state 上,两个都要重新 polish
+        cell->style()->unpolish(cell);
+        cell->style()->polish(cell);
+        value->style()->unpolish(value);
+        value->style()->polish(value);
+    }
+}
+
+void OverviewView::onChannelsChanged(int index)
+{
+    markDirty(index);
+}
+
+void OverviewView::onTemperatureChanged(int index)
+{
+    markDirty(index);
+}
+
+void OverviewView::onInfoChanged(int index)
+{
+    markDirty(index);
+}
+
+void OverviewView::markDirty(int index)
+{
+    if (index < 0 || index >= m_dirty.size())
+        return;
+    m_dirty[index] = true;
+    if (!m_flush.isActive())
+        m_flush.start();
+}
+
+void OverviewView::flushPending()
+{
+    for (int i = 0; i < m_dirty.size(); ++i) {
+        if (!m_dirty.at(i))
+            continue;
+        m_dirty[i] = false;
+        renderStation(i);
+    }
+}

+ 61 - 0
qt-client/src/overviewview.h

@@ -0,0 +1,61 @@
+#ifndef OVERVIEWVIEW_H
+#define OVERVIEWVIEW_H
+
+#include <QObject>
+#include <QTimer>
+#include <QVector>
+
+class QFrame;
+class QLabel;
+class PowerButton;
+class StationStore;
+
+namespace Ui {
+class MainWindow;
+}
+
+/**
+ * 多工位监控总览视图
+ * ------------------------------------------------------------------
+ * 把 StationStore 里的实时数据铺到四张工位卡上:
+ *   · 24 个通道格(PCU0/CPU1 各 12 路,格内显示通道名 + 温度 + 状态配色)
+ *   · 腔体温度 / 运行时间 + 开始测试按钮(任务号与测试模式已按需求移除)
+ * 各工位的高频信号按 200ms 合并刷新,避免每来一个采样就重排一次界面。
+ */
+class OverviewView : public QObject
+{
+    Q_OBJECT
+
+public:
+    OverviewView(Ui::MainWindow *ui, StationStore *store, QObject *parent = nullptr);
+
+signals:
+    void startTestRequested(int index); // 卡片右下角的「开始测试」圆钮
+
+private slots:
+    void onChannelsChanged(int index);
+    void onTemperatureChanged(int index);
+    void onInfoChanged(int index);
+    void flushPending();
+
+private:
+    void cacheWidgets();
+    void renderStation(int index);
+    void renderInfo(int index);
+    void renderChannels(int index);
+    void markDirty(int index);
+
+    Ui::MainWindow *m_ui;
+    StationStore *m_store;
+    QTimer m_flush;
+    QVector<bool> m_dirty;
+
+    QVector<QVector<QFrame *>> m_cells;         // [工位][通道] 格子外框
+    QVector<QVector<QLabel *>> m_cellValues;    // [工位][通道] 温度文字
+
+    QVector<QLabel *> m_temp;
+    QVector<QLabel *> m_runtime;
+    QVector<PowerButton *> m_start;             // [工位] 开始测试圆钮
+};
+
+#endif // OVERVIEWVIEW_H

+ 103 - 0
qt-client/src/powerbutton.cpp

@@ -0,0 +1,103 @@
+#include "powerbutton.h"
+
+#include <QEvent>
+#include <QLinearGradient>
+#include <QPainter>
+#include <QPaintEvent>
+
+PowerButton::PowerButton(QWidget *parent)
+    : QAbstractButton(parent)
+{
+    setCursor(Qt::PointingHandCursor);
+    setFocusPolicy(Qt::NoFocus);          // 键盘焦点交给页面里的输入框,按钮不抢
+    setAttribute(Qt::WA_Hover, true);     // 保证 enterEvent/leaveEvent 可靠触发
+    setToolTip(QStringLiteral("开始测试"));
+    setText(QStringLiteral("开始测试"));   // .ui 里没写 text,构造时给默认文案
+}
+
+QSize PowerButton::sizeHint() const
+{
+    return QSize(74, 64);
+}
+
+QSize PowerButton::minimumSizeHint() const
+{
+    return QSize(64, 58);
+}
+
+void PowerButton::enterEvent(QEvent *event)
+{
+    QAbstractButton::enterEvent(event);
+    update();
+}
+
+void PowerButton::leaveEvent(QEvent *event)
+{
+    QAbstractButton::leaveEvent(event);
+    update();
+}
+
+void PowerButton::paintEvent(QPaintEvent *)
+{
+    QPainter p(this);
+    p.setRenderHint(QPainter::Antialiasing, true);
+
+    // 圆钮:直径取最小边并留出文字的位置,水平居中、贴顶。
+    // 直径 46 + 下面一行 8.5pt 中文(实际需要约 20px 行高)⇒ 控件至少要有 70px 高,
+    // 66px 时最后一排字的下半截会被切掉,所以 infoRow 与按钮高度都按 74 / 72 给足。
+    const qreal d = qMin<qreal>(width() - 8.0, 46.0);
+    const QRectF circle((width() - d) / 2.0, 1.0, d, d);
+
+    QLinearGradient grad(circle.topLeft(), circle.bottomLeft());
+    if (!isEnabled()) {
+        grad.setColorAt(0, QColor("#d4dde6"));
+        grad.setColorAt(1, QColor("#bcc9d6"));
+    } else if (isDown()) {
+        grad.setColorAt(0, QColor("#255f92"));
+        grad.setColorAt(1, QColor("#1a4670"));
+    } else if (underMouse()) {
+        grad.setColorAt(0, QColor("#5aa9e2"));
+        grad.setColorAt(1, QColor("#2f7fc1"));
+    } else {
+        grad.setColorAt(0, QColor("#4a9ad9"));
+        grad.setColorAt(1, QColor("#2a6da8"));
+    }
+
+    p.setBrush(grad);
+    p.setPen(QPen(QColor(255, 255, 255, 70), 1));
+    p.drawEllipse(circle);
+
+    // 内侧一圈淡淡的高光,做出「微微亮着」的开机键质感
+    p.setBrush(Qt::NoBrush);
+    p.setPen(QPen(QColor(255, 255, 255, 40), 1));
+    p.drawEllipse(circle.adjusted(2.5, 2.5, -2.5, -2.5));
+
+    paintPowerGlyph(&p, circle);
+
+    // 下面一行「开始测试」:从圆下方 2px 起写到控件底
+    QFont f = font();
+    f.setPointSizeF(8.5);
+    f.setBold(false);
+    p.setFont(f);
+    p.setPen(isEnabled() ? (underMouse() ? QColor("#2f7fc1") : QColor("#41586f"))
+                         : QColor("#9aa8b6"));
+    const qreal textTop = circle.bottom() + 2.0;
+    const QRectF textRect(0, textTop, width(), height() - textTop);
+    p.drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter, text());
+}
+
+void PowerButton::paintPowerGlyph(QPainter *p, const QRectF &circle) const
+{
+    const qreal d = circle.width();
+    const qreal inset = d * 0.30;
+    const QRectF ring = circle.adjusted(inset, inset, -inset, -inset);
+
+    const QColor glyph = isEnabled() ? QColor(Qt::white) : QColor("#f2f6fa");
+    p->setBrush(Qt::NoBrush);
+    p->setPen(QPen(glyph, qMax(2.0, d * 0.055), Qt::SolidLine, Qt::RoundCap));
+    // 从 120° 起画 300°,顶部留 60° 缺口给竖杠
+    p->drawArc(ring, 120 * 16, 300 * 16);
+
+    const QPointF c = circle.center();
+    p->drawLine(QPointF(c.x(), ring.top() - d * 0.06), QPointF(c.x(), c.y() - d * 0.05));
+}

+ 32 - 0
qt-client/src/powerbutton.h

@@ -0,0 +1,32 @@
+#ifndef POWERBUTTON_H
+#define POWERBUTTON_H
+
+#include <QAbstractButton>
+
+/**
+ * 开机按钮样式的圆形按钮(总览卡右下角「开始测试」)
+ * ------------------------------------------------------------------
+ * 用 QAbstractButton 而不是 QPushButton + QSS:圆环、缺口、竖杠这三个元素
+ * 用样式表拼不出来,直接画更省事,hover / 按下状态也一并自己处理。
+ * 点击信号沿用 QAbstractButton::clicked(),调用方不用区分控件类型。
+ */
+class PowerButton : public QAbstractButton
+{
+    Q_OBJECT
+
+public:
+    explicit PowerButton(QWidget *parent = nullptr);
+
+    QSize sizeHint() const override;
+    QSize minimumSizeHint() const override;
+
+protected:
+    void paintEvent(QPaintEvent *event) override;
+    void enterEvent(QEvent *event) override;
+    void leaveEvent(QEvent *event) override;
+
+private:
+    void paintPowerGlyph(QPainter *p, const QRectF &circle) const;
+};
+
+#endif // POWERBUTTON_H

+ 6 - 0
qt-client/src/resources.qrc

@@ -0,0 +1,6 @@
+<RCC>
+    <qresource prefix="/">
+        <file>style/app.qss</file>
+        <file>assets/logo-mark.png</file>
+    </qresource>
+</RCC>

+ 100 - 0
qt-client/src/sltproto.cpp

@@ -0,0 +1,100 @@
+#include "sltproto.h"
+
+namespace slt {
+
+quint8 crc8(const QByteArray &data)
+{
+    quint8 crc = 0x00;
+
+    for (int k = 0; k < data.size(); ++k) {
+        crc ^= static_cast<quint8>(data.at(k));
+
+        for (int i = 0; i < 8; ++i) {
+            if (crc & 0x80)
+                crc = static_cast<quint8>((crc << 1) ^ 0x07);
+            else
+                crc = static_cast<quint8>(crc << 1);
+        }
+    }
+
+    return crc;
+}
+
+QByteArray buildFrame(quint8 cmd, const QByteArray &payload)
+{
+    QByteArray f;
+    f.append(static_cast<char>(kHdr0));
+    f.append(static_cast<char>(kHdr1));
+    f.append(static_cast<char>(cmd));
+    f.append(static_cast<char>(payload.size()));
+    f.append(payload);
+    f.append(static_cast<char>(crc8(f)));
+    return f;
+}
+
+QByteArray frameRequestChannels()
+{
+    return buildFrame(kCmdReqChannels);
+}
+
+QByteArray frameRequestCt7428()
+{
+    return buildFrame(kCmdReqCt7428);
+}
+
+QVector<Frame> FrameParser::feed(const QByteArray &bytes)
+{
+    QVector<Frame> frames;
+    m_buf.append(bytes);
+
+    // 一帧最少 2(头)+1(cmd)+1(len)+1(crc) = 5 字节
+    while (m_buf.size() >= 5) {
+        // ---- 1. 找帧头 AA 55 ----
+        int head = -1;
+        for (int i = 0; i + 1 < m_buf.size(); ++i) {
+            if (static_cast<quint8>(m_buf.at(i)) == kHdr0
+                && static_cast<quint8>(m_buf.at(i + 1)) == kHdr1) {
+                head = i;
+                break;
+            }
+        }
+
+        if (head < 0) {
+            // 全是噪声:只留最后一个字节(万一它是 AA,下一包才凑得到 55)
+            m_buf = m_buf.right(1);
+            break;
+        }
+        if (head > 0)
+            m_buf.remove(0, head);   // 丢掉帧头前面的垃圾
+
+        if (m_buf.size() < 5)
+            break;
+
+        // ---- 2. 按 LEN 算整帧长度 ----
+        const int len = static_cast<quint8>(m_buf.at(3));
+        const int total = 2 + 1 + 1 + len + 1;
+        if (m_buf.size() < total)
+            break;                   // 还没收完整,等下一包
+
+        // ---- 3. CRC 校验(帧头到 Payload 末,不含 CRC)----
+        const QByteArray body = m_buf.left(total - 1);
+        const quint8 recv = static_cast<quint8>(m_buf.at(total - 1));
+
+        if (crc8(body) == recv) {
+            Frame f;
+            f.cmd = static_cast<quint8>(m_buf.at(2));
+            f.payload = m_buf.mid(4, len);
+            frames.append(f);
+        }
+        // CRC 错的这一帧直接丢掉;无论对错都往前推进,避免卡死在同一段缓冲上
+        m_buf.remove(0, total);
+    }
+
+    // 防止设备失联后一直吐垃圾把缓冲撑爆
+    if (m_buf.size() > 4096)
+        m_buf.clear();
+
+    return frames;
+}
+
+} // namespace slt

+ 75 - 0
qt-client/src/sltproto.h

@@ -0,0 +1,75 @@
+#ifndef SLTPROTO_H
+#define SLTPROTO_H
+
+#include <QByteArray>
+#include <QVector>
+#include <QtGlobal>
+
+/**
+ * 24 路温控设备串口协议帧层
+ * ------------------------------------------------------------------
+ * 对应《PC 上位机 24路温度控制串口通信协议(v1.1)》,这里只做「字节 ⇄ 帧」,
+ * 不含任何界面逻辑:
+ *
+ *   通用帧  | AA 55 | CMD | LEN | Payload | CRC8 |
+ *   串口    115200 8N1
+ *   CRC     CRC-8/ATM:poly 0x07, init 0x00, xorout 0x00, MSB-first
+ *           计算范围 = 帧头起到 Payload 末字节(不含 CRC 本身)
+ *
+ * 温度是 1 字节整数摄氏度,0xFF = 无效哨兵(不是 255℃)。
+ */
+namespace slt {
+
+const quint8 kHdr0 = 0xAA;
+const quint8 kHdr1 = 0x55;
+
+// PC → MCU
+const quint8 kCmdReqChannels = 0x02;   // 请求 24 路 BMC 温度 → 0x82
+const quint8 kCmdReqCt7428   = 0x0D;   // 请求 CT7428 八路温度 → 0x8D
+
+// MCU → PC
+const quint8 kRespChannels = 0x82;     // 载荷 24 字节
+const quint8 kRespCt7428   = 0x8D;     // 载荷 8 字节
+
+// 应答帧的载荷长度
+const int kRespChannelsLen = 24;
+const int kRespCt7428Len   = 8;
+
+// 温度无效哨兵:读到它就是「没接 / 没数据」,界面显示 --
+const quint8 kTempInvalid = 0xFF;
+
+// CRC-8/ATM
+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
+QByteArray frameRequestCt7428();       // AA 55 0D 00 6E
+
+// 解析出来的一个完整帧(payload 不含帧头 / LEN / CRC)
+struct Frame {
+    quint8 cmd;
+    QByteArray payload;
+};
+
+/**
+ * 流式解析器:串口是字节流,一帧可能分几次到、也可能几帧粘在一起,
+ * 所以要把字节喂进来攒着,凑够校验通过再吐出去。
+ * 用法:QVector<Frame> frames = parser.feed(sp->readAll());
+ */
+class FrameParser
+{
+public:
+    void reset() { m_buf.clear(); }
+
+    QVector<Frame> feed(const QByteArray &bytes);
+
+private:
+    QByteArray m_buf;
+};
+
+} // namespace slt
+
+#endif // SLTPROTO_H

+ 291 - 0
qt-client/src/stationdata.cpp

@@ -0,0 +1,291 @@
+#include "stationdata.h"
+
+#include <QChar>
+#include <QJsonArray>
+#include <QtGlobal>
+
+QStringList channelNames()
+{
+    QStringList names;
+    const char *cpus[2] = {"CPU0", "CPU1"};
+    const char *suffix = "ABCDEFGHIJKL";
+    for (int c = 0; c < 2; ++c) {
+        for (int i = 0; i < 12; ++i) {
+            names << QStringLiteral("%1_CH%2")
+                         .arg(QString::fromLatin1(cpus[c]), QChar(QLatin1Char(suffix[i])));
+        }
+    }
+    return names;
+}
+
+StationStore::StationStore(int stationCount, QObject *parent)
+    : QObject(parent)
+    , m_stations(qMax(0, stationCount))
+{
+    // 运行时间走表:1s 一拍,只对已点「开始测试」的工位发 infoChanged 让界面重画
+    m_runtimeTimer.setInterval(1000);
+    connect(&m_runtimeTimer, &QTimer::timeout, this, &StationStore::runtimeTick);
+    m_runtimeTimer.start();
+}
+
+void StationStore::runtimeTick()
+{
+    for (int i = 0; i < m_stations.size(); ++i) {
+        if (m_stations.at(i).startTime.isValid())
+            touchRuntime(i);
+    }
+}
+
+const StationData &StationStore::station(int index) const
+{
+    static const StationData empty;
+    if (index < 0 || index >= m_stations.size())
+        return empty;
+    return m_stations.at(index);
+}
+
+void StationStore::initStation(int index, const StationData &data)
+{
+    if (index < 0 || index >= m_stations.size())
+        return;
+
+    m_stations[index] = data;
+    emit channelsChanged(index);
+    emit temperatureChanged(index);
+}
+
+void StationStore::appendLog(int index, const QString &line)
+{
+    if (index < 0 || index >= m_stations.size())
+        return;
+
+    // 只追加,永不裁剪:详情页切走再进来仍是完整历史
+    m_stations[index].logs.append(line);
+    emit logAppended(index, line);
+}
+
+void StationStore::setChannelState(int index, int channel, ChannelInfo::State state, double temperature)
+{
+    if (index < 0 || index >= m_stations.size())
+        return;
+
+    QVector<ChannelInfo> &channels = m_stations[index].channels;
+    if (channel < 0 || channel >= channels.size())
+        return;
+
+    ChannelInfo &ch = channels[channel];
+    ch.state = state;
+    ch.temperature = temperature;
+
+    // 通道刚装载时先落一个点,曲线不用等到下一次采样才有数据
+    if (temperature >= 0.0) {
+        ch.history.append(ch.temperature);
+        while (ch.history.size() > kTempHistorySize) {
+            ch.history.removeFirst();
+            ++ch.historyStart;
+        }
+    }
+
+    emit channelsChanged(index);
+}
+
+void StationStore::setChannelTemperature(int index, int channel, double temperature)
+{
+    if (index < 0 || index >= m_stations.size())
+        return;
+
+    QVector<ChannelInfo> &channels = m_stations[index].channels;
+    if (channel < 0 || channel >= channels.size())
+        return;
+
+    ChannelInfo &ch = channels[channel];
+    ch.temperature = temperature;
+
+    if (temperature >= 0.0) {
+        ch.history.append(temperature);
+        while (ch.history.size() > kTempHistorySize) {
+            ch.history.removeFirst();
+            ++ch.historyStart;
+        }
+    }
+
+    emit channelsChanged(index);
+}
+
+void StationStore::setCurrentTemp(int index, double temperature)
+{
+    if (index < 0 || index >= m_stations.size())
+        return;
+
+    StationData &d = m_stations[index];
+    d.currentTemp = temperature;
+
+    // 温控曲线:只保留最近 200 点,旧点从头部挤出去;start 记下队首的全局序号,
+    // 曲线横轴因此跟着数据一起向前滚动(可见宽度恒为 200 点)
+    d.tempHistory.append(temperature);
+    while (d.tempHistory.size() > kTempHistorySize) {
+        d.tempHistory.removeFirst();
+        ++d.tempHistoryStart;
+    }
+
+    emit temperatureChanged(index);
+}
+
+void StationStore::setPort(int index, const QString &port)
+{
+    if (index < 0 || index >= m_stations.size())
+        return;
+    if (m_stations.at(index).port == port)
+        return;
+
+    m_stations[index].port = port;
+    emit infoChanged(index);
+}
+
+void StationStore::setStartTime(int index, const QDateTime &start)
+{
+    if (index < 0 || index >= m_stations.size())
+        return;
+
+    m_stations[index].startTime = start;
+    emit infoChanged(index);
+}
+
+void StationStore::touchRuntime(int index)
+{
+    if (index < 0 || index >= m_stations.size())
+        return;
+
+    emit infoChanged(index);
+}
+
+void StationStore::setBackendLink(int index, bool connected, bool busy)
+{
+    if (index < 0 || index >= m_stations.size()) return;
+    m_stations[index].backendConnected = connected;
+    m_stations[index].backendBusy = busy;
+    emit infoChanged(index);
+}
+
+void StationStore::applyBackendState(int index, const QJsonObject &state)
+{
+    if (index < 0 || index >= m_stations.size()) return;
+    StationData &data = m_stations[index];
+    data.phase = state.value(QStringLiteral("phase")).toString();
+    data.runState = state.value(QStringLiteral("run_state")).toString();
+    data.power = state.value(QStringLiteral("power")).toString();
+    data.verdict = state.value(QStringLiteral("verdict")).toString();
+    data.verdictScope = state.value(QStringLiteral("verdict_scope")).toString();
+    data.canStart = state.value(QStringLiteral("can_start")).toBool(false);
+    const qint64 started = state.value(QStringLiteral("started_unix_ms")).toVariant().toLongLong();
+    data.startTime = started > 0 ? QDateTime::fromMSecsSinceEpoch(started) : QDateTime();
+    // Missing measurements remain missing; no temperatures/results are invented.
+    if (state.contains(QStringLiteral("chamber_temperature_c"))) {
+        const QJsonValue temperature = state.value(QStringLiteral("chamber_temperature_c"));
+        setCurrentTemp(index, temperature.isDouble() ? temperature.toDouble() : -1.0);
+    }
+    for (const QJsonValue &value : state.value(QStringLiteral("channels")).toArray()) {
+        const QJsonObject channel = value.toObject();
+        const QString name = channel.value(QStringLiteral("name")).toString();
+        for (int i = 0; i < data.channels.size(); ++i) {
+            if (data.channels[i].name != name) continue;
+            const QString verdict = channel.value(QStringLiteral("state")).toString();
+            const ChannelInfo::State result = verdict == QStringLiteral("pass") ? ChannelInfo::Pass
+                : verdict == QStringLiteral("fail") ? ChannelInfo::Fail : ChannelInfo::Idle;
+            const QJsonValue temperature = channel.value(QStringLiteral("temperature_c"));
+            setChannelState(index, i, result, temperature.isDouble() ? temperature.toDouble() : -1.0);
+            break;
+        }
+    }
+    emit infoChanged(index);
+}
+
+void StationStore::applyCtTemperatures(int index, const QByteArray &raw8)
+{
+    if (index < 0 || index >= m_stations.size())
+        return;
+
+    // 本板 CT7428 八路:跳过无效路(0xFF)后取算术平均,当作这一工位的「腔体温度」。
+    // 八路全无效(设备刚上电 / CPLD 失联时整组回 0xFF)→ 写 -1,界面显示 --℃。
+    double sum = 0.0;
+    int valid = 0;
+    for (int i = 0; i < raw8.size(); ++i) {
+        const quint8 b = static_cast<quint8>(raw8.at(i));
+        if (b == 0xFF)      // slt::kTempInvalid
+            continue;
+        sum += b;
+        ++valid;
+    }
+
+    setCurrentTemp(index, valid > 0 ? sum / valid : -1.0);
+}
+
+void StationStore::applyChannelTemperatures(int index, const QByteArray &raw24)
+{
+    if (index < 0 || index >= m_stations.size())
+        return;
+
+    QVector<ChannelInfo> &channels = m_stations[index].channels;
+    if (raw24.size() != channels.size())
+        return;                       // 应答长度不对(比如还夹着别的 CMD)就整帧丢
+
+    bool changed = false;
+    bool curveChanged = false;
+
+    for (int i = 0; i < channels.size(); ++i) {
+        const quint8 b = static_cast<quint8>(raw24.at(i));
+        ChannelInfo &ch = channels[i];
+
+        if (b == 0xFF) {
+            // Temperature validity and test result are independent.
+            if (ch.temperature >= 0.0) {
+                ch.temperature = -1.0;
+                changed = true;
+            }
+            continue;
+        }
+
+        // A temperature sample is never evidence of a passed memory test.
+        const double t = static_cast<double>(b);
+        if (qAbs(ch.temperature - t) > 0.05) {
+            ch.temperature = t;
+            changed = true;
+        }
+
+        // 每个轮询周期给这个通道落一个点:详情页曲线一路一段连续曲线靠它撑起来
+        ch.history.append(t);
+        while (ch.history.size() > kTempHistorySize) {
+            ch.history.removeFirst();
+            ++ch.historyStart;
+        }
+        curveChanged = true;
+    }
+
+    // 24 路逐格改会连发 24 次信号,这里合并成一次刷,避免界面被刷爆
+    if (changed || curveChanged)
+        emit channelsChanged(index);
+}
+
+int StationStore::countState(int index, ChannelInfo::State state) const{
+    int n = 0;
+    const QVector<ChannelInfo> &channels = station(index).channels;
+    for (const ChannelInfo &ch : channels) {
+        if (ch.state == state)
+            ++n;
+    }
+    return n;
+}
+
+int StationStore::loadedChannels(int index) const
+{
+    int count = 0;
+    for (const ChannelInfo &channel : station(index).channels)
+        if (channel.temperature >= 0.0 || channel.state != ChannelInfo::Idle)
+            ++count;
+    return count;
+}
+
+bool StationStore::hasFailure(int index) const
+{
+    return countState(index, ChannelInfo::Fail) > 0;
+}

+ 122 - 0
qt-client/src/stationdata.h

@@ -0,0 +1,122 @@
+#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) {}
+};
+
+// 一个工位的全部实时数据
+struct StationData {
+    QString deviceId;       // SLT-HT-001
+    QString taskId;         // TASK-20261021-001
+    QString product;        // DDR5 RDIMM
+    QString mode;           // 高温模式
+    QString port;           // 串口名 COM3
+    QString phase;
+    QString runState;
+    QString power;
+    QString verdict;
+    QString verdictScope;
+    bool backendConnected = false;
+    bool backendBusy = false;
+    bool canStart = false;
+
+    double targetTemp = 70.0;
+    double currentTemp = -1.0;     // <0 表示还没采到温度,界面显示 --℃
+
+    QVector<double> tempHistory;   // 最近 kTempHistorySize 个腔体温度,最老的在前
+    int tempHistoryStart = 0;      // tempHistory[0] 对应的全局采样序号(曲线横轴跟着它滚动)
+
+    QDateTime startTime;           // 无效 = 还没点过「开始测试」,界面显示 00:00:00
+
+    QVector<ChannelInfo> channels;      // 24 个
+    QStringList logs;                   // 完整日志,只增不减
+};
+
+// 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);
+    void setChannelState(int index, int channel, ChannelInfo::State state, double temperature = -1.0);
+    void setChannelTemperature(int index, int channel, double temperature);
+    void setCurrentTemp(int index, double temperature);
+    void setPort(int index, const QString &port);
+
+    // 点「开始测试」时把计时起点写进来;传无效 QDateTime 可以把它清回 00:00:00
+    void setStartTime(int index, const QDateTime &start);
+    // 只通知界面「这个工位的运行时间该重画了」,不改任何数据(给每秒走表的定时器用)
+    void touchRuntime(int index);
+    void applyBackendState(int index, const QJsonObject &state);
+    void setBackendLink(int index, bool connected, bool busy);
+
+    // ---- 真实设备数据入口(串口线程把原始字节送上来,换算规则全在这里) ----
+    // CT7428 八路(0x8D 的 8 字节):跳过 0xFF 后取平均 → 腔体温度;全无效 → -1(显示 --℃)
+    void applyCtTemperatures(int index, const QByteArray &raw8);
+    // 24 路 BMC 温度:0xFF → --℃;只更新温度,不推断或覆盖测试 PASS/FAIL
+    void applyChannelTemperatures(int index, const QByteArray &raw24);
+
+    // ---- 统计口径集中在模型里,界面不再各算一遍 ----
+    int countState(int index, ChannelInfo::State state) const;
+    int loadedChannels(int index) const;
+    bool hasFailure(int index) const;
+
+signals:
+    void logAppended(int index, const QString &line);
+    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

+ 413 - 0
qt-client/src/style/app.qss

@@ -0,0 +1,413 @@
+/* ============================================================================
+   DDR5 RDIMM SLT 上位机监控平台 —— 全局样式表
+   所有颜色 / 字号 / 圆角集中在此,改主题只改这个文件。
+   .ui 中通过动态属性 role / tone / pill 作为选择器钩子。
+   ============================================================================ */
+
+QWidget {
+    color: #20323f;
+}
+
+QWidget#centralwidget {
+    background: #e9edf3;
+}
+
+/* ---------------------------------------------------------------- 顶部标题栏 */
+QFrame[role="header"] {
+    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #334a67, stop:1 #273d57);
+    border-bottom: 1px solid #1f334a;
+}
+
+QLabel[role="logo"] {
+    background: transparent;
+    border: none;
+    padding: 0;
+}
+
+QLabel[role="appTitle"] {
+    color: #ffffff;
+    font-size: 23px;
+    font-weight: 700;
+}
+
+QFrame[role="headerSep"] {
+    background: rgba(255, 255, 255, 0.18);
+}
+
+QPushButton[role="win"] {
+    color: #cfe0f0;
+    background: transparent;
+    border: none;
+    font-size: 13px;
+}
+
+QPushButton[role="win"]:hover {
+    background: rgba(255, 255, 255, 0.14);
+    color: #ffffff;
+}
+
+QPushButton#btnWinClose:hover {
+    background: #e81123;
+    color: #ffffff;
+}
+
+/* ---------------------------------------------------------------- 内容区骨架 */
+QWidget[role="contentArea"] {
+    background: #e9edf3;
+}
+
+QFrame[role="breadcrumb"] {
+    background: #f7f9fb;
+    border-bottom: 1px solid #dbe2ea;
+}
+
+QLabel[role="breadcrumbLabel"] {
+    color: #7b8b9c;
+    font-size: 12px;
+}
+
+QLabel[role="pageTitle"] {
+    color: #16324a;
+}
+
+/* ---------------------------------------------------------------- 卡片外框 */
+QFrame[role="card"],
+QFrame[role="station"] {
+    background: #ffffff;
+    border: 1px solid #d9e0e8;
+    border-radius: 6px;
+}
+
+QFrame[role="vsep"] {
+    background: #e8eef4;
+}
+
+QFrame[role="hsep"] {
+    background: #e5ebf2;
+}
+
+/* ---------------------------------------------------------------- 工位卡片 */
+QLabel[role="cardIcon"] {
+    background: #1a7ec2;
+    color: #ffffff;
+    border-radius: 3px;
+    font-size: 15px;
+}
+
+QLabel[role="cardName"] {
+    /* 与卡头左侧图标方块同色 */
+    color: #1a7ec2;
+    font-size: 17px;
+    font-weight: 700;
+}
+
+/* 卡头右侧:串口名 + COM 连接状态灯 */
+/* 串口名:不要外框,只留等宽字(具体位置跟着信息行的上下两行居中) */
+QLabel[role="cardPort"] {
+    color: #3d5a75;
+    background: transparent;
+    border: none;
+    font-family: Consolas, "Courier New", monospace;
+    font-size: 14px;
+    padding: 0;
+}
+
+QLabel[role="comState"] {
+    border-radius: 9px;
+    font-size: 11px;
+    padding: 1px 7px;
+}
+
+QLabel[role="comState"][state="offline"] {
+    color: #8a97a5;
+    background: #f1f3f6;
+    border: 1px solid #dde3ea;
+}
+
+QLabel[role="comState"][state="connecting"] {
+    color: #a8720a;
+    background: #fdf5e4;
+    border: 1px solid #f0dcb0;
+}
+
+QLabel[role="comState"][state="online"] {
+    color: #1f8047;
+    background: #eaf7ef;
+    border: 1px solid #c4e4d0;
+    font-weight: 700;
+}
+
+/* 信息行里的状态灯:plain=true 时只要文字和状态点,不要圆角底色(写在各 state 规则之后) */
+QLabel[role="comState"][plain="true"] {
+    background: transparent;
+    border: none;
+    border-radius: 0;
+    padding: 0;
+}
+
+QPushButton[role="cardDetail"] {
+    color: #2f7fc1;
+    background: transparent;
+    border: none;
+    font-size: 12px;
+    font-weight: 600;
+    padding: 0 2px;
+}
+
+QPushButton[role="cardDetail"]:hover {
+    color: #155f9f;
+}
+
+QFrame[role="infoRow"] {
+    background: #f8fafc;
+    border: 1px solid #e8eef4;
+    border-radius: 4px;
+}
+
+QLabel[role="fieldLabel"] {
+    color: #8394a5;
+    font-size: 11px;
+}
+
+QLabel[role="fieldValue"] {
+    color: #1d3549;
+    font-size: 13px;
+}
+
+QLabel[role="fieldValueBold"] {
+    color: #12314c;
+    font-size: 16px;
+    font-weight: 700;
+}
+
+QLabel[role="fieldSub"] {
+    color: #98a5b3;
+    font-size: 11px;
+    padding-bottom: 1px;
+}
+
+/* 24 通道格子(总览卡与详情页共用 QFrame[role="chCell"],见下方详情页段落) */
+
+/* ---------------------------------------------------------------- 设备详情页 */
+QLabel[role="detailTitle"] {
+    color: #16324a;
+    font-size: 16px;
+    font-weight: 700;
+}
+
+/* 标题里的分隔符与工位号:静态控件,样式全部在 QSS,代码只填文本 */
+QLabel[role="detailTitleDot"] {
+    color: #b3bfcb;
+    font-size: 16px;
+}
+
+QLabel[role="detailDevice"] {
+    color: #2f7fc1;
+    font-size: 16px;
+    font-weight: 700;
+}
+
+QLabel[role="panelTitle"] {
+    color: #17324a;
+    font-size: 13px;
+    font-weight: 700;
+}
+
+/* 总览卡片的通道标题:与上方分隔线、下方格子各留 5px,避免文字贴边 */
+QLabel[role="ovChTitle"] {
+    color: #17324a;
+    font-size: 13px;
+    font-weight: 700;
+    padding: 5px 0 5px 0;
+}
+
+QPushButton[role="detailBack"] {
+    color: #2f7fc1;
+    background: #ffffff;
+    border: 1px solid #cdd7e1;
+    border-radius: 3px;
+    font-size: 12px;
+}
+
+QPushButton[role="detailBack"]:hover {
+    background: #eef4fa;
+    border-color: #b9cfe2;
+}
+
+/* 24 通道格子 */
+QFrame[role="chCell"] {
+    background: #ffffff;
+    border: 1px solid #dfe6ee;
+    border-radius: 4px;
+}
+
+QFrame[role="chCell"] QLabel[role="chCellName"] {
+    color: #7d8b9a;
+    font-size: 11px;
+}
+
+QFrame[role="chCell"] QLabel[role="chCellValue"] {
+    color: #12314c;
+    font-size: 12px;
+    font-weight: 700;
+}
+
+QFrame[role="chCell"][state="pass"] {
+    background: #f4fbf7;
+    border-color: #cfe8d9;
+}
+
+QFrame[role="chCell"][state="pass"] QLabel[role="chCellValue"] {
+    color: #1f8047;
+}
+
+/* 详情页:已装载通道统一蓝色(原先 PASS 用的蓝),不再区分 PASS / FAIL */
+QFrame[role="chCell"][state="loaded"] {
+    background: #f2f8fe;
+    border-color: #cfe1f3;
+}
+
+QFrame[role="chCell"][state="loaded"] QLabel[role="chCellValue"] {
+    color: #1e6aa8;
+}
+
+/* 当前温控曲线看的是这个通道:蓝框高亮(写在各 state 之后才盖得住它们的 border-color) */
+QFrame[role="chCell"][selected="true"] {
+    border: 2px solid #2f7fc1;
+}
+
+QFrame[role="chCell"][state="fail"] {
+    background: #fdf0ef;
+    border-color: #f3cdcb;
+}
+
+QFrame[role="chCell"][state="fail"] QLabel[role="chCellValue"] {
+    color: #c92f2f;
+}
+
+QFrame[role="chCell"][state="idle"] {
+    background: #f5f7f9;
+    border-color: #e4e9ef;
+}
+
+QFrame[role="chCell"][state="idle"] QLabel[role="chCellValue"] {
+    color: #98a5b3;
+}
+
+/* 页签 */
+QPushButton[role="detailTab"] {
+    color: #5d7086;
+    background: #f4f7fa;
+    border: 1px solid #e2e9f1;
+    border-top-left-radius: 4px;
+    border-top-right-radius: 4px;
+    font-size: 12px;
+    padding: 0 10px;
+}
+
+QPushButton[role="detailTab"]:hover {
+    color: #2f7fc1;
+}
+
+QPushButton[role="detailTab"][active="true"] {
+    color: #1a7ec2;
+    background: #ffffff;
+    border-color: #d9e0e8;
+    font-weight: 700;
+}
+
+QLabel[role="placeholder"] {
+    color: #98a5b3;
+    font-size: 12px;
+}
+
+/* 内存参数设置:三列表单(参数名 / 输入框 / 单位),列间用 1px 分隔线隔开 */
+QLabel[role="paramName"] {
+    color: #5d7086;
+    font-size: 12px;
+}
+
+QLineEdit[role="paramEdit"] {
+    background: #ffffff;
+    border: 1px solid #d7e0ea;
+    border-radius: 3px;
+    color: #33465a;
+    font-size: 12px;
+    padding: 0 8px;
+    selection-background-color: #cfe4f7;
+    selection-color: #16324a;
+}
+
+QLineEdit[role="paramEdit"]:focus {
+    border-color: #6ba6d8;
+}
+
+QCheckBox[role="paramCheck"] {
+    spacing: 0;
+}
+
+/* 参数列分隔线:比 vsep 略深,否则在浅灰底上几乎看不见 */
+QFrame[role="paramSep"] {
+    background: #dde6f0;
+}
+
+/* 内存参数页「确定」按钮(功能暂未接,样式先定) */
+QPushButton[role="paramSubmit"] {
+    color: #ffffff;
+    background: #2f7fc1;
+    border: 1px solid #2f7fc1;
+    border-radius: 4px;
+    font-size: 13px;
+    font-weight: 700;
+}
+
+QPushButton[role="paramSubmit"]:hover {
+    background: #2a72ad;
+    border-color: #2a72ad;
+}
+
+QPushButton[role="paramSubmit"]:pressed {
+    background: #256394;
+    border-color: #256394;
+}
+
+QPushButton[role="paramSubmit"]:disabled {
+    color: #ffffff;
+    background: #a9c4db;
+    border-color: #a9c4db;
+}
+
+QCheckBox[role="paramCheck"]::indicator {
+    width: 14px;
+    height: 14px;
+    border: 1px solid #cbd6e1;
+    border-radius: 2px;
+    background: #ffffff;
+}
+
+QCheckBox[role="paramCheck"]::indicator:checked {
+    border-color: #2f7fc1;
+    background: #2f7fc1;
+}
+
+/* 测试日志 */
+QPlainTextEdit[role="log"] {
+    background: #fbfcfd;
+    border: 1px solid #eef2f7;
+    border-radius: 4px;
+    color: #5d7086;
+    font-family: Consolas, "Courier New", monospace;
+    font-size: 11px;
+    padding: 4px;
+}
+
+QSizeGrip {
+    background: transparent;
+}
+
+QToolTip {
+    background: #17324a;
+    color: #ffffff;
+    border: 1px solid #2e557a;
+    padding: 4px 6px;
+}

+ 52 - 0
qt-client/src/uiformat.h

@@ -0,0 +1,52 @@
+#ifndef UIFORMAT_H
+#define UIFORMAT_H
+
+#include <QDateTime>
+#include <QLatin1Char>
+#include <QString>
+
+/**
+ * 界面文本工具(多个视图共用,避免各写一份)
+ * 注意:字号 / 颜色一律在 .ui + app.qss 里定义,这里只做纯文本格式化。
+ */
+namespace ui {
+
+// 图例小圆点 + 名称 + 计数,如 ● PASS 20
+inline QString legendHtml(const QString &text, int count, const QString &color)
+{
+    return QStringLiteral("<span style='color:%1;font-size:11px'>●</span>&nbsp;"
+                          "<span style='color:#5d7086'>%2</span>&nbsp;"
+                          "<b style='color:%1'>%3</b>")
+        .arg(color, text.toHtmlEscaped())
+        .arg(count);
+}
+
+// 运行时长 HH:mm:ss
+// start 无效 = 这个工位还没点过「开始测试」,统一显示 00:00:00
+inline QString formatElapsed(const QDateTime &start)
+{
+    if (!start.isValid())
+        return QStringLiteral("00:00:00");
+
+    qint64 secs = qMax<qint64>(0, start.secsTo(QDateTime::currentDateTime()));
+    const qint64 h = secs / 3600;
+    secs %= 3600;
+    const qint64 m = secs / 60;
+    const qint64 s = secs % 60;
+    return QStringLiteral("%1:%2:%3")
+        .arg(h, 2, 10, QLatin1Char('0'))
+        .arg(m, 2, 10, QLatin1Char('0'))
+        .arg(s, 2, 10, QLatin1Char('0'));
+}
+
+// 温度文本:还没采到数据(<0)时显示 --℃
+inline QString formatTemp(double celsius)
+{
+    if (celsius < 0.0)
+        return QStringLiteral("--℃");
+    return QStringLiteral("%1°C").arg(QString::number(celsius, 'f', 1));
+}
+
+} // namespace ui
+
+#endif // UIFORMAT_H

+ 432 - 0
qt-client/tests/qt_clean_probe.cpp

@@ -0,0 +1,432 @@
+// This harness instantiates the actual MainWindow and clicks its real buttons.
+// Default mode is read-only. Only --mode start invokes physical host controls.
+#include "mainwindow.h"
+#include "backendlink.h"
+#include "stationdata.h"
+#include "localplans.h"
+#include <QAbstractButton>
+#include <QApplication>
+#include <QCommandLineParser>
+#include <QDateTime>
+#include <QDir>
+#include <QFile>
+#include <QFontDatabase>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QLabel>
+#include <QLineEdit>
+#include <QPointer>
+#include <QPlainTextEdit>
+#include <QSaveFile>
+#include <QTemporaryDir>
+#include <QTimer>
+#include <QWebSocket>
+#include <QWebSocketServer>
+#include <functional>
+
+static bool writeJson(const QString &path, const QJsonObject &value)
+{
+    QSaveFile file(path);
+    const QByteArray bytes = QJsonDocument(value).toJson(QJsonDocument::Indented);
+    return file.open(QIODevice::WriteOnly) && file.write(bytes) == bytes.size() && file.commit();
+}
+
+class Fixture : public QObject
+{
+public:
+    QWebSocketServer server{QStringLiteral("Qt clean contract fixture"), QWebSocketServer::NonSecureMode};
+    QPointer<QWebSocket> socket;
+    int connections = 0;
+    int starts = 0;
+    int actions = 0;
+    bool duplicate = false;
+    bool unexpected = false;
+    bool correctParams = true;
+    bool disconnectTest = false;
+    bool silentMode = false;
+    bool runAmt = false;
+    bool amtResultsReady = false;
+    bool earlyAmtExit = false;
+    int amtLaunches = 0;
+    bool failAtEnd = false;
+    bool unexpectedBootMode = false;
+    bool changedBoot = false;
+    bool oldFailedSnapshotSent = false;
+    int uartReplays = 0;
+    QStringList methods;
+    QSet<QString> inputIds;
+    QJsonObject command;
+    QJsonArray events;
+    int step = -1;
+    qint64 started = 0;
+    quint64 sequence = 0;
+
+    explicit Fixture(bool testAmt = false) : runAmt(testAmt)
+    {
+        server.listen(QHostAddress::LocalHost, 0);
+        connect(&server, &QWebSocketServer::newConnection, this, [this] {
+            socket = server.nextPendingConnection();
+            ++connections;
+            QWebSocket *client = socket;
+            connect(client, &QWebSocket::textMessageReceived, this, [this](const QString &text) { receive(text); });
+            connect(client, &QWebSocket::disconnected, client, &QObject::deleteLater);
+            pushState();
+            if (silentMode) return; // Deliberately silent TCP peer: exercise client watchdog.
+            // A fresh socket starts from byte zero. BackendLink must suppress
+            // already displayed bytes and recover anything missed offline.
+            for (const QJsonValue &row : events) send(row.toObject());
+            ++uartReplays;
+        });
+    }
+    QString url() const { return QStringLiteral("ws://127.0.0.1:%1/ws?view=qt-clean").arg(server.serverPort()); }
+    void send(const QJsonObject &frame)
+    {
+        if (socket && socket->state() == QAbstractSocket::ConnectedState)
+            socket->sendTextMessage(QString::fromUtf8(QJsonDocument(frame).toJson(QJsonDocument::Compact)));
+    }
+    QJsonObject station() const
+    {
+        QString stage, phase = QStringLiteral("uefi"), action;
+        int cpu = 0;
+        if (step == 0 || step == 1) { stage = "uip1"; phase = "uip"; action = "continue_uip"; cpu = step; }
+        else if (step == 2 || step == 3) { stage = "amt"; phase = "amt"; action = runAmt ? "start_amt" : "skip_amt"; cpu = step - 2; }
+        else if (runAmt && (step == 4 || step == 5)) { stage = "amt"; phase = "amt"; action = "skip_amt"; cpu = step - 4; }
+        else if (step == (runAmt ? 6 : 4)) { stage = "uip2"; phase = "uefi"; action = "continue_uip"; }
+        else if (step >= (runAmt ? 7 : 5)) { stage = "uefi"; phase = "uefi"; action = "start_mt"; }
+        else { stage = "uefi"; phase = "uefi"; action = "start_mt"; }
+        const QJsonObject input{{"id", QStringLiteral("fixture-input-%1").arg(step)}, {"stage", stage},
+            {"cpu", cpu}, {"ready", true}, {"test_complete", amtResultsReady}, {"actions", QJsonArray{action}}};
+        return QJsonObject{{"station_id", "S1"}, {"connection", "online"}, {"power", "on"}, {"can_start", true},
+            {"phase", phase}, {"run_state", changedBoot || (failAtEnd && step >= 5)
+                || (step < 0 && command.value("state").toString() == "succeeded")
+                    ? "failed" : (step >= 0 ? "waiting_input" : "idle")},
+            {"started_unix_ms", QString::number(started)},
+            {"boot_id", changedBoot ? "fixture-boot-2" : (step >= 0 ? "fixture-boot-1" : "fixture-boot-0")},
+            {"verdict", failAtEnd && step >= 5 ? "fail" : "not_tested"},
+            {"input", input}, {"command", command},
+            {"channels", QJsonArray{QJsonObject{{"name", "CPU0_CHA"}, {"state", "unknown"}, {"temperature_c", 48.0}}}}};
+    }
+    QJsonObject state() const
+    {
+        return QJsonObject{{"version", "0.8.0-fixture"}, {"mode", "fixture"}, {"server_id", "qt-clean-fixture"},
+            {"stations", QJsonArray{station()}}};
+    }
+    void pushState() { send(QJsonObject{{"v", 1}, {"event", "state"}, {"result", state()}}); }
+    void log(const QString &message)
+    {
+        const QByteArray bytes = (message + QLatin1Char('\n')).toUtf8();
+        const quint64 first = sequence;
+        sequence += static_cast<quint64>(bytes.size());
+        const QJsonObject frame{{"v", 1}, {"event", "bios_uart"}, {"result", QJsonObject{
+            {"station_id", "S1"}, {"session_id", "fixture-uart-session"},
+            {"offset", QString::number(first)}, {"next_offset", QString::number(sequence)},
+            {"data_base64", QString::fromLatin1(bytes.toBase64())}}}};
+        events.append(frame);
+        send(frame);
+    }
+    void receive(const QString &text)
+    {
+        const QJsonObject request = QJsonDocument::fromJson(text.toUtf8()).object();
+        const QString method = request.value("method").toString();
+        const QJsonObject params = request.value("params").toObject();
+        methods << method;
+        auto respond = [this, request](const QJsonObject &result) {
+            send(QJsonObject{{"v", 1}, {"id", request.value("id")}, {"ok", true}, {"result", result}});
+        };
+        if (method == "GetState") {
+            if (step < 0 && command.value("state").toString() == "succeeded") oldFailedSnapshotSent = true;
+            respond(state()); return;
+        }
+        if (method == "GetCommand") { respond(command); return; }
+        if (method == "StartTest") {
+            ++starts;
+            command = QJsonObject{{"command_id", params.value("command_id")}, {"state", "queued"}, {"error", ""}};
+            // Reply succeeds before the asynchronously refreshed state. The old
+            // UEFI input must never finish the new client's local plan.
+            QTimer::singleShot(250, this, [this, respond] {
+                const qint64 confirmedStarted = QDateTime::currentMSecsSinceEpoch();
+                command.insert("state", "succeeded");
+                command.insert("result", QJsonObject{{"boot_id", "fixture-boot-1"},
+                    {"started_unix_ms", QString::number(confirmedStarted)}});
+                respond(command);
+                QTimer::singleShot(200, this, [this, confirmedStarted] {
+                    started = confirmedStarted;
+                    step = 0;
+                    log(QStringLiteral("Fixture: fresh BIOS boot confirmed"));
+                    pushState();
+                });
+            });
+            return;
+        }
+        if (method == "StageAction") {
+            ++actions;
+            const QString input = params.value("input_id").toString();
+            if (inputIds.contains(input)) duplicate = true;
+            inputIds.insert(input);
+            const QJsonObject memory = params.value("memory_params").toObject();
+            if (step < 2) correctParams = correctParams && memory.value("tCL").toInt() == 45;
+            if (step == (runAmt ? 6 : 4)) correctParams = correctParams && memory.isEmpty();
+            const QString action = params.value("action").toString();
+            if (action == "start_amt") ++amtLaunches;
+            if ((step == 2 || step == 3) && action != (runAmt ? "start_amt" : "skip_amt")) unexpected = true;
+            if (runAmt && (step == 4 || step == 5) && action == "skip_amt" && !amtResultsReady) earlyAmtExit = true;
+            command = QJsonObject{{"command_id", params.value("command_id")}, {"state", "running"}, {"error", ""}};
+            respond(command);
+            if (unexpectedBootMode && step == 0) {
+                // A new BIOS boot is observed while a submitted stage command
+                // remains running. Failure must not be hidden by either guard.
+                QTimer::singleShot(90, this, [this] {
+                    changedBoot = true;
+                    log(QStringLiteral("Fixture: unexpected BIOS restart during pending stage"));
+                    pushState();
+                });
+                return;
+            }
+            if (step == 0 && socket) {
+                disconnectTest = true;
+                socket->close();
+            }
+            QTimer::singleShot(90, this, [this] {
+                ++step;
+                command.insert("state", "succeeded");
+                log(QStringLiteral("Fixture: stage action %1 completed").arg(actions));
+                pushState();
+                if (runAmt && step == 4) {
+                    QTimer::singleShot(300, this, [this] {
+                        amtResultsReady = true;
+                        log(QStringLiteral("Fixture: actual AMT algorithm results completed"));
+                        pushState();
+                    });
+                }
+            });
+            return;
+        }
+        unexpected = true;
+        send(QJsonObject{{"v", 1}, {"id", request.value("id")}, {"ok", false},
+            {"error", QJsonObject{{"code", "UNEXPECTED_METHOD"}, {"message", method}}}});
+    }
+};
+
+int main(int argc, char **argv)
+{
+    QApplication app(argc, argv);
+    QCommandLineParser parser;
+    parser.addHelpOption();
+    parser.addOption({"mode", "read-only, start, fixture, fixture-amt, fixture-fail, fixture-unexpected-boot, fixture-silent. start physically starts/reboots one host.", "mode", "read-only"});
+    parser.addOption({"url", "Clean backend WebSocket URL", "url"});
+    parser.addOption({"report", "Write JSON verification evidence", "path", "qt-clean-probe.json"});
+    parser.addOption({"screenshot", "Write actual Qt window PNG", "path"});
+    parser.addOption({"station", "Station number 1..4", "number", "1"});
+    parser.addOption({"expect-phase", "Required final phase for a real Start", "phase", "uefi"});
+    parser.addOption({"timeout", "Maximum seconds", "seconds", "90"});
+    parser.process(app);
+    const QString mode = parser.value("mode");
+    if (mode != "read-only" && mode != "start" && mode != "fixture" && mode != "fixture-amt"
+        && mode != "fixture-fail" && mode != "fixture-unexpected-boot" && mode != "fixture-silent") return 2;
+    const int station = parser.value("station").toInt() - 1;
+    if (station < 0 || station > 3) return 2;
+    qputenv("STL_QT_DISABLE_SERIAL", "1");
+    if (!parser.value("url").isEmpty()) qputenv("STL_QT_BACKEND_URL", parser.value("url").toUtf8());
+    QFile style(":/style/app.qss");
+    if (style.open(QIODevice::ReadOnly)) app.setStyleSheet(QString::fromUtf8(style.readAll()));
+    const QStringList families = QFontDatabase().families();
+    for (const QString &family : QStringList{"Noto Sans CJK SC", "WenQuanYi Micro Hei", "DejaVu Sans"}) {
+        if (families.contains(family)) { app.setFont(QFont(family, 9)); break; }
+    }
+
+    QJsonObject checks;
+    QTemporaryDir selfTestDir;
+    const QByteArray oldPlans = qgetenv("STL_QT_PLANS_FILE");
+    qputenv("STL_QT_PLANS_FILE", selfTestDir.filePath("local-plans.json").toUtf8());
+    LocalPlans plans;
+    QString planError;
+    const bool saved = plans.saveMemoryParams(0, QJsonObject{{"tCL", 45}}, &planError);
+    const LocalPlans reloaded;
+    checks.insert("local_plan_saved_and_reloaded", saved && reloaded.memoryParams(0).value("tCL").toInt() == 45);
+    checks.insert("saved_plan_arms_uip_only_for_station", reloaded.plan(0).value("uip").toObject().value("apply_memory_params").toBool()
+        && reloaded.memoryParams(1).value("tCL").toInt() != 45);
+    if (oldPlans.isEmpty()) qunsetenv("STL_QT_PLANS_FILE"); else qputenv("STL_QT_PLANS_FILE", oldPlans);
+    StationStore probeStore(1);
+    StationData data;
+    for (const QString &name : channelNames()) data.channels.append(ChannelInfo(name, -1, ChannelInfo::Idle));
+    probeStore.initStation(0, data);
+    probeStore.applyChannelTemperatures(0, QByteArray(24, char(48)));
+    checks.insert("temperature_never_implies_pass", probeStore.countState(0, ChannelInfo::Pass) == 0
+        && probeStore.station(0).channels.first().temperature == 48.0);
+    probeStore.setChannelState(0, 0, ChannelInfo::Fail, 48);
+    probeStore.applyChannelTemperatures(0, QByteArray(24, char(0xff)));
+    checks.insert("missing_temperature_preserves_fail", probeStore.station(0).channels.first().state == ChannelInfo::Fail
+        && probeStore.station(0).channels.first().temperature < 0.0);
+
+    QTemporaryDir fixtureDir;
+    Fixture *fixture = nullptr;
+    if (mode.startsWith("fixture")) {
+        fixture = new Fixture(mode == "fixture-amt");
+        fixture->failAtEnd = mode == "fixture-fail";
+        fixture->unexpectedBootMode = mode == "fixture-unexpected-boot";
+        fixture->silentMode = mode == "fixture-silent";
+        if (!fixture->server.isListening()) return 2;
+        qputenv("STL_QT_BACKEND_URL", fixture->url().toUtf8());
+        qputenv("STL_QT_CONFIG_DIR", fixtureDir.path().toUtf8());
+        qputenv("STL_QT_PLANS_FILE", fixtureDir.filePath("qt-plans.json").toUtf8());
+        writeJson(fixtureDir.filePath("config.json"), QJsonObject{{"memoryParams", QJsonObject{{"tCL", 44}}},
+            {"qtPlan", QJsonObject{{"uip", QJsonObject{{"action", "continue_uip"}, {"apply_memory_params", false}}},
+            {"amt", QJsonObject{{"action", mode == "fixture-amt" ? "start_amt" : "skip_amt"}, {"exit_after", true}}},
+            {"uefi", QJsonObject{{"action", "hold"}}}}}});
+    }
+    MainWindow window;
+    window.resize(1920, 1080);
+    window.show();
+    BackendLink *backend = window.findChild<BackendLink *>();
+    if (!backend) return 2;
+    const qint64 begin = QDateTime::currentMSecsSinceEpoch();
+    QJsonArray states, phases;
+    QJsonObject latest;
+    int snapshots = 0;
+    int logs = 0;
+    bool clicked = false;
+    bool startedSuccessfully = false;
+    bool finished = false;
+    qint64 fixtureCompletedAt = 0;
+    QString failure;
+    QObject::connect(backend, &BackendLink::stationState, &app, [&](int index, const QJsonObject &state) {
+        if (index != station) return;
+        ++snapshots;
+        latest = state;
+        const QString phase = state.value("phase").toString();
+        if (phases.isEmpty() || phases.last().toString() != phase) phases.append(phase);
+        if (states.isEmpty() || states.last().toObject() != state) states.append(state);
+    });
+    QObject::connect(backend, &BackendLink::logLine, &app, [&](int index, const QString &) { if (index == station) ++logs; });
+    QObject::connect(backend, &BackendLink::commandFinished, &app,
+        [&](int index, const QString &method, bool success, const QString &error) {
+            if (index != station) return;
+            if (!success) failure = error.isEmpty() ? QStringLiteral("command failed") : error;
+            if (method == "StartTest" && success) startedSuccessfully = true;
+        });
+
+    if (fixture && mode != "fixture-silent") {
+        // Calling the real Start slot while offline must neither send nor start timing.
+        QMetaObject::invokeMethod(&window, "startTest", Qt::DirectConnection, Q_ARG(int, 0));
+        checks.insert("offline_start_does_not_start_timer", !window.store()->station(0).startTime.isValid() && fixture->starts == 0);
+        window.findChild<QAbstractButton *>("cardDetail_0")->click();
+        window.findChild<QLineEdit *>("paramEdit_0_2")->setText("45");
+        window.findChild<QLineEdit *>("paramEdit_0_0")->setText("1070");
+        window.findChild<QAbstractButton *>("btnParamSubmit")->click();
+        checks.insert("actual_form_save_is_local", LocalPlans().memoryParams(0).value("tCL").toInt() == 45 && fixture->methods.isEmpty());
+        window.findChild<QLineEdit *>("paramEdit_0_0")->setText("invalid");
+        window.findChild<QAbstractButton *>("btnParamSubmit")->click();
+        checks.insert("invalid_parameter_not_coerced_to_zero", LocalPlans().memoryParams(0).value("mem vdd").toInt() == 1070);
+        window.store()->appendLog(0, QStringLiteral("fixture-unique-live-log"));
+        window.findChild<QAbstractButton *>("btnBackMonitor")->click();
+        window.findChild<QAbstractButton *>("cardDetail_1")->click();
+        checks.insert("partial_plan_clears_other_station_form", window.findChild<QLineEdit *>("paramEdit_0_0")->text().isEmpty()
+            && window.findChild<QLineEdit *>("paramEdit_0_2")->text() == "44");
+        window.findChild<QAbstractButton *>("btnBackMonitor")->click();
+        window.findChild<QAbstractButton *>("cardDetail_0")->click();
+        checks.insert("detail_reopen_does_not_duplicate_live_log", window.findChild<QPlainTextEdit *>("detailLog")
+            ->toPlainText().count(QStringLiteral("fixture-unique-live-log")) == 1);
+        window.findChild<QAbstractButton *>("btnBackMonitor")->click();
+    }
+
+    auto complete = [&](const QString &reason) {
+        if (finished) return;
+        finished = true;
+        checks.insert("actual_mainwindow_created", true);
+        checks.insert("live_websocket_connected", backend->isConnected());
+        checks.insert("clean_station_snapshot_received", snapshots > 0);
+        checks.insert("no_command_error", failure.isEmpty());
+        if (mode != "read-only" && mode != "fixture-silent") {
+            checks.insert("actual_start_button_clicked", clicked);
+            checks.insert("fresh_bios_start_confirmed", startedSuccessfully
+                && latest.value("started_unix_ms").toVariant().toLongLong() >= begin);
+            checks.insert("fresh_boot_id_matches_command", !backend->bootId(station).isEmpty()
+                && latest.value("boot_id").toVariant().toString() == backend->bootId(station));
+            checks.insert("no_firmware_execution_failure", latest.value("run_state").toString() != "failed"
+                && latest.value("verdict").toString() != "fail");
+            checks.insert("expected_phase_reached", latest.value("phase").toString().compare(parser.value("expect-phase"), Qt::CaseInsensitive) == 0);
+            checks.insert("local_plan_finished_or_waiting", !backend->isBusy(station));
+        }
+        if (fixture && mode != "fixture-silent") {
+            checks.insert("old_failed_snapshot_after_start_ignored", fixture->oldFailedSnapshotSent && startedSuccessfully);
+            checks.insert("exactly_one_host_start", fixture->starts == 1);
+            checks.insert("all_expected_prompt_actions", fixture->actions == (fixture->runAmt ? 7 : 5));
+            checks.insert("no_duplicate_prompt_action", !fixture->duplicate);
+            checks.insert("only_clean_methods", !fixture->unexpected);
+            checks.insert("parameters_and_uip2_separation", fixture->correctParams);
+            checks.insert("reconnected_without_reboot_replay", fixture->disconnectTest && fixture->connections >= 2 && fixture->starts == 1);
+            checks.insert("unknown_channel_remains_idle", window.store()->station(0).channels.first().state == ChannelInfo::Idle);
+            checks.insert("raw_uart_replayed_after_reconnect", fixture->uartReplays >= 2);
+            checks.insert("missed_uart_bytes_displayed_once", window.store()->station(0).logs.join("\n")
+                .count(QStringLiteral("Fixture: stage action 1 completed")) == 1);
+            checks.insert("no_event_log_rpc", !fixture->methods.contains(QStringLiteral("ReadEventQueue")));
+            if (fixture->runAmt) {
+                checks.insert("amt_launched_once_per_cpu", fixture->amtLaunches == 2);
+                checks.insert("amt_exits_only_after_real_result", fixture->amtResultsReady && !fixture->earlyAmtExit);
+            }
+            if (fixture->unexpectedBootMode) {
+                checks.insert("unexpected_boot_failure_is_prompt", !failure.isEmpty()
+                    && reason != QStringLiteral("verification timeout")
+                    && QDateTime::currentMSecsSinceEpoch() - begin < 10000);
+                checks.insert("unexpected_boot_stopped_with_pending_stage", fixture->changedBoot
+                    && fixture->command.value("state").toString() == "running" && !backend->isBusy(station));
+            }
+        }
+        if (mode == "fixture-silent") {
+            checks.insert("silent_websocket_was_reconnected", fixture && fixture->connections >= 2);
+            checks.insert("state_received_after_reconnect", snapshots >= 2);
+            checks.insert("watchdog_never_issued_host_start", fixture && fixture->starts == 0);
+        }
+        if (!parser.value("screenshot").isEmpty())
+            checks.insert("screenshot_saved", window.grab().save(parser.value("screenshot")));
+        bool pass = reason.isEmpty();
+        for (auto i = checks.begin(); i != checks.end(); ++i) pass = pass && i.value().toBool();
+        QJsonArray methods;
+        if (fixture) for (const QString &method : fixture->methods) methods.append(method);
+        const QJsonObject report{{"pass", pass}, {"mode", mode}, {"reason", reason}, {"command_error", failure},
+            {"checks", checks}, {"url", backend->url()}, {"phase_history", phases}, {"snapshots", states},
+            {"snapshot_count", snapshots}, {"log_count", logs}, {"fixture_methods", methods},
+            {"command_boot_id", backend->bootId(station)}, {"elapsed_ms", QDateTime::currentMSecsSinceEpoch() - begin}};
+        const bool written = writeJson(parser.value("report"), report);
+        qInfo().noquote() << QJsonDocument(report).toJson(QJsonDocument::Compact);
+        app.exit(pass && written ? 0 : 1);
+    };
+    QTimer poll;
+    poll.setInterval(100);
+    QObject::connect(&poll, &QTimer::timeout, &app, [&] {
+        if (!failure.isEmpty()) { complete(failure); return; }
+        if (mode == "read-only" || mode == "fixture-silent") {
+            if (mode == "fixture-silent") {
+                if (fixture->connections >= 2 && snapshots >= 2) complete({});
+                return;
+            }
+            if (snapshots > 0 && QDateTime::currentMSecsSinceEpoch() - begin >= 3000) complete({});
+            return;
+        }
+        if (!clicked && snapshots > 0) {
+            QAbstractButton *button = window.findChild<QAbstractButton *>(QStringLiteral("startTest_%1").arg(station));
+            if (!button || !button->isEnabled()) return;
+            clicked = true;
+            button->click();
+            if (fixture) button->click(); // Duplicate immediate click must not issue a second StartTest.
+        }
+        if (clicked && startedSuccessfully && !backend->isBusy(station)
+            && latest.value("phase").toString().compare(parser.value("expect-phase"), Qt::CaseInsensitive) == 0) {
+            if (fixture) {
+                if (!fixtureCompletedAt) fixtureCompletedAt = QDateTime::currentMSecsSinceEpoch();
+                if (QDateTime::currentMSecsSinceEpoch() - fixtureCompletedAt < 2000) return;
+            }
+            complete({});
+        }
+    });
+    poll.start();
+    QTimer::singleShot(qMax(5, parser.value("timeout").toInt()) * 1000, &app,
+                      [&] { complete(QStringLiteral("verification timeout")); });
+    const int code = app.exec();
+    // These app-context lambdas capture locals declared after window; remove
+    // them before stack unwinding can destroy those captured variables.
+    QObject::disconnect(backend, nullptr, &app, nullptr);
+    delete fixture;
+    return code;
+}

+ 10 - 0
qt-client/tests/qt_clean_probe.pro

@@ -0,0 +1,10 @@
+QT += core gui widgets serialport websockets printsupport
+CONFIG += c++11 console
+CONFIG -= app_bundle
+TARGET = QtCleanProbe
+TEMPLATE = app
+INCLUDEPATH += $$PWD/../src $$PWD/../src/3rdparty/qcustomplot
+SOURCES += $$PWD/qt_clean_probe.cpp $$PWD/../src/mainwindow.cpp $$PWD/../src/overviewview.cpp $$PWD/../src/detailview.cpp $$PWD/../src/powerbutton.cpp $$PWD/../src/stationdata.cpp $$PWD/../src/localplans.cpp $$PWD/../src/backendlink.cpp $$PWD/../src/comworker.cpp $$PWD/../src/sltproto.cpp $$PWD/../src/comanager.cpp $$PWD/../src/3rdparty/qcustomplot/qcustomplot.cpp
+HEADERS += $$PWD/../src/mainwindow.h $$PWD/../src/overviewview.h $$PWD/../src/detailview.h $$PWD/../src/powerbutton.h $$PWD/../src/stationdata.h $$PWD/../src/localplans.h $$PWD/../src/backendlink.h $$PWD/../src/comworker.h $$PWD/../src/sltproto.h $$PWD/../src/comanager.h $$PWD/../src/3rdparty/qcustomplot/qcustomplot.h
+FORMS += $$PWD/../src/mainwindow.ui
+RESOURCES += $$PWD/../src/resources.qrc

Разница между файлами не показана из-за своего большого размера
+ 0 - 2868
reference/original-archive-manifest.json


+ 95 - 0
scripts/collect_live_evidence.py

@@ -0,0 +1,95 @@
+#!/usr/bin/env python3
+"""Collect actual API and console evidence after a Qt live run (read-only)."""
+import argparse
+import asyncio
+import json
+from pathlib import Path
+import re
+import shlex
+import subprocess
+
+import aiohttp
+
+
+async def rpc(ws, method, params):
+    await ws.send_json({'v': 1, 'id': method, 'method': method, 'params': params})
+    async with asyncio.timeout(20):
+        while True:
+            frame = await ws.receive_json()
+            if frame.get('id') == method:
+                if not frame.get('ok'):
+                    raise RuntimeError(str(frame.get('error')))
+                return frame['result']
+
+
+async def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument('--label', required=True)
+    parser.add_argument('--output-dir', default='evidence')
+    parser.add_argument('--host', default='192.168.2.79')
+    parser.add_argument('--expect-errhandle', action='store_true')
+    args = parser.parse_args()
+    if not re.fullmatch(r'[a-zA-Z0-9_.-]+', args.label):
+        raise SystemExit('Invalid evidence label')
+    output = Path(args.output_dir) / args.label
+    output.mkdir(parents=True, exist_ok=True)
+    collected = {}
+    async with aiohttp.ClientSession() as session:
+        async with session.ws_connect(f'http://{args.host}:8080/ws') as full:
+            for method, params in (
+                ('GetSystemInfo', {}),
+                ('GetStationControl', {'station_id': 'S1'}),
+                ('GetDiagnostic', {'station_id': 'S1'}),
+                ('GetQueue', {'station_id': 'S1', 'limit': 100}),
+            ):
+                collected[method] = await rpc(full, method, params)
+        async with session.ws_connect(f'http://{args.host}:8080/ws?view=qt-clean') as clean:
+            collected['GetState'] = await rpc(clean, 'GetState', {})
+    (output / 'api.json').write_text(json.dumps(collected, ensure_ascii=False, indent=2) + '\n')
+    session_id = collected['GetDiagnostic']['session_id']
+    if not re.fullmatch(r'D-[a-zA-Z0-9_-]+', session_id):
+        raise RuntimeError('Unexpected diagnostic session identifier')
+    for name in ('sol.raw', 'events.jsonl', 'session.json'):
+        remote = f'/home/user/XJKJ-STL/data/diagnostics/S1/{session_id}/{name}'
+        with (output / name).open('wb') as target:
+            subprocess.run(['ssh', '-T', '-o', 'BatchMode=yes', f'user@{args.host}',
+                            'sudo -n cat ' + shlex.quote(remote)],
+                           stdout=target, stderr=subprocess.PIPE, check=True, timeout=30)
+    raw = (output / 'sol.raw').read_bytes().decode('utf-8', 'replace')
+    plain = re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', raw)
+    lines = plain.splitlines()
+    excerpts = []
+    for i, line in enumerate(lines):
+        if ('errhandle' in line.lower() or 'Issue WARM RESET!' in line
+                or '[SYS_BIOS]Version:' in line or 'MRC_STATUS_RESET_REQUIRED' in line):
+            excerpts.append({'line': i + 1, 'text': line[:500], 'following': lines[i + 1:i + 4]})
+    cpus = sorted({int(match.group(1)) for match in re.finditer(
+        r'\[([01])\][^\r\n]*User input command is\s+errhandle disable', plain)})
+    state = next(x for x in collected['GetState']['stations'] if x['station_id'] == 'S1')
+    fw = collected['GetStationControl']['firmware']
+    start = next(x for x in collected['GetQueue']['items']
+                 if x['method'] == 'QtStartTest' and x['state'] == 'succeeded')
+    checks = {
+        'final_uefi_input_ready': state['input']['ready'] and state['input']['stage'] == 'uefi',
+        'start_matches_current_boot': start['result']['boot_id'] == state['boot_id'],
+        'no_false_memory_pass': state['verdict'] != 'pass',
+    }
+    if args.expect_errhandle:
+        checks['both_cpu_errhandle_disable_echoed'] = cpus == [0, 1]
+    summary = {
+        'label': args.label, 'system': collected['GetSystemInfo'],
+        'checks': checks, 'passed': all(checks.values()),
+        'memory_test': 'NOT_TESTED', 'session_id': session_id,
+        'boot_id': state['boot_id'], 'boot_sequence': fw['boot_sequence'],
+        'start': start['result'], 'errhandle_disable_cpu_ids': cpus,
+        'last_uip_apply': collected['GetStationControl']['last_uip_apply'],
+        'excerpts': excerpts,
+    }
+    (output / 'summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n')
+    print(json.dumps({k: v for k, v in summary.items()
+                      if k not in ('last_uip_apply', 'excerpts')}, ensure_ascii=False, indent=2))
+    return 0 if summary['passed'] else 1
+
+
+if __name__ == '__main__':
+    raise SystemExit(asyncio.run(main()))

+ 86 - 0
scripts/deploy_qt_release.py

@@ -0,0 +1,86 @@
+#!/usr/bin/env python3
+"""Deploy an already-built Qt-clean candidate, preserving the former container."""
+import argparse
+import datetime
+import json
+import os
+from pathlib import Path
+import subprocess
+import tarfile
+import time
+
+
+def run(argv, **kwargs):
+    return subprocess.run(argv, check=True, text=True, capture_output=True, **kwargs).stdout.strip()
+
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument('--image', required=True)
+    parser.add_argument('--release', required=True)
+    args = parser.parse_args()
+    release = Path(args.release).resolve()
+    production = Path('/home/user/XJKJ-STL')
+    evidence = release / 'evidence'
+    evidence.mkdir(parents=True, exist_ok=True)
+    container = 'xjkj-stl-backend'
+    previous = json.loads(run(['docker', 'inspect', container]))[0]
+    stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
+    saved_name = 'xjkj-stl-backend-before-qt-' + stamp.lower()
+    backup = production.parent / 'XJKJ-STL-backups' / ('before-qt-' + stamp)
+    backup.mkdir(parents=True)
+    private = release / '.runtime.env'
+    # Preserve the existing authorized runtime credentials without displaying them.
+    values = [value for value in previous['Config']['Env']
+              if value.split('=', 1)[0].startswith('STL_')
+              and not value.startswith('STL_BUILD_COMMIT=')]
+    private.write_text('\n'.join(values) + '\n')
+    private.chmod(0o600)
+    report = {'started_utc': stamp, 'image': args.image,
+              'previous_image': previous['Config']['Image'],
+              'previous_container': saved_name, 'backup': str(backup),
+              'original_source_directory': str(production), 'passed': False}
+    renamed = False
+    try:
+        run(['docker', 'stop', '--time', '120', container])
+        with tarfile.open(backup / 'config-data.tar.gz', 'w:gz') as archive:
+            for name in ('config', 'data'):
+                archive.add(production / name, arcname=name)
+        run(['docker', 'rename', container, saved_name])
+        renamed = True
+        run(['docker', 'run', '-d', '--name', container, '--restart', 'unless-stopped',
+             '--stop-timeout', '120', '--network', 'host', '--env-file', str(private),
+             '-v', str(production / 'config') + ':/app/config:ro',
+             '-v', str(production / 'data') + ':/app/data',
+             args.image, 'python3', '-m', 'stl_backend.server',
+             '--config', 'config/station0-live.json', '--listen', '0.0.0.0:50051',
+             '--web-listen', '0.0.0.0:8080', '--data-dir', '/app/data'])
+        for _ in range(25):
+            p = subprocess.run(['docker', 'exec', container, 'python3', '-c',
+                                "import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/', timeout=2); assert r.status == 200"],
+                               capture_output=True, text=True)
+            if p.returncode == 0:
+                report['passed'] = True
+                break
+            time.sleep(1)
+        if not report['passed']:
+            raise RuntimeError('Candidate did not become HTTP-ready')
+        report['container_id'] = run(['docker', 'inspect', '--format', '{{.Id}}', container])
+        report['runtime_version'] = run(['docker', 'exec', container, 'python3', '-c',
+                                         'import stl_backend; print(stl_backend.__version__)'])
+    except Exception as exc:
+        report['error'] = str(exc)
+        if renamed:
+            subprocess.run(['docker', 'rm', '-f', container], capture_output=True)
+            run(['docker', 'rename', saved_name, container])
+        run(['docker', 'start', container])
+        report['rolled_back'] = True
+        raise
+    finally:
+        private.unlink(missing_ok=True)
+        (evidence / 'deployment.json').write_text(json.dumps(report, indent=2) + '\n')
+        print(json.dumps(report, indent=2), flush=True)
+
+
+if __name__ == '__main__':
+    main()

+ 0 - 89
scripts/explore_firmware_uip.py

@@ -1,89 +0,0 @@
-#!/usr/bin/env python3
-"""Capture SOL evidence without power changes, command guesses or takeover.
-
-Run from an installed checkout. A successful capture only proves that a SOL
-session was opened; it does not validate any UIP, RMT, AMT or UEFI command.
-"""
-from __future__ import annotations
-
-import argparse
-import asyncio
-import json
-from datetime import datetime, timezone
-from pathlib import Path
-import sys
-
-from stl_backend import __version__
-from stl_backend.devices.base import DeviceError
-from stl_backend.devices.hardware import HardwareDevice
-
-
-def utc_now() -> str:
-    return datetime.now(timezone.utc).isoformat()
-
-
-async def capture(args: argparse.Namespace) -> int:
-    directory = args.output / datetime.now(timezone.utc).strftime("sol-%Y%m%dT%H%M%S-%fZ")
-    directory.mkdir(parents=True, exist_ok=False)
-    record = {
-        "backend_version": __version__, "host": args.host, "user": args.user,
-        "cipher_suite": args.cipher, "started_at": utc_now(),
-        "requested_duration_s": args.duration, "status": "connecting",
-        "raw_bytes": 0, "commands_sent": [], "power_commands_sent": [],
-        "firmware_commands_verified": False,
-    }
-    helper = Path(__file__).resolve().parent.parent / "native" / "stl_sol_bridge.py"
-    device = HardwareDevice({"bmc": {
-        "host": args.host, "user": args.user, "password_env": args.password_env,
-        "cipher_suite": args.cipher, "sol_timeout_s": 25,
-        "sol_helper_argv": [sys.executable, str(helper)],
-    }})
-    result = 0
-    try:
-        with (directory / "sol.raw").open("wb") as raw:
-            await device.sol_start()
-            record["connected_at"] = utc_now()
-            try:
-                async with asyncio.timeout(args.duration):
-                    async for chunk in device.sol_read():
-                        raw.write(chunk)
-                        raw.flush()
-                        record["raw_bytes"] += len(chunk)
-            except TimeoutError:
-                # The requested observation period ended normally.
-                pass
-            record["status"] = "capture_complete"
-    except (DeviceError, OSError) as exc:
-        record.update(status="capture_failed", error=str(exc))
-        result = 1
-    except asyncio.CancelledError:
-        record["status"] = "interrupted"
-        raise
-    finally:
-        await device.close()
-        record["finished_at"] = utc_now()
-        (directory / "capture.json").write_text(
-            json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
-        print(json.dumps({"directory": str(directory), **record}, ensure_ascii=False))
-    return result
-
-
-def main() -> int:
-    parser = argparse.ArgumentParser(description="被动捕获 SOL:不修改电源、不发送 BIOS 命令、不抢占会话")
-    parser.add_argument("--host", default="192.168.0.100")
-    parser.add_argument("--user", default="ADMIN")
-    parser.add_argument("--cipher", type=int, default=17)
-    parser.add_argument("--password-env", default="STL_BMC_S1_PASSWORD")
-    parser.add_argument("--duration", type=float, default=30)
-    parser.add_argument("--output", type=Path, default=Path("data/evidence"))
-    args = parser.parse_args()
-    if not 1 <= args.duration <= 3600:
-        parser.error("--duration 必须在 1~3600 秒内")
-    try:
-        return asyncio.run(capture(args))
-    except KeyboardInterrupt:
-        return 130
-
-
-if __name__ == "__main__":
-    raise SystemExit(main())

Разница между файлами не показана из-за своего большого размера
+ 299 - 0
scripts/generate_api_reference.py


+ 2 - 2
scripts/package_delivery.py

@@ -91,8 +91,8 @@ def source_files() -> list[tuple[str, bytes, int]]:
 
 
 def evidence_files(data_dir: Path, extra_dirs: list[Path]):
-    roots = [ROOT / "docs/hardware-evidence", data_dir / "evidence",
-             data_dir / "runs", data_dir / "artifacts", *extra_dirs]
+    roots = [data_dir / "evidence",
+             data_dir / "runs", data_dir / "artifacts", data_dir / "diagnostics", *extra_dirs]
     files, skipped, seen = [], [], set()
     for index, folder in enumerate(roots):
         if not folder.is_dir():

+ 44 - 0
scripts/probe_bmc.py

@@ -0,0 +1,44 @@
+#!/usr/bin/env python3
+"""Run inside the deployed container; secrets remain in its environment."""
+import argparse
+import datetime
+import json
+import os
+import subprocess
+import time
+
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument('--power-off', action='store_true')
+    parser.add_argument('--output')
+    args = parser.parse_args()
+    secret = os.environ.get('STL_BMC_S1_PASSWORD')
+    if not secret:
+        raise SystemExit('STL_BMC_S1_PASSWORD is not available')
+    child_env = dict(os.environ, IPMI_PASSWORD=secret)
+    prefix = ['ipmitool', '-I', 'lanplus', '-H', '192.168.0.100', '-U', 'ADMIN',
+              '-E', '-C', '17', '-N', '2', '-R', '2']
+    report = {'observed_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
+              'host': '192.168.0.100', 'checks': []}
+    commands = [['mc', 'info'], ['chassis', 'power', 'status'], ['sol', 'info', '1']]
+    if args.power_off:
+        commands = [['chassis', 'power', 'status'], ['chassis', 'power', 'off']]
+    for command in commands:
+        begin = time.monotonic()
+        p = subprocess.run(prefix + command, env=child_env, capture_output=True,
+                           text=True, timeout=30)
+        report['checks'].append({'command': ' '.join(command), 'returncode': p.returncode,
+                                 'output': (p.stdout + p.stderr).replace(secret, '[redacted]').strip(),
+                                 'elapsed_s': round(time.monotonic()-begin, 3)})
+    report['passed'] = all(x['returncode'] == 0 for x in report['checks'])
+    rendered = json.dumps(report, ensure_ascii=False, indent=2)
+    print(rendered)
+    if args.output:
+        from pathlib import Path
+        Path(args.output).write_text(rendered + '\n')
+    return 0 if report['passed'] else 1
+
+
+if __name__ == '__main__':
+    raise SystemExit(main())

+ 74 - 0
scripts/probe_ipmi_sol.py

@@ -0,0 +1,74 @@
+#!/usr/bin/env python3
+"""Bounded IPMI SOL roundtrip at an independently verified UEFI Shell prompt."""
+import asyncio
+import datetime
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+
+
+async def main():
+    env = os.environ.copy()
+    env.update(STL_SOL_HOST='192.168.0.100', STL_SOL_USER='ADMIN',
+               STL_SOL_PASSWORD=env['STL_BMC_S1_PASSWORD'], STL_SOL_CIPHER_SUITE='17')
+    folder = Path('/app/data/evidence/qt-clean-080')
+    folder.mkdir(parents=True, exist_ok=True)
+    report = {'observed_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
+              'transport': 'ipmi_sol', 'input_hex': '0d', 'statuses': [],
+              'ready': False, 'passed': False}
+    proc = await asyncio.create_subprocess_exec('python3', 'native/stl_sol_bridge.py',
+        env=env, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
+        stderr=asyncio.subprocess.PIPE)
+    stdout_task = asyncio.create_task(proc.stdout.read())
+    try:
+        deadline = asyncio.get_running_loop().time() + 22
+        while asyncio.get_running_loop().time() < deadline:
+            line = await asyncio.wait_for(proc.stderr.readline(), 22)
+            if not line:
+                break
+            status = json.loads(line)
+            report['statuses'].append(status)
+            if status.get('event') == 'ready':
+                report['ready'] = True
+                break
+            if status.get('event') == 'error':
+                break
+        if report['ready']:
+            proc.stdin.write(b'\r')
+            await proc.stdin.drain()
+            await asyncio.sleep(3)
+        proc.stdin.close()
+        try:
+            await asyncio.wait_for(proc.wait(), 5)
+        except asyncio.TimeoutError:
+            proc.terminate()
+            await asyncio.wait_for(proc.wait(), 5)
+        raw = await stdout_task
+        (folder / 'ipmi-sol-roundtrip.raw').write_bytes(raw)
+        text = re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', raw.decode('utf-8', 'replace'))
+        report['bytes_received'] = len(raw)
+        report['shell_prompt_seen'] = bool(re.search(r'(?:Shell|FS\d+:[^\r\n>]*)>', text, re.I))
+        report['output_excerpt'] = text[-1500:]
+        report['passed'] = report['ready'] and report['shell_prompt_seen']
+    except Exception as exc:
+        report['error'] = type(exc).__name__ + ': ' + str(exc)
+    finally:
+        if proc.returncode is None:
+            proc.terminate()
+            await proc.wait()
+        if report['ready']:
+            child_env = dict(env, IPMI_PASSWORD=env['STL_SOL_PASSWORD'])
+            result = subprocess.run(['ipmitool', '-I', 'lanplus', '-H', env['STL_SOL_HOST'],
+                '-U', env['STL_SOL_USER'], '-E', '-C', '17', 'sol', 'deactivate'],
+                env=child_env, capture_output=True, text=True, timeout=15)
+            report['cleanup_returncode'] = result.returncode
+        rendered = json.dumps(report, ensure_ascii=False, indent=2)
+        (folder / 'ipmi-sol-roundtrip.json').write_text(rendered + '\n')
+        print(rendered)
+    return 0 if report['passed'] else 1
+
+
+if __name__ == '__main__':
+    raise SystemExit(asyncio.run(main()))

+ 33 - 0
scripts/run_qt_fixtures.py

@@ -0,0 +1,33 @@
+#!/usr/bin/env python3
+import json
+import os
+from pathlib import Path
+import subprocess
+
+release = Path('/home/user/XJKJ-STL-qt-clean-0.8.0')
+binary = release / 'qt-client/build-probe/QtCleanProbe'
+evidence = release / 'evidence'
+env = dict(os.environ, QT_QPA_PLATFORM='offscreen')
+env.pop('LD_LIBRARY_PATH', None)
+summary = []
+for mode in ['fixture', 'fixture-amt', 'fixture-fail', 'fixture-unexpected-boot']:
+    report = evidence / ('qt-' + mode + '.json')
+    with (evidence / ('qt-' + mode + '.log')).open('w') as out:
+        p = subprocess.run([str(binary), '--mode', mode, '--report', str(report),
+            '--screenshot', str(evidence / ('qt-' + mode + '.png')), '--timeout', '45'],
+            env=env, stdout=out, stderr=subprocess.STDOUT, timeout=60)
+    data = json.loads(report.read_text()) if report.exists() else {}
+    negative = mode in ('fixture-fail', 'fixture-unexpected-boot')
+    passed = p.returncode == (1 if negative else 0) and data.get('pass') is not negative
+    if negative:
+        passed = passed and data.get('checks', {}).get('no_firmware_execution_failure') is False
+    if mode == 'fixture-unexpected-boot':
+        passed = passed and data.get('checks', {}).get('unexpected_boot_failure_is_prompt') is True
+        passed = passed and data.get('checks', {}).get('unexpected_boot_stopped_with_pending_stage') is True
+    row = {'mode': mode, 'exit_code': p.returncode, 'expected_negative': negative,
+           'passed': passed, 'checks': len(data.get('checks', {})),
+           'false_checks': [key for key, value in data.get('checks', {}).items() if value is False]}
+    summary.append(row)
+    print(json.dumps(row), flush=True)
+(evidence / 'qt-fixtures-summary.json').write_text(json.dumps(summary, indent=2) + '\n')
+raise SystemExit(0 if all(row['passed'] for row in summary) else 1)

Разница между файлами не показана из-за своего большого размера
+ 703 - 37
scripts/test_web_browser.mjs


+ 112 - 0
scripts/test_web_command_recovery.mjs

@@ -0,0 +1,112 @@
+// Exercise the actual app command/queue callbacks with a tiny deterministic DOM.
+import assert from 'node:assert/strict';
+import {readFile} from 'node:fs/promises';
+import vm from 'node:vm';
+
+const source = await readFile(new URL('../src/stl_backend/web/app.js', import.meta.url), 'utf8');
+function fixture() {
+  const elements = new Map(), calls = [];
+  let services, handler;
+  function element(id) {
+    if (!elements.has(id)) {
+      const classes = new Set();
+      elements.set(id, {value:'', textContent:'', innerHTML:'', dataset:{}, disabled:false,
+        classList:{add:value=>classes.add(value),remove:value=>classes.delete(value),contains:value=>classes.has(value),
+          toggle:(value,yes)=>yes?classes.add(value):classes.delete(value)},
+        addEventListener() {}, querySelectorAll:()=>[]});
+    }
+    return elements.get(id);
+  }
+  const window = new EventTarget();
+  Object.assign(window, {
+    stlTransport:{call:async(method,params)=>{calls.push({method,params});return handler(method,params);}},
+    stlFirmware:{init:api=>{services=api;},snapshot:()=>({}),capabilities:()=>({}),render(){},refresh:async()=>{}},
+    stlBootPlan:{init(){}}, stlAmt:{init(){}}, stlDimms:{init(){},render(){}}, stlStages:{init(){},render(){}},
+    stlNavigation:{updateStations(){}},
+  });
+  handler = async method => {
+    if (method==='GetSystemInfo')return {mode:'simulated',version:'0.7.1'};
+    if (method==='ListStations')return {stations:[]};
+    if (method==='GetQueue')return {items:[]};
+    if (method==='ReadEventQueue')return {events:[],next_after_sequence:'0'};
+    if (method==='GetDiagnostic')return {state:'closed'};
+    throw new Error('Unexpected API call '+method);
+  };
+  const baseHandler=handler;
+  vm.runInNewContext(source, {window,document:{getElementById:element,querySelectorAll:()=>[]},
+    TextDecoder,TextEncoder,CustomEvent,setTimeout,clearTimeout,setInterval:()=>0,URL,Blob,atob,btoa});
+  return {services,calls,element,window,setHandler:fn=>{handler=fn;},baseHandler,
+    refreshQueue:()=>element('btn-refresh-commands').onclick()};
+}
+const businessError=(code,message=code)=>Object.assign(new Error(message),{code});
+const f=fixture();
+const lost=businessError('DISCONNECTED','socket closed');
+let accepted=[];
+f.setHandler(async(method,params)=>{
+  if(method==='EnqueueCommand'){accepted.push({...params});throw lost;}
+  if(method==='GetQueueItem')throw businessError('NOT_FOUND');
+  return f.baseHandler(method,params);
+});
+const first=f.services.command('StationPower',{station_id:'S1',action:'host_reset'},'复位 S1');
+const second=f.services.command('StationPower',{station_id:'S2',action:'host_reset'},'复位 S2');
+let firstError,secondError;
+await assert.rejects(first,error=>{firstError=error;return error.code==='DISCONNECTED'&&error.message.includes('提交结果待核对');});
+await assert.rejects(second,error=>{secondError=error;return error.code==='DISCONNECTED';});
+assert.equal(firstError.command_id,accepted[0].command_id);
+assert.equal(secondError.command_id,accepted[1].command_id);
+assert.notEqual(firstError.command_id,secondError.command_id);
+assert.ok(!secondError.message.includes(firstError.command_id),'Each failed write keeps its own id and message');
+assert.equal(lost.message,'socket closed','Shared disconnect reasons are not mutated');
+
+await f.refreshQueue();
+assert.ok(f.calls.some(call=>call.method==='GetQueueItem'&&call.params.command_id===firstError.command_id));
+assert.ok(f.calls.some(call=>call.method==='GetQueueItem'&&call.params.command_id===secondError.command_id));
+assert.ok(f.element('command-queue-updated').textContent.includes('待核对提交 2'));
+assert.ok(f.element('command-queue-error').classList.contains('hidden'),'Unknown acceptance does not fail all queue polling');
+
+const items=accepted.map((request,index)=>({...request,sequence:String(index+1),state:'succeeded',
+  created_unix_ms:'1',updated_unix_ms:'2',detail:'',result:{},error_code:''}));
+f.setHandler(async(method,params)=>{
+  if(method==='EnqueueCommand')throw new Error('A write must never be replayed');
+  if(method==='GetQueue')return {items};
+  if(method==='GetQueueItem')return items.find(item=>item.command_id===params.command_id);
+  return f.baseHandler(method,params);
+});
+await f.refreshQueue();
+assert.equal(f.calls.filter(call=>call.method==='EnqueueCommand').length,2);
+assert.ok(!f.element('command-queue-updated').textContent.includes('待核对提交'));
+assert.ok(f.element('commands-tbody').innerHTML.includes(firstError.command_id));
+assert.ok(f.element('commands-tbody').innerHTML.includes(secondError.command_id));
+
+const denied=fixture();
+denied.setHandler(async(method,params)=>{
+  if(method==='EnqueueCommand')throw businessError('FAILED_PRECONDITION');
+  if(method==='GetQueueItem')throw new Error('Rejected commands must not be tracked as uncertain');
+  return denied.baseHandler(method,params);
+});
+await assert.rejects(denied.services.command('StartAmt',{},'AMT'),error=>error.code==='FAILED_PRECONDITION');
+await denied.refreshQueue();
+assert.equal(denied.calls.filter(call=>call.method==='GetQueueItem').length,0);
+
+const polling=fixture();
+let releaseInfo;
+polling.setHandler((method,params)=>method==='GetSystemInfo'?
+  new Promise(resolve=>{releaseInfo=()=>resolve({mode:'simulated',version:'0.7.1'});}):polling.baseHandler(method,params));
+polling.window.dispatchEvent(new CustomEvent('stl:transport-state',{detail:{state:'open',generation:2}}));
+polling.window.dispatchEvent(new CustomEvent('stl:transport-state',{detail:{state:'open',generation:3}}));
+assert.equal(polling.calls.filter(call=>call.method==='GetSystemInfo').length,1,'Reconnect refresh cannot reenter an active poll');
+assert.equal(polling.calls.filter(call=>call.method==='ListStations').length,1);
+releaseInfo();
+for(let n=0;n<30;n++)await Promise.resolve();
+assert.equal(polling.calls.filter(call=>call.method==='GetQueue').length,1);
+
+const queuePolling=fixture();
+let releaseQueue;
+queuePolling.setHandler((method,params)=>method==='GetQueue'?
+  new Promise(resolve=>{releaseQueue=()=>resolve({items:[]});}):queuePolling.baseHandler(method,params));
+queuePolling.element('command-station-filter').onchange();
+queuePolling.element('command-station-filter').onchange();
+assert.equal(queuePolling.calls.filter(call=>call.method==='GetQueue').length,1,'Queue refresh has its own in-flight guard');
+releaseQueue();
+for(let n=0;n<10;n++)await Promise.resolve();
+console.log('WEB_COMMAND_RECOVERY_SUCCESS: lost acknowledgement ids, independent errors, NOT_FOUND recovery, queue/poll guards, no write replay');

+ 97 - 0
scripts/test_web_transport.mjs

@@ -0,0 +1,97 @@
+// Deterministic browser-transport checks. No server, device or network is used.
+import assert from 'node:assert/strict';
+import {readFile} from 'node:fs/promises';
+import vm from 'node:vm';
+
+const source = await readFile(new URL('../src/stl_backend/web/transport.js', import.meta.url), 'utf8');
+function fixture() {
+  const sockets = [], timers = new Map(), states = [];
+  let nextTimer = 0, now = 0, token = '';
+  class FakeSocket {
+    static OPEN = 1;
+    constructor(url) { this.url=url; this.readyState=0; this.sent=[]; sockets.push(this); }
+    open() { this.readyState=1; this.onopen?.({}); }
+    send(text) { assert.equal(this.readyState,1); this.sent.push(JSON.parse(text)); }
+    answer(id,result) { this.onmessage?.({data:JSON.stringify({v:1,id,ok:true,result})}); }
+    fail(id,code,message) { this.onmessage?.({data:JSON.stringify({v:1,id,ok:false,error:{code,message}})}); }
+    close() { if(this.readyState===3)return; this.readyState=3; this.onclose?.({}); }
+  }
+  const window = new EventTarget();
+  window.addEventListener('stl:transport-state', event=>states.push(event.detail.state));
+  vm.runInNewContext(source, {
+    window, location:{protocol:'https:',host:'bench.example:8443'}, WebSocket:FakeSocket,
+    CustomEvent, sessionStorage:{getItem:()=>token},
+    setTimeout:(fn,delay)=>{const id=++nextTimer;timers.set(id,{fn,when:now+delay});return id;},
+    clearTimeout:id=>timers.delete(id),
+  });
+  const flush = async()=>{await Promise.resolve();await Promise.resolve();};
+  async function tick(ms) {
+    const until=now+ms;
+    while(true) {
+      const next=[...timers].filter(([,timer])=>timer.when<=until).sort((a,b)=>a[1].when-b[1].when)[0];
+      if(!next)break;
+      timers.delete(next[0]);now=next[1].when;next[1].fn();await flush();
+    }
+    now=until;await flush();
+  }
+  return {api:window.stlTransport,sockets,states,timers,flush,tick,setToken:value=>{token=value;}};
+}
+
+const f=fixture();
+f.setToken('test-token');
+const first=f.api.call('GetStationControl',{station_id:'S1'});
+const second=f.api.call('GetQueue',{station_id:'S1'});
+assert.equal(f.sockets.length,1,'Concurrent calls share one connection');
+const socket=f.sockets[0];
+assert.equal(socket.url,'wss://bench.example:8443/ws');
+assert.equal(socket.sent.length,0,'Requests wait for the open handshake');
+socket.open();await f.flush();
+assert.equal(socket.sent.length,2);
+const [one,two]=socket.sent;
+assert.notEqual(one.id,two.id);
+assert.equal(one.v,1);assert.equal(one.authorization,'Bearer test-token');
+assert.deepEqual(one.params,{station_id:'S1'});
+socket.answer(two.id,{items:[]});socket.answer(one.id,{station_id:'S1',dimms:[]});
+assert.equal((await first).station_id,'S1');assert.equal((await second).items.length,0);
+assert.equal(f.api.snapshot().pending,0,'Out-of-order results match their own request IDs');
+
+f.setToken('');
+const missing=f.api.call('UnknownMethod');await f.flush();
+const missingFrame=socket.sent.at(-1);
+assert.equal('authorization' in missingFrame,false,'Empty optional token is omitted');
+const missingCheck=assert.rejects(missing,error=>error.code==='UNIMPLEMENTED'&&error.message.includes('unknown method'));
+socket.fail(missingFrame.id,'UNIMPLEMENTED','unknown method');await missingCheck;
+assert.equal(f.api.snapshot().state,'open','Business error does not break the connection');
+
+const uncertain=f.api.call('EnqueueCommand',{command_id:'original-command',method:'StationPower'});await f.flush();
+const uncertainCheck=assert.rejects(uncertain,error=>error.code==='DISCONNECTED');
+socket.close();await uncertainCheck;
+assert.equal(f.api.snapshot().pending,0);
+await f.tick(2000);
+assert.equal(f.sockets.length,2,'Disconnect opens a fresh channel automatically');
+const restored=f.sockets[1];restored.open();await f.flush();
+assert.equal(restored.sent.length,0,'Uncertain write is not replayed after reconnect');
+assert.equal(f.api.snapshot().generation,2);
+const fresh=f.api.call('GetQueueItem',{command_id:'original-command'});await f.flush();
+restored.answer(restored.sent[0].id,{command_id:'original-command',state:'succeeded'});
+assert.equal((await fresh).state,'succeeded','The UI can recover the original durable queue result');
+
+const late=f.api.call('GetStationControl',{station_id:'S1'});await f.flush();
+const lateId=restored.sent.at(-1).id;
+const timeoutCheck=assert.rejects(late,error=>error.code==='REQUEST_TIMEOUT');
+await f.tick(20000);await timeoutCheck;
+assert.equal(f.api.snapshot().pending,0);
+restored.answer(lateId,{station_id:'S1'});
+assert.equal(f.api.snapshot().pending,0,'Late responses do not recreate timed-out requests');
+const sentBefore=restored.sent.length;
+await f.tick(10000);
+assert.equal(restored.sent.length,sentBefore,'Timeout does not resend a request');
+
+const manual=f.api.reconnect();
+assert.equal(f.sockets.length,3);f.sockets[2].open();await manual;
+assert.equal(f.sockets[2].sent.length,0,'Manual channel reconnect also sends no device operation');
+f.api.disconnect();await f.tick(10000);
+assert.equal(f.sockets.length,3,'Page shutdown stops reconnect attempts');
+assert.equal(f.timers.size,0);
+assert.ok(f.states.includes('open')&&f.states.includes('disconnected')&&f.states.includes('closed'));
+console.log('WEB_TRANSPORT_TEST_SUCCESS: multiplexing, optional token, structured errors, reconnect, no write replay, timeout and shutdown');

+ 105 - 0
scripts/validate_live_actions.py

@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+"""At UEFI, verify idempotency, stale inputs, real directory I/O and missing EFI."""
+import argparse
+import asyncio
+import datetime
+import json
+from pathlib import Path
+import uuid
+import aiohttp
+
+
+class Client:
+    def __init__(self, ws):
+        self.ws, self.state = ws, None
+    async def call(self, method, params):
+        rid = uuid.uuid4().hex
+        await self.ws.send_json({'v': 1, 'id': rid, 'method': method, 'params': params})
+        async with asyncio.timeout(30):
+            while True:
+                frame = await self.ws.receive_json()
+                if frame.get('event') == 'state':
+                    self.state = frame['result']
+                if frame.get('id') == rid:
+                    if not frame.get('ok'):
+                        raise RuntimeError(str(frame.get('error')))
+                    return frame['result']
+    async def command(self, payload):
+        result = await self.call('StageAction', payload)
+        async with asyncio.timeout(60):
+            while result['state'] not in ('succeeded', 'failed', 'interrupted'):
+                await asyncio.sleep(.2)
+                result = await self.call('GetCommand', {'command_id': payload['command_id']})
+        return result
+    async def station(self):
+        value = await self.call('GetState', {})
+        return next(x for x in value['stations'] if x['station_id'] == 'S1')
+
+
+async def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument('--host', default='192.168.2.79:8080')
+    parser.add_argument('--output', required=True)
+    args = parser.parse_args()
+    report = {'observed_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
+              'checks': [], 'passed': False, 'memory_verdict': 'NOT_TESTED'}
+    def check(name, value, detail):
+        report['checks'].append({'name': name, 'passed': bool(value), 'detail': detail})
+        print(json.dumps({'name': name, 'passed': bool(value)}, ensure_ascii=False), flush=True)
+        if not value:
+            raise AssertionError(name)
+    try:
+        async with aiohttp.ClientSession() as session:
+            async with session.ws_connect('http://' + args.host + '/ws') as full_ws, \
+                       session.ws_connect('http://' + args.host + '/ws?view=qt-clean') as clean_ws:
+                full, clean = Client(full_ws), Client(clean_ws)
+                info = await full.call('GetSystemInfo', {})
+                report['system'] = info
+                state = await clean.station()
+                check('actual_uefi_ready', state['input']['ready'] and state['input']['stage'] == 'uefi',
+                      {'phase': state['phase'], 'boot_id': state['boot_id']})
+                queue = await full.call('GetQueue', {'station_id': 'S1', 'limit': 100})
+                started = next(x for x in queue['items'] if x['method'] == 'QtStartTest' and x['state'] == 'succeeded')
+                boot = state['boot_id']
+                duplicate = await clean.call('StartTest', {'station_id': 'S1', 'command_id': started['command_id']})
+                check('duplicate_real_start_does_not_reboot', duplicate['state'] == 'succeeded'
+                    and duplicate['result']['boot_id'] == boot and (await clean.station())['boot_id'] == boot,
+                    duplicate)
+                old = next(x for x in queue['items'] if x['method'] == 'QtStageAction'
+                           and x['arguments']['action'] == 'continue_uip')
+                stale = await clean.command({'station_id': 'S1', 'command_id': 'stale-' + uuid.uuid4().hex,
+                    'input_id': old['arguments']['input_id'], 'action': 'continue_uip'})
+                check('stale_real_prompt_rejected', stale['state'] == 'failed'
+                      and stale['error']['code'] == 'FAILED_PRECONDITION', stale)
+                state = await clean.station()
+                listing = await clean.command({'station_id': 'S1', 'command_id': 'listing-' + uuid.uuid4().hex,
+                    'input_id': state['input']['id'], 'action': 'list_uefi_files', 'path': 'FS0:\\EFI'})
+                check('real_uefi_directory_read', listing['state'] == 'succeeded'
+                      and isinstance(listing['result'].get('files'), list), listing)
+                state = await clean.station()
+                missing = 'FS0:\\EFI\\__qt_missing_' + uuid.uuid4().hex + '.efi'
+                mt = await clean.command({'station_id': 'S1', 'command_id': 'missing-' + uuid.uuid4().hex,
+                    'input_id': state['input']['id'], 'action': 'start_mt', 'mt': {'efi_path': missing}})
+                check('missing_efi_is_explicit_failure', mt['state'] == 'failed'
+                      and mt['error']['code'] == 'FAILED_PRECONDITION', mt)
+                state = await clean.station()
+                check('no_memory_pass_after_missing_efi', state['verdict'] != 'pass',
+                      {'verdict': state['verdict'], 'run_state': state['run_state']})
+                # A harmless subsequent directory query proves that errors do not
+                # corrupt the connection, while leaving the host at its Shell.
+                listing2 = await clean.command({'station_id': 'S1', 'command_id': 'listing-' + uuid.uuid4().hex,
+                    'input_id': state['input']['id'], 'action': 'list_uefi_files', 'path': 'FS0:\\EFI'})
+                check('link_usable_after_rejected_efi', listing2['state'] == 'succeeded', listing2)
+                report['passed'] = True
+    except Exception as exc:
+        report['error'] = type(exc).__name__ + ': ' + str(exc)
+        print(report['error'], flush=True)
+    finally:
+        target = Path(args.output)
+        target.parent.mkdir(parents=True, exist_ok=True)
+        target.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
+    return 0 if report['passed'] else 1
+
+
+if __name__ == '__main__':
+    raise SystemExit(asyncio.run(main()))

+ 503 - 0
scripts/validate_qt_clean.py

@@ -0,0 +1,503 @@
+#!/usr/bin/env python3
+"""Validate Qt-clean v1 against a running backend; read-only unless requested.
+
+No firmware parameters or AMT/MT algorithms are submitted by this driver.
+--start explicitly authorizes one host start/reset. --drive-default-plan additionally
+continues UIP with CR and exits AMT, ending at the actual UEFI Shell prompt.
+Protocol PASS never means that memory tests passed.
+"""
+from __future__ import annotations
+
+import argparse
+import asyncio
+import contextlib
+import datetime as dt
+import json
+import os
+from pathlib import Path
+import sys
+import time
+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
+import uuid
+
+import aiohttp
+
+
+TERMINAL = {"succeeded", "failed", "interrupted", "cancelled"}
+STAGE_RANK = {"unknown": -1, "idle": -1, "boot": 0, "booting": 0,
+              "uip": 1, "uip1": 1, "training": 2, "rmt": 3, "amt": 4,
+              "uip2": 5, "post": 5, "uefi": 6, "mt": 7}
+PRIVATE_KEYS = {"password", "passwd", "secret", "authorization", "token",
+                "firmware_settings", "boot_plan", "boot_execution", "raw_line",
+                "raw_sol", "helper_argv", "traceback"}
+
+
+def timestamp():
+    return dt.datetime.now(dt.timezone.utc).isoformat()
+
+
+def safe_url(url, view=None):
+    p = urlsplit(url)
+    host = p.hostname or ""
+    if ":" in host:
+        host = "[" + host + "]"
+    if p.port:
+        host += ":" + str(p.port)
+    values = [(k, v) for k, v in parse_qsl(p.query) if k == "view"]
+    if view is not None:
+        values = [("view", view)]
+    return urlunsplit((p.scheme, host, p.path or "/ws", urlencode(values), ""))
+
+
+def private_fields(value, path=""):
+    found = []
+    if isinstance(value, dict):
+        for key, item in value.items():
+            low = str(key).lower()
+            here = path + "." + str(key)
+            if low in PRIVATE_KEYS or low.endswith("_password") or low.endswith("_secret"):
+                found.append(here)
+            found.extend(private_fields(item, here))
+    elif isinstance(value, list):
+        for i, item in enumerate(value):
+            found.extend(private_fields(item, f"{path}[{i}]"))
+    return found
+
+
+def station_summary(station):
+    return {key: station.get(key) for key in (
+        "station_id", "connection", "power", "phase", "run_state",
+        "started_unix_ms", "boot_id", "verdict", "input", "command")}
+
+
+class RpcFailure(RuntimeError):
+    def __init__(self, method, error):
+        self.method, self.error = method, error or {}
+        super().__init__(f"{method}: {self.error.get('code', 'ERROR')}: "
+                         f"{self.error.get('message', '')}")
+
+
+class Evidence:
+    def __init__(self, args):
+        self.path = Path(args.output).expanduser().resolve()
+        self.token = os.environ.get(args.token_env, "") if args.token_env else ""
+        self.data = {
+            "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)},
+            "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.",
+        }
+
+    def save(self):
+        self.path.parent.mkdir(parents=True, exist_ok=True)
+        tmp = self.path.with_suffix(self.path.suffix + ".tmp")
+        tmp.write_text(json.dumps(self._redacted(self.data), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+        tmp.replace(self.path)
+
+    def _redacted(self, value):
+        if isinstance(value, dict):
+            return {key: ("[REDACTED]" if str(key).lower() in PRIVATE_KEYS
+                          or str(key).lower().endswith(("_password", "_secret", "_token"))
+                          else self._redacted(item)) for key, item in value.items()}
+        if isinstance(value, list):
+            return [self._redacted(item) for item in value]
+        if isinstance(value, str) and self.token:
+            return value.replace(self.token, "[REDACTED]")
+        return value
+
+    def check(self, name, passed, detail=None, *, skipped=False):
+        row = {"name": name, "status": "SKIP" if skipped else "PASS" if passed else "FAIL",
+               "at_utc": timestamp()}
+        if detail is not None:
+            row["detail"] = detail
+        self.data["checks"].append(row)
+        print(json.dumps(self._redacted(row), ensure_ascii=False), flush=True)
+        self.save()
+        return bool(passed)
+
+    def fail_count(self):
+        return sum(row["status"] == "FAIL" for row in self.data["checks"])
+
+
+class WsClient:
+    def __init__(self, session, url, evidence, token="", *, record_push=True):
+        self.session, self.url, self.evidence = session, url, evidence
+        self.headers = {"Authorization": "Bearer " + token} if token else {}
+        self.record_push = record_push
+        self.ws = self.reader = None
+        self.pending = {}
+        self.counter = 0
+        self.state = None
+        self.state_count = 0
+        self.first_state = asyncio.Event()
+        self.last_summary = {}
+        self.protocol_errors = []
+
+    async def __aenter__(self):
+        self.ws = await self.session.ws_connect(self.url, heartbeat=20, headers=self.headers)
+        self.reader = asyncio.create_task(self._read())
+        return self
+
+    async def __aexit__(self, *exc):
+        await self.ws.close()
+        self.reader.cancel()
+        with contextlib.suppress(asyncio.CancelledError):
+            await self.reader
+
+    async def _read(self):
+        try:
+            async for message in self.ws:
+                if message.type != aiohttp.WSMsgType.TEXT:
+                    if message.type == aiohttp.WSMsgType.ERROR:
+                        raise RuntimeError("WebSocket stream error")
+                    continue
+                try:
+                    frame = json.loads(message.data)
+                except (TypeError, ValueError):
+                    self.protocol_errors.append("non-JSON text response")
+                    continue
+                if not isinstance(frame, dict):
+                    self.protocol_errors.append("response is not an object")
+                    continue
+                request_id = frame.get("id")
+                if request_id in self.pending:
+                    future = self.pending.pop(request_id)
+                    if not future.done():
+                        future.set_result(frame)
+                elif frame.get("event") == "state":
+                    state = frame.get("result")
+                    if isinstance(state, dict):
+                        self.state = state
+                        self.state_count += 1
+                        self.first_state.set()
+                        if self.record_push:
+                            self._record_state(state)
+                    else:
+                        self.protocol_errors.append("state push result is not an object")
+                elif frame.get("event") == "bios_uart" and self.record_push:
+                    result = frame.get("result", {})
+                    if isinstance(result, dict):
+                        self.evidence.data["logs"].append({"station_id": result.get("station_id"),
+                            "session_id": result.get("session_id"), "offset": result.get("offset"),
+                            "next_offset": result.get("next_offset"), "raw_bytes": len(result.get("data_base64", "")) * 3 // 4})
+                    self.evidence.data["logs"] = self.evidence.data["logs"][-4000:]
+                elif request_id is not None:
+                    self.protocol_errors.append("unmatched response id")
+        except Exception as exc:
+            for future in self.pending.values():
+                if not future.done():
+                    future.set_exception(RuntimeError(type(exc).__name__ + ": " + str(exc)))
+
+    def _record_state(self, state):
+        for station in state.get("stations", []):
+            if not isinstance(station, dict):
+                continue
+            summary = station_summary(station)
+            # Ignore naturally changing counters/timestamps unless the useful state changed.
+            key = {k: summary.get(k) for k in ("connection", "power", "phase", "run_state",
+                                              "boot_id", "verdict", "input", "command")}
+            sid = station.get("station_id", "")
+            if key != self.last_summary.get(sid):
+                self.last_summary[sid] = key
+                self.evidence.data["state_transitions"].append({"received_utc": timestamp(), **summary})
+                self.evidence.data["state_transitions"] = self.evidence.data["state_transitions"][-4000:]
+                if sid == self.evidence.data["station_id"]:
+                    print(json.dumps({"station": sid, "phase": summary.get("phase"),
+                                      "run_state": summary.get("run_state"),
+                                      "power": summary.get("power"),
+                                      "input_stage": (summary.get("input") or {}).get("stage")},
+                                     ensure_ascii=False), flush=True)
+
+    async def raw_call(self, method, params=None, *, version=1, timeout=20):
+        self.counter += 1
+        request_id = f"verify-{self.counter}-{uuid.uuid4().hex[:8]}"
+        frame = {"v": version, "id": request_id, "method": method,
+                 "params": {} if params is None else params}
+        future = asyncio.get_running_loop().create_future()
+        self.pending[request_id] = future
+        await self.ws.send_json(frame)
+        try:
+            response = await asyncio.wait_for(future, timeout)
+        finally:
+            self.pending.pop(request_id, None)
+        if response.get("id") != request_id or response.get("v") != 1:
+            raise AssertionError("Invalid response request id or version")
+        return response
+
+    async def call(self, method, params=None, timeout=20):
+        response = await self.raw_call(method, params, timeout=timeout)
+        if response.get("ok") is not True:
+            raise RpcFailure(method, response.get("error"))
+        return response.get("result")
+
+    async def get_state(self):
+        state = await self.call("GetState")
+        if not isinstance(state, dict):
+            raise AssertionError("GetState result must be an object")
+        self.state = state
+        return state
+
+    async def station(self, station_id):
+        state = await self.get_state()
+        return next(s for s in state.get("stations", []) if s.get("station_id") == station_id)
+
+
+async def wait_command(client, command_id, deadline):
+    while time.monotonic() < deadline:
+        result = await client.call("GetCommand", {"command_id": command_id})
+        if result.get("state") in TERMINAL:
+            return result
+        await asyncio.sleep(.5)
+    raise TimeoutError(f"Command {command_id} did not become terminal")
+
+
+async def reject_check(client, evidence, name, method, params, codes, **kwargs):
+    frame = await client.raw_call(method, params, **kwargs)
+    error = frame.get("error") or {}
+    evidence.check(name, frame.get("ok") is False and error.get("code") in codes,
+                   {"code": error.get("code"), "message": error.get("message")})
+
+
+async def readonly_checks(client, evidence, args, session, token):
+    try:
+        await asyncio.wait_for(client.first_state.wait(), 12)
+        evidence.check("automatic_initial_state_push", True,
+                       {"push_count_before_first_request": client.state_count})
+    except TimeoutError:
+        evidence.check("automatic_initial_state_push", False, "No unsolicited state within 12 seconds")
+    state = await client.get_state()
+    evidence.data["initial_state"] = state
+    evidence.check("state_required_fields", all(k in state for k in
+                   ("version", "mode", "server_id", "stations")),
+                   {"version": state.get("version"), "mode": state.get("mode"),
+                    "server_id": state.get("server_id")})
+    stations = state.get("stations", [])
+    ids = [row.get("station_id") for row in stations]
+    evidence.check("station_ids_unique_and_requested_present", args.station in ids and len(ids) == len(set(ids)), ids)
+    required = {"station_id", "connection", "power", "phase", "run_state", "started_unix_ms",
+                "boot_id", "verdict", "input", "command", "channels"}
+    missing = {row.get("station_id", "?"): sorted(required - set(row)) for row in stations if required - set(row)}
+    evidence.check("minimal_station_contract", not missing, missing)
+    forbidden = private_fields(state)
+    evidence.check("no_internal_or_secret_fields_in_clean_state", not forbidden, forbidden)
+    await reject_check(client, evidence, "unknown_rpc_rejected", "NotARealQtMethod", {}, {"UNIMPLEMENTED", "INVALID_ARGUMENT"})
+    await reject_check(client, evidence, "unknown_getstate_field_rejected", "GetState", {"unexpected": True}, {"INVALID_ARGUMENT"})
+    await reject_check(client, evidence, "invalid_params_type_rejected", "GetState", "invalid", {"INVALID_ARGUMENT"})
+    await reject_check(client, evidence, "unsupported_protocol_version_rejected", "GetState", {}, {"INVALID_ARGUMENT"}, version=9)
+    await reject_check(client, evidence, "missing_command_rejected", "GetCommand", {"command_id": "verify-missing-" + uuid.uuid4().hex}, {"NOT_FOUND"})
+    await reject_check(client, evidence, "event_log_not_in_qt_clean", "ReadEventQueue", {"station_id": args.station}, {"UNIMPLEMENTED"})
+    await reject_check(client, evidence, "invalid_uart_offset_rejected", "ReadBiosUart", {"station_id": args.station, "offset": -1}, {"INVALID_ARGUMENT"})
+
+    legacy = {}
+    for view in ("full", "qt"):
+        async with WsClient(session, safe_url(args.url, view), evidence, token, record_push=False) as old:
+            info = await old.call("GetSystemInfo")
+            legacy[view] = info
+            evidence.check(f"legacy_{view}_GetSystemInfo", isinstance(info, dict) and bool(info.get("version")), info)
+            if view == "full":
+                listed = await old.call("ListStations")
+                evidence.check("legacy_full_ListStations", isinstance(listed, dict) and isinstance(listed.get("stations"), list),
+                               {"station_count": len(listed.get("stations", []))})
+                if args.check_unconfigured:
+                    ctl = await old.call("GetStationControl", {"station_id": args.check_unconfigured})
+                    evidence.data["unconfigured_capabilities"] = {
+                        "station_id": args.check_unconfigured, "capabilities": ctl.get("capabilities", {})}
+    evidence.data["legacy_system_info"] = legacy
+    evidence.check("legacy_and_clean_version_match", all(info.get("version") == state.get("version") for info in legacy.values()))
+    # A second connection gets its own complete initial snapshot, independent of the first.
+    async with WsClient(session, args.url, evidence, token, record_push=False) as other:
+        await asyncio.wait_for(other.first_state.wait(), 12)
+        evidence.check("second_client_gets_initial_snapshot", other.state.get("server_id") == state.get("server_id"))
+    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
+    if args.backend_source:
+        sys.path.insert(0, str(Path(args.backend_source).resolve() / "src"))
+    try:
+        import grpc
+        from google.protobuf.empty_pb2 import Empty
+        from stl_backend.generated import bench_pb2_grpc
+        metadata = (("authorization", "Bearer " + token),) if token else ()
+        async with grpc.aio.insecure_channel(args.grpc_address) as channel:
+            stub = bench_pb2_grpc.BenchServiceStub(channel)
+            info = await stub.GetSystemInfo(Empty(), timeout=15, metadata=metadata)
+            stations = await stub.ListStations(Empty(), timeout=15, metadata=metadata)
+        evidence.check("native_grpc_readonly_compatibility", bool(info.version) and bool(stations.stations),
+                       {"version": info.version, "mode": info.mode, "station_count": len(stations.stations)})
+    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
+    caps = evidence.data.get("unconfigured_capabilities", {}).get("capabilities", {})
+    if caps.get("bmc_power") is not False:
+        evidence.check("unconfigured_station_has_no_power_capability", False,
+                       "Refused StartTest: full interface did not explicitly report bmc_power=false")
+        return
+    sid = args.check_unconfigured
+    cid = "verify-unconfigured-" + uuid.uuid4().hex
+    before = await client.station(sid)
+    try:
+        accepted = await client.call("StartTest", {"station_id": sid, "command_id": cid})
+        result = accepted if accepted.get("state") in TERMINAL else await wait_command(client, cid, time.monotonic() + 45)
+        error = result.get("error") or {}
+        rejected = result.get("state") == "failed"
+    except RpcFailure as exc:
+        result, error, rejected = None, exc.error, True
+    after = await client.station(sid)
+    evidence.data["unconfigured_start"] = {"station_id": sid, "command_id": cid, "result": result, "error": error}
+    evidence.check("unconfigured_start_rejected_without_boot", rejected and before.get("boot_id") == after.get("boot_id"),
+                   {"error": error, "before_power": before.get("power"), "after_power": after.get("power")})
+
+
+async def start_test(client, evidence, args):
+    station = await client.station(args.station)
+    before = station_summary(station)
+    cid = "verify-start-" + uuid.uuid4().hex
+    params = {"station_id": args.station, "command_id": cid}
+    row = {"method": "StartTest", "params": params, "before": before, "sent_utc": timestamp()}
+    evidence.data["commands"].append(row)
+    evidence.save()
+    accepted = await client.call("StartTest", params)
+    row["accepted"] = accepted
+    replay_pending = await client.call("StartTest", params)
+    row["replay_while_pending"] = replay_pending
+    evidence.check("start_same_id_pending_replay", accepted.get("command_id") == cid and replay_pending.get("command_id") == cid)
+    done = await wait_command(client, cid, time.monotonic() + args.timeout)
+    row["completed"] = done
+    if not evidence.check("start_command_succeeded", done.get("state") == "succeeded", done):
+        raise RuntimeError("Host start did not succeed")
+    result = done.get("result") or {}
+    expected = {"off": "host_on", "on": "host_reset"}.get(result.get("previous_power"))
+    evidence.check("start_power_action_matches_live_power", expected is not None and result.get("power_action") == expected,
+                   {"previous_power": result.get("previous_power"), "power_action": result.get("power_action")})
+    evidence.check("start_requires_new_bios_boot_evidence", result.get("boot_observed") is True and bool(result.get("boot_id"))
+                   and result.get("boot_id") != result.get("previous_boot_id"),
+                   {k: result.get(k) for k in ("previous_boot_id", "boot_id", "boot_observed", "started_unix_ms")})
+    replay_done = await client.call("StartTest", params)
+    row["replay_after_completion"] = replay_done
+    evidence.check("start_same_id_completed_replay", replay_done.get("command_id") == cid
+                   and replay_done.get("state") == "succeeded"
+                   and (replay_done.get("result") or {}).get("boot_id") == result.get("boot_id"))
+    now = await client.station(args.station)
+    evidence.data["boot_evidence"] = result
+    evidence.data["after_start"] = station_summary(now)
+    evidence.check("state_agrees_with_completed_start", now.get("boot_id") == result.get("boot_id"))
+    return result.get("boot_id")
+
+
+async def drive_plan(client, evidence, args, boot_id):
+    deadline = time.monotonic() + args.timeout
+    handled = set()
+    rank, stages = -1, []
+    while time.monotonic() < deadline:
+        station = await client.station(args.station)
+        if station.get("boot_id") != boot_id:
+            raise RuntimeError("Unexpected new BIOS boot during local validation plan; no stage input replayed")
+        phase = station.get("phase", "unknown")
+        new_rank = STAGE_RANK.get(phase, -1)
+        if new_rank >= 0 and new_rank < rank:
+            evidence.check("overall_phase_never_regresses", False, {"previous_rank": rank, "phase": phase})
+            raise RuntimeError("Overall phase regressed")
+        rank = max(rank, new_rank)
+        if not stages or stages[-1] != phase:
+            stages.append(phase)
+            evidence.data["default_plan_stages"] = stages
+            evidence.save()
+        point = station.get("input") or {}
+        if point.get("ready") and point.get("stage") == "uefi":
+            evidence.data["after_default_plan"] = station_summary(station)
+            evidence.check("default_plan_reached_real_uefi_prompt", phase == "uefi", {"stages": stages, "input": point})
+            evidence.check("overall_phase_never_regresses", True, stages)
+            return
+        stage = point.get("stage")
+        action = "continue_uip" if stage in ("uip", "uip1", "uip2") else "skip_amt" if stage == "amt" else None
+        key = point.get("id")
+        if point.get("ready") and action and key and key not in handled:
+            actions = point.get("actions") or []
+            if action not in actions:
+                await asyncio.sleep(.5)
+                continue
+            handled.add(key)
+            cid = "verify-stage-" + uuid.uuid4().hex
+            params = {"command_id": cid, "station_id": args.station,
+                      "input_id": key, "action": action}
+            row = {"method": "StageAction", "params": params, "input": point, "sent_utc": timestamp()}
+            evidence.data["commands"].append(row)
+            evidence.save()
+            row["accepted"] = await client.call("StageAction", params)
+            done = await wait_command(client, cid, min(deadline, time.monotonic() + 90))
+            row["completed"] = done
+            evidence.check("stage_action_" + action + "_" + str(len(handled)), done.get("state") == "succeeded", done)
+            if done.get("state") != "succeeded":
+                raise RuntimeError("Stage action failed; not retrying hardware input")
+            evidence.save()
+        await asyncio.sleep(.5)
+    raise TimeoutError("Default local validation plan did not reach UEFI before deadline")
+
+
+async def run(args, evidence):
+    token = os.environ.get(args.token_env, "") if args.token_env else ""
+    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)
+            if args.start:
+                boot_id = await start_test(client, evidence, args)
+                if args.drive_default_plan:
+                    await drive_plan(client, evidence, args, boot_id)
+            evidence.data["final_state"] = await client.get_state()
+            evidence.data["state_push_count"] = client.state_count
+            evidence.check("websocket_frames_valid", not client.protocol_errors, client.protocol_errors)
+            evidence.check("final_state_has_no_internal_or_secret_fields", not private_fields(evidence.data["final_state"]))
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+    parser.add_argument("--url", required=True, help="ws://HOST:8080/ws?view=qt-clean")
+    parser.add_argument("--output", required=True, help="JSON evidence file")
+    parser.add_argument("--station", default="S1")
+    parser.add_argument("--timeout", type=float, default=900, help="Seconds per host start / local plan")
+    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:
+        parser.error("--drive-default-plan requires --start")
+    if args.timeout <= 0:
+        parser.error("--timeout must be positive")
+    if dict(parse_qsl(urlsplit(args.url).query)).get("view") != "qt-clean":
+        parser.error("--url must explicitly select view=qt-clean")
+    evidence = Evidence(args)
+    evidence.save()
+    try:
+        asyncio.run(run(args, evidence))
+    except KeyboardInterrupt:
+        evidence.check("validation_completed", False, "Interrupted; already accepted hardware commands may continue")
+    except Exception as exc:
+        evidence.check("validation_completed", False, {"error": type(exc).__name__, "message": str(exc)[:1200]})
+    evidence.data["finished_utc"] = timestamp()
+    evidence.data["protocol_verdict"] = "FAIL" if evidence.fail_count() else "PASS"
+    evidence.save()
+    print(json.dumps({"protocol_verdict": evidence.data["protocol_verdict"],
+                      "memory_verdict": evidence.data["memory_verdict"], "output": str(evidence.path)}, ensure_ascii=False))
+    return 1 if evidence.fail_count() else 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 1 - 1
src/stl_backend/__init__.py

@@ -1,3 +1,3 @@
 """XJKJ-STL memory thermal testing backend."""
-__version__ = "0.1.2"
+__version__ = "0.8.1.1.dev0"
 

+ 1 - 0
src/stl_backend/application/__init__.py

@@ -0,0 +1 @@
+"""Run orchestration, acquisition and commands composed by the Bench facade."""

+ 0 - 0
src/stl_backend/application/acquisition.py


Некоторые файлы не были показаны из-за большого количества измененных файлов