Compare commits

...
Author SHA1 Message Date
阿白叔 7d4f6bde0b test: record native DxDataBook redraw evidence
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m22s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 4m22s
Core regression / JavaScript syntax (pull_request) Successful in 14s
2026-11-25 10:11:26 +08:00
阿白叔 ad3ee4151c fix: recover DxDataBook control redraw races
Core regression / Python core, intervention UI and release configuration (push) Failing after 4m30s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 4m36s
Core regression / JavaScript syntax (pull_request) Successful in 8s
2026-11-25 10:08:25 +08:00
阿白叔 3187b304c6 fix: retry DxDataBook lookup before native mutation
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m20s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Failing after 5m54s
Core regression / JavaScript syntax (pull_request) Successful in 11s
2026-11-25 09:57:37 +08:00
abaishu0730 46deb9cec8 Merge pull request 'feat: 升级 DeepSeek Harness 并支持运行时更新' (#32) from codex/dsh-runtime-update into main
Core regression / Python core, intervention UI and release configuration (push) Failing after 20m55s
Core regression / JavaScript syntax (push) Successful in 10s
2026-11-20 17:21:04 +08:00
阿白叔 488bf027cc feat: update DeepSeek Harness and support runtime upgrades
Core regression / Python core, intervention UI and release configuration (push) Successful in 16m20s
Core regression / JavaScript syntax (push) Successful in 11s
Core regression / Python core, intervention UI and release configuration (pull_request) Failing after 11m11s
Core regression / JavaScript syntax (pull_request) Successful in 7s
2026-11-20 15:43:58 +08:00
abaishu0730 bd80f86357 Merge pull request 'feat: 新增独立工程校验工作台与可追溯换料闭环' (#30) from codex/independent-verification into main
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m43s
Core regression / JavaScript syntax (push) Successful in 6s
2026-11-20 11:23:52 +08:00
30 changed files with 5101 additions and 3339 deletions

No files matched your search

+2 -1
View File
@@ -49,8 +49,9 @@ jobs:
npm install --prefix /opt/ci-node --no-audit --no-fund node@24.11.1 npm install --prefix /opt/ci-node --no-audit --no-fund node@24.11.1
node --version node --version
npm ci --prefix integration/dsh --no-audit --no-fund npm ci --prefix integration/dsh --no-audit --no-fund
- name: Read-only model availability (real Harness, no remote model calls) - name: Runtime and model availability (real Harness, no remote model calls)
run: | run: |
node tools/verify_dsh_runtime.mjs
node tools/verify_dsh_model_availability.mjs node tools/verify_dsh_model_availability.mjs
node --test tests/integration/test_dsh_standard_compat.mjs node --test tests/integration/test_dsh_standard_compat.mjs
node tools/verify_dsh_incident_restart.mjs node tools/verify_dsh_incident_restart.mjs
@@ -0,0 +1,26 @@
# Issue #33 D6 · DxDataBook 加载失败验证
现场 `WIFI_RTL8723DU` 的 `LWB01` 在加载目标 `4885-S018D0-M220` 时超时。原报告记录了可见列表窗口,阶段为 `preflight`,本项写入凭据为 `prepared`。同代次此前的项已有写入凭据,项目进入保留和对账流程。类似的失败也出现在 `BOB` 与 `BOB_SHIELD` 的目标 `4885-S033D0-M220` 上。现场空标题窗口 `10750260` 属于同批后续 `WIFI_RTL8192FC` 会话的启动阶段。它与 `LWB01` 超时分属不同 CAD 进程和代次。现场日志能定位超时阶段及保留原因,库服务状态和窗口复建情况仍待同代次采样。
加载阶段根据 DxDataBook 控件是否已存在采用 45 秒或 20 秒窗口。加载过程重新发现同一窗口下的列表与筛选器,控件重建后重发筛选并重新验证行稳定性。超时前写下本项凭据状态,超时后至多重试一次。重试要求本项仍有身份匹配的 `prepared` 凭据。空窗口处理进一步要求窗口在本次浏览后出现,属于同一 CAD 进程、线程和替换对话框,且替换对话框已被禁用。窗口和子控件证据先写盘,随后才发送关闭消息并观察结果。替换提交、属性恢复和保存继续使用既有的写入凭据与关闭检查点。
## Windows 验证
| 场景 | 观测结果 |
| --- | --- |
| 冷加载列表重建注入 | 原列表 `10` 更新为 `20`,筛选器从 `11` 切换到 `21`,稳定性窗口重新计时,最终使用新列表。 |
| 控件枚举与访问之间发生重建 | 筛选消息返回 Win32 `1400`,或列表读取返回 UIA `0x80040201`。两种故障都在当前加载时限内重取控件,访问新筛选器并选中正确的行。 |
| 真实 Win32 空窗口,凭据 `prepared` | 私有桌面创建的 HWND `19728876` 属于替换对话框,保存窗口树后只关闭该窗口。加载重试一次后返回目标,原有同 PID 无关窗口仍打开,凭据仍为 `prepared`。 |
| 真实 Win32 空窗口,凭据 `mutation_possible` | 窗口 `1183362` 具备同样的结构和归属,仅留下诊断。未重试,窗口与写入凭据均保留。 |
| 先前已有暂存写入,当前项失败 | Windows `cscript.exe` 执行生产 VBS 清理过程。当前未写且无暂存项时经过原始状态核验并以 `SaveChanges=False` 关闭。已有前项暂存写入、当前项写入状态无法确认或保存已请求时,保留工程供对账。 |
真实 HWND 注入运行生产窗口检查和加载重试代码,测试用 Win32 窗口模拟 DxDataBook 的无按钮提示。测试将等待时间缩短到 1.5 秒,筛选响应由测试控制。原始诊断见 [prepared.json](evidence/2026-11-25-issue33-d6/prepared.json) 和 [mutation_possible.json](evidence/2026-11-25-issue33-d6/mutation_possible.json)。
另一组注入使用原生 ListView、Edit、UIA 行读取和消息驱动生产 `run_native`,CAD COM 属性与菜单资源由替身提供。先销毁筛选框触发 Win32 `1400`,再销毁列表触发 UIA `0x80040201`。程序复取新列表和筛选器,扫描两行后命中精确料号。提交回调只触发一次并读到持久化状态 `mutation_possible`。只有相似料号的对照执行两次筛选后超时,提交数为零,凭据仍为 `prepared`。 [精确命中](evidence/2026-11-25-issue33-d6/native-controls-positive.json) [没有精确命中](evidence/2026-11-25-issue33-d6/native-controls-negative.json)
定向回归 114 项通过,包含加载、窗口归属、写入凭据、VBS 失败收尾和现有目标 Cell 路径。另执行扩展集成测试时,丢失 UID 的旧测试出现保存回读证明缺失,用 `origin/main` 的原始 VBS 同例复现。
## 真实工程副本
- 现场备份 `WIFI_RTL8723DU` 使用本机 `Skyworth_Lib` 中央库替代现场 `S:\mentor_lib.lmc`,BOM 核验找到 `LWB01` 并确认 UID。执行停在 `open_project` 249 秒,回到 `open_sheet` 安全边界时停止,关闭检查点仍观测到工程打开。写入凭据为 `prepared`,工程保护标记保留。此次在进入 DxDataBook 前结束,现场目标件换料及保存回读尚待验证。 [现场副本记录](evidence/2026-11-25-issue33-d6/field-copy.json)
- `Audio_D2128` 副本上,`RV05` 从 `4100-CA0000-T7` 换为 `4100-CA0000-T0`。已存在的 DxDataBook 控件在 2.703 秒内返回目标。原生替换报告成功,保存请求和返回各一次,工程完成关闭及重新读取,状态为 `saved_ok/project_committed`,独立网表比对为 `verified`。关闭整个 CAD 进程时超出 15 秒并触发资源释放保护标记,任务目录未产生业务不确定标记。 [正常副本记录](evidence/2026-11-25-issue33-d6/normal-copy.json)
@@ -0,0 +1,36 @@
{
"mode": "field",
"environment": "Windows, DxDesigner 7.9.5, source runtime",
"library_mapping": "Skyworth_Lib",
"library_lmc_unchanged": true,
"project": "WIFI_RTL8723DU.prj",
"request_old_new_refdes": [
"483C-S018D0-M210",
"4885-S018D0-M220",
"LWB01"
],
"attempt": {
"session_id": "bf846ff076254e5fbb3bc7ccf1ee859d",
"generation": 1,
"attempt_id": "44a747ec3c5d440fb60d5a2a407b8037",
"job_id": "08d6ebdc6cc540f7b2296a2ef737947a_0",
"state": "prepared"
},
"native": [],
"status_log": [
"job_id\tstate\tcode\tmessage"
],
"operation_log_excerpt": [
"2026/11/25 9:57:21\tINFO\tstage=open_project target=<copy-root>\\project\\WIFI_RTL8723DU.prj",
"2026/11/25 10:01:30\tERROR\tstage=open_sheet number=-2147220644 source=QuickPartReplace.SafeStop description=stopped at a safe boundary before native mutation after inactivity; prewrite pause closure was not proven: %7F3A%5C11%5BF9%8C61",
"quick_run_uncertain monitor_failure error=project close checkpoint failed: owned CAD still has a project open; no implicit save or discard\\r\\n"
],
"independent_verification": [
"not_completed"
],
"uncertain_flags_relative_to_data_root": [
"batch-resources/bf846ff076254e5fbb3bc7ccf1ee859d/generation-1/uncertain.flag",
"tasks/546160ef-0e8f-4b15-8394-e35f8c562366/quick-run/uncertain.flag"
],
"queue_outcome": "project remained open at the close checkpoint"
}
@@ -0,0 +1,33 @@
[
{
"stage": "preflight",
"databook": {
"loads": [
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "mutation_possible",
"list_handle": 17,
"filter_handle": 18,
"error": "Native DxDataBook did not finish loading target part: NEW",
"elapsed_seconds": 1.594,
"dialogs": [
{
"hwnd": 1183362,
"owner": 200514,
"pid": 56180,
"title": "",
"children": [],
"browser": false,
"dismissible": true
}
],
"attempt_state": "mutation_possible",
"retry": false
}
]
},
"window_closed": [],
"marker_state": "mutation_possible"
}
]
@@ -0,0 +1,91 @@
{
"attempt": "prepared",
"events": [
{
"controls": [
21630720,
528470
]
},
{
"edit_hwnd": 528470,
"text": "NEW"
},
{
"read_list": 21630720,
"row_count": 1
},
{
"read_list": 21630720,
"row_count": 1
},
{
"edit_hwnd": 528470,
"text": "NEW"
},
{
"read_list": 21630720,
"row_count": 1
},
{
"read_list": 21630720,
"row_count": 1
}
],
"report": {
"native_command": {
"id": 33977,
"executable": "C:\\Users\\ABS_Windows\\AppData\\Local\\Programs\\Python\\Python312\\python.exe",
"trigger": "resource_command"
},
"native_options": {
"1704": {
"text": "Option",
"checked": true
},
"1105": {
"text": "Option",
"checked": true
},
"1697": {
"text": "Option",
"checked": true
},
"1700": {
"text": "Option",
"checked": true
}
},
"databook": {
"main_visible_before_browse": true,
"browse_button": 3017658,
"loads": [
{
"mode": "cold",
"timeout_seconds": 45,
"attempt_state_before_load": "prepared",
"list_handle": 21630720,
"filter_handle": 528470,
"error": "Native DxDataBook did not finish loading target part: NEW",
"elapsed_seconds": 3.437,
"dialogs": [],
"attempt_state": "prepared",
"retry": true
},
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "prepared",
"list_handle": 21630720,
"filter_handle": 528470,
"error": "Native DxDataBook did not finish loading target part: NEW",
"elapsed_seconds": 3.344,
"dialogs": [],
"attempt_state": "prepared",
"retry": false
}
]
}
},
"error": "TimeoutError('Native DxDataBook did not finish loading target part: NEW')"
}
@@ -0,0 +1,143 @@
{
"attempt": "mutation_possible",
"events": [
{
"controls": [
21696256,
594006
]
},
{
"controls": [
21761792,
659542
]
},
{
"dead_edit": 594006,
"winerror": 1400
},
{
"edit_hwnd": 659542,
"text": "NEW"
},
{
"read_list": 21761792,
"row_count": 2
},
{
"controls": [
21827328,
725078
]
},
{
"dead_ui_list": 21761792,
"hresult": -2147220991,
"exception": "COMError(-2147220991, '\u4e8b\u4ef6\u65e0\u6cd5\u8c03\u7528\u4efb\u4f55\u8ba2\u6237', (None, None, None, 0, None))"
},
{
"edit_hwnd": 725078,
"text": "NEW"
},
{
"read_list": 21827328,
"row_count": 2
},
{
"read_list": 21827328,
"row_count": 2
},
{
"submit": "mutation_possible"
}
],
"report": {
"native_command": {
"id": 33977,
"executable": "C:\\Users\\ABS_Windows\\AppData\\Local\\Programs\\Python\\Python312\\python.exe",
"trigger": "resource_command"
},
"native_options": {
"1704": {
"text": "Option",
"checked": true
},
"1105": {
"text": "Option",
"checked": true
},
"1697": {
"text": "Option",
"checked": true
},
"1700": {
"text": "Option",
"checked": true
}
},
"databook": {
"main_visible_before_browse": true,
"browse_button": 3017658,
"loads": [
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "prepared",
"list_handle": 21827328,
"filter_handle": 725078,
"elapsed_seconds": 6.125
}
],
"list_handle": 21827328,
"list_visible": true,
"main_visible_after_load": true
},
"library_row": [
"DATA",
"NEW",
"LIB:EXACT",
"",
"Exact",
"Target"
],
"slot_count": 1,
"row_rectangle": [
157,
398,
769,
422
],
"list_handle": 21827328,
"target_text": "NEW",
"symbol_text": "LIB:EXACT",
"target_submit_enabled": true,
"transaction": {
"snapshot_sha256": "d36e0c485331eac7b3c0d25de6dbfc5e915b761dd7eb738caf49b69d89640daa",
"project_path": "g:\\dx33\\acceptance\\d6-native-controls-03\\positive\\synthetic.prj",
"sheet_identity": "MAIN:1",
"old_part_number": "OLD",
"new_part_number": "NEW",
"source_uids": [
"uid"
],
"target_selectors": null,
"library_row": [
"DATA",
"NEW",
"LIB:EXACT",
"",
"Exact",
"Target"
],
"target_symbol": "LIB:EXACT",
"slot_count": 1
},
"stage": "native_replace_verified",
"replaced_uids": [
"uid"
],
"promoted_pins": []
},
"error": null
}
@@ -0,0 +1,78 @@
{
"mode": "normal",
"environment": "Windows, DxDesigner 7.9.5, source runtime",
"library_mapping": "Skyworth_CBB_Lib",
"library_lmc_unchanged": true,
"project": "Audio_D2128.prj",
"request_old_new_refdes": [
"4100-CA0000-T7",
"4100-CA0000-T0",
"RV05"
],
"attempt": {
"session_id": "588db35caf664589a499f02800559ff0",
"generation": 1,
"attempt_id": "65d0375a0a3e4e02a0e0225f5cd7da1d",
"job_id": "3fd4cca09997419cbf0850fe2907f1b5_0",
"state": "mutation_possible"
},
"native": [
{
"ok": true,
"stage": "native_replace_applied",
"databook": {
"main_visible_before_browse": true,
"browse_button": 1577092,
"loads": [
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "prepared",
"list_handle": 266464,
"filter_handle": 266532,
"elapsed_seconds": 2.703
}
],
"list_handle": 266464,
"list_visible": true,
"main_visible_after_load": true
},
"library_row": [
"RESISTOR",
"4100-CA0000-T0",
"skyworth:res01",
"unassigned",
"RESC1608N",
"0R",
""
],
"replaced_uids": [
"$2I2014"
],
"pin_promotion_phase": "promotion_complete"
}
],
"status_log": [
"job_id\tstate\tcode\tmessage",
"3fd4cca09997419cbf0850fe2907f1b5_0\tawaiting_native_replace\t\tSnapshot captured; automatic native replacement is starting.",
"3fd4cca09997419cbf0850fe2907f1b5_0\tpending_save\tsession_staged\tWrites staged; awaiting engineering project save and saved native data verification.",
"3fd4cca09997419cbf0850fe2907f1b5_0\tpending_save\tproject_saved\tEngineering project saved and closed; awaiting saved native data verification.",
"3fd4cca09997419cbf0850fe2907f1b5_0\tsaved_ok\tproject_committed\t%5DE5%7A0B%7EDF%4E00%4FDD%5B58%FF0C%539F%751F%6570%636E%6838%9A8C%901A%8FC7%3002"
],
"operation_log_excerpt": [
"2026/11/25 10:03:45\tINFO\tstage=open_project target=<copy-root>\\project\\Audio_D2128.prj",
"2026/11/25 10:03:59\tINFO\tstage=open_sheet schematic=Audio-D2128 sheet=S905L CVBS-LR",
"2026/11/25 10:04:49\tINFO\tnative_helper_exit code=0",
"2026/11/25 10:05:16\tINFO\treplacement RV05 4100-CA0000-T7 -> 4100-CA0000-T0",
"2026/11/25 10:05:17\tINFO\tsave_requested job=3fd4cca09997419cbf0850fe2907f1b5_0",
"2026/11/25 10:05:17\tINFO\tsave_returned job=3fd4cca09997419cbf0850fe2907f1b5_0",
"2026/11/25 10:05:22\tINFO\tproject_closed job=3fd4cca09997419cbf0850fe2907f1b5_0"
],
"independent_verification": [
"verified"
],
"uncertain_flags_relative_to_data_root": [
"batch-resources/588db35caf664589a499f02800559ff0/generation-1/uncertain.flag"
],
"queue_outcome": "CAD exit exceeded 15 seconds during batch resource cleanup after the saved business receipt"
}
@@ -0,0 +1,44 @@
[
{
"stage": "preflight",
"databook": {
"loads": [
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "prepared",
"list_handle": 17,
"filter_handle": 18,
"error": "Native DxDataBook did not finish loading target part: NEW",
"elapsed_seconds": 1.547,
"dialogs": [
{
"hwnd": 19728876,
"owner": 134972,
"pid": 5004,
"title": "",
"children": [],
"browser": false,
"dismissible": true
}
],
"attempt_state": "prepared",
"retry": true,
"closed_dialog": 19728876
},
{
"mode": "warm",
"timeout_seconds": 20,
"attempt_state_before_load": "prepared",
"list_handle": 17,
"filter_handle": 18,
"elapsed_seconds": 0.187
}
]
},
"window_closed": [
19728876
],
"marker_state": "prepared"
}
]
+9 -1
View File
@@ -4,7 +4,7 @@
主工具顶部固定显示左右两个入口:左侧 **任务中心**,右侧 **DSH助手**,单击直接切换,无需展开菜单。助手也可按 `Ctrl+Shift+D` 打开;切回任务中心再进入助手时保留同一个网页、会话和未发送草稿。右侧“任务监管”读取主工具当前选中的任务。 主工具顶部固定显示左右两个入口:左侧 **任务中心**,右侧 **DSH助手**,单击直接切换,无需展开菜单。助手也可按 `Ctrl+Shift+D` 打开;切回任务中心再进入助手时保留同一个网页、会话和未发送草稿。右侧“任务监管”读取主工具当前选中的任务。
这里直接运行 [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`。 这里直接运行 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 的官方前端与运行时,通过 Qt WebEngine 嵌入主窗口。当前 npm 版本以 `integration/dsh/package.json` 为准。官方三栏框架、原生 SVG、鲸鱼悬停动画、输入编辑器、模型选择、侧栏与停靠交互均由上游代码提供。项目增加任务监管插件和“DSH助手”名称,不再使用 Qt 控件重画聊天页面。上游许可见 `licenses/DeepSeek-Harness-MIT.txt`。
不显示上游账户登录、注册、充值和首次产品引导,也不注册其账户模型提供方。左下角 **工具设置** 单击打开原生设置页,包含“DSH工具”“通用设置”和“模型”;首页提示和任务监管面板围绕器件替换任务。输入框下方选择已配置的模型。 不显示上游账户登录、注册、充值和首次产品引导,也不注册其账户模型提供方。左下角 **工具设置** 单击打开原生设置页,包含“DSH工具”“通用设置”和“模型”;首页提示和任务监管面板围绕器件替换任务。输入框下方选择已配置的模型。
@@ -178,6 +178,14 @@ node tools/verify_dsh_runtime.mjs
python tools/accept_dsh_desktop.py python tools/accept_dsh_desktop.py
``` ```
源码工作区可从 npm 更新 DSH。先退出任务中心,运行更新命令,再重新打开任务中心。
```powershell
powershell -ExecutionPolicy Bypass -File tools/Install-DshRuntime.ps1 -Version latest
```
将 `latest` 换成 `0.2.2-rc.5` 这样的完整版本号即可安装指定版本。脚本先在临时目录启动候选运行时并验证任务插件,通过后更新依赖声明、锁文件和实际依赖。更新成功时会打印 `build/dsh-update-…` 路径,其中 `previous` 保存旧运行时,`verification/report.json` 记录验收结果。便携版随应用打包 DSH,通过重新构建的应用发行包更新。
CLI 验证启动真实官方内核,检查工具与 preset 名单,实际读取快照、执行禁止工具探针,并测试本机请求认证、跨任务与过期动作边界。桌面验收启动真实主工具,用 Qt 鼠标事件单击左右导航,用 Chromium Input 事件操作官方页面,核对全新数据下无账户或引导弹窗、工具设置、任务刷新、会话、侧栏、SVG 动画、模型选择、草稿保留、取消确认和正常退出。验收只使用独立测试数据,不启动 CAD 或修改用户工程;未配置模型的验收不计为真实模型回复验证。 CLI 验证启动真实官方内核,检查工具与 preset 名单,实际读取快照、执行禁止工具探针,并测试本机请求认证、跨任务与过期动作边界。桌面验收启动真实主工具,用 Qt 鼠标事件单击左右导航,用 Chromium Input 事件操作官方页面,核对全新数据下无账户或引导弹窗、工具设置、任务刷新、会话、侧栏、SVG 动画、模型选择、草稿保留、取消确认和正常退出。验收只使用独立测试数据,不启动 CAD 或修改用户工程;未配置模型的验收不计为真实模型回复验证。
已配置本机模型时,可执行真实 API 桌面验收: 已配置本机模型时,可执行真实 API 桌面验收:
+4138 -3271
View File
File diff suppressed because it is too large. Load diff
+11 -3
View File
@@ -2,7 +2,15 @@
"name": "dxdesigner-dsh-runtime", "name": "dxdesigner-dsh-runtime",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": {"doctor": "node start.mjs --doctor", "start": "node start.mjs"}, "scripts": {
"engines": {"node": ">=24.9.0"}, "doctor": "node start.mjs --doctor",
"dependencies": {"@deepseek-ai/dsh": "0.2.1-rc.5", "fflate": "0.8.3"} "start": "node start.mjs"
},
"engines": {
"node": ">=24.9.0"
},
"dependencies": {
"@deepseek-ai/dsh": "0.2.2-rc.5",
"fflate": "0.8.3"
}
} }
+1 -1
View File
@@ -12,7 +12,7 @@ export const FILE_TOOLS=['read','read_image','write','edit','glob','grep','worki
const root = path.dirname(fileURLToPath(import.meta.url)); const root = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
export const VERSION = '0.2.1-rc.5'; export const VERSION = require('./package.json').dependencies['@deepseek-ai/dsh'];
export const DISABLED = [ export const DISABLED = [
'desktop-product-telemetry','product-analytics','session-telemetry-otel', 'desktop-product-telemetry','product-analytics','session-telemetry-otel',
]; ];
@@ -1123,7 +1123,8 @@ Sub QPDiscardFailedBatchProject(ByRef ErrorDescription)
If (Not QP_BatchMode And Not QP_SessionMode) Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub If (Not QP_BatchMode And Not QP_SessionMode) Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub
HasStagedItems = False HasStagedItems = False
If IsObject(QP_SessionItems) Then HasStagedItems = (QP_SessionItems.Count > 0) If IsObject(QP_SessionItems) Then HasStagedItems = (QP_SessionItems.Count > 0)
If QP_NativeMutationPossible Or QP_BatchSaveRequested Or QP_BatchSaveCommitted Or HasStagedItems Then If QP_NativeMutationPossible Or QP_NativeCallActive Or QP_RestoreTransactionOpen Or _
QP_BatchSaveRequested Or QP_BatchSaveCommitted Or HasStagedItems Then
ErrorDescription = "write or save outcome requires reconciliation; owned project retained without automatic save or discard" ErrorDescription = "write or save outcome requires reconciliation; owned project retained without automatic save or discard"
Exit Sub Exit Sub
End If End If
@@ -1658,6 +1659,7 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
End If End If
CommandLine = CommandLine & " --native-helper --snapshot " & Chr(34) & SnapshotPath & Chr(34) CommandLine = CommandLine & " --native-helper --snapshot " & Chr(34) & SnapshotPath & Chr(34)
Set Shell = CreateObject("WScript.Shell") Set Shell = CreateObject("WScript.Shell")
QP_Stage = "native_replace"
QP_NativeCallActive = True QP_NativeCallActive = True
QPProgress "native_replace", 0, 1 QPProgress "native_replace", 0, 1
ExitCode = Shell.Run(CommandLine, 0, True) ExitCode = Shell.Run(CommandLine, 0, True)
+1 -1
View File
@@ -1,5 +1,5 @@
DeepSeek Harness native frontend and runtime DeepSeek Harness native frontend and runtime
Pinned release: @deepseek-ai/dsh 0.2.1-rc.5 Package: @deepseek-ai/dsh
Source: https://github.com/deepseek-ai/deepseek-harness Source: https://github.com/deepseek-ai/deepseek-harness
MIT License MIT License
@@ -12,9 +12,6 @@ from uuid import uuid4
from .snapshot import TaskSnapshot from .snapshot import TaskSnapshot
from ..trial_task_center.path_access import retry_sharing_violation from ..trial_task_center.path_access import retry_sharing_violation
HARNESS_VERSION = '0.2.1-rc.5'
def integration_root() -> Path: def integration_root() -> Path:
if getattr(sys, 'frozen', False): if getattr(sys, 'frozen', False):
return Path(sys._MEIPASS) / 'dsh-runtime' return Path(sys._MEIPASS) / 'dsh-runtime'
@@ -292,7 +292,8 @@ def wait_for(callback, description, timeout=15):
raise TimeoutError(description) raise TimeoutError(description)
def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_interval=0.15): def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_interval=0.15,
scope=lambda: None):
deadline = time.monotonic() + timeout deadline = time.monotonic() + timeout
previous = None previous = None
stable_since = None stable_since = None
@@ -309,7 +310,7 @@ def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_in
previous = stable_since = None previous = stable_since = None
time.sleep(poll_interval) time.sleep(poll_interval)
continue continue
signature = tuple(tuple(str(value) for value in columns) for _, columns in latest) signature = (scope(), tuple(tuple(str(value) for value in columns) for _, columns in latest))
now = time.monotonic() now = time.monotonic()
if signature != previous: if signature != previous:
previous = signature previous = signature
@@ -321,6 +322,106 @@ def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_in
raise TimeoutError(f"Native DxDataBook did not finish loading target part: {target}") raise TimeoutError(f"Native DxDataBook did not finish loading target part: {target}")
def load_databook_target(snapshot, report, target, *, controls, browse, filter_part,
list_rows, dialogs, close_dialog):
"""Load the target before the native submit boundary and retry a prepared batch once."""
from .batch_attempt import can_retry_attempt
diagnostic = report.setdefault('databook', {})
loads = diagnostic['loads'] = []
baseline = {row['hwnd'] for row in dialogs()}
initial = snapshot_attempt(snapshot)
warm = controls() is not None
for index in range(2):
timeout = 20 if warm else 45
started = time.monotonic()
load = {'mode': 'warm' if warm else 'cold', 'timeout_seconds': timeout,
'attempt_state_before_load': initial[1]['state'] if initial else None}
loads.append(load)
save_report(snapshot, report)
pair = None
def read():
nonlocal pair
current = controls()
if current is None:
pair = None
return []
try:
if current != pair:
filter_part(current[1])
pair = current
load.update(list_handle=pair[0], filter_handle=pair[1])
return list_rows(pair[0])
except Exception as error:
if (getattr(error, 'winerror', None) != 1400 # ERROR_INVALID_WINDOW_HANDLE
and getattr(error, 'hresult', None) != -2147220991): # UIA_E_ELEMENTNOTAVAILABLE
raise
pair = None
return []
try:
if index == 0 or controls() is None:
browse()
rows = wait_for_library_rows(read, target, timeout=timeout, scope=lambda: pair)
except TimeoutError as error:
load['error'] = str(error)
load['elapsed_seconds'] = round(time.monotonic() - started, 3)
load['dialogs'] = [row for row in dialogs() if row['hwnd'] not in baseline]
bound = snapshot_attempt(snapshot)
prepared = initial is not None and initial[1]['state'] == 'prepared' and can_retry_attempt(*initial)
load['attempt_state'] = bound[1]['state'] if bound else None
blockers = [row for row in load['dialogs'] if not row.get('browser')]
candidates = [row for row in blockers if row['dismissible']]
retry = index == 0 and prepared and bool(os.environ.get('DXPART_DESKTOP'))
# A different modal must get its normal operator handling.
retry = retry and (not blockers or len(blockers) == len(candidates) == 1)
load['retry'] = retry
save_report(snapshot, report)
if not retry:
raise
if candidates:
close_dialog(candidates[0])
load['closed_dialog'] = candidates[0]['hwnd']
warm = True
else:
load['elapsed_seconds'] = round(time.monotonic() - started, 3)
return pair[0], rows
def databook_dialogs(gui, process, pid, replacement, main_handle):
from .cad_dialogs import _text
replacement_thread, _ = process.GetWindowThreadProcessId(replacement)
rows = []
def dialog(handle, _):
if (handle in {replacement, main_handle} or not gui.IsWindowVisible(handle)
or process.GetWindowThreadProcessId(handle)[1] != pid
or gui.GetClassName(handle) != '#32770'):
return
owner = gui.GetWindow(handle, 4) # GW_OWNER
row = {'hwnd': handle, 'owner': owner, 'pid': pid, 'title': '', 'children': [],
'browser': False, 'dismissible': False}
rows.append(row)
children = []
try:
row['title'] = _text(handle)
gui.EnumChildWindows(handle, lambda child, _: children.append(child), None)
row['children'] = [{'hwnd': child, 'parent': gui.GetParent(child), 'class': gui.GetClassName(child),
'id': gui.GetDlgCtrlID(child)} for child in children[:64]]
row['browser'] = {('SysListView32', 4000), ('Edit', 4006)} <= {
(child['class'], child['id']) for child in row['children']}
row['dismissible'] = (not row['title'].strip() and not children and owner == replacement
and process.GetWindowThreadProcessId(handle)[0] == replacement_thread
and not gui.IsWindowEnabled(replacement))
except (OSError, gui.error) as error:
row['read_error'] = str(error)
gui.EnumWindows(dialog, None)
return rows
def target_symbol_matches(displayed, library_symbol, slot_count): def target_symbol_matches(displayed, library_symbol, slot_count):
actual = str(displayed).casefold() actual = str(displayed).casefold()
expected = str(library_symbol).casefold() expected = str(library_symbol).casefold()
@@ -848,8 +949,8 @@ def run_native(snapshot, report):
raise ValueError("Multiple replacement dialogs") raise ValueError("Multiple replacement dialogs")
return matches[0] if matches else None return matches[0] if matches else None
def message(handle, code, wparam=0, lparam=0): def message(handle, code, wparam=0, lparam=0, *, timeout=15000):
return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, 15000) return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, timeout)
def control_text(control): def control_text(control):
buffer = ctypes.create_unicode_buffer(2048) buffer = ctypes.create_unicode_buffer(2048)
@@ -865,9 +966,9 @@ def run_native(snapshot, report):
control = dlg_item(dialog, identifier) control = dlg_item(dialog, identifier)
if not control: if not control:
raise ValueError(f"Required native option {identifier} is unavailable") raise ValueError(f"Required native option {identifier} is unavailable")
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1: if message(control, 0x00F0)[1] != 1:
click(control) click(control)
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1: if message(control, 0x00F0)[1] != 1:
raise ValueError(f"Native option {identifier} was not enabled") raise ValueError(f"Native option {identifier} was not enabled")
report.setdefault("native_options", {})[str(identifier)] = { report.setdefault("native_options", {})[str(identifier)] = {
"text": control_text(control), "text": control_text(control),
@@ -896,31 +997,68 @@ def run_native(snapshot, report):
"main_visible_before_browse": bool(win32gui.IsWindowVisible(main_handle)), "main_visible_before_browse": bool(win32gui.IsWindowVisible(main_handle)),
"browse_button": int(dlg_item(dialog, 1366)), "browse_button": int(dlg_item(dialog, 1366)),
} }
click(dlg_item(dialog, 1366))
def part_list(): def query_message(handle, code, wparam=0, lparam=0):
report["databook"]["main_visible_during_wait"] = bool( try:
win32gui.IsWindowVisible(main_handle) message(handle, code, wparam, lparam, timeout=5000)
) except win32gui.error as error:
if error.winerror == 1460:
raise TimeoutError('Native DxDataBook browse or filter did not respond') from error
raise
def browse():
button = dlg_item(dialog, 1366)
if button and win32gui.IsWindowEnabled(dialog) and win32gui.IsWindowEnabled(button):
query_message(button, 0x00F5) # BM_CLICK
def controls():
lists, filters = {}, {}
for handle in owned_windows(include_hidden=True): for handle in owned_windows(include_hidden=True):
if win32gui.GetClassName(handle) == "SysListView32" and win32gui.GetDlgCtrlID(handle) == 4000: try:
return handle kind = (win32gui.GetClassName(handle), win32gui.GetDlgCtrlID(handle))
return None if kind == ('SysListView32', 4000):
list_handle = wait_for(part_list, "Native DxDataBook part list did not open", timeout=30) lists[handle] = win32gui.GetAncestor(handle, 2)
elif kind == ('Edit', 4006):
filters[handle] = win32gui.GetAncestor(handle, 2)
except win32gui.error:
if win32gui.IsWindow(handle):
raise
pairs = [(part_list, part_filter) for part_list, list_root in lists.items()
for part_filter, filter_root in filters.items() if list_root == filter_root]
visible = [pair for pair in pairs if all(win32gui.IsWindowVisible(handle) for handle in pair)]
pairs = visible or pairs
return pairs[0] if len(pairs) == 1 else None
def filter_part(handle):
query_message(handle, win32con.WM_SETTEXT, 0, metadata[3])
def current_library_rows(list_handle):
try:
return [(row, [text.window_text() for text in row.children(control_type="Text")])
for row in desktop.window(handle=list_handle).descendants(control_type="ListItem")]
except Exception:
if win32gui.IsWindow(list_handle):
raise
return []
def dialogs():
return databook_dialogs(win32gui, win32process, process_id, dialog, main_handle)
def close_dialog(expected):
if expected not in dialogs():
raise OSError('DxDataBook dialog changed before close')
win32gui.PostMessage(expected['hwnd'], win32con.WM_CLOSE, 0, 0)
wait_for(lambda: not win32gui.IsWindowVisible(expected['hwnd']),
'Native DxDataBook dialog did not close', timeout=3)
list_handle, rows = load_databook_target(snapshot, report, metadata[3], controls=controls,
browse=browse, filter_part=filter_part, list_rows=current_library_rows,
dialogs=dialogs, close_dialog=close_dialog)
report["databook"].update( report["databook"].update(
list_handle=int(list_handle), list_handle=int(list_handle),
list_visible=bool(win32gui.IsWindowVisible(list_handle)), list_visible=bool(win32gui.IsWindowVisible(list_handle)),
main_visible_after_load=bool(win32gui.IsWindowVisible(main_handle)), main_visible_after_load=bool(win32gui.IsWindowVisible(main_handle)),
) )
filter_handles = [handle for handle in owned_windows(include_hidden=True)
if win32gui.GetDlgCtrlID(handle) == 4006 and win32gui.GetClassName(handle) == "Edit"]
if len(filter_handles) != 1:
raise ValueError("Cannot uniquely identify native Part Number filter")
message(filter_handles[0], win32con.WM_SETTEXT, 0, metadata[3])
def current_library_rows():
return [(row, [text.window_text() for text in row.children(control_type="Text")])
for row in desktop.window(handle=list_handle).descendants(control_type="ListItem")]
rows = wait_for_library_rows(current_library_rows, metadata[3])
row, columns = exact_target(rows, metadata[3]) row, columns = exact_target(rows, metadata[3])
report["library_row"] = columns report["library_row"] = columns
symbol_parts = columns[2].split(":", 1) symbol_parts = columns[2].split(":", 1)
@@ -930,6 +1068,9 @@ def run_native(snapshot, report):
report["slot_count"] = slot_count report["slot_count"] = slot_count
if slot_count < 1: if slot_count < 1:
raise ValueError("Library target has no valid slots") raise ValueError("Library target has no valid slots")
current_pair = controls()
if current_pair is None or current_pair[0] != list_handle:
raise ValueError("DxDataBook controls changed after target selection")
rectangle = row.rectangle() rectangle = row.rectangle()
list_rectangle = win32gui.GetWindowRect(list_handle) list_rectangle = win32gui.GetWindowRect(list_handle)
if rectangle.height() <= 0 or rectangle.top < list_rectangle[1] or rectangle.bottom > list_rectangle[3]: if rectangle.height() <= 0 or rectangle.top < list_rectangle[1] or rectangle.bottom > list_rectangle[3]:
+175
View File
@@ -0,0 +1,175 @@
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import native_helper as native
from dx_productivity.trial_task_center.batch_attempt import prepare_attempt, read_attempt
@pytest.fixture
def attempt(tmp_path, monkeypatch):
job = 'job'
project = tmp_path / 'board.prj'
record_path = tmp_path / 'attempt.json'
snapshot = tmp_path / f'snapshot-{job}.tsv'
snapshot.write_text(f'M\t{project}\tOLD\tNEW\tMAIN:1\nC\tuid\tR1\t0\t0\t0\t1\t\n', encoding='utf-8')
(tmp_path / 'command.tsv').write_text(
f'job_id\ttask_id\tproject_path\n{job}\ttask\t{project}\n', encoding='utf-8')
record = prepare_attempt(record_path, session_id='session', generation=1,
job_id=job, task_id='task', project_path=project)
for name, value in {
'DXPART_DESKTOP': 'dx-test',
'DXPART_ATTEMPT_FILE': record_path,
'DXPART_ATTEMPT_ID': record['attempt_id'],
'DXPART_BATCH_GENERATION': record['generation'],
'DXPART_BATCH_SESSION_ID': record['session_id'],
}.items():
monkeypatch.setenv(name, str(value))
return snapshot, record_path
@pytest.fixture
def clock(monkeypatch):
now = [0.]
monkeypatch.setattr(native, 'time', SimpleNamespace(
monotonic=lambda: now[0], sleep=lambda seconds: now.__setitem__(0, now[0] + seconds)))
return now
def test_cold_list_recreation_reapplies_filter_and_uses_the_new_handle(attempt, clock):
snapshot, record = attempt
report, filtered = {}, []
browsing = False
def browse():
nonlocal browsing
browsing = True
def controls():
if browsing:
return (10, 11) if clock[0] < .3 else (20, 21)
return None
list_handle, rows = native.load_databook_target(snapshot, report, 'NEW',
controls=controls, browse=browse, filter_part=lambda handle: filtered.append(handle),
list_rows=lambda handle: [(handle, ['GATE', 'NEW', 'lib:SYM'])],
dialogs=lambda: (), close_dialog=lambda handle: pytest.fail('unexpected close'))
assert (list_handle, rows[0][0], filtered) == (20, 20, [11, 21])
assert report['databook']['loads'][0]['mode'] == 'cold'
assert read_attempt(record)['state'] == 'prepared'
@pytest.mark.parametrize('during', ['filter', 'rows'])
def test_control_destroyed_between_discovery_and_access_is_reacquired(attempt, clock, during):
snapshot, record = attempt
state = {'controls': (10, 11)}
visited = []
def destroyed():
state['controls'] = (20, 21)
error = OSError('stale DxDataBook control')
if during == 'filter':
error.winerror = 1400
else:
error.hresult = -2147220991
raise error
def filter_part(handle):
visited.append(handle)
if during == 'filter' and handle == 11:
destroyed()
def rows(handle):
if during == 'rows' and handle == 10:
destroyed()
return [(handle, ['GATE', 'NEW', 'lib:SYM'])]
report = {}
handle, _ = native.load_databook_target(snapshot, report, 'NEW',
controls=lambda: state['controls'], browse=lambda: None, filter_part=filter_part,
list_rows=rows, dialogs=lambda: (), close_dialog=lambda _: pytest.fail('unexpected close'))
assert handle == 20 and visited == [11, 21]
assert len(report['databook']['loads']) == 1
assert read_attempt(record)['state'] == 'prepared'
@pytest.mark.parametrize('already_written', [False, True])
def test_timeout_reissues_filter_once_only_with_bound_prepared_attempt(attempt, clock, already_written):
snapshot, record = attempt
if already_written:
native.mark_snapshot_mutation(snapshot)
report, filters = {}, []
def run():
return native.load_databook_target(snapshot, report, 'NEW',
controls=lambda: (10, 11), browse=lambda: None,
filter_part=lambda handle: filters.append(handle), list_rows=lambda handle: [],
dialogs=lambda: (), close_dialog=lambda handle: pytest.fail('unexpected close'))
with pytest.raises(TimeoutError, match='DxDataBook'):
run()
loads = report['databook']['loads']
assert [load['mode'] for load in loads] == ['warm'] * (1 if already_written else 2)
assert len(filters) == len(loads)
assert read_attempt(record)['state'] == ('mutation_possible' if already_written else 'prepared')
def test_retry_closes_only_new_owned_empty_dialog_and_persists_evidence_first(attempt, clock):
snapshot, record = attempt
report, closed = {}, []
blank = {'hwnd': 19, 'owner': 7, 'title': '', 'children': [], 'dismissible': True}
previous = dict(blank, hwnd=18)
named = dict(blank, hwnd=20, title='Save', dismissible=False)
def dialogs():
return [previous, named] if clock[0] == 0 else [previous, blank, named]
def close(row):
import json
evidence = json.loads(snapshot.with_suffix('.tsv.native.json').read_bytes())
assert evidence['databook']['loads'][0]['dialogs'][0]['hwnd'] == 19
assert evidence['databook']['loads'][0]['attempt_state'] == 'prepared'
closed.append(row['hwnd'])
native.load_databook_target(snapshot, report, 'NEW',
controls=lambda: (10, 11), browse=lambda: None, filter_part=lambda handle: None,
list_rows=lambda handle: [(handle, ['GATE', 'NEW', 'lib:SYM'])] if closed else [],
dialogs=dialogs, close_dialog=close)
assert closed == [19]
assert len(report['databook']['loads']) == 2
assert read_attempt(record)['state'] == 'prepared'
def test_named_or_unowned_prompt_keeps_operator_handling(attempt, clock):
snapshot, _ = attempt
report = {}
with pytest.raises(TimeoutError, match='DxDataBook'):
native.load_databook_target(snapshot, report, 'NEW',
controls=lambda: (10, 11), browse=lambda: None, filter_part=lambda handle: None,
list_rows=lambda handle: [],
dialogs=lambda: [{'hwnd': 20, 'dismissible': False}] if clock[0] else [],
close_dialog=lambda row: pytest.fail('unrecognized prompt was closed'))
assert len(report['databook']['loads']) == 1
def test_dialog_fingerprint_requires_same_owner_pid_thread_and_empty_controls(monkeypatch):
from dx_productivity.trial_task_center import cad_dialogs
owner, pid = 7, 8
windows = {10: (1, pid, owner), 11: (1, pid, 99), 12: (2, pid, owner),
13: (1, 99, owner), 14: (1, pid, owner), owner: (1, pid, 99)}
monkeypatch.setattr(cad_dialogs, '_text', lambda hwnd: '')
gui = SimpleNamespace(
error=RuntimeError, IsWindowVisible=lambda hwnd: True, IsWindowEnabled=lambda hwnd: False,
EnumWindows=lambda callback, _: [callback(hwnd, None) for hwnd in windows],
GetWindow=lambda hwnd, _: windows[hwnd][2],
EnumChildWindows=lambda hwnd, callback, _: callback(20, None) if hwnd == 14 else None,
GetClassName=lambda hwnd: 'Button' if hwnd == 20 else '#32770',
GetDlgCtrlID=lambda hwnd: 1, GetParent=lambda hwnd: 14,
)
process = SimpleNamespace(GetWindowThreadProcessId=lambda hwnd: windows[hwnd][:2])
rows = native.databook_dialogs(gui, process, pid, owner, 99)
assert [row['hwnd'] for row in rows] == [10, 11, 12, 14]
assert [row['hwnd'] for row in rows if row['dismissible']] == [10]
assert rows[-1]['children'] == [{'hwnd': 20, 'parent': 14, 'class': 'Button', 'id': 1}]
+6 -3
View File
@@ -3,7 +3,8 @@ import test_accuracy_vbs_guards as guards
@pytest.mark.parametrize('fault', ['', 'snapshot', 'identity', 'transaction', 'native', @pytest.mark.parametrize('fault', ['', 'snapshot', 'identity', 'transaction', 'native',
'save_requested', 'save_committed', 'close']) 'native_unresolved', 'prior_staged_write', 'save_requested',
'save_committed', 'close'])
def test_safe_pause_cannot_interrupt_verified_failure_cleanup(tmp_path, fault): def test_safe_pause_cannot_interrupt_verified_failure_cleanup(tmp_path, fault):
output = guards.run_vbs(tmp_path, ['QPProgress', 'QPDiscardFailedBatchProject', output = guards.run_vbs(tmp_path, ['QPProgress', 'QPDiscardFailedBatchProject',
'QPCloseBatchProject', 'QPReadUtf8'], ''' 'QPCloseBatchProject', 'QPReadUtf8'], '''
@@ -33,6 +34,8 @@ Set QP_Fso=CreateObject("Scripting.FileSystemObject")
QP_Root="''' + str(tmp_path) + '''":QP_AttemptToken="token":QP_ProgressSequence=0 QP_Root="''' + str(tmp_path) + '''":QP_AttemptToken="token":QP_ProgressSequence=0
QP_BatchMode=True:QP_OwnedProject=True:QP_OwnedProjectPath="board.prj" QP_BatchMode=True:QP_OwnedProject=True:QP_OwnedProjectPath="board.prj"
QP_NativeMutationPossible=''' + str(fault == 'native') + ''' QP_NativeMutationPossible=''' + str(fault == 'native') + '''
QP_NativeCallActive=''' + str(fault == 'native_unresolved') + '''
If ''' + str(fault == 'prior_staged_write') + ''' Then QP_SessionItems.Add "previous-job", "restored_ok"
QP_BatchSaveRequested=''' + str(fault == 'save_requested') + ''' QP_BatchSaveRequested=''' + str(fault == 'save_requested') + '''
QP_BatchSaveCommitted=''' + str(fault == 'save_committed') + ''' QP_BatchSaveCommitted=''' + str(fault == 'save_committed') + '''
Class FakeApp Class FakeApp
@@ -85,8 +88,8 @@ End Sub
Sub QPLog(ByVal Root,ByVal Level,ByVal Message) Sub QPLog(ByVal Root,ByVal Level,ByVal Message)
End Sub End Sub
''') ''')
paused_before = fault != 'native' paused_before = fault not in {'native', 'native_unresolved'}
paused_after = fault not in {'native', 'transaction'} paused_after = fault not in {'native', 'native_unresolved', 'transaction'}
assert output.splitlines()[-1] == f'result:{paused_before}:{not fault}:{bool(fault)}:{paused_after}' assert output.splitlines()[-1] == f'result:{paused_before}:{not fault}:{bool(fault)}:{paused_after}'
+2 -1
View File
@@ -152,6 +152,7 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk
elif code == 0xF5 and handle == 1695: elif code == 0xF5 and handle == 1695:
submits.append(handle) submits.append(handle)
raise RuntimeError('native submit reached') raise RuntimeError('native submit reached')
return 1, 1
gui = SimpleNamespace(error=RuntimeError, GetAncestor=lambda *args: 1, EnumWindows=enum_windows, gui = SimpleNamespace(error=RuntimeError, GetAncestor=lambda *args: 1, EnumWindows=enum_windows,
EnumChildWindows=lambda *args: None, IsWindowVisible=lambda handle: True, EnumChildWindows=lambda *args: None, IsWindowVisible=lambda handle: True,
GetClassName=lambda handle: {2: '#32770', 3: 'SysListView32', 4: 'Edit'}.get(handle, 'Main'), GetClassName=lambda handle: {2: '#32770', 3: 'SysListView32', 4: 'Edit'}.get(handle, 'Main'),
@@ -179,7 +180,7 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk
monkeypatch.setattr(native_helper, 'selection', lambda *args: None) monkeypatch.setattr(native_helper, 'selection', lambda *args: None)
monkeypatch.setattr(native_helper, 'replacement_command_from_resources', lambda *args: 33977) monkeypatch.setattr(native_helper, 'replacement_command_from_resources', lambda *args: 33977)
monkeypatch.setattr(native_helper, 'wait_for', lambda callback, *args, **kwargs: callback()) monkeypatch.setattr(native_helper, 'wait_for', lambda callback, *args, **kwargs: callback())
monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args: callback()) monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args, **kwargs: callback())
monkeypatch.setattr(native_helper, 'wait_for_native_target', lambda callback, *args: callback()) monkeypatch.setattr(native_helper, 'wait_for_native_target', lambda callback, *args: callback())
report = {} report = {}
with pytest.raises(ValueError if fail_at else RuntimeError, match='重新读取目标封装' if fail_at else 'native submit reached'): with pytest.raises(ValueError if fail_at else RuntimeError, match='重新读取目标封装' if fail_at else 'native submit reached'):
+65 -5
View File
@@ -1,14 +1,74 @@
param() param(
[string]$Version
)
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$dshRepoRoot = Split-Path -Parent $PSScriptRoot $dshRepoRoot = Split-Path -Parent $PSScriptRoot
$dshRuntimeRoot = Join-Path $dshRepoRoot 'integration/dsh' $dshRuntimeRoot = Join-Path $dshRepoRoot 'integration/dsh'
$dshNodeCommand = Get-Command node -ErrorAction Stop $dshNodeCommand = Get-Command node -ErrorAction Stop
$dshNodeVersion = & $dshNodeCommand.Source -p 'process.versions.node' $dshNodeVersion = & $dshNodeCommand.Source -p 'process.versions.node'
if ([version]$dshNodeVersion -lt [version]'24.9.0') { throw 'DSH requires Node.js 24.9.0 or later.' } if ([version]$dshNodeVersion -lt [version]'24.9.0') { throw 'DSH requires Node.js 24.9.0 or later.' }
Push-Location -LiteralPath $dshRuntimeRoot $dshNpm = (Get-Command npm.cmd -ErrorAction Stop).Source
$dshRegistry = 'https://registry.npmjs.org/'
$dshBuild = Join-Path $dshRepoRoot 'build'
New-Item -ItemType Directory -Path $dshBuild -Force | Out-Null
$dshInstallLock = [IO.File]::Open((Join-Path $dshBuild 'dsh-install.lock'), 'OpenOrCreate', 'ReadWrite', 'None')
try { try {
& npm.cmd ci --ignore-scripts --no-audit --no-fund if (-not $Version) {
& $dshNpm --prefix $dshRuntimeRoot ci --ignore-scripts --no-audit --no-fund
if ($LASTEXITCODE -ne 0) { throw 'DSH installation failed.' } if ($LASTEXITCODE -ne 0) { throw 'DSH installation failed.' }
& $dshNodeCommand.Source start.mjs --doctor & $dshNodeCommand.Source (Join-Path $dshRuntimeRoot 'start.mjs') --doctor
if ($LASTEXITCODE -ne 0) { throw 'DSH runtime verification failed.' } if ($LASTEXITCODE -ne 0) { throw 'DSH runtime verification failed.' }
} finally { Pop-Location } return
}
if ($Version -cnotmatch '\A(?:latest|\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\z') {
throw 'Use latest or an exact version, for example 0.2.2-rc.5.'
}
# Keep the candidate and previous installation on the same volume for rename.
$dshStage = Join-Path $dshBuild ('dsh-update-' + [Guid]::NewGuid().ToString('N'))
$dshCandidate = Join-Path $dshStage 'candidate'
$dshPrevious = Join-Path $dshStage 'previous'
$dshEntries = @('package.json', 'package-lock.json', 'node_modules')
$dshBackedUp = @()
$dshPublished = @()
New-Item -ItemType Directory -Path $dshCandidate, $dshPrevious -Force | Out-Null
try {
Copy-Item -LiteralPath @(
(Join-Path $dshRuntimeRoot 'package.json')
(Join-Path $dshRuntimeRoot 'package-lock.json')
(Join-Path $dshRuntimeRoot 'start.mjs')
(Join-Path $dshRuntimeRoot 'task-plugin')
) -Destination $dshCandidate -Recurse
& $dshNpm --prefix $dshCandidate install --save-exact --ignore-scripts --no-audit --no-fund --registry=$dshRegistry "@deepseek-ai/dsh@$Version"
if ($LASTEXITCODE -ne 0) { throw 'DSH candidate installation failed.' }
& $dshNodeCommand.Source (Join-Path $PSScriptRoot 'verify_dsh_runtime.mjs') $dshCandidate (Join-Path $dshStage 'verification')
if ($LASTEXITCODE -ne 0) { throw 'DSH candidate failed the runtime check. The previous runtime is still available.' }
foreach ($dshEntry in $dshEntries) {
$dshLive = Join-Path $dshRuntimeRoot $dshEntry
if (Test-Path -LiteralPath $dshLive) {
Move-Item -LiteralPath $dshLive -Destination (Join-Path $dshPrevious $dshEntry)
$dshBackedUp += $dshEntry
}
Move-Item -LiteralPath (Join-Path $dshCandidate $dshEntry) -Destination $dshLive
$dshPublished += $dshEntry
}
} catch {
try {
foreach ($dshEntry in $dshPublished) {
Move-Item -LiteralPath (Join-Path $dshRuntimeRoot $dshEntry) -Destination (Join-Path $dshCandidate $dshEntry)
}
foreach ($dshEntry in $dshBackedUp) {
Move-Item -LiteralPath (Join-Path $dshPrevious $dshEntry) -Destination (Join-Path $dshRuntimeRoot $dshEntry)
}
} catch {
throw "DSH rollback failed. Previous files: $dshPrevious. $($_.Exception.Message)"
}
throw
}
Write-Output "DSH updated. Previous files and verification: $dshStage"
} finally {
$dshInstallLock.Dispose()
}
+2 -1
View File
@@ -13,7 +13,8 @@ const {loadProfileDirectory,composeEntries}=await load('@deepseek-ai/dsh-app-boo
const {runProfile,INSTALL_ANCHOR}=await load('@deepseek-ai/dsh/profile-boot'); const {runProfile,INSTALL_ANCHOR}=await load('@deepseek-ai/dsh/profile-boot');
const {createLaunchEnvironmentSnapshot}=await load('@deepseek-ai/dsh-launch-environment'); const {createLaunchEnvironmentSnapshot}=await load('@deepseek-ai/dsh-launch-environment');
const installed=require('@deepseek-ai/dsh/package.json'); const installed=require('@deepseek-ai/dsh/package.json');
if(installed.version!=='0.2.1-rc.5')throw Error('Runtime version mismatch'); const expected=require('../package.json').dependencies['@deepseek-ai/dsh'];
if(installed.version!==expected)throw Error('Runtime version mismatch');
const original=loadProfileDirectory('paired-source',path.resolve(source),INSTALL_ANCHOR); const original=loadProfileDirectory('paired-source',path.resolve(source),INSTALL_ANCHOR);
const effective=composeEntries([...original.layers.map(layer=>layer.patches),original.patches]); const effective=composeEntries([...original.layers.map(layer=>layer.patches),original.patches]);
// Copy effective routing/model/shell budgets, never credential values to reports. // Copy effective routing/model/shell budgets, never credential values to reports.
+2 -1
View File
@@ -1,4 +1,5 @@
/** Check actual shell file access separately from model behavior. */ /** Check actual shell file access separately from model behavior. */
import {executeTool} from './dsh_tool_probe.mjs';
import {mkdir,mkdtemp,writeFile} from 'node:fs/promises'; import {mkdir,mkdtemp,writeFile} from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
import os from 'node:os'; import os from 'node:os';
@@ -17,7 +18,7 @@ try{
const agent=ctx.agents.get(sessionId); const agent=ctx.agents.get(sessionId);
const filename=path.join(process.env.DX_DSH_WORKSPACE,'input.txt'); const filename=path.join(process.env.DX_DSH_WORKSPACE,'input.txt');
await writeFile(filename,'SHELL_FILE_READ_OK'); await writeFile(filename,'SHELL_FILE_READ_OK');
const result=await ctx.tools.execute({agent,callId:crypto.randomUUID(),name:'pwsh', const result=await executeTool(ctx, {agent,callId:crypto.randomUUID(),name:'pwsh',
arguments:{description:'Read the owned shell verification file',command:`[System.IO.File]::ReadAllText('${filename.replaceAll("'","''")}')`},signal:AbortSignal.timeout(30000)}); arguments:{description:'Read the owned shell verification file',command:`[System.IO.File]::ReadAllText('${filename.replaceAll("'","''")}')`},signal:AbortSignal.timeout(30000)});
console.log(JSON.stringify({root,result})); console.log(JSON.stringify({root,result}));
}finally{await shutdown.shutdown(0);} }finally{await shutdown.shutdown(0);}
+8
View File
@@ -0,0 +1,8 @@
/** Run one tool through the installed Harness batch executor. */
export async function executeTool(ctx, {callId, name, arguments: args, ...options}) {
const {results} = await ctx.tools.execute({
...options,
calls: [{type: 'tool-call', id: callId, name, arguments: JSON.stringify(args ?? {})}],
});
return results[0].result;
}
+33 -6
View File
@@ -1,13 +1,19 @@
/** Real native Harness incident diagnosis; no engineering mutations or issue writes. */ /** Real native Harness incident diagnosis; no engineering mutations or issue writes. */
import {executeTool} from './dsh_tool_probe.mjs';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import {mkdir,writeFile} from 'node:fs/promises'; import {mkdir,mkdtemp,writeFile} from 'node:fs/promises';
import {createRequire} from 'node:module';
import path from 'node:path'; import path from 'node:path';
import {pathToFileURL} from 'node:url';
import {bootRuntime} from '../integration/dsh/start.mjs'; import {bootRuntime} from '../integration/dsh/start.mjs';
const output=path.resolve('build/dsh-auto-runtime'); const output=path.resolve('build/dsh-auto-runtime');
await mkdir(output,{recursive:true}); await mkdir(output,{recursive:true});
process.env.DX_DSH_HOME=path.join(output,'home'); const offline=process.argv.includes('--fixture');
process.env.DX_DSH_CONTEXT_FILE=path.join(output,'context.json'); const fixture=offline?await mkdtemp(path.join(output,'run-')):output;
if(offline)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(fixture,'home');
process.env.DX_DSH_CONTEXT_FILE=path.join(fixture,'context.json');
await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'different-current-task',revision:'other',status:'draft'})); await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'different-current-task',revision:'other',status:'draft'}));
const snapshot={task_id:'auto-failure-fixture',revision:'incident',status:'failed',issue_code:'worker_error', const snapshot={task_id:'auto-failure-fixture',revision:'incident',status:'failed',issue_code:'worker_error',
issue:'受控诊断验收:执行前 worker 失败,没有工程写入。',rules_count:1,progress:{failed_items:1,total:1,completed:0}}; issue:'受控诊断验收:执行前 worker 失败,没有工程写入。',rules_count:1,progress:{failed_items:1,total:1,completed:0}};
@@ -31,6 +37,27 @@ process.stdout.write=function(chunk,...args){
}; };
let timer; let timer;
try{ try{
if(offline){
const require=createRequire(new URL('../integration/dsh/start.mjs',import.meta.url));
const {LlmAdapter}=await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-llm')).href);
let snapshotRequested=false;
class DiagnosticFixture extends LlmAdapter{
providerInfo(provider){return {id:provider,name:'Auto runtime fixture'};}
async listModels(provider){return [{provider,id:'fixture',name:'Fixture'}];}
async *stream(options){
const readSnapshot=options.purpose!=='session-title'&&!snapshotRequested;
if(readSnapshot)snapshotRequested=true;
const block=readSnapshot
?{type:'tool-call',id:crypto.randomUUID(),name:'dx_task_snapshot',arguments:'{}'}
:{type:'text',text:'Controlled diagnosis fixture. {"action":"none"}'};
yield {type:'block-start',index:0,blockType:block.type};
yield {type:'block-end',index:0,block};
yield {type:'finish',reason:{kind:readSnapshot?'tool-calls':'stop'}};
}
}
ctx.llm.registerAdapter(['auto-runtime-fixture'],new DiagnosticFixture());
await ctx.agentDefaultModel.saveSelection({provider:'auto-runtime-fixture',model:'fixture'});
}
timer=setTimeout(()=>rejectResult(Error('native_auto_test_timeout')),135000); timer=setTimeout(()=>rejectResult(Error('native_auto_test_timeout')),135000);
ctx.emit('dx/diagnose-request',{request_id:'cli-auto-request',incident_id:'0123456789abcdef01234567', ctx.emit('dx/diagnose-request',{request_id:'cli-auto-request',incident_id:'0123456789abcdef01234567',
phase:'diagnose',snapshot,evidence:JSON.stringify(snapshot)}); phase:'diagnose',snapshot,evidence:JSON.stringify(snapshot)});
@@ -38,7 +65,7 @@ try{
const previousParent=process.env.DX_DSH_PARENT_PIPE; const previousParent=process.env.DX_DSH_PARENT_PIPE;
process.env.DX_DSH_PARENT_PIPE='1'; process.env.DX_DSH_PARENT_PIPE='1';
try{ try{
const denial=await ctx.tools.execute({callId:'automatic-creation-denial',name:'dx_task_create', const denial=await executeTool(ctx, {callId:'automatic-creation-denial',name:'dx_task_create',
arguments:{name:'Must never open a dialog'},agent:ctx.agents.get(sessionId),signal:AbortSignal.timeout(1500)}); arguments:{name:'Must never open a dialog'},agent:ctx.agents.get(sessionId),signal:AbortSignal.timeout(1500)});
assert.equal(denial.isError,true); assert.equal(denial.isError,true);
assert.equal(creationBodyRan,false,'Automatic incident must be denied before desktop request emission'); assert.equal(creationBodyRan,false,'Automatic incident must be denied before desktop request emission');
@@ -48,7 +75,7 @@ try{
['dx_task_execute',{operation:'start',task_ids:['auto-failure-fixture']}], ['dx_task_execute',{operation:'start',task_ids:['auto-failure-fixture']}],
['dx_task_operations',{operation:'history'}], ['dx_task_operations',{operation:'history'}],
]){ ]){
const result=await ctx.tools.execute({callId:'automatic-denial-'+name,name,arguments:args, const result=await executeTool(ctx, {callId:'automatic-denial-'+name,name,arguments:args,
agent:ctx.agents.get(sessionId),signal:AbortSignal.timeout(1500)}); agent:ctx.agents.get(sessionId),signal:AbortSignal.timeout(1500)});
assert.equal(result.isError,true); assert.equal(result.isError,true);
assert.equal(creationBodyRan,false); assert.equal(creationBodyRan,false);
@@ -65,7 +92,7 @@ try{
assert.ok(!text.includes('different-current-task')); assert.ok(!text.includes('different-current-task'));
const report={status:'passed',session_id:value.session_id,reply:value.reply, const report={status:'passed',session_id:value.session_id,reply:value.reply,
incidentBoundSnapshot:true,automaticTaskCreationDenied:true,toolResults:tools}; incidentBoundSnapshot:true,automaticTaskCreationDenied:true,toolResults:tools};
await writeFile(path.join(output,'report.json'),JSON.stringify(report,null,2)); await writeFile(path.join(fixture,'report.json'),JSON.stringify(report,null,2));
original(JSON.stringify(report)+'\n'); original(JSON.stringify(report)+'\n');
}finally{ }finally{
clearTimeout(timer); clearTimeout(timer);
+2 -1
View File
@@ -1,4 +1,5 @@
/** Exercise actual Harness file tools against owned folders and ZIP archives. */ /** Exercise actual Harness file tools against owned folders and ZIP archives. */
import {executeTool} from './dsh_tool_probe.mjs';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import {mkdir,mkdtemp,writeFile,readFile,readdir} from 'node:fs/promises'; import {mkdir,mkdtemp,writeFile,readFile,readdir} from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
@@ -24,7 +25,7 @@ try{
const names=ctx.tools.schemas(agent).map(x=>x.name); const names=ctx.tools.schemas(agent).map(x=>x.name);
for(const name of ['read','read_image','write','edit','glob','grep','working_directory','extract_zip']) for(const name of ['read','read_image','write','edit','glob','grep','working_directory','extract_zip'])
assert.ok(names.includes(name),'Missing file capability: '+name); assert.ok(names.includes(name),'Missing file capability: '+name);
const call=async(name,args)=>ctx.tools.execute({name,arguments:args,callId:crypto.randomUUID(),agent,signal:AbortSignal.timeout(20000)}); const call=async(name,args)=>executeTool(ctx, {name,arguments:args,callId:crypto.randomUUID(),agent,signal:AbortSignal.timeout(20000)});
const ok=async(name,args)=>{ const ok=async(name,args)=>{
const result=await call(name,args);assert.equal(result.isError,false,name+': '+JSON.stringify(result));return result; const result=await call(name,args);assert.equal(result.isError,false,name+': '+JSON.stringify(result));return result;
}; };
+2 -1
View File
@@ -1,4 +1,5 @@
/** Real Harness, two processes: automatic diagnosis must stay isolated after restart. */ /** Real Harness, two processes: automatic diagnosis must stay isolated after restart. */
import {executeTool} from './dsh_tool_probe.mjs';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import {mkdir,mkdtemp,writeFile,readFile,unlink,symlink} from 'node:fs/promises'; import {mkdir,mkdtemp,writeFile,readFile,unlink,symlink} from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
@@ -96,7 +97,7 @@ if(!phase){
const resumed=await ctx.sessionController.resolveAgent(sessionId); const resumed=await ctx.sessionController.resolveAgent(sessionId);
assert.ok(resumed.agent,JSON.stringify(resumed.error)); assert.ok(resumed.agent,JSON.stringify(resumed.error));
const agent=resumed.agent; const agent=resumed.agent;
const call=(owner,name,args={})=>ctx.tools.execute({name,arguments:args,callId:crypto.randomUUID(),agent:owner,signal:AbortSignal.timeout(5000)}); const call=(owner,name,args={})=>executeTool(ctx, {name,arguments:args,callId:crypto.randomUUID(),agent:owner,signal:AbortSignal.timeout(5000)});
const snapshot=await call(agent,'dx_task_snapshot'); const snapshot=await call(agent,'dx_task_snapshot');
assert.equal(snapshot.isError,false,JSON.stringify(snapshot)); assert.equal(snapshot.isError,false,JSON.stringify(snapshot));
assert.equal(snapshot.value.task_id,'incident-original','historical diagnosis must not read the current task'); assert.equal(snapshot.value.task_id,'incident-original','historical diagnosis must not read the current task');
+5 -4
View File
@@ -12,8 +12,9 @@ export async function verifyModelSettings(c, output) {
}); });
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const endpoint=`http://127.0.0.1:${server.address().port}/v1`; 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 rendered=`e.getBoundingClientRect().width>0&&!e.closest('details:not([open])')`;
const button=text=>`[...document.querySelectorAll('button')].find(e=>e.getBoundingClientRect().width>0&&e.textContent.trim()===${JSON.stringify(text)})`; const visible=selector=>`[...document.querySelectorAll(${JSON.stringify(selector)})].find(e=>${rendered})`;
const button=text=>`[...document.querySelectorAll('button')].find(e=>${rendered}&&e.textContent.trim()===${JSON.stringify(text)})`;
async function wait(expression){ async function wait(expression){
const end=Date.now()+20000; const end=Date.now()+20000;
while(Date.now()<end){if(await c.evaluate(expression))return;await new Promise(r=>setTimeout(r,100));} while(Date.now()<end){if(await c.evaluate(expression))return;await new Promise(r=>setTimeout(r,100));}
@@ -49,7 +50,7 @@ export async function verifyModelSettings(c, output) {
const candidate=`[...document.querySelectorAll('[role="dialog"] label')].find(e=>e.textContent.includes('issue16-fixture-model'))?.querySelector('input[type="checkbox"]')`; 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); if(!await c.evaluate(`(${candidate})?.checked`))await c.click(candidate);
assert.equal(await c.evaluate(`(${candidate})?.checked`),true); assert.equal(await c.evaluate(`(${candidate})?.checked`),true);
await c.click(button('添加所选')); await c.click(button('更新列表'));
await wait(`!![...document.querySelectorAll('input')].find(x=>x.value==='issue16-fixture-model')`); await wait(`!![...document.querySelectorAll('input')].find(x=>x.value==='issue16-fixture-model')`);
await c.screenshot(path.join(output,'custom-model-discovery.png')); await c.screenshot(path.join(output,'custom-model-discovery.png'));
await c.click(button('创建提供商')); await c.click(button('创建提供商'));
@@ -58,7 +59,7 @@ export async function verifyModelSettings(c, output) {
// Reopen the real editor to read committed fields, not the submitted draft. // 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 c.click(`[...document.querySelectorAll('li')].find(e=>e.textContent.includes('issue16-fixture'))?.querySelector('button')`);
await wait(`document.body.innerText.includes('自定义设置')`); await wait(`document.body.innerText.includes('自定义设置')`);
await c.click(`[...document.querySelectorAll('summary')].find(e=>e.textContent.includes('自定义设置'))`); await c.click(`[...document.querySelectorAll('summary')].find(e=>e.textContent.includes('自定义设置')&&e.closest('details').querySelector('input[aria-label="API 地址"]')?.value===${JSON.stringify(endpoint)})`);
await wait(`!![...document.querySelectorAll('input')].find(x=>x.value==='issue16-fixture-model')`); await wait(`!![...document.querySelectorAll('input')].find(x=>x.value==='issue16-fixture-model')`);
await c.screenshot(path.join(output,'custom-model-persisted.png')); await c.screenshot(path.join(output,'custom-model-persisted.png'));
return {status:'passed',provider:'issue16-fixture',model:'issue16-fixture-model',requests, return {status:'passed',provider:'issue16-fixture',model:'issue16-fixture-model',requests,
+2 -1
View File
@@ -1,4 +1,5 @@
/** Compare the embedded assistant with the installed official Standard preset. */ /** Compare the embedded assistant with the installed official Standard preset. */
import {executeTool} from './dsh_tool_probe.mjs';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import {mkdir,mkdtemp,writeFile,readFile} from 'node:fs/promises'; import {mkdir,mkdtemp,writeFile,readFile} from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
@@ -29,7 +30,7 @@ try{
assert.deepEqual(names(embedded),names(native),'Existing dx-task sessions must retain the full native tool catalog'); assert.deepEqual(names(embedded),names(native),'Existing dx-task sessions must retain the full native tool catalog');
for(const tool of ['read','write','edit','pwsh','get_goal','create_goal','update_goal','todo_write','subagent']) for(const tool of ['read','write','edit','pwsh','get_goal','create_goal','update_goal','todo_write','subagent'])
assert.ok(names(embedded).includes(tool),'Missing native capability: '+tool); assert.ok(names(embedded).includes(tool),'Missing native capability: '+tool);
const call=(name,args)=>ctx.tools.execute({name,arguments:args,callId:crypto.randomUUID(),agent:embedded,signal:AbortSignal.timeout(20000)}); const call=(name,args)=>executeTool(ctx, {name,arguments:args,callId:crypto.randomUUID(),agent:embedded,signal:AbortSignal.timeout(20000)});
const filename=path.join(process.env.DX_DSH_WORKSPACE,'native-write.txt'); const filename=path.join(process.env.DX_DSH_WORKSPACE,'native-write.txt');
const written=await call('write',{file_path:filename,content:'native file operations'}); const written=await call('write',{file_path:filename,content:'native file operations'});
assert.equal(written.isError,false,JSON.stringify(written)); assert.equal(written.isError,false,JSON.stringify(written));
+14 -8
View File
@@ -1,20 +1,26 @@
/** Exercise the real official runtime and policy pipeline without CAD or a model. */ /** Exercise the real official runtime and policy pipeline without CAD or a model. */
import {executeTool} from './dsh_tool_probe.mjs';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import {mkdir,writeFile} from 'node:fs/promises'; import {mkdir,writeFile} from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
import {fileURLToPath,pathToFileURL} from 'node:url'; import {fileURLToPath,pathToFileURL} from 'node:url';
import {createRequire} from 'node:module'; import {createRequire} from 'node:module';
import {bootRuntime,TASK_TOOLS} from '../integration/dsh/start.mjs';
const repo=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); const repo=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
const output=path.join(repo,'build/dsh-native-cli-verification'); const runtime=path.resolve(process.argv[2]??path.join(repo,'integration/dsh'));
const {bootRuntime,TASK_TOOLS,VERSION}=await import(pathToFileURL(path.join(runtime,'start.mjs')).href);
const output=path.resolve(process.argv[3]??path.join(repo,'build/dsh-native-cli-verification'));
await mkdir(output,{recursive:true}); await mkdir(output,{recursive:true});
delete process.env.DX_DSH_PARENT_PIPE;
if(process.argv[2]){
for(const key of ['DSH_API_KEY','DSH_API_BASE','DSH_MODEL','DX_DSH_MODELS','DSH_PERMISSION_MODE'])delete process.env[key];
}
process.env.DX_DSH_HOME=path.join(output,'home'); process.env.DX_DSH_HOME=path.join(output,'home');
process.env.DX_DSH_CONTEXT_FILE=path.join(output,'context.json'); process.env.DX_DSH_CONTEXT_FILE=path.join(output,'context.json');
await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'cli-verification',status:'paused', await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'cli-verification',status:'paused',
revision:'cli-revision',rules_count:2,progress:{},issue:'',issue_code:'',events:[]})); revision:'cli-revision',rules_count:2,progress:{},issue:'',issue_code:'',events:[]}));
const {ctx,shutdown}=await bootRuntime({announce:false}); const {ctx,shutdown}=await bootRuntime({announce:false});
const report={}; const report={version:VERSION};
try { try {
const schemas=ctx.tools.schemas(); const schemas=ctx.tools.schemas();
report.tools=schemas.map(x=>x.name); report.tools=schemas.map(x=>x.name);
@@ -26,10 +32,10 @@ try {
report.configuredModels=(await ctx.llm.listModels('dx')).map(model=>model.id); report.configuredModels=(await ctx.llm.listModels('dx')).map(model=>model.id);
assert.ok(report.configuredModels.includes(process.env.DSH_MODEL)); assert.ok(report.configuredModels.includes(process.env.DSH_MODEL));
} }
const snapshot=await ctx.tools.execute({callId:'verify-read',name:'dx_task_snapshot',arguments:{},signal:new AbortController().signal}); const snapshot=await executeTool(ctx, {callId:'verify-read',name:'dx_task_snapshot',arguments:{},signal:new AbortController().signal});
assert.equal(snapshot.isError,false,JSON.stringify(snapshot)); assert.equal(snapshot.isError,false,JSON.stringify(snapshot));
report.snapshotRead=true; report.snapshotRead=true;
const desktopOnly=await ctx.tools.execute({callId:'verify-desktop-only',name:'dx_task_create',arguments:{name:'CLI must not mutate'},signal:new AbortController().signal}); const desktopOnly=await executeTool(ctx, {callId:'verify-desktop-only',name:'dx_task_create',arguments:{name:'CLI must not mutate'},signal:new AbortController().signal});
assert.equal(desktopOnly.isError,true); assert.equal(desktopOnly.isError,true);
report.creationRequiresDesktopConfirmation=true; report.creationRequiresDesktopConfirmation=true;
for(const [name,args] of [ for(const [name,args] of [
@@ -38,16 +44,16 @@ try {
['dx_task_execute',{operation:'start',task_ids:['fixture']}], ['dx_task_execute',{operation:'start',task_ids:['fixture']}],
['dx_task_operations',{operation:'history'}], ['dx_task_operations',{operation:'history'}],
]){ ]){
const result=await ctx.tools.execute({callId:'desktop-only-'+name,name,arguments:args,signal:AbortSignal.timeout(2000)}); const result=await executeTool(ctx, {callId:'desktop-only-'+name,name,arguments:args,signal:AbortSignal.timeout(2000)});
assert.equal(result.isError,true,name+' requires parent desktop'); assert.equal(result.isError,true,name+' requires parent desktop');
} }
report.lifecycleRequiresDesktop=true; report.lifecycleRequiresDesktop=true;
const require=createRequire(path.join(repo,'integration/dsh/package.json')); const require=createRequire(path.join(runtime,'package.json'));
const {defineTool}=await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-tools')).href); const {defineTool}=await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-tools')).href);
let bodyRan=false; let bodyRan=false;
const release=ctx.tools.register(defineTool({name:'forbidden_probe',description:'Never executes',parameters:{}, const release=ctx.tools.register(defineTool({name:'forbidden_probe',description:'Never executes',parameters:{},
output:{schema:{type:'boolean'},render:()=>[{type:'text',text:'probe'}]},execute:async()=>{bodyRan=true;return true;}})); output:{schema:{type:'boolean'},render:()=>[{type:'text',text:'probe'}]},execute:async()=>{bodyRan=true;return true;}}));
const extension=await ctx.tools.execute({callId:'verify-extension',name:'forbidden_probe',arguments:{},signal:new AbortController().signal}); const extension=await executeTool(ctx, {callId:'verify-extension',name:'forbidden_probe',arguments:{},signal:new AbortController().signal});
release(); release();
assert.equal(extension.isError,false); assert.equal(extension.isError,false);
assert.equal(bodyRan,true); assert.equal(bodyRan,true);
+2 -1
View File
@@ -1,4 +1,5 @@
/** PR18 #197: no silently omitted names, bounded workers, real cancellation. */ /** PR18 #197: no silently omitted names, bounded workers, real cancellation. */
import {executeTool} from './dsh_tool_probe.mjs';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import {mkdir,mkdtemp,writeFile,readdir,readFile} from 'node:fs/promises'; import {mkdir,mkdtemp,writeFile,readdir,readFile} from 'node:fs/promises';
import {spawnSync} from 'node:child_process'; import {spawnSync} from 'node:child_process';
@@ -25,7 +26,7 @@ process.env.DX_DSH_HOME=path.join(root,'home');process.env.DX_DSH_CONTEXT_FILE=p
await writeFile(process.env.DX_DSH_CONTEXT_FILE,'{"task_id":"zip-review","revision":"zip-review","status":"observe"}'); await writeFile(process.env.DX_DSH_CONTEXT_FILE,'{"task_id":"zip-review","revision":"zip-review","status":"observe"}');
const {ctx,shutdown}=await bootRuntime({announce:false}); const {ctx,shutdown}=await bootRuntime({announce:false});
try{ try{
const call=(file,signal=AbortSignal.timeout(30000))=>ctx.tools.execute({name:'extract_zip', const call=(file,signal=AbortSignal.timeout(30000))=>executeTool(ctx, {name:'extract_zip',
arguments:{file_path:path.join(root,file),output_directory:root},callId:crypto.randomUUID(),signal}); arguments:{file_path:path.join(root,file),output_directory:root},callId:crypto.randomUUID(),signal});
const before=await readdir(root); const before=await readdir(root);
for(const file of ['proto.zip','proto-bad.zip']){ for(const file of ['proto.zip','proto-bad.zip']){