Compare commits

..
8 Commits
Author SHA1 Message Date
阿白叔 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
30 changed files with 1232 additions and 52 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: |
+7 -5
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 列。
@@ -26,7 +26,7 @@ DSH助手围绕真实任务中心工作,支持:
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。
详细的能力边界、异常介入、证据链、排期和工单说明见 [DSH助手使用与监管说明](docs/user/dsh-ai-supervision.md)。源码环境可用下面的命令检查运行时门禁:
@@ -44,7 +44,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,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 秒。
+9 -1
View File
@@ -6,7 +6,15 @@
这里直接运行 [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 玻璃材质;“减少透明度”与系统高对比度等回退规则继续生效。
模型由本机保存的主工具配置加载;也支持启动进程的 `DSH_API_BASE`、`DSH_MODEL`、`DSH_API_KEY`。未配置模型时可查看任务上下文和操作面板,不能获得真实模型回复。
+156 -8
View File
@@ -1,7 +1,9 @@
/** 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';
@@ -28,12 +30,14 @@ 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:'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 +59,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);
@@ -73,12 +215,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,6 +230,17 @@ 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))) {
await shutdown.shutdown(1);
+1 -1
View File
@@ -13,7 +13,7 @@ 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,'工程修改与执行核验由任务中心完成。模型不直接访问工程文件或执行命令。'));
+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():
@@ -37,9 +37,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;}')
@@ -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()
@@ -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))
+3
View File
@@ -32,6 +32,7 @@ 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('--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')
@@ -146,6 +147,8 @@ def main():
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.outbox_only:
command.append('--outbox-only')
state['child'] = subprocess.Popen(command, cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+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())
+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
+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));
}
}
+16 -4
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.');
@@ -92,7 +104,7 @@ try {
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} 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,7);
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));}
}
}
+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))