Compare commits

..
Author SHA1 Message Date
阿白叔 b00ca7dac9 fix(dsh): validate ZIP entries and bound decompression workers
Core regression / Python core and release configuration (push) Successful in 20s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 17s
Core regression / JavaScript syntax (pull_request) Successful in 3s
2026-11-04 20:58:06 +08:00
阿白叔 705c15eb93 fix(dsh): restore native file tools and official loading UI
Core regression / Python core and release configuration (push) Successful in 20s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 15s
Core regression / JavaScript syntax (pull_request) Successful in 3s
2026-11-04 19:05:21 +08:00
阿白叔 1340f6c233 build: stage immutable release files without duplicate copies
Core regression / Python core and release configuration (push) Successful in 18s
Core regression / JavaScript syntax (push) Successful in 3s
2026-11-04 15:47:21 +08:00
阿白叔 5aeddacfc9 build: prepare V1.2.2 with portable 7-Zip self-extraction
Core regression / Python core and release configuration (push) Successful in 17s
Core regression / JavaScript syntax (push) Successful in 3s
2026-11-04 15:22:24 +08:00
abaishu0730 453d288a6c Merge pull request 'UI:完善毛玻璃工作台、操作历史和同任务安全续跑' (#15) from codex/ui-update into main
Core regression / Python core and release configuration (push) Successful in 16s
Core regression / JavaScript syntax (push) Successful in 4s
2026-11-04 14:40:47 +08:00
阿白叔 c86b0eefa0 fix-history-recording-at-service-commit-boundaries
Core regression / Python core and release configuration (push) Successful in 17s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s
2026-11-04 14:14:25 +08:00
阿白叔 56588a9203 merge-main-ui-host-compatibility
Core regression / Python core and release configuration (push) Successful in 16s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s
2026-11-03 18:07:39 +08:00
abaishu0730 d36f3c2995 Merge pull request 'fix(dsh): restore Acrylic and safe native model settings' (#17) from codex/dsh-issue16 into main
Core regression / Python core and release configuration (push) Successful in 15s
Core regression / JavaScript syntax (push) Successful in 3s
2026-11-03 17:42:00 +08:00
阿白叔 af46ee1617 fix(dsh): bind migrated model routes to credential sources
Core regression / Python core and release configuration (push) Successful in 18s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 15s
Core regression / JavaScript syntax (pull_request) Successful in 3s
2026-11-03 17:28:22 +08:00
阿白叔 374e1cd5bf fix(dsh): preserve acrylic and restore durable native model settings
Core regression / Python core and release configuration (push) Successful in 15s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 15s
Core regression / JavaScript syntax (pull_request) Successful in 3s
2026-11-03 11:41:50 +08:00
43 changed files with 1748 additions and 92 deletions

No files matched your search

+1
View File
@@ -38,6 +38,7 @@ jobs:
tests/dsh/test_issue_broker.py
tests/packaging/test_dsh_runtime_staging.py
tests/packaging/test_release_configuration.py
tests/packaging/test_self_extracting_release.py
--junitxml=build/ci-results.xml --tb=short
- name: Windows release scope
run: |
+10 -6
View File
@@ -4,11 +4,11 @@
面向 **Windows + DxDesigner / Expedition Enterprise 7.9.5** 的器件批量替换工具。一个工程对应一个任务,可以只替换同料号下的部分位号;支持直接编辑和 Excel BOM 导入,同批工程按顺序执行。
**最新版本:V1.2.1(预发布)** · [下载便携包](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.2.1/DxPartReplace-1.2.1.zip) · [版本说明与附件](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/tag/v1.2.1) · [完整使用说明](docs/user/v1.1.0-project-tasks.md)
**最新版本:V1.2.2(预发布)** · [自解压 EXE](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.2.2/DxPartReplace-1.2.2.exe) · [ZIP 便携包](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.2.2/DxPartReplace-1.2.2.zip) · [版本说明与附件](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/tag/v1.2.2) · [完整使用说明](docs/user/v1.1.0-project-tasks.md)
V1.2.1 提供完整 Node/Qt 运行时、DSH 任务功能和全部 UI 资源。升级前备份 data,完整更新 EXE 与 _internal,不要只替换 EXE。
V1.2.2 新增操作历史、安全续跑与内置 7-Zip 的自解压 EXE,同时提供完整 Node/Qt 运行时、DSH 任务功能和全部 UI 资源。升级前备份 data,完整更新 EXE 与 _internal,不要只替换 EXE。
本版修复冻结应用缺少 SVG 资源的问题,保留维护者配置的工单上报能力,并增加云端 CI。[本版变更](docs/releases/v1.2.1.md)。
本版合并 PR15 与 PR17,补齐操作历史和模型设置,提供自解压 EXE 与 ZIP 两种同内容发行包。[本版变更](docs/releases/v1.2.2.md)。
本版提供[目标封装选择](docs/user/target-cell-selection.md):目标封装可留空,此时工具不主动覆写封装,可后续与中心库同步;需要指定时,在料号规则中读取并选择合法封装。BOM 保持原 11 列。
@@ -24,9 +24,11 @@ DSH助手围绕真实任务中心工作,支持:
- 发生异常时自动介入,收集脱敏证据链、保留诊断记录,并在需要时提交受限 Git 工单。
- 在右侧任务监管中查看运行、影响、排期、经验、工单和用量;审计损坏、证据缺失和未知计数会明确显示。
AI 不能直接写入 CAD、运行 Shell、访问任意文件或绕过确认门禁。自动异常诊断为只读;不确定执行不会自动重放,恢复必须重新核对冻结计划、检查点和业务证据。未配置模型时仍可使用任务监管和本地恢复功能,但不会产生真实模型回复。
AI 不能直接写入 CAD、运行 Shell 或绕过确认门禁。普通对话可按用户要求读取本地文件;自动异常诊断为只读事件快照。不确定执行不会自动重放,恢复必须重新核对冻结计划、检查点和业务证据。未配置模型时仍可使用任务监管和本地恢复功能,但不会产生真实模型回复。
模型配置保存在本机任务中心数据目录,密钥使用 Windows DPAPI 保护,不写入仓库或环境变量。首次接入可在 **工具设置 → DSH工具** 中配置 OpenAI 兼容端点和模型;开发环境也可通过 `DSH_API_BASE`、`DSH_MODEL`、`DSH_API_KEY` 临时提供配置。不要把 API key、Git 凭据或 `integration/dsh/issue-bootstrap.json` 提交到 Git。
首次接入打开 **工具设置 → 模型 → 添加模型提供商 → 自定义模型 API**,填写 API 地址、协议和密钥,点击 **获取可用模型** 并选择需要的模型,也可手动填写模型 ID。保存后在输入框下方选择模型。设置保存在任务中心数据目录的专用 Harness profile,重启会保留;主工具预配置的密钥继续由 Windows DPAPI 保护,模型设置页新增的密钥使用 Harness 本地凭据存储。开发环境也可通过 `DSH_API_BASE`、`DSH_MODEL`、`DSH_API_KEY` 临时提供配置。不要把数据目录、API key 或 Git 凭据提交到 Git。
对话输入框的 **+ → 文件** 可上传文本、ZIP 等文件;也可通过官方工作区入口选择本地文件夹,或直接提供路径让助手读取、搜索。ZIP 会解压到新的文件夹,返回真实路径后继续分析内容,不覆盖已有文件。启动展示直接使用 Harness 官方加载动画。
详细的能力边界、异常介入、证据链、排期和工单说明见 [DSH助手使用与监管说明](docs/user/dsh-ai-supervision.md)。源码环境可用下面的命令检查运行时门禁:
@@ -44,7 +46,9 @@ node tools/verify_dsh_runtime.mjs
### 第 1 步:解压并打开应用
[下载 V1.2.1 便携包](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.2.1/DxPartReplace-1.2.1.zip),**完整解压**,双击 `DxPartReplace.exe`。保留它与 `_internal` 的相对位置,无需安装 Python;本机需要可用的 DxDesigner、许可证和中央库。
推荐下载上方自解压 EXE,双击后选择新的解压目录,完成后运行目录内的 DxPartReplace.exe。自解压引擎已内置,无需另外安装 7-Zip,也无需通过 Windows 资源管理器解压。
[下载 V1.2.2 便携包](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.2.2/DxPartReplace-1.2.2.zip),**完整解压**,双击 `DxPartReplace.exe`。保留它与 `_internal` 的相对位置,无需安装 Python;本机需要可用的 DxDesigner、许可证和中央库。
打开后看到下图主窗口。首次使用请准备完整的工程副本,执行前保存并关闭待处理工程。
@@ -0,0 +1,18 @@
# PR #17 提供方迁移修复
目标:修复 PR #17 评论 #168 的旧地址与新密钥错配,保留原生自定义提供方及其独立凭据。
设计:`dx` 且引用启动环境 `DSH_API_KEY` 的配置归主工具管理,每次启动从当前主工具配置完整刷新;独立凭据的提供方保留。Harness 的插件 config 整块替换,因此用户 providers 存在时须同时纳入当前主工具提供方。迁移旧生成配置时,生成的 dx 默认模型回到当前主工具默认值;原生用户选定的有效 dx 模型和自定义提供方默认模型继续保留。没有主工具配置时清除旧应用管理的路由与默认选择。修改前保存原文件备份,重复初始化不重复改写。
凭据来源补充:上游本地保存的引用优先于环境变量。显式 dx 使用本地保存的 DSH_API_KEY 时,整条路由和密钥作为原生用户覆盖保留。启用了主工具模型、却只有孤立本地密钥时拒绝启动,不从历史 policy 猜测地址;没有主工具模型时不阻断其他独立提供方。首次正常启动即在原生用户配置中物化完整的应用 dx,确保此后模型页仅修改密钥也能保留它所属的地址和模型。配置准备不修改凭据文件,解析错误不包含密钥原文。
绑定证明以 Harness 真实 composition 为准,保留 name assertion / insert 语义,拒绝凭据、模型适配器和默认模型的重复 ID。从有效 credentials 配置解析实际文件路径。启动前确认最终应用路由与当前配置一致;桌面接入前再次核对实际凭据来源和仅在内存中的密钥摘要,避免环境与文件来源互换。
不采用只删除旧 dx 的方案:用户的 providers 整块覆盖会遮住新的应用提供方。不采用保留旧地址并换密钥的方案:会破坏凭据绑定。
执行步骤:
- [x] 新增真实 Harness/本机 HTTP 回归,覆盖旧 overlay、更换提供方、已有迁移结果、自定义提供方/默认模型、重复启动及主工具配置清除;先确认当前代码失败。
- [x] 在启动配置准备阶段按来源刷新应用提供方,保留其他原生配置及凭据文件。
- [x] 跑 HTTP 回归、现有 runtime/profile 检查、Python 回归和实际 Qt 模型设置点击;未复现点击失败,保留原脚本。
- [x] 更新验收记录与 PR 描述,检查 diff 和秘密泄露后提交、推送到现有 PR;不合并。
+7
View File
@@ -0,0 +1,7 @@
# V1.2.2
本版本合并 PR15 的操作历史与安全续跑改进,并提供带内置 7-Zip 解压引擎的 Windows 自解压包。
下载 `DxPartReplace-1.2.2.exe` 可使用自解压界面选择目标目录;`DxPartReplace-1.2.2.zip` 作为同内容回退包。两种包都包含完整的 `DxPartReplace.exe`、`_internal`、DSH Node 运行时、Qt WebEngine 依赖和资源文件。
解压后请保留 `DxPartReplace.exe` 与 `_internal` 的相对位置。本机仍需可用的 DxDesigner、许可证和中央库。沿用旧任务前先安全退出旧版本并备份 `data`,不要同时使用不同版本打开同一数据目录。
+50
View File
@@ -0,0 +1,50 @@
# 工单 #16:DSH 切换材质与模型设置
基线:`main@3cec9ad`。工单:[切换DSH工具遇到的一些问题](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/issues/16)。
## 修复内容
首次展示 WebEngine 时,Qt 将透明主窗口重建为 RHI 图形合成表面。返回任务中心后,重新调用 Acrylic API 或预设 alpha buffer 均不能恢复玻璃效果。DSH 现在通过 `WA_DontCreateNativeAncestors` 和 `WA_NativeWindow` 独立承载 Chromium 原生表面,保留任务中心的原 HWND 与 Acrylic。未改变系统透明度策略及“减少透明度”回退。
恢复官方 `ui-settings-models` 插件,提供模型提供商、自定义模型 API、手动模型列表和“获取可用模型”。通过上游公开的配置项关闭凭据引导,并使用固定 Harness 版本对应的欢迎说明配置,保留无账户/充值入口的任务工具界面。
重启验收发现旧启动脚本还会覆盖原生用户 `cordis.patch.yml`。应用配置现放在独立 `@dx/dsh-policy` bundle 中,原生用户配置作为上层保留。识别到旧应用生成的 overlay 时,先保存包含 SHA256 的逐字节备份,再迁移提供商与默认模型配置。原生模型页新增密钥使用 Harness 本地凭据存储,主工具预配置继续使用 DPAPI,文档分别说明。
## Windows 实际显示与点击
- 修复前屏幕截图:进入 DSH 再返回后,侧栏和右侧摘要对两种自有底图的差异均为 **0**;Acrylic 属性仍显示 true,因此属性不能作为显示成功证明。
- 最终材质验收:`build/dsh-issue16-acrylic-final/acceptance.json`。主 HWND 全程相同,切换前后侧栏差异均为 **21.82**,右侧摘要差异均约 **9.30**;数据表差异为 **0**,保持实色。减少透明度、紧凑布局和正常关闭通过。
- 模型页面实际输入/点击:`build/dsh-issue16-model-final/desktop-report.json`。添加自定义 API、调用自有本机测试服务器的 `GET /v1/models`、选择模型、保存提供商、重新打开编辑器读回模型均通过。未调用真实模型生成、CAD 或远端工单接口。
- 独立新进程重启报告:`build/dsh-issue16-model-final/restart-report.json`。重启真实 Harness 后读取到页面创建的 `issue16-fixture-model`,未发起模型请求。
- 同轮桌面验收还通过无登录/首次引导、官方页面、侧栏、SVG 动画、模型选择器、原生取消确认、导航后草稿保留及清洁退出。
## 回归
- DSH、UI、打包、队列与安全停止:412 passed(在原生子窗口修复后运行)。
- `node tools/verify_dsh_profile_settings.mjs`:原生设置重复初始化不改写、真实提供方加载、旧配置迁移与原字节备份通过。
- 官方 runtime CLI 门禁、模型结果裁剪与 dock 启动检查通过。
- 首轮独立代码审查未发现新增阻断问题;后续 PR 评论 #168 发现的提供方迁移缺陷及补充验证见下文。
## PR #17 评论 #168:提供方与凭据绑定
原迁移按插件 ID 整行保存 `llm-pi-ai`,把旧版自动生成的 dx 地址、模型和默认选择提升为用户覆盖。更换主工具提供方后,旧地址/模型覆盖新策略,环境中的密钥却已经换新。原有 412 项回归及模型列表读取没有覆盖真正请求的地址与认证头。
修复后,引用启动环境 DSH_API_KEY 的应用 dx 每次完整刷新,并与同一插件中的自定义提供方共同保留。旧生成默认选择迁移到当前主工具默认值;原生有效选择和自定义默认模型保留。已迁移过一次的数据也会纠正;没有主工具配置时移除旧应用路由。改写前备份,重复准备不会再次改写原生配置。
上游本地凭据优先于环境变量,因此进一步按真实来源区分:显式 dx 使用已保存的 DSH_API_KEY 时,整条用户路由保留;主工具模型启用时,孤立保存密钥没有有效提供方地址证据便拒绝启动,不猜测历史地址。没有主工具模型时,无关孤立引用不阻断其他独立提供方。正常首次准备就物化应用 dx 的完整配置,确保原生模型页只保存密钥后仍有地址和模型绑定。配置准备不改写凭据文件,元数据解析错误不引用密钥原文。
凭据绑定使用 Harness 真正的 composition 结果校验,不能把被 name assertion 跳过或只执行 insert 的行当成绑定;保留旧模型行的原有语义。对 credentials、llm-pi-ai、agent-default-model 的重复 ID 明确拒绝,避免 Loader 的最后项挂载语义与检查结果不同。实际凭据路径从有效 credentials 配置解析,兼容备用 path / dshHome。桌面接入前通过真正挂载的凭据服务再次核对来源和仅内存保存的值摘要,环境管理路由也必须完整等于当前主工具配置。
验证:
- `node tools/verify_dsh_provider_switch.mjs`:先在旧地址断言处观察失败,再验证修复。最终 **18 个场景通过、14 次真实 Harness 本机 HTTP 请求**;逐一核对 `/v1/chat/completions` 目的服务器、模型与虚构认证头,含旧 overlay、自定义默认模型、已迁移数据、原生自定义提供方、有效 dx 选择、独立凭据 dx、本地保存密钥、只修改密钥、孤立密钥拒绝、被跳过的配置行、重复插件 ID、备用凭据路径及主配置移除。报告:`build/dsh-provider-switch-verification/run-HgwLis/report.json`。
- 额外的本地保存密钥与孤立密钥用例均在修复前观察失败。孤立密钥拒绝不改变原用户补丁,也不发起模型请求。
- `node tools/verify_dsh_profile_settings.mjs`:原生独立配置保留、真实提供方加载、迁移与逐字节备份通过。
- `python -m pytest -q tests/v1_1 tests/ui tests/dsh tests/packaging --tb=short`:**1353 passed**,1 条 pywinauto COM 模式警告。
- `python -X utf8 tools/accept_dsh_desktop.py --output build/pr17-review168-final --port 9290 --provider-config <本机配置目录> --model-settings-check`:最终源码的真实 Qt/CDP 点击、输入、获取模型、创建、编辑器读回和正常关闭通过,未复现评论中的 API 地址点击被遮挡。未修改点击脚本,本机验收通过不作为已定位该次失败原因的证明。
- runtime 七项工具门禁、模型结果和 dock 启动验证通过。JS 语法与 `git diff --check` 通过。
- 最终独立复审重新验证了备用文件显式绑定与重复 ID 的拒绝,未发现新增已验证 P1/P2;5 个提交文件扫描本机已知凭据,无匹配。
所有新增模型请求仅到 127.0.0.1 自有测试端点,使用虚构密钥;没有外部模型生成、CAD 写入、远端工单写入或 EXE 构建。
本轮没有构建冻结 EXE;发布包须从修复分支重新构建,源码验收不替代发布包验收。
@@ -47,4 +47,11 @@ Windows 11 build 26200、125% 缩放:操作历史导航、真实配置改动
- 并发回归先复现“服务缓存锁内初始化历史记录、等待数据库锁”的反向锁序,再改为在缓存锁外构造任务服务,仅在短临界区发布缓存。并发/界面交接组 46 passed,DSH 源码未修改。
- 恢复提交增加“数据库和文件已经绑定,但最终提交标记尚未删除”的中断点;补记保留原生结果原文,避免重放时把正常文件判为冲突。回执/证据/恢复组 54 passed。
- 图页缺失、清单变化或读取异常统一按语义基线冲突处理,不能降级成普通安全失败后越过核验。生产 VBScript 与原生失败保护组 75 passed。
- 图页缺失、清单变化或读取异常统一按语义基线冲突处理,不能降级成普通安全失败后越过核验。生产 VBScript 与原生失败保护组 75 passed。
## 同步主分支后的验证
主分支合入 #17 后产生两个冲突。`ui/dsh_native.py` 完整采用主分支版本,DSH 功能与主分支保持一致;验收脚本保留双方检查入口和历史页检查。没有合并 PR #15。
- 同步后默认全套再次 **1233 passed**(301.74 秒,1 条现有 STA 提示);DSH/打包 **214 passed**。
- 原生两轮 WebEngine 导航差分复验:侧栏背景差分 20.18,不透明表格差分 0,窗口句柄不变,alpha=8,Acrylic 保持启用。证据:`build/history-execution-native-after-main/roundtrip-probe.json`。
- 同步后的整套截图流在历史清空断言处未完成,后续截图复跑被“外部窗口遮挡”所有权检查阻止,没有抓取其他窗口。使用独立、无截图的 Windows 原生探针复验相同的 WebEngine 切换、搜索、详情及真实 QMessageBox 确认:clear_success=true、表格和数据库历史均为 0、任务保留、Acrylic=true、CAD=false。证据:`build/history-execution-native-after-main/native-history-result.json`。因此不把整套截图脚本宣称为同步后全量通过。
@@ -0,0 +1,40 @@
# DSH 原生文件能力与加载页
基线:同步项目 `main@1340f6c`,包含 V1.2.2、操作历史与 UI 更新;保留已合并的 PR #17 修复。
## 变更
- 恢复官方附件栏、文件引用、目录选择、文件侧栏及其后端;普通对话开放原生 read/read_image、glob/grep、working_directory。启动检查从固定七项任务工具改为七项任务工具加六项文件能力。自动异常会话仍只接受其事件快照。
- 增加 extract_zip,复用运行时已有的 fflate 并显式固定依赖;向新目录解压后返回真实路径、条目与截断标记。解压前检查目录越界、数量、大小、重复条目和 CRC。路径、校验或写入失败不保留本次半成品,不覆盖已有文件。支持普通 ZIP;不支持加密、多卷、ZIP64。
- 启动直接打开固定官方前端的原版 index.html,通过其公开 __DSH_BOOT_READY__ 等待信号展示原版 HARNESS 动画。运行时就绪后进入官方 HTTP 页面并关闭本地资源访问;删除额外首页标语。没有改写上游 HTML、SVG、CSS 或动画。
- 实测一次冷启动需 139.59 秒,原 120 秒计时器提前终止正常启动;等待上限调整到 300 秒。最终验收启动等待 30.49 秒。
- 模型调用的文件操作追加既有工具审计,记录名称、回执和错误状态,不记录文件内容。
## 验证
- CLI:`node tools/verify_dsh_files.mjs`。先在缺少 read 能力的断言处观察失败;修复后验证中文/空格目录、读取、搜索、切换目录、ZIP 文本和二进制、重复解压不覆盖、路径越界、损坏包及 CRC 拒绝。独立审查也验证了单字节损坏的包在创建输出前被拒绝。
- 真正上传与模型操作:`python -X utf8 tools/accept_dsh_desktop.py --output build/dsh-files-live-verified --port 9298 --provider-config <本机配置目录> --file-check --live-model`。
- 实际点击官方 + → 文件,在真实 Qt 文件选择框输入自有文本和 ZIP 路径并点击打开;在 Harness 存储中核对两份文件字节一致。自然语言提示未指定工具名,真实测试 API 模型调用 read → extract_zip → read,三次均成功,并准确返回 `DSH_UPLOAD_CONTENT_中文`、`DSH_ZIP_UPLOAD_CONTENT_中文` 和真实解压目录。没有 CAD 操作或用户原始文件修改。
- `build/dsh-files-live-verified/desktop-report.json`:status=passed、storedBytesMatched=true、modelToolSucceeded=true、cleanShutdown=true,uncaughtErrors=false、unexpectedUiErrors=false。官方加载、鲸鱼 SVG 动画、模型选择器、原生取消确认及导航后草稿保留通过。
- 原版加载页实际截图:`build/dsh-files-live-verified/official-loading.png`,使用 Chromium Page.captureScreenshot 验证 HARNESS 与官方 spinner。附件截图 `file-uploaded.png`,真实回复截图 `dsh-native-final.png`。
- Python 回归:`python -m pytest -q tests/dsh tests/packaging --tb=short` 为 217 passed、1 skipped(当前环境未指定官方 7-Zip 发布工具);`python -m pytest -q tests/ui --tb=short` 为 193 passed。合计 410 passed、1 skipped。
- 最终 `verify_dsh_files.mjs` 还实际创建自动诊断会话,确认 read 与 extract_zip 在执行前被拒绝,避免继承普通对话的文件访问;该隔离用例不配置模型,不作自动诊断成功验证。`verify_dsh_profile_settings.mjs` 的原生配置保留、迁移与原字节备份通过。`verify_dsh_runtime.mjs` 确认 13 项预期工具、非预期工具拒绝、会话/上下文接口认证及任务中心确认门禁。
- 最终独立代码审查未发现新增阻断问题;Python 编译、变更 JS 语法及 diff 检查通过。
## 验收脚本兼容
官方文件菜单实际名称为“文件 file”,修正选择器;CDP 发现页在总时限内重试短暂的连接超时。pytest-qt 会在 fixture 结束前删除注册窗口,UI 夹具现在检查 isValid,避免再次关闭已删除窗口;原失败单项复验通过。
既有协议单测的轻量 UI stub 同步增加 hide、官方加载入口和 WebEngine settings;保留原 UTF-8 分块、重启及坏行恢复断言,并检查真实 HTTP 握手后关闭本地文件访问。
本次未构建或分发新 EXE,不把源码与本机验收等同于发布包验收。
## 合并前评论 #197:文件名完整性与解压线程
原 fflate 异步 unzip 使用普通对象接收文件,根目录 `__proto__` 会被静默漏掉;同时每个较大的条目都可能启动一个 Worker,文件总大小上限无法限制线程数量。新增真实 Harness 回归先在“特殊文件应明确拒绝”的断言处观察失败。
解压现由专用 Node Worker 执行,全进程最多同时处理两个压缩包,其余排队。每包先做不解压的整包元数据预检,明确拒绝无法可靠表示的根目录 `__proto__`;再在该 Worker 中解压,核对完整名称集合、长度和 CRC 后才传回主进程写入新目录。没有在主服务线程同步解压,也不再按 ZIP 条目创建线程。活动调用取消时终止 Worker,等待退出才结算并释放槽位;排队调用取消后直接移出队列。
`node tools/verify_dsh_zip_review.mjs`:合法与损坏的特殊文件名均被明确拒绝,无输出目录;4 个压缩包并行、每包 20 个 600 KiB 文件,全部文件完整,恰好创建 4 个 Worker,峰值为 2;活动取消后 Worker 全部退出且不产生半成品。独立审查还验证了 5 个请求中取消一个排队请求,4 个成功、峰值 2、全部线程退出。Worker 文件会随 task-plugin 目录递归打包。
最终 `python -m pytest -q tests/v1_1 tests/ui tests/dsh tests/packaging --tb=short`:1463 passed、1 skipped(未指定官方 7-Zip 发布工具)、1 条 pywinauto COM 模式警告。原有真实 Harness 文件/目录/ZIP/CRC/自动会话隔离回归再次通过;最终独立审查无新增阻断发现。
@@ -0,0 +1,43 @@
# PR #15:补齐业务变更的操作历史
针对[审查评论 179](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/15#issuecomment-179)。修复范围为操作历史接入,不修改 DSH 业务逻辑,也不执行真实 CAD、模型或 DSH 运行时。
## 根因及修复边界
原实现依赖 `_MUTATIONS` 手工登记入口,遗漏时直接执行业务动作,不生成历史。助手创建任务、采集位号和重新读取绑定工程因此存在历史缺口。同类入口检查还发现 Value 策略已登记,但调用路径没有经过捕获器。
- 助手创建:纳入普通历史事务;一次确认产生的任务、工程和规则按任务分组记录,重放同一请求不重复生成历史。
- 采集位号:读取工程时保留原执行互斥,读取结束后仅对已有的位号保存事务捕获差异;默认料号、位号计划模式和新增位号一起记录。
- 重新读取:文件状态检查和随后上下文读取在历史事务外,只捕获 `sync_projects` 对工程可用性等字段的实际修改。
- Value 策略:复用统一的服务入口捕获逻辑,记录开关的前后值;重复保存相同值不生成记录。
采集和工程刷新使用显式的 `capture_history=False` 保留外层执行准入,并在内部短保存阶段调用历史捕获器,避免重复记录及长时间持有数据库访问锁。
## 回归证据
新增 13 项真实服务入口回归,覆盖四类操作的准确差异、助手请求重放、无变化刷新/轮询、重复采集、取消采集、四类历史写入失败时的事务回滚,以及 CAD 读取等待期间另一线程仍可写入独立历史。
断言按 `operation` 精确选择事件,检查实际字段前后值,避免全文搜索误命中临时工程路径造成假阳性。
在干净的 PR 提交 `56588a9` 源码快照上运行同一组精确记录断言,四项均因历史事件缺失失败;修复后的 13 项全部通过。未改动当前工作树源码来制造这个失败对照。
验证命令与结果:
- `python -m pytest -q tests/v1_1/test_history_service_entrypoints.py`:13 项通过。
- 历史及执行相关定向测试组:92 项通过;随后增加的 Value 策略回归包含在上述 13 项中。
- `python -m pytest -q tests/dsh tests/packaging tests/trial_task_center/test_service.py tests/trial_task_center/test_quick_run.py tests/trial_task_center/test_store.py`:282 项通过。
- 独立代码审查未发现可操作问题,包括 Value 策略入口及采集、刷新事务边界的补充检查。
### 原生脚本时限对照
同步工作目录中单独运行原生保护测试时,正向用例触发 `subprocess.TimeoutExpired`:`cscript.exe` 等待 Python 标记辅助程序超过测试的 15 秒限制;其他 4 个保护用例通过。直接调用同一标记程序和已生成的 VBScript 则正常返回,分别耗时 7.69 秒和 6.16 秒。
为区分代码差异和运行位置影响,将干净提交的源码、测试及 VBS 导出至 `F:/dxpt-ui-history-verify-20261104/entrypoint-baseline-2`,再将相同提交加本次全部 3 个源码修改导出至独立的 `native-current-snapshot`。两份快照在同步目录外运行原测试、保持原有 15 秒时限,均为 **5 项通过**(57.05 秒 / 49.54 秒)。没有改动原生保护代码或放宽测试时限。这支持运行位置/本机耗时影响的判断,尚未定位具体的系统级延迟来源。
### 默认全套
`python -m pytest -q --tb=short`:**1245 项通过、1 项超时失败、1 条现有 pywinauto STA 提示**,耗时 1169.33 秒。
该次超时出现在同组的 `missing-path` 参数分支,并非单独复跑时超时的正向分支,异常同为 `cscript.exe` 的 15 秒等待超时。两个版本快照的整个 5 项参数组均已通过,不能将本次默认全套描述为全部通过。原生测试、VBS、辅助程序和 DSH 源码均未修改。
全套结束后,在原同步工作目录中以原时限单独复跑 `-k missing-path`:**1 项通过、4 项未选择**,耗时 6.86 秒。
+20 -2
View File
@@ -6,7 +6,25 @@
这里直接运行 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 的官方前端与运行时,固定 npm 版本 `0.2.1-rc.5`,通过 Qt WebEngine 嵌入主窗口。官方三栏框架、原生 SVG、鲸鱼悬停动画、输入编辑器、模型选择、侧栏与停靠交互均由上游代码提供。项目增加任务监管插件和“DSH助手”名称,不再使用 Qt 控件重画聊天页面。上游许可见 `licenses/DeepSeek-Harness-MIT.txt`。
不显示上游账户登录、注册、充值和首次产品引导,也不注册其账户模型提供方。左下角 **工具设置** 单击打开原生设置页中的“DSH工具”说明;首页提示和任务监管面板围绕器件替换任务。输入框下方仍可选择主工具已经配置的模型。
不显示上游账户登录、注册、充值和首次产品引导,也不注册其账户模型提供方。左下角 **工具设置** 单击打开原生设置页,包含“DSH工具”“通用设置”和“模型”;首页提示和任务监管面板围绕器件替换任务。输入框下方选择已配置的模型。
在 **模型 → 添加模型提供商 → 自定义模型 API** 中填写 Provider ID、API 地址、协议及可选密钥,点击 **获取可用模型**,勾选后点 **添加所选**,最后 **创建提供商**。也可手动添加模型 ID。获取失败会保留表单,便于修正地址或手动填写。已有提供方点击 **编辑** 可修改其模型目录;保存后即时生效。
模型页面使用官方 Harness 设置与凭据服务:用户设置保存在 `dsh/harness-home/profiles/dx-task/cordis.patch.yml`,新增的密钥通过官方本地凭据服务保存在 `dsh/harness-home/.credentials.yaml`;此文件不使用主工具的 DPAPI 格式。主工具预配置的 `provider.json` 和 DPAPI 密钥仍可加载。应用固定策略作为独立 bundle 提供;应用管理的 `dx` 提供方随主工具配置完整更新,自定义提供方及其独立凭据保留。旧版生成的 `dx` 默认模型在迁移时回到当前主工具默认值;原生用户选定且仍有效的模型及自定义提供方默认选择保留。改写配置前逐字节备份,重复启动不重复改写。
在原生模型页为现有 `dx` 保存密钥后,该提供方作为用户覆盖保留其地址、模型和本地密钥,不再随主工具自动切换。如果当前启用了主工具模型,但旧数据中存在本地 `DSH_API_KEY` 密钥、却没有对应的有效 `dx` 配置,DSH 会明确拒绝启动,避免把未知来源的密钥发到当前地址。恢复时先备份整个数据目录,将密钥配置为具有独立凭据引用的自定义提供方;不要只搬运密钥文件。主工具模型未启用时,无关的孤立引用不会阻断独立提供方。不要将凭据文件分发或提交到仓库。
DSH 使用独立原生子窗口承载 WebEngine,切回任务中心后保留原有 Acrylic 玻璃材质;“减少透明度”与系统高对比度等回退规则继续生效。
启动时直接展示官方前端的 HARNESS 加载动画,不再绘制额外的 Qt 加载页面;运行时就绪后进入官方对话界面。
### 文件、文件夹与 ZIP
点击输入框 **+ → 文件**,在文件选择框中选取文件。上传卡片显示进度,失败可重试;上传成功后可连同问题发送。文本由助手实际读取,图片还需要所选模型支持图片输入。
侧栏的官方工作区入口可选择本机文件夹;也可以在对话中直接提供绝对路径,或用 `@` 引用文件。助手可以读取 UTF-8 文本、查看目录中的文件、搜索内容,并切换会话的当前目录。选择文件夹不会自动执行 CAD 或修改工程。
例如:“读取这个文件夹里的说明,搜索失败原因”;或上传 ZIP 后说:“解压附件,读取其中说明文件并告诉我内容”。ZIP 解压到当前目录下新建的 `dsh-extracted-*` 文件夹,也可指定一个已有输出父目录;返回绝对目录与文件清单,重复解压会创建新目录。解压前校验路径、大小和 CRC,失败不会留下可误认为成功的输出。本轮支持普通 ZIP,不支持加密、多卷及 ZIP64;压缩文件上限 64 MiB、解压总量 256 MiB、最多 10000 项。上传其他格式不等于模型已经能够解析其内容。
模型由本机保存的主工具配置加载;也支持启动进程的 `DSH_API_BASE`、`DSH_MODEL`、`DSH_API_KEY`。未配置模型时可查看任务上下文和操作面板,不能获得真实模型回复。
@@ -48,7 +66,7 @@
用户在原执行轮次请求安全暂停或强制结束后,该停止意图会随轮次传递到自动诊断;即使最后一个失败项已收尾、队列结果显示“已结束”,也不会自动准备或执行重试。诊断和证据上报仍可继续。只有用户重新确认执行新轮次,才会创建新的执行控制对象;原轮次的停止记录不会被清除。
- 普通对话开放快照、创建、任务列表及详情、预检、任务管理、受控执行、综合监管七项能力;综合监管包含影响、运行恢复、排期、经验与工单查询。自动异常诊断会话仍只允许事件快照,其他调用在执行前被拒绝。Shell、通用文件访问、插件安装、子智能体及模型直接 CAD 写入工具均未注册;额外工具会被 guard 阻断。
- 普通对话除七项任务能力外,开放本地文件读取、图片读取、文件发现与内容搜索、切换目录和 ZIP 解压;附件、文件引用、文件夹选择使用官方界面。自动异常诊断会话仍只允许事件快照。通用 Shell、插件安装、子智能体及模型直接 CAD 写入工具未注册;任务修改和工程执行继续走任务中心原有确认。
- **刷新任务上下文**重新发布当前任务快照。
- 手动点击 **准备失败项重试**须在任务中心确认,并通过现有重试按钮的状态检查;该按钮只准备重试。自动介入使用上文限定的一次重试闭环。
- **安全暂停**须确认且当前确有执行控制器,使用原队列的安全边界暂停。
+2 -1
View File
@@ -5,7 +5,8 @@
"packages": {
"": {
"dependencies": {
"@deepseek-ai/dsh": "0.2.1-rc.5"
"@deepseek-ai/dsh": "0.2.1-rc.5",
"fflate": "0.8.3"
},
"name": "dxdesigner-dsh-runtime"
},
+1 -1
View File
@@ -4,5 +4,5 @@
"type": "module",
"scripts": {"doctor": "node start.mjs --doctor", "start": "node start.mjs"},
"engines": {"node": ">=24.9.0"},
"dependencies": {"@deepseek-ai/dsh": "0.2.1-rc.5"}
"dependencies": {"@deepseek-ai/dsh": "0.2.1-rc.5", "fflate": "0.8.3"}
}
+168 -16
View File
@@ -1,10 +1,15 @@
/** Application-owned composition around the unmodified official Harness web UI. */
import {createRequire} from 'node:module';
import {fileURLToPath} from 'node:url';
import {mkdir, writeFile, readFile, cp} from 'node:fs/promises';
import {mkdir, writeFile, readFile, cp, rename} from 'node:fs/promises';
import {createHash,randomUUID} from 'node:crypto';
import {isDeepStrictEqual} from 'node:util';
import path from 'node:path';
import {createInterface} from 'node:readline';
export const TASK_TOOLS=['dx_task_snapshot','dx_task_create','dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute','dx_task_operations'];
export const FILE_TOOLS=['read','read_image','glob','grep','working_directory','extract_zip'];
const root = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
export const VERSION = '0.2.1-rc.5';
@@ -12,13 +17,12 @@ export const DISABLED = [
'preset-standard','preset-cordis','preset-minimal','preset-ptc',
'tool-plugin-manager','plugin-manager','ui-plugin-manager','ui-settings-plugins',
'ui-settings-plugin-inventory','ui-agent-preset','cordis-host-runner','cordis-client-runner',
'ui-cordis','ui-sidebar-terminal','terminal-controller','ui-sidebar-files',
'workspace-files','ui-sidebar-documentpreview','ui-sidebar-browser','office-to-pdf',
'open-in-app','ui-open-in-app','directory-picker','ui-directory-picker-native',
'ui-directory-picker-browse','ui-attachment','file-reference-local',
'ui-reference','ui-skill','ui-subagent','ui-schedule','ui-goal','ui-jobs',
'ui-cordis','ui-sidebar-terminal','terminal-controller',
'ui-sidebar-documentpreview','ui-sidebar-browser','office-to-pdf',
'open-in-app','ui-open-in-app',
'ui-skill','ui-subagent','ui-schedule','ui-goal','ui-jobs',
'ui-settings-shell','ui-settings-subagent','ui-settings-web-search','ui-settings-agent-loop',
'ui-permission','ui-plan','plan-mode','agent-instructions','tool-working-directory',
'ui-permission','ui-plan','plan-mode','agent-instructions',
'tool-bash','tool-pwsh','tool-fs','tool-fs-search','tool-web','tool-skill','tool-jobs',
'tool-schedule','tool-goal','tool-todo','tool-present','tool-workflow',
'tool-subagent','tool-subagent-control','tool-subagent-fork',
@@ -28,12 +32,16 @@ export const DISABLED = [
// This embedded tool uses its application-owned API configuration, without
// upstream accounts, billing, credential onboarding or product feedback.
'ui-settings-account','account-controller','deepseek-account','llm-deepseek-account',
'ui-settings-models','ui-message-feedback','message-feedback','command-feedback',
'ui-message-feedback','message-feedback','command-feedback',
];
export function overlay() {
const rows = DISABLED.map(id => ({id, disabled:true}));
rows.push({id:'agent-preset-registry',config:{default:'dx-task'}});
rows.push({id:'ui-settings-general',config:{welcomeNoticeVersion:'2026-09-28.1'}});
rows.push({id:'ui-settings-models',config:{credentialOnboarding:false}});
rows.push({id:'tool-fs',disabled:false,config:{read:true,readImage:true,write:false,edit:false}});
rows.push({id:'tool-fs-search',disabled:false,config:{sampleOverCapGlobResults:false}});
rows.push({id:'web-runtime',config:{openBrowser:false,printUrl:false,surfaceContext:false}});
rows.push({id:'sandbox-policy',config:{mode:'read-only',workspaceRoot:process.env.DX_DSH_WORKSPACE}});
rows.push({id:'permission',config:{presets:{'read-only':{sandbox:'read-only',approval:'ask'}}}});
@@ -55,6 +63,144 @@ export function overlay() {
return rows;
}
async function replaceJson(filename,value) {
const temporary=filename+'.'+randomUUID()+'.tmp';
const {unlink}=await import('node:fs/promises');
try{await writeFile(temporary,JSON.stringify(value,null,2));await rename(temporary,filename);}
finally{await unlink(temporary).catch(error=>{if(error.code!=='ENOENT')throw error;});}
}
async function readOptionalModelMetadata(filename) {
let text;
try{text=await readFile(filename,'utf8');}catch(error){if(error.code==='ENOENT')return;throw error;}
try{return require('js-yaml').load(text);}catch{
// YAML parser errors can quote the line containing a credential.
throw Error('Cannot parse stored model metadata: '+path.basename(filename));
}
}
function modelEntry(rows,id) {
const entries=rows.filter(row=>row.id===id);
if(entries.length>1)throw Error('Duplicate '+id+' prevents verifying model binding; startup refused.');
return entries[0];
}
function refreshApplicationModels(rows,application,{legacy=false,storedHostKey=false,previousApplication=[],boundDx}={}) {
const current=application.find(row=>row.id==='llm-pi-ai')?.config.providers.dx;
let userLlm=rows.filter(row=>row.id==='llm-pi-ai'&&row.config).at(-1);
if(current&&storedHostKey&&!boundDx){
// A generated policy alone cannot prove which endpoint a saved key belongs
// to. Never attach an unbound local credential to today's host endpoint.
throw Error('Stored DSH_API_KEY has no provider binding; configure a native provider with its own credential reference before starting DSH.');
}
if(!userLlm&&current){
userLlm={id:'llm-pi-ai',config:{providers:{dx:current}}};
rows=[...rows,userLlm];
}
const prior=boundDx;
if(storedHostKey&&prior?.apiKeyEnv==='DSH_API_KEY'&&!rows.some(row=>row.id==='agent-default-model')){
const saved=previousApplication.find(row=>row.id==='agent-default-model')?.config;
const config=saved?.provider==='dx'&&prior.models?.some(model=>model.id===saved.model)
?saved:{provider:'dx',model:prior.models[0].id};
rows=[...rows,{id:'agent-default-model',config}];
}
// A native provider with its own credential reference (or deliberately no
// credential) owns its complete route. Only an environment-sourced
// DSH_API_KEY belongs to the host; a saved native key owns its user route.
const managed=prior===undefined||(prior.apiKeyEnv==='DSH_API_KEY'&&!storedHostKey);
return rows.flatMap(row=>{
if(row.id==='agent-default-model'&&row.config?.provider==='dx'&&managed
&&(legacy||!current?.models.some(model=>model.id===row.config.model)))return [];
if(row.id!=='llm-pi-ai'||!row.config)return [row];
const providers={...row.config.providers};
if(providers.dx===undefined||(providers.dx.apiKeyEnv==='DSH_API_KEY'&&!storedHostKey)){
if(current)providers.dx=current;else delete providers.dx;
}
// Harness replaces an entire plugin config, rather than deep-merging it.
// Keep the host route beside custom routes in any overriding user row.
return [{...row,config:{...row.config,providers}}];
});
}
export async function prepareProfileDirectory(dir) {
// The official settings page writes the user patch. Application defaults
// belong to a bundle below it. Only host-owned model routes are refreshed;
// independent native providers and their credential references remain intact.
await mkdir(dir,{recursive:true});
const application=overlay();
const userPatch=path.join(dir,'cordis.patch.yml');
const previousApplication=await readOptionalModelMetadata(path.join(dir,'node_modules/@dx/dsh-policy/cordis.patch.yml'))??[];
const policyDir=path.join(dir,'node_modules','@dx','dsh-policy');
await mkdir(policyDir,{recursive:true});
await cp(path.join(root,'task-plugin'),path.join(dir,'node_modules','@dx','dsh-task'),{recursive:true});
await replaceJson(path.join(policyDir,'package.json'),{name:'@dx/dsh-policy',version:VERSION,
private:true,dsh:{bundle:{patch:'./cordis.patch.yml'}}});
await replaceJson(path.join(policyDir,'cordis.patch.yml'),application);
await replaceJson(path.join(dir,'package.json'),{private:true,type:'module',
dependencies:{'@dx/dsh-task':'file:'+path.join(root,'task-plugin'),'@dx/dsh-policy':'file:'+policyDir},
dsh:{profile:{bundles:['@deepseek-ai/dsh-base','@deepseek-ai/dsh-web-app','@dx/dsh-policy']}}});
const {loadProfileDirectory,composeEntries}=await import('@deepseek-ai/dsh-app-boot');
const profile=loadProfileDirectory('dx-dsh',dir,require.resolve('@deepseek-ai/dsh/package.json'),{userLayer:false});
const layers=profile.layers.map(layer=>layer.patches);
// Remove only the generated host route when testing whether a user binding
// actually applies. Use Harness semantics, including name assertions/inserts.
const withoutHost=profile.layers.map(layer=>layer.packageName==='@dx/dsh-policy'
?layer.patches.filter(row=>row.id!=='llm-pi-ai'):layer.patches);
let hostCredentialBinding;
const refresh=async(rows,legacy=false)=>{
const effective=composeEntries([...layers,rows]);
const credentials=modelEntry(effective,'credentials');
modelEntry(effective,'llm-pi-ai');modelEntry(effective,'agent-default-model');
let storedHostKey=false,savedKey;
if(credentials?.disabled!==true){
if(credentials?.name!=='@deepseek-ai/dsh-credentials-local')
throw Error('Cannot verify the configured model credential provider; startup refused.');
const {resolveDshHome}=await import('@deepseek-ai/dsh-home-paths');
const config=credentials.config??{};
const home=resolveDshHome(config.dshHome,{DSH_HOME:path.resolve(dir,'../..')});
const stored=await readOptionalModelMetadata(path.resolve(config.path??path.join(home,'.credentials.yaml')));
savedKey=stored?.version===undefined?stored?.DSH_API_KEY:stored?.refs?.DSH_API_KEY;
storedHostKey=typeof savedKey==='string'&&savedKey.length>0;
}
const boundDx=modelEntry(composeEntries([...withoutHost,rows]),'llm-pi-ai')?.config?.providers?.dx;
const next=refreshApplicationModels(rows,application,{legacy,storedHostKey,previousApplication,boundDx});
const actual=modelEntry(composeEntries([...layers,next]),'llm-pi-ai')?.config?.providers?.dx;
if(storedHostKey&&actual?.apiKeyEnv==='DSH_API_KEY'
&&(!boundDx||!isDeepStrictEqual(actual,boundDx)))
throw Error('Stored DSH_API_KEY has no provider binding after Harness composition; startup refused.');
if(!storedHostKey&&actual?.apiKeyEnv==='DSH_API_KEY'
&&!isDeepStrictEqual(actual,application.find(row=>row.id==='llm-pi-ai')?.config.providers.dx))
throw Error('Application model route did not match the current provider; startup refused.');
if(actual?.apiKeyEnv==='DSH_API_KEY')hostCredentialBinding={source:storedHostKey?'file':'env',
digest:createHash('sha256').update((storedHostKey?savedKey:process.env.DSH_API_KEY)??'').digest('hex')};
return next;
};
let prior;
try{prior=await readFile(userPatch,'utf8');}catch(error){if(error.code!=='ENOENT')throw error;}
if(prior!==undefined){
const {load}=require('js-yaml');
const rows=load(prior);
const legacy=Array.isArray(rows)&&rows.some(row=>Array.isArray(row?.insert)
&&row.insert.some(entry=>entry.id==='dx-task'&&entry.name==='@dx/dsh-task')
&&row.insert.some(entry=>entry.id==='preset-dx-task'));
const editable=new Set(['llm-pi-ai','llm-deepseek','agent-default-model']);
const userRows=legacy?rows.filter(row=>editable.has(row?.id)&&row.config):rows;
const next=Array.isArray(userRows)?await refresh(userRows,legacy):userRows;
if(legacy||JSON.stringify(next)!==JSON.stringify(rows)){
const digest=createHash('sha256').update(prior).digest('hex');
const backup=userPatch+(legacy?'.legacy-':'.models-')+digest+'.bak';
try{await writeFile(backup,prior,{flag:'wx'});}catch(error){
if(error.code!=='EEXIST'||await readFile(backup,'utf8')!==prior)throw error;
}
await replaceJson(userPatch,next);
}
}else if(application.some(row=>row.id==='llm-pi-ai')){
const next=await refresh([]);
await replaceJson(userPatch,next);
}
return {hostCredentialBinding};
}
export async function bootRuntime({announce=true} = {}) {
const installed = require('@deepseek-ai/dsh/package.json');
if (installed.version !== VERSION) throw Error('Unsupported Harness version: ' + installed.version);
@@ -64,7 +210,7 @@ export async function bootRuntime({announce=true} = {}) {
await readFile(path.join(root,'task-plugin/client.js'));
if (process.argv.includes('--doctor')) {
console.log(JSON.stringify({status:'ready',version:VERSION,frontend:'official',
tools:['dx_task_snapshot','dx_task_create','dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute','dx_task_operations'],genericTools:false,node:process.version}));
tools:[...TASK_TOOLS,...FILE_TOOLS],fileTools:true,genericShell:false,node:process.version}));
return;
}
if (!process.env.DX_DSH_HOME || !process.env.DX_DSH_CONTEXT_FILE) throw Error('Task center context is required');
@@ -73,12 +219,7 @@ export async function bootRuntime({announce=true} = {}) {
process.env.DX_DSH_WORKSPACE = path.join(process.env.DX_DSH_HOME,'workspace');
await mkdir(process.env.DX_DSH_WORKSPACE,{recursive:true});
const dir = path.join(process.env.DX_DSH_HOME,'profiles','dx-task');
await mkdir(path.join(dir,'node_modules','@dx'),{recursive:true});
await cp(path.join(root,'task-plugin'),path.join(dir,'node_modules','@dx','dsh-task'),{recursive:true});
await writeFile(path.join(dir,'package.json'), JSON.stringify({private:true,type:'module',
dependencies:{'@dx/dsh-task':'file:'+path.join(root,'task-plugin')},
dsh:{profile:{bundles:['@deepseek-ai/dsh-base','@deepseek-ai/dsh-web-app']}}}));
await writeFile(path.join(dir,'cordis.patch.yml'),JSON.stringify(overlay(),null,2));
const modelBinding=await prepareProfileDirectory(dir);
const {runProfile, INSTALL_ANCHOR} = await import('@deepseek-ai/dsh/profile-boot');
const {loadProfileDirectory,composeEntries} = await import('@deepseek-ai/dsh-app-boot');
const {createLaunchEnvironmentSnapshot} = await import('@deepseek-ai/dsh-launch-environment');
@@ -93,8 +234,19 @@ export async function bootRuntime({announce=true} = {}) {
patchFiles:[],args:['--no-open','--host','127.0.0.1','--port','0'],
environment:createLaunchEnvironmentSnapshot([{source:'process',values:process.env}])});
await ctx.loader.await();
// Check the mounted service as well as its composition: an unexpected
// credential source must fail before exposing the runtime to the desktop.
if(modelBinding.hostCredentialBinding){
const actual=ctx.get('credentials')?await ctx.credentials.resolve('DSH_API_KEY')
:{source:'env',value:process.env.DSH_API_KEY};
if(actual?.source!==modelBinding.hostCredentialBinding.source||typeof actual?.value!=='string'
||createHash('sha256').update(actual.value).digest('hex')!==modelBinding.hostCredentialBinding.digest){
await shutdown.shutdown(1);
throw Error('Host model credential source changed during startup; startup refused.');
}
}
const names=ctx.tools.schemas().map(tool=>tool.name);
if(names.length!==7 || !['dx_task_snapshot','dx_task_create','dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute','dx_task_operations'].every(name=>names.includes(name))) {
if(names.length!==TASK_TOOLS.length+FILE_TOOLS.length || ![...TASK_TOOLS,...FILE_TOOLS].every(name=>names.includes(name))) {
await shutdown.shutdown(1);
throw Error('The task capability guard did not initialize; assistant startup refused.');
}
+4 -4
View File
@@ -13,10 +13,12 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{
h('h3',null,'任务能力'),
h('ul',null,...['在对话中创建和修改任务;具体工程与执行范围由原生窗口确认','实时监管当前执行、阶段、耗时与保存/失败/未命中计数','保存执行回执,重启后核对原队列并手动确认恢复','预览精确位号影响;仅有料号映射时明确标记未知匹配数量','检索历史异常经验,仅将持久化核验通过的记录标为已验证','只读同步已有 Git 工单状态与评论,查看本地证据','查看会话 Token、耗时与超时状态,配置响应时限并停止模型生成','设置任务优先级、执行时间与依赖,通过原生窗口确认排期'].map(text=>h('li',{key:text},text))),
h('h3',null,'模型与数据'),
h('p',null,'使用主工具配置的模型,在输入框下方选择。会话保存在本机任务中心数据目录。'),
h('p',null,'在“模型”设置页添加模型提供商或自定义模型 API,填写地址后可获取可用模型,也可手动填写模型 ID。保存后在输入框下方选择,模型设置和会话在重启后保留。'),
h('h3',null,'异常工单'),
h('p',null,'随工具预置专用工单上报身份,无需安装 Git 或登录。未解决的异常自动提交项目工单,并上传脱敏诊断证据。'),
h('p',null,'工程修改与执行核验由任务中心完成。模型不直接访问工程文件或执行命令。'));
h('h3',null,'文件与文件夹'),
h('p',null,'可上传文件、选择本地文件夹,或在对话中提供路径。助手可读取和搜索文件,ZIP 解压到新的文件夹后继续分析;重复解压不会覆盖已有文件。'),
h('p',null,'工程修改与执行核验由任务中心完成。'));
}
function SettingsLauncher({wide,openSettings}){
return h('button',{'data-testid':'dx-tool-settings',type:'button','aria-label':'工具设置',onClick:()=>openSettings(),
@@ -276,8 +278,6 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{
},'dx-task: automatic incident conversation');
ctx.slots.inject('settings.launcher',()=>ctx.slots.register({name:'settings.launcher',priority:-10},SettingsLauncher));
ctx.slots.inject('settings.section',()=>ctx.slots.register({name:'settings.section',id:'dx-tool',order:-100,label:()=>'DSH工具'},ToolSettings));
ctx.slots.inject('conversation.hero.options',()=>ctx.slots.register({name:'conversation.hero.options',id:'dx-tool-hint'},
()=>h('p',{style:{fontSize:13,color:'var(--dsw-alias-label-secondary)',textAlign:'center',margin:'4px 0 12px'}},'任务异常分析 · 规则内处理 · 执行监管')));
ctx.sidebarRightTabs.register({id:'@dx/dsh-task',kind:'dx-task',priority:'extension',title:()=>'任务监管',guide:[{id:'dx-task',order:0,title:()=>'任务监管',description:()=>'当前任务与受控操作'}]});
ctx.slots.inject('sidebar.right.pane.tab',()=>ctx.slots.register({name:'sidebar.right.pane.tab',key:'@dx/dsh-task'},TaskPanel));
ctx.slots.inject('sidebar.brand.name',()=>ctx.slots.register({name:'sidebar.brand.name',priority:-10},()=>h('span',null,'DSH助手')));
+80
View File
@@ -0,0 +1,80 @@
import {mkdir,mkdtemp,writeFile,realpath,rm} from 'node:fs/promises';
import path from 'node:path';
import {Worker} from 'node:worker_threads';
import {defineTool} from '@deepseek-ai/dsh-tools';
export const fileToolNames=['read','read_image','glob','grep','working_directory','extract_zip'];
const pending=[];
let running=0;
function startPending(){
while(running<2&&pending.length){
const job=pending.shift();
if(job.signal.aborted){job.abort();continue;}
running++;
try{
const bytes=Uint8Array.from(job.bytes);
job.worker=new Worker(new URL('./zip-worker.mjs',import.meta.url),{
workerData:{bytes,fflateUrl:import.meta.resolve('fflate')},transferList:[bytes.buffer],env:{},execArgv:[]});
let result,failure;
job.worker.once('message',value=>{result=value;});
job.worker.once('error',error=>{failure=error;});
job.worker.once('exit',code=>{
running--;job.signal.removeEventListener('abort',job.abort);
if(job.signal.aborted)job.reject(job.signal.reason??Error('ZIP extraction cancelled'));
else if(failure||result?.error||code!==0||!result?.entries)
job.reject(failure??Error(result?.error??'ZIP worker exited without a result'));
else job.resolve(result.entries);
startPending();
});
}catch(error){
running--;job.signal.removeEventListener('abort',job.abort);job.reject(error);
}
}
}
function decompress(bytes,signal){
signal.throwIfAborted();
return new Promise((resolve,reject)=>{
const job={bytes,signal,resolve,reject};
job.abort=()=>{
if(job.worker){void job.worker.terminate();return;}
const index=pending.indexOf(job);if(index>=0)pending.splice(index,1);
reject(signal.reason??Error('ZIP extraction cancelled'));
};
signal.addEventListener('abort',job.abort,{once:true});pending.push(job);startPending();
});
}
export function registerFileTools(ctx){
ctx.tools.register(defineTool({name:'extract_zip',
description:'Extract a local or uploaded ZIP archive into a new folder, returning its absolute path and file names. Relative paths use the conversation working directory. output_directory optionally selects an existing parent folder; defaults to the conversation working directory. Never overwrites existing files. Read the returned paths to inspect extracted content. ZIP only; encrypted archives are unsupported.',
parameters:{file_path:{type:'string',required:true},output_directory:{type:'string'}},
output:{schema:{type:'object',additionalProperties:true},render:(_args,value)=>[{type:'text',text:JSON.stringify(value)}]},
execute:async(args,exec)=>{
if(typeof args.file_path!=='string'||!args.file_path.trim())throw Error('file_path is required');
const cwd=exec.agent?ctx.workingDirectory.get(exec.agent.session):process.env.DX_DSH_WORKSPACE;
const target=await ctx.fs.resolve(args.file_path,{cwd,signal:exec.signal});
const bytes=await ctx.fs.readBytes(target,exec.signal,64*1024*1024);
const files=await decompress(bytes,exec.signal);
exec.signal.throwIfAborted();
const parent=await realpath(path.resolve(cwd,args.output_directory||'.'));
const directory=await mkdtemp(path.join(parent,'dsh-extracted-'));
try{
for(const [name,data] of files){
exec.signal.throwIfAborted();
const output=path.resolve(directory,name.replaceAll('\\','/'));
const relative=path.relative(directory,output);
if(relative.startsWith('..')||path.isAbsolute(relative))throw Error('Unsafe ZIP entry path');
if(name.endsWith('/'))await mkdir(output,{recursive:true});
else{await mkdir(path.dirname(output),{recursive:true});await writeFile(output,data,{flag:'wx'});}
}
return {directory,files:files.slice(0,200).map(([name])=>name),total_entries:files.length,truncated:files.length>200};
}catch(error){
// Only this invocation's newly created temporary output is removed.
if(path.dirname(directory)===parent&&path.basename(directory).startsWith('dsh-extracted-'))
await rm(directory,{recursive:true,force:true});
throw error;
}
}}));
}
+5 -3
View File
@@ -5,8 +5,9 @@ import {defineTool} from '@deepseek-ai/dsh-tools';
import {registerLifecycle,lifecycleNames} from './lifecycle.mjs';
import {registerRuntimeUsage} from './runtime_usage.mjs';
import {modelSnapshot} from './model_results.mjs';
import {registerFileTools,fileToolNames} from './files.mjs';
export const inject=['webServer','connection','tools','workspaceRegistry','sessionController','agents','llm'];
export const inject=['webServer','connection','tools','workspaceRegistry','sessionController','agents','llm','fs','workingDirectory'];
const actions=new Set(['retry_failed','pause_task','refresh_snapshot','retry_issue','open_evidence']);
export async function readContext(){
const value=JSON.parse(await readFile(process.env.DX_DSH_CONTEXT_FILE,'utf8'));
@@ -19,7 +20,7 @@ export async function apply(ctx){
const creations=new Map();
let auditTail=Promise.resolve();
ctx.on('tools/result',(exec,result)=>{
if(!['dx_task_snapshot','dx_task_create',...lifecycleNames].includes(exec.name))return;
if(!['dx_task_snapshot','dx_task_create',...lifecycleNames,...fileToolNames].includes(exec.name))return;
const row={at:new Date().toISOString(),name:exec.name,call_id:exec.callId,is_error:result.isError,
task_id:result.value?.task_id||'',revision:result.value?.revision||'',
status:result.value?.status,task_ids:result.value?.task_ids||result.value?.tasks?.map(t=>t.task_id)||[]};
@@ -112,7 +113,8 @@ export async function apply(ctx){
}finally{clearTimeout(timer);exec.signal.removeEventListener('abort',cancel);creations.delete(request_id);}
}}));
registerLifecycle(ctx);
ctx.tools.guard(exec=>exec.name==='dx_task_snapshot'||(['dx_task_create',...lifecycleNames].includes(exec.name)&&!incidentSnapshots.has(exec.agent?.id))?
registerFileTools(ctx);
ctx.tools.guard(exec=>exec.name==='dx_task_snapshot'||(['dx_task_create',...lifecycleNames,...fileToolNames].includes(exec.name)&&!incidentSnapshots.has(exec.agent?.id))?
undefined:'This tool is not enabled for this session. Automatic incident sessions may only read their snapshot.');
const workspace=await ctx.workspaceRegistry.create(process.env.DX_DSH_WORKSPACE,'DxDesigner 任务中心');
ctx.webServer.register({kind:'exact',path:'/dx/workspace',handler:async(req,res)=>{
@@ -0,0 +1,55 @@
import {parentPort,workerData} from 'node:worker_threads';
import {crc32} from 'node:zlib';
function zipChecksums(bytes){
const data=Buffer.from(bytes.buffer,bytes.byteOffset,bytes.byteLength);
let end=data.length-22;
for(;end>=Math.max(0,data.length-65557);end--)
if(data.readUInt32LE(end)===0x06054b50&&end+22+data.readUInt16LE(end+20)===data.length)break;
if(end<0||data.readUInt32LE(end)!==0x06054b50)throw Error('Invalid ZIP central directory');
if(data.readUInt16LE(end+4)||data.readUInt16LE(end+6))throw Error('Multi-volume ZIP is unsupported');
const count=data.readUInt16LE(end+10),entries=[];
if(count===65535||count>10000)throw Error('ZIP exceeds 10000 entries');
let offset=data.readUInt32LE(end+16);
for(let i=0;i<count;i++){
if(offset+46>end||data.readUInt32LE(offset)!==0x02014b50)throw Error('Invalid ZIP entry');
if(data.readUInt16LE(offset+8)&1)throw Error('Encrypted ZIP is unsupported');
const size=data.readUInt32LE(offset+24);
if(size===0xffffffff)throw Error('ZIP64 entries are unsupported');
entries.push({crc:data.readUInt32LE(offset+16),size});
offset+=46+data.readUInt16LE(offset+28)+data.readUInt16LE(offset+30)+data.readUInt16LE(offset+32);
if(offset>end)throw Error('Invalid ZIP entry length');
}
return entries;
}
try{
const {unzipSync}=await import(workerData.fflateUrl);
const bytes=workerData.bytes,checksums=zipChecksums(bytes),expected=new Map();
let expanded=0,count=0;
// A metadata-only pass finishes before any entry is decompressed.
unzipSync(bytes,{filter:entry=>{
const name=entry.name.replaceAll('\\','/');
if(name.startsWith('/')||name.split('/').some(part=>part==='..'||/[\x00-\x1f:]/.test(part)))
throw Error('Unsafe ZIP entry path');
if(entry.name==='__proto__')throw Error('Unsupported ZIP entry name: __proto__');
if(expected.has(entry.name))throw Error('Duplicate ZIP entry');
const checksum=checksums[count];
if(!checksum||checksum.size!==entry.originalSize)throw Error('Invalid ZIP entry size');
expected.set(entry.name,checksum);
expanded+=entry.originalSize;
if(++count>10000||expanded>256*1024*1024)throw Error('ZIP exceeds 10000 entries or 256 MiB expanded size');
return false;
}});
if(count!==checksums.length)throw Error('Invalid ZIP entry count');
// Synchronous inflation is confined to this single, terminable worker.
const files=unzipSync(bytes),entries=Object.entries(files);
if(entries.length!==expected.size||[...expected.keys()].some(name=>!Object.hasOwn(files,name)))
throw Error('ZIP decompressed file names do not match the archive');
for(const [name,data] of entries){
const checksum=expected.get(name);
if(!checksum||data.length!==checksum.size||crc32(data)!==checksum.crc)throw Error('ZIP checksum mismatch: '+name);
}
parentPort.postMessage({entries},[...new Set(entries.map(([,data])=>data.buffer))]);
}catch(error){parentPort.postMessage({error:error.message});}
finally{parentPort.close();}
+6
View File
@@ -33,6 +33,12 @@ legacy_runtime_datas = [
# The native assistant loads the official web UI; include its pinned Node runtime.
dsh_root = project_root / 'integration' / 'dsh'
for required in ('node_modules/@deepseek-ai/dsh/package.json', 'issue-bootstrap.json',
'start.mjs', 'package.json', 'task-plugin/host.mjs'):
if not (dsh_root / required).is_file():
raise RuntimeError(f'Complete DSH release runtime is required; missing: {required}')
if shutil.which('node') is None:
raise RuntimeError('Node executable is required for the complete release')
if (dsh_root / 'issue-bootstrap.json').is_file():
legacy_runtime_datas.append((str(dsh_root / 'issue-bootstrap.json'), 'dsh-runtime'))
if (dsh_root / 'node_modules' / '@deepseek-ai' / 'dsh' / 'package.json').is_file():
+21
View File
@@ -0,0 +1,21 @@
# Windows self-extracting release
Build the complete application with `Build-DxPartReplace.ps1` first. The spec now fails if the installed DSH package, reporter configuration or Node executable is missing. Keep the entire installed `integration/dsh/node_modules` tree, including lazy runtime dependencies.
Use the official **7-Zip 26.05 x64** tools from:
- Binary: https://github.com/ip7z/7zip/releases/download/26.05/7z2605-x64.exe
- SHA256: `fd99e86f57d8f429ef5ed045bf98315af962e2309b0f1ba87a147a44c71647d0`
- Source and license: https://github.com/ip7z/7zip/releases/tag/26.05 and https://www.7-zip.org/license.txt
Extract the installer with an existing 7-Zip tool into a build-only directory. No machine-wide installation is needed. Use that directory's `7z.exe`, `7z.dll`, `7z.sfx` and `License.txt`. The standard `7z.sfx` opens a destination selector and extracts to a persistent directory. It is not the install-to-temp SFX module; it takes no installer configuration and does not auto-launch or delete the extracted application.
```powershell
python tools/build_self_extracting_release.py --source-dir dist/DxPartReplace --output-dir G:/dx-release-1.2.2 --version 1.2.2 --seven-zip build/7zip-2605/full/7z.exe --sfx-stub build/7zip-2605/full/7z.sfx --license build/7zip-2605/full/License.txt
```
Use a fresh output directory and keep the completed build input unchanged during packaging. The tool rejects an existing directory, overlapping input/output paths and an application input containing `data`. It stages the complete input using same-volume hardlinks (copying when links are unavailable), includes the 7-Zip license, produces independent EXE + ZIP archives, and writes artifact and per-file SHA256 hashes. LZMA2 level 3 and bounded solid blocks keep decoding memory modest; tiny files still incur filesystem costs, so do not promise a fixed speedup across machines.
Before publishing, run the self-extracting EXE itself with `-y -o<fresh directory>`, compare every resulting file and every ZIP member against the manifest, and run `tools/verify_packaged_runtime.py` and Qt/DSH UI acceptance on that extracted EXE. Neither merely listing the archive nor the source UI tests replaces this check.
The optional Windows integration test exercises the real SFX with Chinese/spaced paths and empty/binary files. Set `DX_SFX_TEST_TOOLS` to the official tools directory and run `python -m pytest tests/packaging/test_self_extracting_release.py`. Linux CI runs the portable output-protection checks and explicitly skips the Windows integration.
+4 -4
View File
@@ -1,8 +1,8 @@
# UTF-8
VSVersionInfo(
ffi=FixedFileInfo(
filevers=(1, 2, 1, 0),
prodvers=(1, 2, 1, 0),
filevers=(1, 2, 2, 0),
prodvers=(1, 2, 2, 0),
mask=0x3f,
flags=0x2,
OS=0x40004,
@@ -15,11 +15,11 @@ VSVersionInfo(
StringTable('040904B0', [
StringStruct('CompanyName', 'DxProductivity'),
StringStruct('FileDescription', 'DxDesigner Part Replacement'),
StringStruct('FileVersion', '1.2.1.0'),
StringStruct('FileVersion', '1.2.2.0'),
StringStruct('InternalName', 'DxPartReplace'),
StringStruct('OriginalFilename', 'DxPartReplace.exe'),
StringStruct('ProductName', 'DxDesigner Part Replacement'),
StringStruct('ProductVersion', '1.2.1')
StringStruct('ProductVersion', '1.2.2')
])
]),
VarFileInfo([VarStruct('Translation', [1033, 1200])])
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "dx-productivity"
version = "1.2.1"
version = "1.2.2"
requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
@@ -17,22 +17,25 @@ from .store_read_model import checkpoint, read_lock
_MUTATIONS={
'create_task','create_project_tasks','create_scanned_task','update_task','delete_task',
'create_task','create_project_tasks','create_assistant_project_tasks','create_scanned_task','update_task','delete_task',
'restore_task','purge_task','add_rule','update_rule','delete_rule','move_rule',
'replace_target_plan','import_target_plan','save_bom_batch','save_plan_drafts',
'set_value_policy','move_project_task','set_project_selected','select_all_projects',
'clear_project_selection','scan_projects',
'clear_project_selection','scan_projects','refresh_bound_project','collect_target_inventory',
}
# start_new_round deliberately records inside its existing compensating
# transaction. Wrapping its filesystem moves in another transaction would let
# its inner savepoint report committed before the outer history COMMIT.
_LABELS={'create_task':'新建任务','create_project_tasks':'创建工程任务','create_scanned_task':'创建工程任务',
# Inventory collection and bound-project refresh capture only their save phase;
# their external reads and subsequent context reads stay outside this transaction.
_LABELS={'create_task':'新建任务','create_project_tasks':'创建工程任务','create_assistant_project_tasks':'助手创建工程任务','create_scanned_task':'创建工程任务',
'update_task':'编辑任务','delete_task':'归档任务','restore_task':'恢复任务','purge_task':'删除任务记录',
'add_rule':'添加规则','update_rule':'修改规则','delete_rule':'删除规则','move_rule':'调整规则顺序',
'replace_target_plan':'保存位号计划','import_target_plan':'导入位号计划','save_bom_batch':'保存 BOM 计划',
'save_plan_drafts':'保存位号计划','set_value_policy':'修改 Value 策略','move_project_task':'调整任务顺序',
'set_project_selected':'修改工程选择','select_all_projects':'全选工程',
'clear_project_selection':'清空工程选择','scan_projects':'扫描工程'}
'clear_project_selection':'清空工程选择','scan_projects':'扫描工程','refresh_bound_project':'重新读取工程',
'collect_target_inventory':'采集位号计划'}
_TABLES={
'tasks':(('task_id',),('task_id','name','note','discovery_root','status','copy_part_number_to_value',
@@ -276,9 +276,11 @@ class TaskCenterService:
paths = (project.path,)
except FileNotFoundError:
pass
self._store.sync_projects(task_id, project.discovery_root, paths)
from .history_recording import record_operation
record_operation(self, 'refresh_bound_project', task_id,
lambda: self._store.sync_projects(task_id, project.discovery_root, paths))
return self._refresh_project_context(task_id, allow_legacy=False)
return self._idle_quick_run_operation("refresh_bound_project", task_id, refresh)
return self._idle_quick_run_operation("refresh_bound_project", task_id, refresh, capture_history=False)
def _refresh_project_context(self, task_id: str, *, allow_legacy: bool, read_control=None) -> ProjectTaskContext:
def refresh() -> ProjectTaskContext:
@@ -478,16 +480,19 @@ class TaskCenterService:
runtime=runtime, **control_options(stop_event, on_progress))
check_cancelled(stop_event)
metric['completed_units'] = len(rows)
with self._store.transaction():
if self._store.list_target_plan(task_id) != prior:
raise TaskCenterError('target_identity', '位号计划在采集时已改变,请重新采集')
current = self._store.record_target_inventory(task_id, rows)
known = {row.target.key: row for row in prior}
seeded = seed_defaults(current, rules)
result = tuple(known.get(row.target.key, row) for row in seeded)
check_cancelled(stop_event)
return self._store.replace_target_plan(task_id, result)
return self._idle_quick_run_operation("collect_target_inventory", task_id, collect)
from .history_recording import record_operation
def save_inventory():
with self._store.transaction():
if self._store.list_target_plan(task_id) != prior:
raise TaskCenterError('target_identity', '位号计划在采集时已改变,请重新采集')
current = self._store.record_target_inventory(task_id, rows)
known = {row.target.key: row for row in prior}
seeded = seed_defaults(current, rules)
result = tuple(known.get(row.target.key, row) for row in seeded)
check_cancelled(stop_event)
return self._store.replace_target_plan(task_id, result)
return record_operation(self, 'collect_target_inventory', task_id, save_inventory)
return self._idle_quick_run_operation("collect_target_inventory", task_id, collect, capture_history=False)
def scan_projects(self, task_id: str, root: Path) -> tuple[ProjectRecord, ...]:
def scan_and_sync() -> tuple[ProjectRecord, ...]:
@@ -713,10 +718,7 @@ class TaskCenterService:
details={"copy_part_label_to_value": enabled})
return task
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
return self._operation("set_value_policy", task_id, update)
return self._idle_quick_run_operation("set_value_policy", task_id, update)
def execute_quick_run(self, task_id: str, *, expected_item: tuple[str, str, str, str] | None = None, runtime=None) -> QuickRunStepResult:
"""Execute one replacement rule through restoration and verification."""
@@ -1229,12 +1231,17 @@ class TaskCenterService:
name: str,
task_id: str | None,
action: Callable[[], _Result],
*,
capture_history: bool = True,
) -> _Result:
from .task_queue import assert_task_queue_idle
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
from .history_recording import record_operation
return self._operation(name, task_id, lambda: record_operation(self, name, task_id, action))
# External reads can capture their short save phase explicitly,
# retaining execution admission without holding the DB lock here.
wrapped = (lambda: record_operation(self, name, task_id, action)) if capture_history else action
return self._operation(name, task_id, wrapped)
def _manual_operation(self, name: str, task_id: str, action: Callable[[], _Result]) -> _Result:
def checked_action():
@@ -6,7 +6,7 @@ import codecs
from pathlib import Path
from PySide6.QtCore import QProcess, QProcessEnvironment, QTimer, QUrl, Signal, Qt
from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile, QWebEngineSettings
from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile, QWebEngineSettings, QWebEngineScript
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWidgets import QLabel, QPushButton, QVBoxLayout, QWidget
from shiboken6 import isValid
@@ -17,9 +17,10 @@ from ...dsh.snapshot import TaskSnapshot
class LocalHarnessPage(QWebEnginePage):
allowed_port = None
loading_url = QUrl()
def acceptNavigationRequest(self, url, kind, is_main_frame):
return url.scheme() == 'about' or (url.scheme() == 'http' and url.host() == '127.0.0.1' and url.port() == self.allowed_port)
return (url == self.loading_url and url.scheme() == 'file') or url.scheme() == 'about' or (url.scheme() == 'http' and url.host() == '127.0.0.1' and url.port() == self.allowed_port)
def createWindow(self, _kind):
return None
@@ -37,9 +38,10 @@ class NativeHarnessView(QWidget):
def __init__(self, data_root: Path, parent=None):
super().__init__(parent)
# Give Chromium its own native composition boundary. Otherwise its
# texture compositor turns the shared Acrylic top-level surface opaque,
# even after this workspace is hidden again.
# Isolate Chromium's RHI surface in this child HWND. Otherwise showing
# WebEngine recreates the translucent task-center HWND as an opaque
# graphics surface and Acrylic stays white after the view is hidden.
self.setAttribute(Qt.WidgetAttribute.WA_DontCreateNativeAncestors)
self.setAttribute(Qt.WidgetAttribute.WA_NativeWindow)
self.setObjectName('dshNativeWorkspace')
self.setStyleSheet('QWidget#dshNativeWorkspace {background:white;}')
@@ -63,10 +65,17 @@ class NativeHarnessView(QWidget):
self.profile.setCachePath(str(self.data_root / 'browser/cache'))
self.profile.setPersistentCookiesPolicy(QWebEngineProfile.PersistentCookiesPolicy.NoPersistentCookies)
self.web.setPage(LocalHarnessPage(self.profile, self.web))
bootstrap = QWebEngineScript()
bootstrap.setName('Official Harness loading until local runtime is ready')
bootstrap.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentCreation)
bootstrap.setWorldId(QWebEngineScript.ScriptWorldId.MainWorld)
bootstrap.setSourceCode("if(location.protocol==='file:'){globalThis.__DSH_BOOT_READY__={promise:new Promise(()=>{})};}")
self.web.page().scripts().insert(bootstrap)
self.web.settings().setAttribute(QWebEngineSettings.WebAttribute.JavascriptCanOpenWindows, False)
self.web.settings().setAttribute(QWebEngineSettings.WebAttribute.LocalContentCanAccessFileUrls, False)
self.status = QLabel('正在启动 DSH助手…')
self.status.setWordWrap(True)
self.status.hide()
self.retry = QPushButton('重试启动')
self.retry.hide()
self.retry.clicked.connect(self.start)
@@ -139,9 +148,9 @@ class NativeHarnessView(QWidget):
return
self._stopping = False
self._started = False
self.status.setText('正在加载 DeepSeek Harness 官方界面…')
self.status.show()
self.status.hide()
self.retry.hide()
self._show_official_loading(root)
env = QProcessEnvironment()
try:
for key, value in launch_environment(self.data_root).items():
@@ -155,7 +164,16 @@ class NativeHarnessView(QWidget):
self.process.setProgram(node)
self.process.setArguments([str(root / 'start.mjs')])
self.process.start()
self.timeout.start(120000)
# Cold startup of the official file plugins can exceed two minutes.
self.timeout.start(300000)
def _show_official_loading(self, root: Path):
frontend = root / 'node_modules/@deepseek-ai/dsh-web-frontend/dist/index.html'
if frontend.is_file():
self.web.page().loading_url = QUrl.fromLocalFile(str(frontend.resolve()))
self.web.settings().setAttribute(QWebEngineSettings.WebAttribute.LocalContentCanAccessFileUrls, True)
self.web.show()
self.web.load(self.web.page().loading_url)
def _reset_output(self):
self._buffer = ''
@@ -186,6 +204,7 @@ class NativeHarnessView(QWidget):
self.web.page().allowed_port = url.port()
self.timeout.stop()
self.status.hide()
self.web.settings().setAttribute(QWebEngineSettings.WebAttribute.LocalContentCanAccessFileUrls, False)
self.web.load(url)
self.ready.emit()
queued, self._diagnosis_queue = self._diagnosis_queue, []
@@ -219,6 +238,7 @@ class NativeHarnessView(QWidget):
self.timeout.stop()
self.status.setText(text)
self.status.show()
self.web.hide()
self.retry.show()
def _finished(self, *_):
@@ -21,6 +21,8 @@ OPERATIONS={'quick_run_executed':'替换执行','quick_run_prepared':'准备执
'quick_run_recovered':'核验恢复','quick_run_queue_paused':'暂停执行',
'quick_run_retry_prepared':'准备失败项重试','create_project_tasks':'创建工程任务',
'create_task':'新建任务','update_task':'编辑任务','delete_task':'归档任务',
'create_assistant_project_tasks':'助手创建工程任务','collect_target_inventory':'采集位号计划',
'refresh_bound_project':'重新读取工程',
'restore_task':'恢复任务','purge_task':'删除任务记录','add_rule':'添加规则',
'update_rule':'修改规则','delete_rule':'删除规则','move_rule':'调整规则顺序',
'replace_target_plan':'保存位号计划','save_plan_drafts':'保存位号计划',
@@ -1 +1 @@
VERSION = "1.2.1"
VERSION = "1.2.2"
@@ -0,0 +1,81 @@
from pathlib import Path
import os
import subprocess
import sys
import zipfile
import pytest
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'tools'))
from build_self_extracting_release import build_release
from verify_self_extracting_release import verify
def test_release_refuses_existing_output_without_deleting_it(tmp_path):
source = tmp_path / 'app'
source.mkdir()
output = tmp_path / 'valuable'
output.mkdir()
sentinel = output / 'keep.txt'
sentinel.write_text('user files')
tool = tmp_path / 'tool.exe'
tool.write_bytes(b'MZ')
with pytest.raises((FileExistsError, ValueError)):
build_release(source, output, version='1.2.2', seven_zip=tool, sfx_stub=tool)
assert sentinel.read_text() == 'user files'
def test_release_rejects_output_inside_source(tmp_path):
source = tmp_path / 'app'
source.mkdir()
tool = tmp_path / 'tool.exe'
tool.write_bytes(b'MZ')
with pytest.raises(ValueError, match='inside'):
build_release(source, source / 'out', version='1.2.2', seven_zip=tool, sfx_stub=tool)
assert not (source / 'out').exists()
def test_release_refuses_user_data_in_payload(tmp_path):
source = tmp_path / 'app'
(source / 'data').mkdir(parents=True)
(source / 'data' / 'tasks.db').write_bytes(b'private')
tool = tmp_path / 'tool.exe'
tool.write_bytes(b'MZ')
with pytest.raises(ValueError, match='data'):
build_release(source, tmp_path / 'out', version='1.2.2', seven_zip=tool, sfx_stub=tool)
assert not (tmp_path / 'out').exists()
@pytest.mark.skipif(os.name != 'nt' or not os.environ.get('DX_SFX_TEST_TOOLS'),
reason='Windows and explicit official 7-Zip tools required')
def test_actual_sfx_and_zip_extract_identical_unicode_and_empty_files(tmp_path):
tools = Path(os.environ['DX_SFX_TEST_TOOLS']).resolve()
source = tmp_path / 'payload'
source.mkdir()
(source / 'DxPartReplace.exe').write_bytes(b'sample application')
(source / '中文 目录').mkdir()
(source / '中文 目录' / '空.txt').write_bytes(b'')
(source / '中文 目录' / 'file.bin').write_bytes(bytes(range(256)) * 2048)
(source / 'licenses').mkdir()
original_license=source/'licenses'/'7-Zip-LICENSE.txt'
original_license.write_text('original input must remain unchanged')
output = tmp_path / 'release'
manifest = build_release(source, output, version='1.2.2', seven_zip=tools/'7z.exe',
sfx_stub=tools/'7z.sfx', license_path=tools/'License.txt')
assert original_license.read_text() == 'original input must remain unchanged'
destination = tmp_path / '解压 结果'
result = verify(output/'release-manifest-1.2.2.json', destination)
assert result['passed'] and result['files'] == 4
with zipfile.ZipFile(output/'DxPartReplace-1.2.2.zip') as archive:
assert archive.testzip() is None
assert {p.relative_to(destination).as_posix() for p in destination.rglob('*') if p.is_file()} == set(archive.namelist())
assert len(archive.namelist()) == 4 == manifest['file_count']
for name in archive.namelist():
assert (destination/name).read_bytes() == archive.read(name)
assert (destination/'DxPartReplace'/'中文 目录'/'file.bin').read_bytes() == bytes(range(256))*2048
with (output/'DxPartReplace-1.2.2.exe').open('ab') as stream:
stream.write(b'corrupt download')
with pytest.raises(ValueError, match='Artifact checksum'):
verify(output/'release-manifest-1.2.2.json', tmp_path/'corrupt-extraction')
assert not (tmp_path/'corrupt-extraction').exists()
+7 -1
View File
@@ -5,6 +5,7 @@ from types import SimpleNamespace
from pathlib import Path
import subprocess
import pytest
from shiboken6 import isValid
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.service import TaskCenterService
@@ -45,4 +46,9 @@ def ui(qtbot, tmp_path):
open_task(tasks[0])
yield SimpleNamespace(window=window,service=service,store=store,tasks=tasks,
calls=calls,settle=settle,open=open_task,data=data)
settle();window.plan_panel.discard_all();window.close();store.close()
if isValid(window):
settle()
if isValid(window):
window.plan_panel.discard_all()
window.close()
store.close()
+6 -2
View File
@@ -201,7 +201,8 @@ def test_runtime_restart_discards_partial_protocol_and_utf8_characters(qtbot,tmp
setattr(state.process,method,lambda *args:None)
state.is_running=False
state.data_root=tmp_path
state.status=SimpleNamespace(setText=lambda *args:None,show=lambda:None)
state.status=SimpleNamespace(setText=lambda *args:None,show=lambda:None,hide=lambda:None)
state._show_official_loading=lambda root:None
state.retry=SimpleNamespace(hide=lambda:None)
state.timeout=SimpleNamespace(start=lambda *args:None)
package=tmp_path/'node_modules/@deepseek-ai/dsh/package.json'
@@ -264,7 +265,9 @@ def test_bad_line_does_not_block_following_local_runtime_handshake(qtbot):
state,chunks=protocol_state(qtbot)
loaded=[];ready=[]
page=SimpleNamespace(allowed_port=None)
state.web=SimpleNamespace(page=lambda:page,load=loaded.append)
settings_calls=[]
state.web=SimpleNamespace(page=lambda:page,load=loaded.append,
settings=lambda:SimpleNamespace(setAttribute=lambda *args:settings_calls.append(args)))
state.timeout=SimpleNamespace(stop=lambda:None)
state.status=SimpleNamespace(hide=lambda:None)
state._diagnosis_queue=[]
@@ -273,4 +276,5 @@ def test_bad_line_does_not_block_following_local_runtime_handshake(qtbot):
NativeHarnessView._stdout(state)
assert state._started and ready==[True]
assert page.allowed_port==12345
assert settings_calls[-1][1] is False
assert [url.toString()for url in loaded]==['http://127.0.0.1:12345/']
@@ -0,0 +1,173 @@
"""Real service mutations must commit their history at the same SQL boundary."""
from concurrent.futures import ThreadPoolExecutor
from threading import Event
from types import SimpleNamespace
import pytest
from dx_productivity.dsh.task_creation import validate_creation_spec
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.history_store import HistoryRepository
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import ComponentTarget
@pytest.fixture
def case(tmp_path):
root=tmp_path/'projects'
paths=[]
for name in ('A','B'):
path=root/name/'board.prj';path.parent.mkdir(parents=True)
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
paths.append(path)
store=TaskStore(tmp_path/'tasks.db')
service=TaskCenterService(store,configure_logging(tmp_path/'data'))
spec=validate_creation_spec({'name':'Assistant history','note':'sample',
'rules':[{'old_part_number':'OLD','new_part_number':'NEW'}]})
yield SimpleNamespace(store=store,service=service,root=root,paths=tuple(paths),spec=spec,
history=HistoryRepository(store))
store.close()
def bound_task(case):
task=case.service.create_project_tasks(case.root,selected_paths=(case.paths[0],))[0]
case.service.add_rule(task.task_id,'OLD','NEW')
target=ComponentTarget(case.paths[0],'MAIN','1','uid-1','R1','OLD','10K')
case.service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory=lambda *args,**kwargs:(target,)
return task
def events(case,operation):
return tuple(row for row in case.history.page().rows if row['operation']==operation)
def test_assistant_creation_records_task_project_and_rule_changes_per_task(case):
result=case.service.create_assistant_project_tasks('a'*32,case.spec,case.root,case.paths)
rows=events(case,'create_assistant_project_tasks')
assert len(rows)==2 and {row['task_id'] for row in rows}==set(result['task_ids'])
for row in rows:
changes=row['details']['changes']
assert {change['table'] for change in changes}=={'tasks','projects','rules'}
assert all(change['before'] is None for change in changes)
rule=next(change for change in changes if change['table']=='rules')
assert rule['after']['old_part_number']=='OLD' and rule['after']['new_part_number']=='NEW'
def test_assistant_request_replay_does_not_duplicate_history(case):
first=case.service.create_assistant_project_tasks('a'*32,case.spec,case.root,case.paths)
before=case.history.page().rows
replay=case.service.create_assistant_project_tasks('a'*32,case.spec,case.root,case.paths)
assert replay['replayed'] and replay['task_ids']==first['task_ids']
assert case.history.page().rows==before
def test_refresh_bound_project_records_exact_availability_change(case):
task=bound_task(case)
case.paths[0].rename(case.paths[0].with_suffix('.moved'))
case.service.refresh_bound_project(task.task_id)
rows=events(case,'refresh_bound_project')
assert len(rows)==1
change=next(change for change in rows[0]['details']['changes'] if change['table']=='projects')
assert change['before']['available']==1 and change['after']['available']==0
assert not case.store.list_projects(task.task_id)[0].available
def test_unchanged_refresh_and_context_polling_do_not_manufacture_history(case):
task=bound_task(case)
before=case.history.page().rows
for _ in range(2):
case.service.refresh_bound_project(task.task_id)
case.service.task_context(task.task_id)
assert case.history.page().rows==before
def test_collect_inventory_records_plan_defaults_and_mode_in_one_event(case):
task=bound_task(case)
case.service.collect_target_inventory(task.task_id,('OLD',),runtime=object())
rows=events(case,'collect_target_inventory')
assert len(rows)==1 and rows[0]['task_id']==task.task_id
changes=rows[0]['details']['changes']
target=next(change for change in changes if change['table']=='target_plan')
assert target['before'] is None
assert target['after']['refdes']=='R1' and target['after']['new_part_number']=='NEW'
task_change=next(change for change in changes if change['table']=='tasks')
assert task_change['before']['target_plan_mode']==0 and task_change['after']['target_plan_mode']==1
def test_identical_inventory_collection_does_not_duplicate_history(case):
task=bound_task(case)
case.service.collect_target_inventory(task.task_id,('OLD',),runtime=object())
before=case.history.page().rows
case.service.collect_target_inventory(task.task_id,('OLD',),runtime=object())
assert case.history.page().rows==before
def test_value_policy_records_actual_change_and_ignores_repeated_value(case):
task=bound_task(case)
case.service.set_copy_part_number_to_value(task.task_id,True)
rows=events(case,'set_value_policy')
assert len(rows)==1
change=next(change for change in rows[0]['details']['changes'] if change['table']=='tasks')
assert change['before']['copy_part_number_to_value']==0 and change['after']['copy_part_number_to_value']==1
before=case.history.page().rows
case.service.set_copy_part_number_to_value(task.task_id,True)
assert case.history.page().rows==before
@pytest.mark.parametrize('operation',['create_assistant_project_tasks','collect_target_inventory','refresh_bound_project','set_value_policy'])
def test_history_write_failure_rolls_back_each_real_service_mutation(case,monkeypatch,operation):
task=None if operation=='create_assistant_project_tasks' else bound_task(case)
before=case.history.page().rows
def fail(*args,**kwargs):raise OSError('controlled history write failure')
monkeypatch.setattr(HistoryRepository,'append',fail)
with pytest.raises(TaskCenterError):
if operation=='create_assistant_project_tasks':
case.service.create_assistant_project_tasks('b'*32,case.spec,case.root,case.paths)
elif operation=='collect_target_inventory':
case.service.collect_target_inventory(task.task_id,('OLD',),runtime=object())
elif operation=='set_value_policy':
case.service.set_copy_part_number_to_value(task.task_id,True)
else:
case.paths[0].rename(case.paths[0].with_suffix('.moved'))
case.service.refresh_bound_project(task.task_id)
assert case.history.page().rows==before
if task is None:
assert case.store.list_tasks()==() and case.store.assistant_creation_receipt('b'*32) is None
elif operation=='collect_target_inventory':
assert case.store.list_target_plan(task.task_id)==() and not case.store.get_task(task.task_id).target_plan_mode
elif operation=='set_value_policy':
assert not case.store.get_task(task.task_id).copy_part_number_to_value
else:
assert case.store.list_projects(task.task_id)[0].available
def test_cancelled_inventory_read_saves_neither_plan_nor_history(case):
task=bound_task(case)
before=case.history.page().rows;stop=Event()
def collect(*args,**kwargs):stop.set();return ()
case.service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory=collect
with pytest.raises(TaskCenterError) as error:
case.service.collect_target_inventory(task.task_id,('OLD',),runtime=object(),stop_event=stop)
assert error.value.code=='operation_cancelled'
assert case.history.page().rows==before and not case.store.list_target_plan(task.task_id)
def test_history_writes_remain_available_while_cad_inventory_read_is_waiting(case):
task=bound_task(case);started=Event();release=Event()
def collect(*args,**kwargs):
started.set()
if not release.wait(5):raise RuntimeError('inventory test was not released')
return (ComponentTarget(case.paths[0],'MAIN','1','uid-1','R1','OLD','10K'),)
case.service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory=collect
with ThreadPoolExecutor(max_workers=2) as pool:
inventory=pool.submit(case.service.collect_target_inventory,task.task_id,('OLD',),runtime=object())
try:
assert started.wait(3)
other=pool.submit(case.history.append,task_id=task.task_id,task_name=task.name,
operation='probe',summary='concurrent history write')
other.result(timeout=2)
finally:release.set()
assert inventory.result(timeout=5)
assert len(events(case,'collect_target_inventory'))==1 and len(events(case,'probe'))==1
+46 -2
View File
@@ -31,6 +31,7 @@ def main():
parser.add_argument('--output',type=Path,default=Path('build/acrylic-acceptance'))
parser.add_argument('--webengine-roundtrip',action='store_true')
parser.add_argument('--history',action='store_true')
parser.add_argument('--dsh-switch',action='store_true',help='Measure live Acrylic after entering the actual DSH WebEngine page')
args=parser.parse_args();out=args.output.resolve();out.mkdir(parents=True,exist_ok=True)
app=QApplication([]);app.setFont(QFont('Microsoft YaHei UI',9))
def settle(seconds=.2):
@@ -83,6 +84,9 @@ def main():
report['native_enabled']=True
def capture(name):
QCursor.setPos(window.mapToGlobal(QPoint(12,12)))
report.setdefault('surfaces',{})[name]={
'hwnd':int(window.winId()),'translucent':window.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground),
'alpha':window.windowHandle().format().alphaBufferSize(),'acrylic':window.property('acrylicEnabled')}
settle(.7)
QToolTip.hideText();settle(.12)
geo=window.geometry();scale=screen.devicePixelRatio()
@@ -149,6 +153,40 @@ def main():
(out/'roundtrip-probe.json').write_text(json.dumps(report,indent=2),encoding='utf8')
assert report[f'roundtrip_{index}_sidebar_difference']>2,report
assert report[f'roundtrip_{index}_table_difference']<1.5,report
if args.dsh_switch:
from PySide6.QtTest import QTest
QTest.mouseClick(window.dsh_navigation,Qt.MouseButton.LeftButton)
deadline=time.monotonic()+120
while time.monotonic()<deadline:
settle(.1)
if window._dsh_view is not None and window._dsh_view._started:break
assert window._dsh_view is not None and window._dsh_view._started,'DSH did not start'
# READY precedes the Chromium load; require the real visible page.
loaded=[]
window._dsh_view.web.page().runJavaScript("document.body?.innerText?.includes('DSH助手')",loaded.append)
deadline=time.monotonic()+60
while time.monotonic()<deadline:
settle(.1)
if loaded and loaded[-1]:break
if loaded:
loaded.clear()
window._dsh_view.web.page().runJavaScript("document.body?.innerText?.includes('DSH助手')",loaded.append)
assert loaded and loaded[-1],'Official DSH UI did not load'
capture('dsh-before-return')
QTest.mouseClick(window.task_center_navigation,Qt.MouseButton.LeftButton)
settle(.5)
background.phase=0;background.update();capture('returned-backdrop-a')
background.phase=1;background.update();capture('returned-backdrop-b')
returned=ImageChops.difference(captures['returned-backdrop-a'],captures['returned-backdrop-b'])
assert report['surfaces']['native-app-backdrop-a']['hwnd']==report['surfaces']['returned-backdrop-a']['hwnd'],report
report['after_dsh_sidebar_difference']=mean(returned.crop(sidebar))
report['after_dsh_header_difference']=mean(returned.crop(header))
report['after_dsh_table_difference']=mean(returned.crop(table))
(out/'surface-probe.json').write_text(json.dumps(report,indent=2),encoding='utf8')
assert report['after_dsh_sidebar_difference']>2,report
assert report['after_dsh_header_difference']>2,report
assert report['after_dsh_table_difference']<1.5,report
report['real_dsh_switch_restored_acrylic']=True
window.plan_panel.find_text.setText('RV');window.plan_panel.find()
report['visible_search_feedback']=window.plan_panel.find_result.isVisible()
assert '2 / 6'in window.plan_panel.find_result.text()
@@ -234,15 +272,21 @@ def main():
modal.grab().save(str(out/'native-app-history-clear-confirm.png'))
QTest.mouseClick(modal.button(QMessageBox.StandardButton.Yes),Qt.MouseButton.LeftButton)
QTimer.singleShot(100,confirm_history)
assert panel.clear_button.isEnabled(),{'status':panel.status.text(),'mutation_enabled':panel._mutations_enabled}
panel.clear_button.click();wait_history()
assert panel.table.rowCount()==0
assert panel.table.rowCount()==0,{'status':panel.status.text(),'clear_success':panel._clear_success,
'mutation_enabled':panel._mutations_enabled,'rows':panel.table.rowCount()}
assert len(service.tasks())==2
capture('native-app-history-cleared')
report['history_search_clear_and_task_preservation']=True
window.task_center_action.trigger();settle(.2)
window.project_options_button.setChecked(True);settle(.2)
report['options_exposed']=window.run_panel.copy_value_check.isVisible()
window.plan_panel.discard_all();window.close();settle(.3);store.close();logging.shutdown()
window.plan_panel.discard_all();window.close()
deadline=time.monotonic()+15
while window.isVisible() and time.monotonic()<deadline:settle(.1)
assert not window.isVisible(),'Window did not finish shutdown'
settle(.3);store.close();logging.shutdown()
background.close();app.processEvents()
(out/'acceptance.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(report,ensure_ascii=True))
+69 -4
View File
@@ -32,6 +32,8 @@ def main():
parser.add_argument('--port', type=int, default=9227)
parser.add_argument('--provider-config', type=Path)
parser.add_argument('--live-model', action='store_true')
parser.add_argument('--model-settings-check', action='store_true', help='Create an isolated custom provider using a local model-list fixture')
parser.add_argument('--file-check', action='store_true', help='Pick and upload a real local text file and ZIP in the official UI')
parser.add_argument('--incident', action='store_true', help='Inject a read-only controlled failure and verify automatic diagnosis and Git escalation')
parser.add_argument('--outbox-only', action='store_true', help='Verify failed publication stays in local outbox without creating another real issue')
parser.add_argument('--without-git', action='store_true', help='Simulate a client with no Git credentials or executable')
@@ -39,6 +41,13 @@ def main():
args = parser.parse_args()
output = args.output.resolve()
output.mkdir(parents=True, exist_ok=True)
if args.file_check:
import zipfile
fixtures = output / 'file-fixtures'
fixtures.mkdir(exist_ok=True)
(fixtures / 'dsh-upload.txt').write_text('DSH_UPLOAD_CONTENT_中文\n', encoding='utf8')
with zipfile.ZipFile(fixtures / 'dsh-upload.zip', 'w', zipfile.ZIP_DEFLATED) as archive:
archive.writestr('中文目录/说明.txt', 'DSH_ZIP_UPLOAD_CONTENT_中文')
data = output / ('data-' + time.strftime('%Y%m%d-%H%M%S'))
project_root = output / 'source-projects'
source_hashes = {}
@@ -64,14 +73,16 @@ def main():
os.environ.pop('QT_QPA_PLATFORM', None)
from PySide6.QtCore import QTimer, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QMessageBox, QDialogButtonBox
from PySide6.QtWidgets import QApplication, QMessageBox, QDialogButtonBox, QFileDialog, QLineEdit
if args.file_check:
QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeDialogs)
from dx_productivity.trial_task_center import application
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
from dx_productivity.trial_task_center.ui.dsh_task_creation import DshTaskCreationDialog
report = {'driver': 'Qt QTest mouse clicks + Chromium CDP Input events', 'checks': []}
state = {'phase': 'select', 'child': None, 'creation_step': 'input',
'deadline': time.monotonic() + (420 if args.incident else 300 if args.create_task else 240 if args.live_model else 150)}
'deadline': time.monotonic() + (600 if args.file_check else 420 if args.incident else 300 if args.create_task else 240 if args.live_model else 150)}
def build_window(service):
if not args.create_task:
@@ -90,6 +101,8 @@ def main():
def failed(error):
report.update(status='failed', error=type(error).__name__ + ': ' + str(error))
if window._dsh_view is not None:
report['runtimeStatus'] = window._dsh_view.status.text()
(output / 'desktop-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
child = state['child']
if child and child.poll() is None:
@@ -101,7 +114,43 @@ def main():
try:
if time.monotonic() > state['deadline']:
raise TimeoutError('Native desktop acceptance timed out')
if state['phase'] == 'ready' and window._dsh_view is not None and window._dsh_view.retry.isVisible():
from dx_productivity.dsh.provider_config import load_provider
key = load_provider(data / 'dsh').get('DSH_API_KEY', '')
diagnostic = window._dsh_view.last_error
if key:
diagnostic = diagnostic.replace(key, '[redacted]')
report['startupDiagnostic'] = diagnostic[-8000:]
raise RuntimeError(window._dsh_view.status.text())
modal = QApplication.activeModalWidget()
if state['phase'] == 'ready' and window._dsh_view is not None and not report.get('officialLoadingPassed') and not state.get('checkingLoading'):
state['checkingLoading'] = True
def loading_ready(value):
state['checkingLoading'] = False
if value and not report.get('officialLoadingPassed'):
assert not window._dsh_view.status.isVisible()
report['officialLoadingPassed'] = True
state['loadingCapture'] = subprocess.Popen(['node', str(REPO / 'tools/dsh_cdp.mjs'),
'--capture-loading', str(args.port), str(output / 'official-loading.png')],
cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
report['checks'].append('unmodified official frontend HARNESS loading spinner rendered before local runtime readiness')
window._dsh_view.web.page().runJavaScript("!!document.querySelector('[data-dsh-boot] [data-dsh-boot-spinner]')", loading_ready)
if args.file_check and isinstance(modal, QFileDialog) and not modal.property('dshAcceptancePicked'):
modal.setProperty('dshAcceptancePicked', True)
selected = (output / 'file-picker-request.json')
assert selected.is_file(), 'Unexpected file picker'
files = json.loads(selected.read_text(encoding='utf8'))
edit = modal.findChild(QLineEdit, 'fileNameEdit')
assert edit is not None
QApplication.clipboard().setText(' '.join('"' + str(Path(f).resolve()) + '"' for f in files))
edit.setFocus()
QTest.keyClick(edit, Qt.Key.Key_A, Qt.KeyboardModifier.ControlModifier)
QTest.keyClick(edit, Qt.Key.Key_V, Qt.KeyboardModifier.ControlModifier)
buttons = modal.findChild(QDialogButtonBox)
assert buttons is not None
QTest.mouseClick(buttons.button(QDialogButtonBox.StandardButton.Open), Qt.MouseButton.LeftButton)
report['checks'].append('selected owned text and ZIP fixtures in the real Qt file picker and clicked Open')
if args.create_task and isinstance(modal, DshTaskCreationDialog):
if state['creation_step'] == 'input':
assert modal.name_edit.text() == 'DSH对话换料验收'
@@ -123,6 +172,7 @@ def main():
assert window.task_list.list.count() == 0
click_navigation(window.dsh_action)
state['phase'] = 'ready'
state['runtimeWaitStarted'] = time.monotonic()
report['checks'].append('opened native assistant from an empty task center')
elif state['phase'] == 'select' and window.task_list.list.count() and not window._task_query.busy:
item = window.task_list.list.item(0)
@@ -141,11 +191,18 @@ def main():
assert window.content_stack.currentWidget() is window._dsh_view
report['checks'].append('clicked task row and opened DSH with one click on the right navigation item')
state['phase'] = 'ready'
state['runtimeWaitStarted'] = time.monotonic()
elif state['phase'] == 'ready' and window._dsh_view is not None and window._dsh_view._started:
if 'runtimeWaitStarted' in state:
report['runtimeWaitSeconds'] = round(time.monotonic() - state['runtimeWaitStarted'], 2)
script = 'verify_dsh_task_creation_ui.mjs' if args.create_task else 'verify_dsh_incident_ui.mjs' if args.incident else 'verify_dsh_native_ui.mjs'
command = ['node', str(REPO / 'tools' / script), str(output), str(args.port), '--confirm-cancel']
if args.live_model:
command.append('--live-model')
if args.model_settings_check:
command.append('--model-settings-check')
if args.file_check:
command.append('--file-check')
if args.outbox_only:
command.append('--outbox-only')
state['child'] = subprocess.Popen(command, cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
@@ -212,6 +269,14 @@ def main():
application._load_window = lambda: build_window
code = application.main(['--data-root', str(data)])
capture = state.get('loadingCapture')
if capture is not None:
try:
capture.communicate(timeout=5)
except subprocess.TimeoutExpired:
capture.terminate()
capture.communicate(timeout=5)
report['officialLoadingScreenshot'] = capture.returncode == 0
if code or report.get('status') != 'passed':
print(json.dumps(report, ensure_ascii=False))
return 1
@@ -223,8 +288,8 @@ def main():
audit_file = data / 'dsh/harness-home/task-tool-audit.jsonl'
audit = [json.loads(line) for line in audit_file.read_text(encoding='utf8').splitlines()] if audit_file.is_file() else []
report['modelToolCalls'] = audit
expected_tool = 'dx_task_create' if args.create_task else 'dx_task_snapshot'
report['modelToolSucceeded'] = any(row['name'] == expected_tool and row['is_error'] is False for row in audit)
expected_tools = ['read', 'extract_zip'] if args.file_check else ['dx_task_create' if args.create_task else 'dx_task_snapshot']
report['modelToolSucceeded'] = all(any(row['name'] == name and row['is_error'] is False for row in audit) for name in expected_tools)
(output / 'desktop-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
print(json.dumps(report, ensure_ascii=True))
return 0 if report['cleanShutdown'] and not report['uncaughtErrors'] and not report['unexpectedUiErrors'] and (not (args.live_model or args.incident or args.create_task) or report['modelToolSucceeded']) else 1
+130
View File
@@ -0,0 +1,130 @@
"""Create the ZIP and 7-Zip self-extracting artifacts for a release."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
from pathlib import Path
import shutil
import subprocess
import zipfile
from self_extracting_release import build_sfx
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _zip_tree(source: Path, output: Path) -> int:
files = 0
with zipfile.ZipFile(output, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=6, allowZip64=True) as archive:
for path in sorted(source.rglob("*")):
if path.is_file():
archive.write(path, path.relative_to(source.parent).as_posix())
files += 1
return files
def _stage_file(source, destination):
# Release input is immutable during packaging. Same-volume links avoid a
# second copy of tens of thousands of runtime files; archives are independent.
try:
os.link(source, destination)
except OSError:
shutil.copyfile(source, destination)
return destination
def build_release(source_dir: Path, output_dir: Path, *, version: str, seven_zip: Path, sfx_stub: Path,
license_path: Path | None = None) -> dict:
source_dir = Path(source_dir).resolve(strict=True)
output_dir = Path(output_dir).resolve()
if not source_dir.is_dir():
raise ValueError("source_dir must be a directory")
if output_dir.is_relative_to(source_dir) or source_dir.is_relative_to(output_dir):
raise ValueError('Output must not be inside or contain the source directory')
if (source_dir / 'data').exists():
raise ValueError('Release input must not include user data')
if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.]+)?', version):
raise ValueError('Invalid release version')
seven_zip = Path(seven_zip).resolve(strict=True)
sfx_stub = Path(sfx_stub).resolve(strict=True)
output_dir.mkdir(parents=True, exist_ok=False)
staging = output_dir / "staging" / "DxPartReplace"
shutil.copytree(source_dir, staging, copy_function=_stage_file)
if license_path is not None:
license_target = staging / "licenses" / "7-Zip-LICENSE.txt"
license_target.parent.mkdir(parents=True, exist_ok=True)
# Break a possible staging hardlink before replacing a pre-existing notice.
license_target.unlink(missing_ok=True)
shutil.copyfile(Path(license_path).resolve(strict=True), license_target)
archive_7z = output_dir / f"DxPartReplace-{version}.7z"
subprocess.run([
str(seven_zip), "a", "-t7z", "-mx=3", "-m0=LZMA2", "-mmt=4", "-ms=64m",
str(archive_7z), "DxPartReplace"
], cwd=staging.parent, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
timeout=3600)
zip_path = output_dir / f"DxPartReplace-{version}.zip"
file_count = _zip_tree(staging, zip_path)
sfx_path = output_dir / f"DxPartReplace-{version}.exe"
build_sfx(sfx_stub, archive_7z, sfx_path)
archive_7z.unlink()
manifest = {
"version": version,
"file_count": file_count,
"artifacts": {
zip_path.name: {"bytes": zip_path.stat().st_size, "sha256": _sha256(zip_path)},
sfx_path.name: {"bytes": sfx_path.stat().st_size, "sha256": _sha256(sfx_path)},
},
"extractor": {
"kind": "7zip-sfx",
"stub": sfx_stub.name,
"stub_sha256": _sha256(sfx_stub),
"compressor": seven_zip.name,
"compressor_sha256": _sha256(seven_zip),
"version_output": subprocess.check_output([str(seven_zip)], text=True, errors='replace')[:500],
"settings": "LZMA2 level 3, 4 threads, 64 MiB solid blocks",
},
"files": {path.relative_to(staging.parent).as_posix(): _sha256(path)
for path in sorted(staging.rglob('*')) if path.is_file()},
}
(output_dir / f"release-manifest-{version}.json").write_text(
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
(output_dir / f"SHA256SUMS-{version}.txt").write_text(
"".join(f"{item['sha256']} {name}\n" for name, item in manifest["artifacts"].items()),
encoding="ascii",
)
return manifest
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--source-dir", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--version", required=True)
parser.add_argument("--seven-zip", type=Path, required=True)
parser.add_argument("--sfx-stub", type=Path, required=True)
parser.add_argument("--license", type=Path)
args = parser.parse_args()
manifest = build_release(args.source_dir, args.output_dir, version=args.version,
seven_zip=args.seven_zip, sfx_stub=args.sfx_stub,
license_path=args.license)
print(json.dumps(manifest, ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+15 -5
View File
@@ -1,12 +1,14 @@
/** Tiny CDP driver for the real Qt Chromium page; no browser mocks. */
import {writeFile} from 'node:fs/promises';
export async function connect(port=9226) {
export async function connect(port=9226,{loading=false}={}) {
let target;
const deadline=Date.now()+45000;
const deadline=Date.now()+60000;
while(Date.now()<deadline){
const targets=await fetch(`http://127.0.0.1:${port}/json`,{signal:AbortSignal.timeout(3000)}).then(r=>r.json());
target=targets.find(x=>x.type==='page'&&x.url?.startsWith('http://127.0.0.1:'));
let targets;
try{targets=await fetch(`http://127.0.0.1:${port}/json`,{signal:AbortSignal.timeout(10000)}).then(r=>r.json());}
catch{await new Promise(resolve=>setTimeout(resolve,100));continue;}
target=targets.find(x=>x.type==='page'&&(loading?x.url?.startsWith('file:'):x.url?.startsWith('http://127.0.0.1:')));
if(target)break;
await new Promise(resolve=>setTimeout(resolve,100));
}
@@ -60,11 +62,19 @@ export async function connect(port=9226) {
}
if(process.argv[1]?.endsWith('dsh_cdp.mjs')) {
const client=await connect(Number(process.argv[2] || 9226));
const loading=process.argv[2]==='--capture-loading';
const client=await connect(Number(process.argv[loading?3:2] || 9226),{loading});
try {
if(loading){
const actual=await client.evaluate(`({official:!!document.querySelector('[data-dsh-boot-spinner]'),text:document.body.innerText})`);
if(!actual.official||!actual.text.includes('HARNESS'))throw Error('Official loading page was not rendered');
await client.screenshot(process.argv[4]);
console.log(JSON.stringify({officialLoading:true}));
}else{
console.log(JSON.stringify(await client.evaluate(`({title:document.title,text:document.body.innerText,
buttons:[...document.querySelectorAll('button')].map(x=>({text:x.innerText,label:x.getAttribute('aria-label'),title:x.title})),
svg:document.querySelectorAll('svg').length,animations:document.getAnimations().length,
animatedSvg:document.querySelectorAll('animate,animateTransform,animateMotion').length,canvas:document.querySelectorAll('canvas').length})`)));
}
}finally{client.close();}
}
+45
View File
@@ -0,0 +1,45 @@
"""Build a 7-Zip SFX wrapper around a prepared .7z release archive."""
from __future__ import annotations
from pathlib import Path
import os
import shutil
def build_sfx(
stub: Path,
archive: Path,
output: Path,
) -> Path:
"""Use the official 7z.sfx extractor (not the temporary installer stub).
Its native dialog selects a persistent destination. No installer config,
registry modifications, temporary extraction or automatic launch is needed.
"""
stub = Path(stub)
archive = Path(archive)
output = Path(output)
if not stub.is_file() or not archive.is_file():
raise FileNotFoundError("SFX stub and archive must both exist")
if output.exists():
raise FileExistsError(output)
with stub.open('rb') as stream:
if stream.read(2) != b'MZ':
raise ValueError('Expected Windows SFX executable')
with archive.open('rb') as stream:
if stream.read(6) != b'7z\xbc\xaf\x27\x1c':
raise ValueError('Expected 7z archive')
output.parent.mkdir(parents=True, exist_ok=True)
temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp")
try:
with temporary.open("xb") as target:
for source in (stub, archive):
with source.open('rb') as stream:
shutil.copyfileobj(stream, target, 1024 * 1024)
target.flush()
os.fsync(target.fileno())
os.replace(temporary, output)
finally:
temporary.unlink(missing_ok=True)
return output
+44
View File
@@ -0,0 +1,44 @@
/** Upload owned files via the real composer menu and Qt's actual file chooser. */
import assert from 'node:assert/strict';
import {writeFile,readdir,readFile} from 'node:fs/promises';
import path from 'node:path';
export async function verifyFileUi(c,output){
const wait=async(expression)=>{
const end=Date.now()+30000;
while(Date.now()<end){if(await c.evaluate(expression))return;await new Promise(r=>setTimeout(r,100));}
throw Error('File UI timed out: '+expression);
};
const fixtures=path.join(output,'file-fixtures');
const files=['dsh-upload.txt','dsh-upload.zip'].map(name=>path.join(fixtures,name));
await writeFile(path.join(output,'file-picker-request.json'),JSON.stringify(files));
// Plus opens the official command menu; choose its native attachment action.
const plus=`[...document.querySelectorAll('button[aria-label="添加文件或调用指令"]')].find(e=>e.getBoundingClientRect().width>0)`;
await c.click(plus);
const fileOption=`[...document.querySelectorAll('[role="option"],button')].find(e=>e.getBoundingClientRect().width>0&&/^文件\\s*file/.test(e.textContent.trim()))`;
await wait(`!!(${fileOption})`);
await c.click(fileOption);
await wait(`document.body.innerText.includes('dsh-upload.txt')&&document.body.innerText.includes('dsh-upload.zip')`);
await wait(`![...document.querySelectorAll('[role="progressbar"]')].some(e=>e.getBoundingClientRect().width>0)`);
await c.screenshot(path.join(output,'file-uploaded.png'));
// Validate the uploaded bytes in Harness's actual owned storage, not the DOM echo.
const roots=(await readdir(output)).filter(x=>x.startsWith('data-'));
assert.equal(roots.length,1);
const home=path.join(output,roots[0],'dsh/harness-home');
const expected=await Promise.all(files.map(f=>readFile(f)));
const found=new Set();
async function scan(dir){
for(const entry of await readdir(dir,{withFileTypes:true})){
const filename=path.join(dir,entry.name);
if(entry.isDirectory())await scan(filename);
else if(entry.isFile()){
const data=await readFile(filename);
expected.forEach((bytes,i)=>{if(data.equals(bytes))found.add(i);});
}
}
}
const end=Date.now()+20000;
while(found.size<files.length&&Date.now()<end){await scan(home);if(found.size<files.length)await new Promise(r=>setTimeout(r,150));}
assert.equal(found.size,2,'text and ZIP must reach actual Harness file storage unchanged');
return {status:'passed',realQtFilePicker:true,textAndZipUploaded:true,storedBytesMatched:true};
}
+77
View File
@@ -0,0 +1,77 @@
/** Exercise actual Harness file tools against owned folders and ZIP archives. */
import assert from 'node:assert/strict';
import {mkdir,mkdtemp,writeFile,readFile,readdir} from 'node:fs/promises';
import path from 'node:path';
import {createRequire} from 'node:module';
import {bootRuntime} from '../integration/dsh/start.mjs';
const require=createRequire(new URL('../integration/dsh/start.mjs',import.meta.url));
const {zipSync,strToU8}=require('fflate');
const output=path.resolve('build/dsh-files-verification');await mkdir(output,{recursive:true});
const root=await mkdtemp(path.join(output,'run-'));
for(const key of ['DSH_API_KEY','DSH_API_BASE','DSH_MODEL','DX_DSH_MODELS'])delete process.env[key];
process.env.DX_DSH_HOME=path.join(root,'home');process.env.DX_DSH_CONTEXT_FILE=path.join(root,'context.json');
await writeFile(process.env.DX_DSH_CONTEXT_FILE,'{"task_id":"files-fixture","revision":"files","status":"observe"}');
const source=path.join(root,'输入 文件夹');await mkdir(source);
await writeFile(path.join(source,'说明.txt'),'DSH_FILE_CONTENT_中文\n');
const archive=path.join(source,'资料.zip');
await writeFile(archive,zipSync({'子目录/说明.txt':strToU8('DSH_ZIP_CONTENT_中文'),'binary.bin':new Uint8Array([0,1,2,255])}));
const {ctx,shutdown}=await bootRuntime({announce:false});
try{
const names=ctx.tools.schemas().map(x=>x.name);
for(const name of ['read','read_image','glob','grep','working_directory','extract_zip'])
assert.ok(names.includes(name),'Missing file capability: '+name);
const workspace=await ctx.workspaceRegistry.create(process.env.DX_DSH_WORKSPACE,'File fixture');
const {sessionId}=await ctx.sessionController.create({workspaceId:workspace.id,agentPreset:'dx-task'});
const agent=ctx.agents.get(sessionId);
const call=async(name,args)=>ctx.tools.execute({name,arguments:args,callId:crypto.randomUUID(),agent,signal:AbortSignal.timeout(20000)});
const ok=async(name,args)=>{
const result=await call(name,args);assert.equal(result.isError,false,name+': '+JSON.stringify(result));return result;
};
assert.match(JSON.stringify(await ok('read',{file_path:path.join(source,'说明.txt')})),/DSH_FILE_CONTENT_中文/);
assert.match(JSON.stringify(await ok('glob',{pattern:'*',path:source})),/说明.txt/);
assert.match(JSON.stringify(await ok('grep',{pattern:'DSH_FILE_CONTENT',path:source})),/DSH_FILE_CONTENT/);
await ok('working_directory',{cd:source});
assert.match(JSON.stringify(await ok('read',{file_path:'说明.txt'})),/DSH_FILE_CONTENT/);
const extracted=await ok('extract_zip',{file_path:'资料.zip'});
const destination=extracted.value.directory;
assert.equal(await readFile(path.join(destination,'子目录/说明.txt'),'utf8'),'DSH_ZIP_CONTENT_中文');
assert.deepEqual(new Uint8Array(await readFile(path.join(destination,'binary.bin'))),new Uint8Array([0,1,2,255]));
assert.match(JSON.stringify(await ok('read',{file_path:path.join(destination,'子目录/说明.txt')})),/DSH_ZIP_CONTENT/);
assert.notEqual((await ok('extract_zip',{file_path:archive})).value.directory,destination,'repeated extraction must not overwrite');
await writeFile(path.join(source,'unsafe.zip'),zipSync({'../escaped.txt':strToU8('must not escape')}));
const before=await readdir(source);
assert.equal((await call('extract_zip',{file_path:'unsafe.zip'})).isError,true);
assert.deepEqual(await readdir(source),before,'unsafe archive must not publish a partial directory');
await writeFile(path.join(source,'broken.zip'),'not a zip');
assert.equal((await call('extract_zip',{file_path:'broken.zip'})).isError,true);
const corrupt=Buffer.from(zipSync({'evidence.txt':strToU8('ORIGINAL_CONTENT')},{level:0}));
const payload=corrupt.indexOf(Buffer.from('ORIGINAL_CONTENT'));assert.ok(payload>0);corrupt[payload]=88;
await writeFile(path.join(source,'corrupt.zip'),corrupt);
assert.equal((await call('extract_zip',{file_path:'corrupt.zip'})).isError,true,'CRC mismatch must not report successful extraction');
assert.equal(await readFile(path.join(source,'说明.txt'),'utf8'),'DSH_FILE_CONTENT_中文\n');
ctx.emit('dx/diagnose-request',{request_id:'files-incident-probe',incident_id:'a'.repeat(24),phase:'diagnose',
snapshot:{task_id:'files-fixture'},evidence:'Owned fixture; no model is configured.'});
let incident;
const deadline=Date.now()+20000;
while(Date.now()<deadline){
incident=ctx.agents.list().find(value=>value.id!==agent.id);
if(incident)break;
await new Promise(resolve=>setTimeout(resolve,50));
}
assert.ok(incident,'automatic incident session must be created');
let marked=false;
while(Date.now()<deadline){
const snapshot=await ctx.tools.execute({name:'dx_task_snapshot',arguments:{},callId:crypto.randomUUID(),agent:incident,signal:AbortSignal.timeout(2000)});
if(snapshot.value?.revision==='a'.repeat(24)){marked=true;break;}
await new Promise(resolve=>setTimeout(resolve,50));
}
assert.ok(marked,'incident snapshot must be bound before checking admission');
for(const [name,args] of [['read',{file_path:path.join(source,'说明.txt')}],['extract_zip',{file_path:archive}]]){
const denied=await ctx.tools.execute({name,arguments:args,callId:crypto.randomUUID(),agent:incident,signal:AbortSignal.timeout(2000)});
assert.equal(denied.isError,true,'automatic incident must not inherit interactive file access');
}
const report={status:'passed',realHarness:true,read:true,folderSearch:true,workingDirectory:true,
zipTextAndBinary:true,repeatedExtractionNoOverwrite:true,zipTraversalRejected:true,invalidZipRejected:true,corruptZipRejected:true,
automaticSessionIsolation:true};
await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report));
}finally{await shutdown.shutdown(0);}
+69
View File
@@ -0,0 +1,69 @@
/** Real settings form, provider discovery and persistence against an owned fixture. */
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import path from 'node:path';
export async function verifyModelSettings(c, output) {
const requests=[];
const server=createServer((req,res)=>{
requests.push({method:req.method,path:req.url});
res.writeHead(req.url==='/v1/models'?200:404,{'Content-Type':'application/json'});
res.end(JSON.stringify({object:'list',data:[{id:'issue16-fixture-model',object:'model',owned_by:'acceptance'}]}));
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const endpoint=`http://127.0.0.1:${server.address().port}/v1`;
const visible=selector=>`[...document.querySelectorAll(${JSON.stringify(selector)})].find(e=>e.getBoundingClientRect().width>0)`;
const button=text=>`[...document.querySelectorAll('button')].find(e=>e.getBoundingClientRect().width>0&&e.textContent.trim()===${JSON.stringify(text)})`;
async function wait(expression){
const end=Date.now()+20000;
while(Date.now()<end){if(await c.evaluate(expression))return;await new Promise(r=>setTimeout(r,100));}
throw Error('Models acceptance timed out: '+expression);
}
async function type(selector,text){
await c.click(visible(selector));
await c.call('Input.insertText',{text});
await wait(`(${visible(selector)})?.value===${JSON.stringify(text)}`);
}
try{
// The caller has reached the actual upstream Custom model API form.
await type('input[aria-label="Provider ID"]','issue16-fixture');
await type('input[aria-label="API 地址"]',endpoint);
const protocol='select[aria-label="API 协议"]';
// This is a native keyboard selection, not a direct settings RPC.
const choices=await c.evaluate(`[...(${visible(protocol)}).options].map(x=>x.value)`);
const target=choices.indexOf('openai-completions');
assert.ok(target>=0);
await c.click(visible(protocol));
await c.call('Input.dispatchKeyEvent',{type:'keyDown',key:'Home',code:'Home',windowsVirtualKeyCode:36});
await c.call('Input.dispatchKeyEvent',{type:'keyUp',key:'Home',code:'Home',windowsVirtualKeyCode:36});
for(let i=0;i<target;i++){
await c.call('Input.dispatchKeyEvent',{type:'keyDown',key:'ArrowDown',code:'ArrowDown',windowsVirtualKeyCode:40});
await c.call('Input.dispatchKeyEvent',{type:'keyUp',key:'ArrowDown',code:'ArrowDown',windowsVirtualKeyCode:40});
}
await c.call('Input.dispatchKeyEvent',{type:'keyDown',key:'Enter',code:'Enter',windowsVirtualKeyCode:13});
await c.call('Input.dispatchKeyEvent',{type:'keyUp',key:'Enter',code:'Enter',windowsVirtualKeyCode:13});
await wait(`(${visible(protocol)}).value==='openai-completions'`);
await c.click(button('获取可用模型'));
await wait(`document.body.innerText.includes('issue16-fixture-model')`);
assert.deepEqual(requests,[{method:'GET',path:'/v1/models'}]);
const candidate=`[...document.querySelectorAll('[role="dialog"] label')].find(e=>e.textContent.includes('issue16-fixture-model'))?.querySelector('input[type="checkbox"]')`;
if(!await c.evaluate(`(${candidate})?.checked`))await c.click(candidate);
assert.equal(await c.evaluate(`(${candidate})?.checked`),true);
await c.click(button('添加所选'));
await wait(`!![...document.querySelectorAll('input')].find(x=>x.value==='issue16-fixture-model')`);
await c.screenshot(path.join(output,'custom-model-discovery.png'));
await c.click(button('创建提供商'));
await wait(`!document.querySelector('input[aria-label="Provider ID"]')`);
await wait(`document.body.innerText.includes('issue16-fixture')`);
// Reopen the real editor to read committed fields, not the submitted draft.
await c.click(`[...document.querySelectorAll('li')].find(e=>e.textContent.includes('issue16-fixture'))?.querySelector('button')`);
await wait(`document.body.innerText.includes('自定义设置')`);
await c.click(`[...document.querySelectorAll('summary')].find(e=>e.textContent.includes('自定义设置'))`);
await wait(`!![...document.querySelectorAll('input')].find(x=>x.value==='issue16-fixture-model')`);
await c.screenshot(path.join(output,'custom-model-persisted.png'));
return {status:'passed',provider:'issue16-fixture',model:'issue16-fixture-model',requests,
credentialsUsed:false,remoteModelCalls:false};
}finally{
server.closeAllConnections();await new Promise(resolve=>server.close(resolve));
}
}
+24 -7
View File
@@ -33,9 +33,21 @@ try {
assert.equal(await c.evaluate(`${accountEntries}.length`),0);
report.checks.push('one click opens native tool settings with DSH capabilities and no account entry');
await c.screenshot(path.join(output,'dsh-tool-settings.png'));
await c.call('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape'});
await c.call('Input.dispatchKeyEvent',{type:'keyUp',key:'Escape',code:'Escape'});
await wait(`!document.querySelector('[data-testid="dx-tool-settings-panel"]')`);
await c.click(`[...document.querySelectorAll('[data-shortcut-modal="settings"] nav button')].find(e=>e.textContent.trim()==='模型')`);
await wait(`document.body.innerText.includes('自定义模型 API')||document.body.innerText.includes('添加模型提供商')`);
if(!await c.evaluate(`document.body.innerText.includes('自定义模型 API')`))
await c.click(`[...document.querySelectorAll('button')].find(e=>e.textContent.includes('添加模型提供商'))`);
await wait(`document.body.innerText.includes('自定义模型 API')`);
await c.click(`[...document.querySelectorAll('button')].find(e=>e.textContent.trim()==='自定义模型 API')`);
await wait(`!!document.querySelector('input[aria-label="Provider ID"]')&&document.body.innerText.includes('获取可用模型')`);
report.checks.push('actual model settings clicks reveal custom API and fetch-model controls');
await c.screenshot(path.join(output,'dsh-custom-model-settings.png'));
if(process.argv.includes('--model-settings-check')){
const {verifyModelSettings}=await import('./verify_dsh_model_settings.mjs');
report.modelSettings=await verifyModelSettings(c,output);
}
await c.click(`[...document.querySelectorAll('[data-shortcut-modal="settings"] button')].find(e=>e.textContent.trim()==='关闭')`);
await wait(`!document.querySelector('[role="dialog"]')`);
await c.screenshot(path.join(output,'dsh-tool-home.png'));
const context=await c.evaluate(`fetch('/dx/context').then(r=>r.json())`);
assert.ok(context.task_id,'Select a task in the task center before running this test.');
@@ -46,6 +58,10 @@ try {
await c.click(`document.querySelectorAll('button[aria-label="新建会话"]')[1]`);
await wait(`!!document.querySelector('[data-testid="dx-task-panel"]')`);
report.checks.push('native new conversation retains task dock');
if(process.argv.includes('--file-check')){
const {verifyFileUi}=await import('./verify_dsh_file_ui.mjs');
report.files=await verifyFileUi(c,output);
}
if(!liveModel) {
await c.click(`document.querySelector('button[aria-label="收起侧边栏"]')`);
await wait(`!!document.querySelector('button[aria-label="打开侧边栏"]')`);
@@ -74,7 +90,8 @@ try {
await c.call('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape'});
await c.call('Input.dispatchKeyEvent',{type:'keyUp',key:'Escape',code:'Escape'});
await c.click(`document.querySelector('[contenteditable="true"]')`);
const prompt=liveModel ? '请分析当前任务的状态和异常,告诉我任务名称、现在进展到哪一步以及接下来可以做什么。不要修改工程。' : '请分析当前任务的异常,并说明允许的处理方式。';
const fileCheck=process.argv.includes('--file-check');
const prompt=liveModel ? (fileCheck?'请分析当前任务的附件:读取上传的 dsh-upload.txt,再解压 dsh-upload.zip 并读取其中说明.txt,分别告诉我这两份文本的完整内容和解压后的真实目录。不要修改原文件或运行 CAD。':'请分析当前任务的状态和异常,告诉我任务名称、现在进展到哪一步以及接下来可以做什么。不要修改工程。') : '请分析当前任务的异常,并说明允许的处理方式。';
report.prompt=prompt;
report.explicitToolNamesInPrompt=false;
await c.call('Input.insertText',{text:prompt});
@@ -84,15 +101,15 @@ try {
if(liveModel) {
await c.click(`document.querySelector('button[aria-label="发送消息"]')`);
const replies=`[...document.querySelectorAll('[data-chat-group-part="response"]')].map(e=>e.innerText).join('\\n')`;
await wait(`(${replies}).length>30 && /任务|状态/.test(${replies})`,100000);
await wait(`![...document.querySelectorAll('button[aria-label="停止生成"]')].some(e=>e.getBoundingClientRect().width>0)`,100000);
await wait(fileCheck?`(${replies}).includes('DSH_UPLOAD_CONTENT')&&(${replies}).includes('DSH_ZIP_UPLOAD_CONTENT')`:`(${replies}).length>30 && /任务|状态/.test(${replies})`,fileCheck?180000:100000);
await wait(`![...document.querySelectorAll('button[aria-label="停止生成"]')].some(e=>e.getBoundingClientRect().width>0)`,fileCheck?180000:100000);
report.reply=await c.evaluate(replies);
report.liveModelReplyTested=true;
report.liveTurnCompleted=true;
report.checks.push('real API reply rendered through the official Harness conversation');
await c.click(`document.querySelector('[contenteditable="true"]')`);
await c.call('Input.insertText',{text:'请分析当前任务的下一步。'});
} else report.reason='No model credential configured in this isolated acceptance profile.';
} else report.reason='Live model generation was not requested for this acceptance run.';
await c.screenshot(path.join(output,'dsh-native-final.png'));
if(process.argv.includes('--confirm-cancel')) {
await c.click(`[...document.querySelectorAll('button')].find(e=>e.textContent.trim()==='准备失败项重试')`);
+40
View File
@@ -0,0 +1,40 @@
/** Boot the actual Harness over native user settings and a legacy profile. */
import assert from 'node:assert/strict';
import {mkdtemp,mkdir,readFile,writeFile,readdir} from 'node:fs/promises';
import path from 'node:path';
import {bootRuntime,overlay,prepareProfileDirectory,TASK_TOOLS,FILE_TOOLS} from '../integration/dsh/start.mjs';
const output=path.resolve('build/dsh-profile-settings-verification');
await mkdir(output,{recursive:true});
const base=await mkdtemp(path.join(output,'run-'));
process.env.DX_DSH_HOME=path.join(base,'home');
process.env.DX_DSH_CONTEXT_FILE=path.join(base,'context.json');
await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'',revision:'settings-test',status:'observe'}));
const dir=path.join(process.env.DX_DSH_HOME,'profiles/dx-task');
await mkdir(dir,{recursive:true});
const profile=[{id:'llm-pi-ai',config:{providers:{'profile-fixture':{
api:'openai-completions',baseURL:'http://127.0.0.1:1/v1',models:[{id:'persisted-fixture-model'}]}}}}];
const patch=path.join(dir,'cordis.patch.yml');
const original='# Native user settings\n'+JSON.stringify(profile,null,2)+'\n';
await writeFile(patch,original);
await prepareProfileDirectory(dir);await prepareProfileDirectory(dir);
assert.equal(await readFile(patch,'utf8'),original,'application preparation must not rewrite a native user layer');
const legacyDir=path.join(base,'legacy');
await mkdir(legacyDir,{recursive:true});
const old=JSON.stringify([...overlay(),...profile],null,2);
await writeFile(path.join(legacyDir,'cordis.patch.yml'),old);
await prepareProfileDirectory(legacyDir);
const migrated=await readFile(path.join(legacyDir,'cordis.patch.yml'),'utf8');
assert.ok(JSON.parse(migrated).some(x=>x.id==='llm-pi-ai'&&x.config.providers['profile-fixture']));
const backups=(await readdir(legacyDir)).filter(x=>x.includes('.legacy-'));
assert.equal(backups.length,1);
assert.equal(await readFile(path.join(legacyDir,backups[0]),'utf8'),old);
await prepareProfileDirectory(legacyDir);
assert.equal(await readFile(path.join(legacyDir,'cordis.patch.yml'),'utf8'),migrated);
const {ctx,shutdown}=await bootRuntime({announce:false});
try{
assert.deepEqual((await ctx.llm.listModels('profile-fixture')).map(x=>x.id),['persisted-fixture-model']);
assert.equal(ctx.tools.schemas().length,TASK_TOOLS.length+FILE_TOOLS.length);
console.log(JSON.stringify({status:'passed',nativeSettingsPreserved:true,actualProviderRestored:true,
legacyMigrationPreservedModels:true,byteBackup:true,modelRequests:0}));
}finally{await shutdown.shutdown(0);}
+200
View File
@@ -0,0 +1,200 @@
/** Real Harness requests must keep each provider endpoint, model and credential together. */
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {spawn} from 'node:child_process';
import {mkdir,mkdtemp,readFile,writeFile,readdir} from 'node:fs/promises';
import {createRequire} from 'node:module';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {bootRuntime,overlay,prepareProfileDirectory} from '../integration/dsh/start.mjs';
const script=fileURLToPath(import.meta.url);
const require=createRequire(new URL('../integration/dsh/start.mjs',import.meta.url));
const {load}=require('js-yaml');
const appKeys=['DSH_API_BASE','DSH_MODEL','DSH_API_KEY','DX_DSH_MODELS','DSH_HOME','DX_DSH_HOME','DX_DSH_CONTEXT_FILE','DX_DSH_PARENT_PIPE'];
const selection=ctx=>ctx.agentDefaultModel.currentSelection();
async function runChild(specPath,env){
return new Promise(resolve=>{
const child=spawn(process.execPath,[script,'--child',specPath],{env,stdio:['ignore','pipe','pipe'],windowsHide:true});
let stdout='',stderr='';child.stdout.on('data',x=>stdout+=x);child.stderr.on('data',x=>stderr+=x);
const timeout=setTimeout(()=>child.kill(),60000);
child.on('close',code=>{clearTimeout(timeout);resolve({code,stdout,stderr});});
});
}
async function stream(ctx,provider,model){
const chunks=[];
for await(const chunk of ctx.llm.stream({provider,model,messages:[{role:'user',content:[{type:'text',text:'fixture request'}]}],
maxTokens:8,signal:AbortSignal.timeout(15000)}))chunks.push(chunk);
assert.equal(chunks.find(x=>x.type==='finish')?.reason.kind,'stop','owned fixture stream must finish successfully');
assert.equal(chunks.filter(x=>x.type==='text-delta').map(x=>x.text).join(''),'ok');
}
if(process.argv[2]==='--child'){
const spec=JSON.parse(await readFile(process.argv[3],'utf8'));
if(spec.orphanKey){
await assert.rejects(bootRuntime({announce:false}),/Stored DSH_API_KEY has no provider binding|Duplicate .* prevents verifying model binding|Application model route did not match/);
console.log('DX_SWITCH_REPORT '+JSON.stringify({status:'passed',unboundCredentialRefused:true}));
process.exit(0);
}
const {ctx,shutdown}=await bootRuntime({announce:false});
try{
if(spec.hostAbsent){
assert.ok(!ctx.llm.listProviders().some(x=>x.id==='dx'));
await stream(ctx,'custom','custom-model');
console.log('DX_SWITCH_REPORT '+JSON.stringify({status:'passed',customWorksWithoutHost:true}));
}else{
// Send even when the model catalogue is stale: detect the actual HTTP credential destination.
const dxModels=(await ctx.llm.listModels('dx')).map(x=>x.id);
await stream(ctx,'dx',dxModels[0]);
if(spec.custom){
assert.deepEqual((await ctx.llm.listModels('custom')).map(x=>x.id),['custom-model']);
await stream(ctx,'custom','custom-model');
}
assert.deepEqual(dxModels,spec.customDx?['custom-dx-model']:['new-model','alternate-model']);
assert.deepEqual(selection(ctx),spec.expectedDefault);
console.log('DX_SWITCH_REPORT '+JSON.stringify({status:'passed',dxModels,selection:selection(ctx)}));
}
}finally{await shutdown.shutdown(0);}
}else{
const output=path.resolve('build/dsh-provider-switch-verification');await mkdir(output,{recursive:true});
const base=await mkdtemp(path.join(output,'run-'));
const requests=[];
async function endpoint(name){
const server=createServer(async(req,res)=>{
let text='';for await(const chunk of req)text+=chunk;
const body=text?JSON.parse(text):{};
requests.push({server:name,path:req.url,authorization:req.headers.authorization,model:body.model});
res.writeHead(200,{'Content-Type':'text/event-stream'});
res.end('data: '+JSON.stringify({id:'fixture',object:'chat.completion.chunk',created:1,model:body.model,
choices:[{index:0,delta:{role:'assistant',content:'ok'},finish_reason:null}]})+'\n\n'+
'data: '+JSON.stringify({id:'fixture',object:'chat.completion.chunk',created:1,model:body.model,
choices:[{index:0,delta:{},finish_reason:'stop'}]})+'\n\ndata: [DONE]\n\n');
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
return {server,url:`http://127.0.0.1:${server.address().port}/v1`};
}
const old=await endpoint('old'),next=await endpoint('new'),custom=await endpoint('custom');
const cleanEnv={...process.env};for(const key of appKeys)delete cleanEnv[key];
const nextEnv={DSH_API_BASE:next.url,DSH_MODEL:'new-model',DSH_API_KEY:'fixture-new-key',DX_DSH_MODELS:'["new-model","alternate-model"]'};
const cases=[
{name:'legacy-switch',legacy:true},
{name:'legacy-custom-default',legacy:true,custom:true,expectedDefault:{provider:'custom',model:'custom-model'}},
{name:'already-migrated-switch',custom:true},
{name:'native-custom-provider',custom:true,omitDx:true},
{name:'native-dx-selection',expectedDefault:{provider:'dx',model:'alternate-model'},selected:'alternate-model'},
{name:'native-independent-dx',customDx:true,expectedDefault:{provider:'dx',model:'custom-dx-model'}},
{name:'native-stored-dx-key',customDx:true,storedHostKey:true,expectedDefault:{provider:'dx',model:'custom-dx-model'}},
{name:'legacy-stored-dx-key',legacy:true,customDx:true,storedHostKey:true,expectedDefault:{provider:'dx',model:'custom-dx-model'}},
{name:'native-key-only-edit',customDx:true,storedHostKey:true,keyOnly:true,expectedDefault:{provider:'dx',model:'custom-dx-model'}},
{name:'unbound-stored-key',storedHostKey:true,orphanKey:true},
{name:'ignored-name-binding',storedHostKey:true,orphanKey:true,ignoredName:true},
{name:'legacy-ignored-name-binding',legacy:true,storedHostKey:true,orphanKey:true,ignoredName:true},
{name:'insert-is-not-a-binding',storedHostKey:true,orphanKey:true,insertOnly:true},
{name:'alternate-unbound-key',alternateCredentials:true,storedHostKey:true,orphanKey:true},
{name:'alternate-bound-key',alternateCredentials:true,customDx:true,storedHostKey:true,expectedDefault:{provider:'dx',model:'custom-dx-model'}},
{name:'duplicate-credentials',storedHostKey:true,orphanKey:true,duplicate:'credentials'},
{name:'duplicate-model-adapter',orphanKey:true,duplicate:'llm-pi-ai'},
];
const reports=[];
try{
for(const spec of cases){
if(process.argv[2]==='--case'&&process.argv[3]!==spec.name)continue;
const home=path.join(base,spec.name),dir=path.join(home,'profiles/dx-task');await mkdir(dir,{recursive:true});
const credentialsFile=path.join(home,spec.alternateCredentials?'alternate-credentials.yaml':'.credentials.yaml');
Object.assign(process.env,{DSH_API_BASE:old.url,DSH_MODEL:'old-model',DSH_API_KEY:'fixture-old-key',DX_DSH_MODELS:'["old-model"]'});
let rows=overlay();
if(!spec.legacy)rows=rows.filter(x=>['llm-pi-ai','agent-default-model'].includes(x.id));
const llm=rows.find(x=>x.id==='llm-pi-ai');
if(spec.omitDx)delete llm.config.providers.dx;
if(spec.custom)llm.config.providers.custom={api:'openai-completions',baseURL:custom.url,apiKeyEnv:'FIXTURE_CUSTOM_KEY',models:[{id:'custom-model'}]};
if(spec.customDx)llm.config.providers.dx={api:'openai-completions',baseURL:custom.url,
apiKeyEnv:spec.storedHostKey?'DSH_API_KEY':'FIXTURE_CUSTOM_KEY',models:[{id:'custom-dx-model'}]};
if(spec.keyOnly){
rows=[];
Object.assign(process.env,{DSH_API_BASE:custom.url,DSH_MODEL:'custom-dx-model',DX_DSH_MODELS:'["custom-dx-model"]'});
}
if(spec.orphanKey&&!spec.ignoredName&&!spec.insertOnly&&!spec.duplicate)rows=[];
if(spec.ignoredName)llm.name='@deepseek-ai/previous-llm-name';
if(spec.insertOnly)llm.insert=[];
if(spec.alternateCredentials)rows.push({id:'credentials',config:{path:credentialsFile}});
if(spec.duplicate)rows.push({insert:[{id:spec.duplicate,
name:spec.duplicate==='credentials'?'@deepseek-ai/dsh-credentials-local':'@deepseek-ai/dsh-llm-pi-ai',
config:spec.duplicate==='credentials'?{path:path.join(home,'empty-store.yaml')}:structuredClone(llm.config)}]});
const defaultRow=rows.find(x=>x.id==='agent-default-model');
if(defaultRow)defaultRow.config=spec.expectedDefault??{provider:'dx',model:spec.selected??'old-model'};
const patch=path.join(dir,'cordis.patch.yml');
if(spec.keyOnly){
await writeFile(patch,'[]');await prepareProfileDirectory(dir);
rows=load(await readFile(patch,'utf8'));
assert.equal(rows.find(x=>x.id==='llm-pi-ai').config.providers.dx.baseURL,custom.url,
'host route must be materialized before the official UI can save a key-only edit');
}
const original=JSON.stringify(rows,null,2);
await writeFile(patch,original);
const refs={FIXTURE_CUSTOM_KEY:'fixture-custom-key',...spec.storedHostKey?{DSH_API_KEY:'fixture-custom-key'}:{}};
const credentials=JSON.stringify({version:1,refs});
await writeFile(credentialsFile,credentials,{mode:0o600});
const context=path.join(home,'context.json');await writeFile(context,'{"status":"observe","revision":"switch-fixture"}');
spec.expectedDefault??={provider:'dx',model:'new-model'};
const specPath=path.join(home,'spec.json');await writeFile(specPath,JSON.stringify(spec));
const env={...cleanEnv,...nextEnv,DX_DSH_HOME:home,DX_DSH_CONTEXT_FILE:context};
const firstRequest=requests.length;
const result=await runChild(specPath,env);
const calls=requests.slice(firstRequest);
if(spec.orphanKey){
assert.deepEqual(calls,[],'unbound stored key must not make requests');
assert.equal(result.code,0,spec.name+': '+result.stderr);
assert.equal(await readFile(patch,'utf8'),original,'refused profile must stay unchanged');
reports.push({name:spec.name,status:'passed',unboundCredentialRefused:true});
continue;
}
assert.equal(calls.length,spec.custom?2:1,spec.name+': request count; '+result.stderr);
const dx=calls[0];
assert.equal(dx.server,spec.customDx?'custom':'new',spec.name+': wrong server received the current key');
assert.equal(dx.authorization,spec.customDx?'Bearer fixture-custom-key':'Bearer fixture-new-key',spec.name+': credential source');
assert.equal(dx.model,spec.customDx?'custom-dx-model':'new-model');
assert.equal(dx.path,'/v1/chat/completions');
if(spec.custom)assert.deepEqual(calls[1],{server:'custom',path:'/v1/chat/completions',authorization:'Bearer fixture-custom-key',model:'custom-model'});
assert.equal(result.code,0,spec.name+': '+result.stderr+'\n'+result.stdout);
// Harness itself adds a browser-session record; model references must survive unchanged.
assert.deepEqual(load(await readFile(credentialsFile,'utf8')).refs,
refs,'stored provider credentials must be untouched');
Object.assign(process.env,nextEnv);
const migrated=await readFile(patch,'utf8');
const credentialsAfterBoot=await readFile(credentialsFile,'utf8');
await prepareProfileDirectory(dir);
assert.equal(await readFile(credentialsFile,'utf8'),credentialsAfterBoot,'profile preparation must not rewrite credentials');
assert.equal(await readFile(patch,'utf8'),migrated,'second boot must not rewrite the same profile');
if(spec.legacy){
const backup=(await readdir(dir)).find(x=>x.includes('.legacy-'));
assert.equal(await readFile(path.join(dir,backup),'utf8'),original);
}
reports.push({name:spec.name,status:'passed',calls:calls.map(({authorization,...rest})=>({...rest,credentialMatched:true}))});
}
// Removing host configuration must not leave a stale application route backed by a new key later.
if(process.argv[2]!=='--case'){
const dir=path.join(base,'already-migrated-switch/profiles/dx-task');
for(const key of ['DSH_API_BASE','DSH_API_KEY','DSH_MODEL','DX_DSH_MODELS'])delete process.env[key];
await prepareProfileDirectory(dir);
const cleared=load(await readFile(path.join(dir,'cordis.patch.yml'),'utf8'));
assert.equal(cleared.find(x=>x.id==='llm-pi-ai')?.config.providers.dx,undefined);
assert.ok(cleared.find(x=>x.id==='llm-pi-ai').config.providers.custom);
assert.equal(cleared.find(x=>x.id==='agent-default-model'),undefined);
const home=path.resolve(dir,'../..'),credentialsFile=path.join(home,'.credentials.yaml');
const stored=load(await readFile(credentialsFile,'utf8'));stored.refs.DSH_API_KEY='fixture-orphan-key';
await writeFile(credentialsFile,JSON.stringify(stored));
const specPath=path.join(home,'no-host-spec.json');await writeFile(specPath,'{"hostAbsent":true}');
const count=requests.length;
const result=await runChild(specPath,{...cleanEnv,DX_DSH_HOME:home,DX_DSH_CONTEXT_FILE:path.join(home,'context.json')});
assert.equal(result.code,0,'independent provider must work without host configuration: '+result.stderr);
assert.deepEqual(requests.slice(count),[{server:'custom',path:'/v1/chat/completions',authorization:'Bearer fixture-custom-key',model:'custom-model'}]);
reports.push({name:'no-host-with-unused-stored-key',status:'passed',calls:[{server:'custom',path:'/v1/chat/completions',model:'custom-model',credentialMatched:true}]});
}
const report={status:'passed',realHarness:true,externalModelCalls:false,cases:reports,hostRemoval:process.argv[2]!=='--case'};
await writeFile(path.join(base,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report));
}finally{
for(const {server} of [old,next,custom]){server.closeAllConnections();await new Promise(resolve=>server.close(resolve));}
}
}
+2 -2
View File
@@ -4,7 +4,7 @@ import {mkdir,writeFile} from 'node:fs/promises';
import path from 'node:path';
import {fileURLToPath,pathToFileURL} from 'node:url';
import {createRequire} from 'node:module';
import {bootRuntime} from '../integration/dsh/start.mjs';
import {bootRuntime,TASK_TOOLS,FILE_TOOLS} from '../integration/dsh/start.mjs';
const repo=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
const output=path.join(repo,'build/dsh-native-cli-verification');
@@ -18,7 +18,7 @@ const report={};
try {
const schemas=ctx.tools.schemas();
report.tools=schemas.map(x=>x.name);
assert.deepEqual(report.tools,['dx_task_snapshot','dx_task_create','dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute','dx_task_operations']);
assert.deepEqual([...report.tools].sort(),[...TASK_TOOLS,...FILE_TOOLS].sort());
const presets=await ctx.agentPresets.list();
report.presets=presets.map(x=>x.id);
assert.deepEqual(report.presets,['dx-task']);
+55
View File
@@ -0,0 +1,55 @@
/** PR18 #197: no silently omitted names, bounded workers, real cancellation. */
import assert from 'node:assert/strict';
import {mkdir,mkdtemp,writeFile,readdir,readFile} from 'node:fs/promises';
import {spawnSync} from 'node:child_process';
import {createRequire,syncBuiltinESMExports} from 'node:module';
import path from 'node:path';
import {bootRuntime} from '../integration/dsh/start.mjs';
const output=path.resolve('build/dsh-zip-review-verification');await mkdir(output,{recursive:true});
const root=await mkdtemp(path.join(output,'run-'));
const fixture=spawnSync('python',['-c',
`import sys,zipfile,struct\nfrom pathlib import Path\np=Path(sys.argv[1])\nwith zipfile.ZipFile(p/'proto.zip','w',zipfile.ZIP_STORED) as z:z.writestr('__proto__','ORIGINAL_CONTENT')\ndata=bytearray((p/'proto.zip').read_bytes());n,e=struct.unpack_from('<HH',data,26);data[30+n+e]^=1;(p/'proto-bad.zip').write_bytes(data)\nwith zipfile.ZipFile(p/'many.zip','w',zipfile.ZIP_DEFLATED) as z:\n for i in range(20):z.writestr(str(i)+'.txt',b'x'*(600*1024))\n`,root],{encoding:'utf8'});
assert.equal(fixture.status,0,fixture.stderr);
const require=createRequire(import.meta.url),threads=require('node:worker_threads');
const NativeWorker=threads.Worker;
let active=0,peak=0,created=0,abortOnWorker;
threads.Worker=new Proxy(NativeWorker,{construct(target,args){
const worker=Reflect.construct(target,args);active++;created++;peak=Math.max(peak,active);
worker.once('exit',()=>active--);
if(abortOnWorker){const cancel=abortOnWorker;abortOnWorker=undefined;queueMicrotask(cancel);}
return worker;
}});
syncBuiltinESMExports();
for(const key of ['DSH_API_BASE','DSH_MODEL','DSH_API_KEY','DX_DSH_MODELS'])delete process.env[key];
process.env.DX_DSH_HOME=path.join(root,'home');process.env.DX_DSH_CONTEXT_FILE=path.join(root,'context.json');
await writeFile(process.env.DX_DSH_CONTEXT_FILE,'{"task_id":"zip-review","revision":"zip-review","status":"observe"}');
const {ctx,shutdown}=await bootRuntime({announce:false});
try{
const call=(file,signal=AbortSignal.timeout(30000))=>ctx.tools.execute({name:'extract_zip',
arguments:{file_path:path.join(root,file),output_directory:root},callId:crypto.randomUUID(),signal});
const before=await readdir(root);
for(const file of ['proto.zip','proto-bad.zip']){
const result=await call(file);
assert.equal(result.isError,true,'unsupported __proto__ entry must be explicitly rejected, including corrupt payload');
assert.deepEqual(await readdir(root),before,'rejected archive must not publish an empty success directory');
}
peak=0;created=0;
const results=await Promise.all(Array.from({length:4},()=>call('many.zip')));
for(const result of results){
assert.equal(result.isError,false,JSON.stringify(result));
assert.equal(result.value.total_entries,20);
for(let i=0;i<20;i++)assert.equal((await readFile(path.join(result.value.directory,i+'.txt'))).length,600*1024);
}
assert.equal(created,4,'each archive must use one worker, with no per-entry worker fan-out');
assert.ok(peak<=2,'ZIP decompression must use at most two workers across concurrent calls, actual '+peak);
assert.equal(active,0,'completed calls must release all workers');
const cancel=new AbortController(),prior=await readdir(root);
abortOnWorker=()=>cancel.abort(new Error('owned cancellation fixture'));
const cancelled=await call('many.zip',cancel.signal).catch(error=>({isError:true,error}));
assert.equal(cancelled.isError,true);
assert.equal(active,0,'cancelled call must settle only after its worker exits');
assert.deepEqual(await readdir(root),prior,'cancel must not publish a partial directory');
const report={status:'passed',realHarness:true,protoEntryExplicitlyRejected:true,corruptProtoRejected:true,
parallelArchives:4,filesPerArchive:20,peakWorkers:peak,cancelledWorkerStopped:true};
await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report));
}finally{threads.Worker=NativeWorker;syncBuiltinESMExports();await shutdown.shutdown(0);}
+59
View File
@@ -0,0 +1,59 @@
"""Run the delivered SFX and verify its files and every ZIP member against SHA256."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import time
import zipfile
def digest(stream):
return hashlib.file_digest(stream, 'sha256').hexdigest()
def verify(manifest_path: Path, destination: Path):
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
root = manifest_path.resolve().parent
destination = destination.resolve()
if destination.exists():
raise FileExistsError('Use a fresh extraction destination')
for name, expected in manifest['artifacts'].items():
with (root/name).open('rb') as stream:
if digest(stream) != expected['sha256']:
raise ValueError('Artifact checksum mismatch: '+name)
version = manifest['version']
started = time.monotonic()
subprocess.run([str(root/f'DxPartReplace-{version}.exe'), '-y', '-o'+str(destination)],
check=True, timeout=1800, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
elapsed = time.monotonic()-started
actual = {p.relative_to(destination).as_posix(): p for p in destination.rglob('*') if p.is_file()}
if set(actual) != set(manifest['files']):
raise ValueError('Self-extracted file set differs from manifest')
for name, path in actual.items():
with path.open('rb') as stream:
if digest(stream) != manifest['files'][name]:
raise ValueError('Self-extracted checksum mismatch: '+name)
with zipfile.ZipFile(root/f'DxPartReplace-{version}.zip') as archive:
if len(archive.namelist()) != len(actual) or set(archive.namelist()) != set(actual):
raise ValueError('ZIP file set differs from manifest')
# Reading to EOF also checks ZIP CRC for every member.
for name in archive.namelist():
with archive.open(name) as stream:
if digest(stream) != manifest['files'][name]:
raise ValueError('ZIP checksum mismatch: '+name)
return dict(passed=True, files=len(actual), sfx_extraction_seconds=round(elapsed, 3),
actual_sfx_executed=True, zip_crc_and_sha256=True,
destination=str(destination))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('manifest', type=Path)
parser.add_argument('destination', type=Path)
parser.add_argument('--report', type=Path, required=True)
args = parser.parse_args()
result = verify(args.manifest, args.destination)
args.report.write_text(json.dumps(result, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
print(json.dumps(result, ensure_ascii=False, indent=2))