Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ef40a2e61 |
No files matched your search
@@ -1,37 +0,0 @@
|
||||
# Issue 33 D2 · 工程路径错误提示验收
|
||||
|
||||
工程读取和任务创建的路径检查直接调用 `lstat()`。目录不存在或扫描后工程移走时,文件系统异常进入统一兜底,现场报告仅能看到“发生未处理异常”。目录存在且能读取属性时,`scandir()` 仍可能因缺少列目录权限失败。
|
||||
|
||||
修复在路径检查和读取处分类处理这些预期错误。读取对话框和创建任务的错误提示均显示完整路径、分类代码、处理建议和可关联日志的 `DXT` 编号。预期错误写入一条应用日志。未知异常保留 traceback。
|
||||
|
||||
## Windows 11 实测
|
||||
|
||||
使用 Qt 按钮启动读取、真实文件系统与任务库。第五例在成功扫描两个候选工程后重命名其中一个文件,从实际服务入口创建选定任务并检查主窗口所用的错误格式和任务数据库。
|
||||
|
||||
| 输入 | 基线 `46deb9c` | 修复后代码 | 修复后错误编号 |
|
||||
| --- | --- | --- | --- |
|
||||
| 不存在的目录 | 通用兜底 | `path_missing` | `DXT-20261125-3EE8F667` |
|
||||
| 普通文件作为目录 | 英文非目录文案 | `path_not_directory` | `DXT-20261125-92876D74` |
|
||||
| 路径中途遇到普通文件 | 通用兜底 | `path_not_directory` | `DXT-20261125-0C615FE8` |
|
||||
| ACL 拒绝列目录 | 通用兜底 | `path_denied` | `DXT-20261125-ED64EEA9` |
|
||||
| 工程在扫描后被移走 | 通用兜底 | `path_missing` | `DXT-20261125-CA48D2FF` |
|
||||
|
||||
ACL 测试对临时目录中的当前用户拒绝 `FILE_LIST_DIRECTORY`,两个版本的文件系统操作均触发原生 `WinError 5`。创建任务失败后库中仍有 0 条任务。五个路径输入的通用兜底率从 4/5 降到 0/5。额外注入的 `RuntimeError` 对照组仍触发一次 `unhandled_exception`,并保留 traceback。
|
||||
|
||||
## 复跑
|
||||
|
||||
在仓库根目录运行。使用未占用的临时目录保存测试日志。
|
||||
|
||||
```powershell
|
||||
$env:PYTHONUTF8 = '1'
|
||||
python -m pytest -q -s tests/v1_1/test_project_path_errors.py tests/v1_1/test_scan_responsiveness.py tests/v1_1/test_project_long_paths.py tests/v1_1/test_path_access.py tests/trial_task_center/test_logging_setup.py --basetemp build/issue33-d2
|
||||
```
|
||||
|
||||
实测 35 项通过。以下命令按错误记录统计扫描和创建任务的通用兜底率。路径用例与故障对照分别统计时,从相应测试目录读取日志。
|
||||
|
||||
```powershell
|
||||
$rows = Get-ChildItem build/issue33-d2 -Recurse -Filter application.log |
|
||||
Select-String 'error_id=\S+ operation=(scan_project_directory|create_project_tasks) (code=\S+ )?message='
|
||||
$generic = $rows | Where-Object { $_.Line -match 'code=unhandled_exception |message=发生未处理异常$' }
|
||||
'{0}/{1}' -f @($generic).Count, @($rows).Count
|
||||
```
|
||||
@@ -1,26 +0,0 @@
|
||||
# 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 @@
|
||||
# 工单 #33 根因分析与 1.3.3 本地预验收
|
||||
|
||||
现场基线为 Windows 便携版 1.3.2,修复基线为 main 的 46deb9c。原始交付包 SHA-256 为 `1ac99eac3cf79bbf1f011d1d5fe833e92b98fba2c01546b3cfaf55a90b82d5b3`,本地逐项复核包内清单的 4,469 个文件全部一致。[工单与附件](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/issues/33)
|
||||
|
||||
## 原始记录还原
|
||||
|
||||
1. 在 `05_实测证据/data_full132/task-queues/55e1032ac965453b8adf307da1400511.json` 中,100 项分为 6 completed、3 skipped、2 blocked、89 pending。任务列表中的 92 draft 包含了队列已跳过的三项。09:30:17 的监控显示第 11 项 BOB_Shield 在做替换前快照,09:32:18 显示资源待清理。
|
||||
2. 首批在第 10 项 BOB 的第 23 个操作和第 11 项 BOB_Shield 的第 18 个操作加载 `4885-S033D0-M220` 超时,各自的 native.json 均标记 preflight。第 10 项已写入 isolated_tasks,并实际派发了第 11 项。第 11 项仅写入 blocked。不能把整批归因于“遇到第一个失败就停”。另一个 91 项检查点记录了 WiFi 工程加载 `4885-S018D0-M220` 超时。工具报告的空窗口与这个超时属于不同 generation,尚不能认定窗口引起该次超时。
|
||||
3. 首批资源目录 `1d5d999ec63045b49661466928de9a01` 的 business-result.json 报 paused=true,current_task_id 对应 BOB_Shield。supervisor.json 的 finished 描述监督器退出。session.json 的最终状态是 isolated、blocking=false、mentor_released=true、desktop_released=false。任务隔离、队列暂停、监督器退出、资源是否可再租用分别有自己的证据。后续批次另有 blocking=true 的记录。现场没有足够证据指认持有桌面句柄的外部进程。
|
||||
|
||||
## 单项修复和判据
|
||||
|
||||
| 项 | 已定位的入口或失效条件 | 修改与本地复验 |
|
||||
|---|---|---|
|
||||
| D2 路径错误 | 工程根校验和扫描后登记有不同失败窗口,文件系统异常落到通用错误提示 | 分别注入目录不存在、选择了普通文件、扫描后移走、访问被拒;检查 GUI 中路径、码、修复建议,日志按同类输入统计兜底数并保留真正未知异常的诊断 |
|
||||
| D1 同根双开 | 单工程和队列执行锁在主窗口启动后才生效,两个 GUI 可先打开同一数据库并启动恢复 | 在首次打开数据库之前取得 data-root 级互斥;4 个进程同时打开同根,再试异根、helper 和持有者异常退出,检查持有者 PID、唤醒回执、应用启动次数以及原任务 ID |
|
||||
| D6 原生加载 | 需区分本次加载尚未点击写入与前序位号已暂存。当前预读不能证明整个工程仍无修改;列表控件刷新也可能令旧 HWND 失效 | 使用工程副本分别注入首次/热加载、列表重建、超时前已写/未写、不同 owner 的空弹窗。记录 attempt/generation、写前标记、前后属性、关闭与保存回执。仅在本项未写且身份可证时有限重试;写入可能性跨重启必须保留 |
|
||||
| D7 资源收尾 | 一条历史隔离回执已经可以不拦下一批;同名桌面、租约归还及对象物理消失有不同寿命 | 对照正常关闭、带窗口的自有 writer、仅有外部 OpenDesktop 句柄、证据缺失四组。按 PID 和创建时间确认自有进程退出、关闭自有句柄、重新枚举,再以有界退避重查。外部持有期间不得记 released;外部释放后应自动收敛。记录旧租约与新租约,禁止旧代清理新 owner |
|
||||
| D8 整批停顿 | 第一个不确定工程已被隔离,第二个未获得同等隔离结果;队列持久化暂停后,资源提示变成可用也未推进原队列 | 基于已验收的 D7 结果复验两次连续失败,区分同写源与无关工程、主动暂停与故障等待。只恢复原队列、原计划、未派发项;活 writer、未知归属或同写源仍隔离。比对操作 ID、保存次数、所有任务终态和 UI 文案 |
|
||||
| D5 BOM 列 | 表头映射只读取已知列;“失败 0 行”无法告知额外列未采用 | 实际导入现场 B3 工作簿,再导入带两列、近义列、缺列、重复列、公式和标准模板。额外列一次列出并提示近义列,核对预览、保存结果和持久化规则 |
|
||||
| D3 窗口 | ui-layout.ini 保存分栏和排序,主窗口仍用默认尺寸 | 从真实主窗口调整大小、位置和最大化后退出重启,测 125% 缩放与失去屏幕后的可见区域;损坏 ini 应可启动 |
|
||||
| D4 零结果 | TaskList._render 只更新列表和数值,缺少对空列表原因的呈现 | 用 Qt 键盘输入现场关键词 zzzz_no_match,切换筛选、组合搜索、回收站和空库,清除条件后验证原集合及选择;核对实际显示的关键词、筛选名与匹配数 |
|
||||
|
||||
## 分层复跑与交付口径
|
||||
|
||||
本机复跑以下两条基线命令,分别校验现场原件和生产调度器。第二条使用真实 SQLite、BOM 读取、任务队列及检查点,CAD 执行由夹具驱动。得到 99 completed、1 blocked、199 次操作,耗时 608.3 秒。这个单故障场景在修复前已能跑完,因此不能用它单独验收 D8。
|
||||
|
||||
```powershell
|
||||
python tools/inspect_issue33_field.py G:/dx33/acceptance/field.zip
|
||||
python tools/measure_task_queue.py --projects 100 --sheets 1 --rules 1 --behavior uncertain_stop --output build/issue33-baseline100
|
||||
```
|
||||
|
||||
- **本地预验收**使用独立 data-root 和工程副本。每项记录软件提交、输入、触发步骤、期望/实际结果、日志和可复跑命令。重启测试复用同一测试根。验证命令和结果随各单项 PR 提交。工单指定 D6、D7、D8 按序合入,不能用其他批次的通过报告替代当前批次。
|
||||
- **整批故障注入**先跑 8 项混合队列,再跑 100 工程固定顺序。对第 10、11 项连续注入现场两种失败,独立工程继续,另设一个共享 iCDB 的依赖工程以验证隔离。第 23 个位号前后分别中断,复用同一 queue_id 两次重启,逐项比较 saved 的操作 ID 与次数。未知写入不能计入成功。
|
||||
- **现场复测**用发行候选包与六套固定试卷逐题执行。卷六的暂停、重启、不重放和下一批启动优先。验收要求卷四、六各至少 80 分,总分至少 500/600,六卷无 P0 复发。正常批次检查 uncertain.flag=0,收尾核对桌面枚举与活进程。如仅运行夹具或源码,报告应标明该范围并单列真实 Mentor、现场库、物理副屏等待测项。
|
||||
- 本地采集目录为 `G:/dx33/acceptance`。现场 ZIP 留存原样,复验使用副本。原始打分仍是 373/600;菜单驱动、多选自动化和模型端点限流单列,分数只随实际复跑更新。
|
||||
@@ -1,17 +0,0 @@
|
||||
# Issue #33 D1 同数据目录单实例
|
||||
|
||||
`application.main` 原先直接配置日志、打开 `task-center.db` 并执行启动恢复。现场 `data_lock` 日志有两次同根 `application_start`,两实例均成功读取任务列表。现有执行租约只在执行操作中生效。
|
||||
|
||||
GUI 现在先取得 `.gui-instance.lock` 的内核文件锁,再打开日志和数据库。第二次启动经 Qt 本地套接字请求激活现有窗口,该窗口写入 `instance_conflict` 并在状态栏提示。锁保持到 SQLite 和后台读线程关闭,进程强制结束时由操作系统回收。启动参数中的工作进程和 CLI 在 GUI 文件锁之前分流。
|
||||
|
||||
## Windows 复测
|
||||
|
||||
```powershell
|
||||
$env:QT_QPA_PLATFORM = 'offscreen'
|
||||
python -m pytest -q tests/v1_1/test_single_instance.py
|
||||
```
|
||||
|
||||
- 四个真实 GUI 子进程并发打开同一目录,其中两个使用大写路径。日志有一次 `application_start`、一次启动恢复和三次 `instance_conflict`,三个转发进程均返回 0。
|
||||
- 另一个数据目录的窗口与持锁窗口同时存活。同根 `--native-helper` 执行自身参数校验并返回 2,冲突计数仍为三次。
|
||||
- 强制结束持锁进程后,同根 `--smoke-test` 成功启动并正常关闭,预先写入的任务 ID 仍在 SQLite。另一数据目录的进程继续运行。
|
||||
- 修改前运行同一并发场景时,三个竞争进程没有退出,测试失败。测试使用 Qt offscreen,验证激活请求已处理。Windows 桌面前台切换和实际 CAD 写入需通过交互式验收复核。
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
[
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
||||
@@ -1,91 +0,0 @@
|
||||
{
|
||||
"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')"
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
[
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
||||
@@ -1123,8 +1123,7 @@ Sub QPDiscardFailedBatchProject(ByRef ErrorDescription)
|
||||
If (Not QP_BatchMode And Not QP_SessionMode) Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub
|
||||
HasStagedItems = False
|
||||
If IsObject(QP_SessionItems) Then HasStagedItems = (QP_SessionItems.Count > 0)
|
||||
If QP_NativeMutationPossible Or QP_NativeCallActive Or QP_RestoreTransactionOpen Or _
|
||||
QP_BatchSaveRequested Or QP_BatchSaveCommitted Or HasStagedItems Then
|
||||
If QP_NativeMutationPossible Or QP_BatchSaveRequested Or QP_BatchSaveCommitted Or HasStagedItems Then
|
||||
ErrorDescription = "write or save outcome requires reconciliation; owned project retained without automatic save or discard"
|
||||
Exit Sub
|
||||
End If
|
||||
@@ -1659,7 +1658,6 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
|
||||
End If
|
||||
CommandLine = CommandLine & " --native-helper --snapshot " & Chr(34) & SnapshotPath & Chr(34)
|
||||
Set Shell = CreateObject("WScript.Shell")
|
||||
QP_Stage = "native_replace"
|
||||
QP_NativeCallActive = True
|
||||
QPProgress "native_replace", 0, 1
|
||||
ExitCode = Shell.Run(CommandLine, 0, True)
|
||||
|
||||
@@ -9,13 +9,12 @@ import platform
|
||||
import sys
|
||||
from typing import Sequence
|
||||
|
||||
from PySide6.QtCore import QTimer, QThreadPool, Qt
|
||||
from PySide6.QtCore import QTimer, QThreadPool
|
||||
from PySide6.QtGui import QIcon
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.single_instance import InstanceUnavailable, gui_instance, listen_for_activation
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.version import VERSION
|
||||
|
||||
@@ -162,28 +161,10 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
from dx_productivity.trial_task_center.sceneos_cli import run
|
||||
|
||||
return run(data_root)
|
||||
try:
|
||||
with gui_instance(data_root) as endpoint:
|
||||
if endpoint is None:
|
||||
return 0
|
||||
return _run_gui(argv, arguments, data_root, endpoint)
|
||||
except (OSError, InstanceUnavailable) as error:
|
||||
message = f'无法打开 DxPartReplace。\n{data_root}\n{error}'
|
||||
if sys.stderr is not None:
|
||||
print(message, file=sys.stderr)
|
||||
if os.name == 'nt' and bool(getattr(sys, 'frozen', False)):
|
||||
import ctypes
|
||||
|
||||
ctypes.windll.user32.MessageBoxW(None, message, 'DxPartReplace', 0x30)
|
||||
return 1
|
||||
|
||||
|
||||
def _run_gui(argv, arguments, data_root, endpoint):
|
||||
logging_context = configure_logging(data_root)
|
||||
install_exception_hooks(logging_context)
|
||||
store: TaskStore | None = None
|
||||
window = None
|
||||
activation_server = None
|
||||
try:
|
||||
database_path = data_root / "task-center.db"
|
||||
_log_startup(logging_context, data_root, database_path)
|
||||
@@ -196,16 +177,6 @@ def _run_gui(argv, arguments, data_root, endpoint):
|
||||
configure_application_identity(qt_application)
|
||||
window = _load_window()(service)
|
||||
window.show()
|
||||
|
||||
def activate():
|
||||
logging_context.logger.info('instance_conflict data_root=%s', data_root)
|
||||
window.setWindowState(window.windowState() & ~Qt.WindowState.WindowMinimized)
|
||||
window.show()
|
||||
window.raise_()
|
||||
window.activateWindow()
|
||||
window.statusBar().showMessage('此数据目录已在使用,已切换到现有窗口。', 6000)
|
||||
|
||||
activation_server = listen_for_activation(endpoint, activate)
|
||||
if arguments.smoke_test:
|
||||
QTimer.singleShot(0, lambda: (window.close(), qt_application.quit()))
|
||||
exit_code = qt_application.exec()
|
||||
@@ -216,8 +187,6 @@ def _run_gui(argv, arguments, data_root, endpoint):
|
||||
logging_context.report_exception("startup", error)
|
||||
return 1
|
||||
finally:
|
||||
if activation_server is not None:
|
||||
activation_server.close()
|
||||
if store is not None:
|
||||
# The window invalidates queued UI results on close. Finish the
|
||||
# remaining read before releasing the shared SQLite connection.
|
||||
|
||||
@@ -27,7 +27,3 @@ class TaskCenterError(ValueError):
|
||||
def _new_error_id() -> str:
|
||||
date = datetime.now(timezone.utc).strftime("%Y%m%d")
|
||||
return f"DXT-{date}-{secrets.token_hex(4).upper()}"
|
||||
|
||||
|
||||
class ProjectPathError(TaskCenterError):
|
||||
"""An expected filesystem failure while reading or selecting projects."""
|
||||
@@ -17,7 +17,7 @@ import time
|
||||
import traceback
|
||||
from typing import Any, Mapping
|
||||
|
||||
from .errors import ProjectPathError, TaskCenterError
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import internal_path
|
||||
from .retention import rotate_text_log
|
||||
|
||||
@@ -62,18 +62,15 @@ class LoggingContext:
|
||||
reported = error
|
||||
else:
|
||||
reported = TaskCenterError("unhandled_exception", "发生未处理异常")
|
||||
message = reported.message
|
||||
if not isinstance(error, ProjectPathError):
|
||||
detail = "".join(
|
||||
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
|
||||
)
|
||||
message += "\n" + detail.rstrip()
|
||||
detail = "".join(
|
||||
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
|
||||
)
|
||||
self.logger.error(
|
||||
"error_id=%s operation=%s code=%s message=%s",
|
||||
"error_id=%s operation=%s message=%s\n%s",
|
||||
reported.error_id,
|
||||
operation,
|
||||
reported.code,
|
||||
message,
|
||||
reported.message,
|
||||
detail.rstrip(),
|
||||
)
|
||||
_flush_handlers(self.logger)
|
||||
return reported
|
||||
|
||||
@@ -292,8 +292,7 @@ def wait_for(callback, description, timeout=15):
|
||||
raise TimeoutError(description)
|
||||
|
||||
|
||||
def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_interval=0.15,
|
||||
scope=lambda: None):
|
||||
def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_interval=0.15):
|
||||
deadline = time.monotonic() + timeout
|
||||
previous = None
|
||||
stable_since = None
|
||||
@@ -310,7 +309,7 @@ def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_in
|
||||
previous = stable_since = None
|
||||
time.sleep(poll_interval)
|
||||
continue
|
||||
signature = (scope(), tuple(tuple(str(value) for value in columns) for _, columns in latest))
|
||||
signature = tuple(tuple(str(value) for value in columns) for _, columns in latest)
|
||||
now = time.monotonic()
|
||||
if signature != previous:
|
||||
previous = signature
|
||||
@@ -322,106 +321,6 @@ 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}")
|
||||
|
||||
|
||||
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):
|
||||
actual = str(displayed).casefold()
|
||||
expected = str(library_symbol).casefold()
|
||||
@@ -949,8 +848,8 @@ def run_native(snapshot, report):
|
||||
raise ValueError("Multiple replacement dialogs")
|
||||
return matches[0] if matches else None
|
||||
|
||||
def message(handle, code, wparam=0, lparam=0, *, timeout=15000):
|
||||
return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, timeout)
|
||||
def message(handle, code, wparam=0, lparam=0):
|
||||
return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, 15000)
|
||||
|
||||
def control_text(control):
|
||||
buffer = ctypes.create_unicode_buffer(2048)
|
||||
@@ -966,9 +865,9 @@ def run_native(snapshot, report):
|
||||
control = dlg_item(dialog, identifier)
|
||||
if not control:
|
||||
raise ValueError(f"Required native option {identifier} is unavailable")
|
||||
if message(control, 0x00F0)[1] != 1:
|
||||
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1:
|
||||
click(control)
|
||||
if message(control, 0x00F0)[1] != 1:
|
||||
if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1:
|
||||
raise ValueError(f"Native option {identifier} was not enabled")
|
||||
report.setdefault("native_options", {})[str(identifier)] = {
|
||||
"text": control_text(control),
|
||||
@@ -997,68 +896,31 @@ def run_native(snapshot, report):
|
||||
"main_visible_before_browse": bool(win32gui.IsWindowVisible(main_handle)),
|
||||
"browse_button": int(dlg_item(dialog, 1366)),
|
||||
}
|
||||
click(dlg_item(dialog, 1366))
|
||||
|
||||
def query_message(handle, code, wparam=0, lparam=0):
|
||||
try:
|
||||
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 = {}, {}
|
||||
def part_list():
|
||||
report["databook"]["main_visible_during_wait"] = bool(
|
||||
win32gui.IsWindowVisible(main_handle)
|
||||
)
|
||||
for handle in owned_windows(include_hidden=True):
|
||||
try:
|
||||
kind = (win32gui.GetClassName(handle), win32gui.GetDlgCtrlID(handle))
|
||||
if kind == ('SysListView32', 4000):
|
||||
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)
|
||||
if win32gui.GetClassName(handle) == "SysListView32" and win32gui.GetDlgCtrlID(handle) == 4000:
|
||||
return handle
|
||||
return None
|
||||
list_handle = wait_for(part_list, "Native DxDataBook part list did not open", timeout=30)
|
||||
report["databook"].update(
|
||||
list_handle=int(list_handle),
|
||||
list_visible=bool(win32gui.IsWindowVisible(list_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])
|
||||
report["library_row"] = columns
|
||||
symbol_parts = columns[2].split(":", 1)
|
||||
@@ -1068,9 +930,6 @@ def run_native(snapshot, report):
|
||||
report["slot_count"] = slot_count
|
||||
if slot_count < 1:
|
||||
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()
|
||||
list_rectangle = win32gui.GetWindowRect(list_handle)
|
||||
if rectangle.height() <= 0 or rectangle.top < list_rectangle[1] or rectangle.bottom > list_rectangle[3]:
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from threading import Event
|
||||
|
||||
import os
|
||||
@@ -11,44 +10,20 @@ from pathlib import Path
|
||||
import stat
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import ProjectPathError, TaskCenterError
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import canonical_path, internal_path, strip_extended_prefix
|
||||
from .models import TaskRecord, TaskStatus
|
||||
from .scanner import _is_schematic_project, _reject_reparse
|
||||
from .store import TaskStore
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _path_errors(path: Path):
|
||||
try:
|
||||
yield
|
||||
except FileNotFoundError as error:
|
||||
raise ProjectPathError(
|
||||
"path_missing", f"找不到路径「{path}」。请确认目录或工程是否已移动或删除,然后重新选择并读取。"
|
||||
) from error
|
||||
except PermissionError as error:
|
||||
raise ProjectPathError(
|
||||
"path_denied", f"无法读取路径「{path}」。请检查当前用户的读取权限,然后重试。"
|
||||
) from error
|
||||
except NotADirectoryError as error:
|
||||
raise _not_directory(path) from error
|
||||
|
||||
|
||||
def _not_directory(path: Path) -> ProjectPathError:
|
||||
return ProjectPathError(
|
||||
"path_not_directory", f"路径「{path}」中有一项不是目录。请选择工程目录后重试。"
|
||||
)
|
||||
|
||||
|
||||
def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]:
|
||||
root = Path(os.path.abspath(strip_extended_prefix(root)))
|
||||
with _path_errors(root):
|
||||
for ancestor in (*reversed(root.parents), root):
|
||||
details = internal_path(ancestor).lstat()
|
||||
_reject_reparse(details, ancestor)
|
||||
if not stat.S_ISDIR(details.st_mode):
|
||||
raise _not_directory(root)
|
||||
root = canonical_path(root, strict=True)
|
||||
for ancestor in (*reversed(root.parents), root):
|
||||
_reject_reparse(internal_path(ancestor).lstat(), ancestor)
|
||||
root = canonical_path(root, strict=True)
|
||||
if not internal_path(root).is_dir():
|
||||
raise TaskCenterError("discovery_root", "project root is not a directory")
|
||||
excluded = tuple(canonical_path(path) for path in excluded_roots)
|
||||
if any(root.is_relative_to(blocked) for blocked in excluded):
|
||||
raise TaskCenterError("discovery_root", "project root is inside an excluded directory")
|
||||
@@ -75,13 +50,12 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
|
||||
while pending:
|
||||
check_cancelled()
|
||||
directory = pending.pop()
|
||||
_reject_reparse(internal_path(directory).lstat(), directory)
|
||||
children = []
|
||||
with _path_errors(directory):
|
||||
_reject_reparse(internal_path(directory).lstat(), directory)
|
||||
with os.scandir(internal_path(directory)) as entries:
|
||||
for entry in entries:
|
||||
check_cancelled()
|
||||
children.append(entry)
|
||||
with os.scandir(internal_path(directory)) as entries:
|
||||
for entry in entries:
|
||||
check_cancelled()
|
||||
children.append(entry)
|
||||
projects: list[Path] = []
|
||||
folders: list[Path] = []
|
||||
for entry in sorted(children, key=lambda item: item.name.casefold()):
|
||||
@@ -89,13 +63,12 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
|
||||
path = Path(strip_extended_prefix(entry.path))
|
||||
if any(path.is_relative_to(blocked) for blocked in excluded):
|
||||
continue
|
||||
with _path_errors(path):
|
||||
details = entry.stat(follow_symlinks=False)
|
||||
_reject_reparse(details, path)
|
||||
if stat.S_ISDIR(details.st_mode):
|
||||
folders.append(path)
|
||||
elif stat.S_ISREG(details.st_mode) and path.suffix.casefold() == ".prj" and _is_schematic_project(path):
|
||||
projects.append(canonical_path(path, strict=True))
|
||||
details = entry.stat(follow_symlinks=False)
|
||||
_reject_reparse(details, path)
|
||||
if stat.S_ISDIR(details.st_mode):
|
||||
folders.append(path)
|
||||
elif stat.S_ISREG(details.st_mode) and path.suffix.casefold() == ".prj" and _is_schematic_project(path):
|
||||
projects.append(canonical_path(path, strict=True))
|
||||
found.extend(projects)
|
||||
visited += 1
|
||||
if on_progress is not None:
|
||||
@@ -111,41 +84,35 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
|
||||
ancestor_projects: dict[Path, bool] = {}
|
||||
for candidate in selected_paths:
|
||||
path = Path(os.path.abspath(strip_extended_prefix(candidate)))
|
||||
if path == root or not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
|
||||
if not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
|
||||
raise TaskCenterError("project_selection", "selected project is outside discovery results")
|
||||
relative = path.relative_to(root)
|
||||
cursor = root
|
||||
with _path_errors(path):
|
||||
for part in relative.parts:
|
||||
cursor /= part
|
||||
details = internal_path(cursor).lstat()
|
||||
_reject_reparse(details, cursor)
|
||||
if cursor != path and not stat.S_ISDIR(details.st_mode):
|
||||
raise _not_directory(path)
|
||||
if not stat.S_ISREG(details.st_mode) or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
|
||||
raise TaskCenterError("project_selection", "selected file is not a schematic project")
|
||||
for part in relative.parts:
|
||||
cursor /= part
|
||||
_reject_reparse(internal_path(cursor).lstat(), cursor)
|
||||
if not internal_path(path).is_file() or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
|
||||
raise TaskCenterError("project_selection", "selected file is not a schematic project")
|
||||
# A project in any ancestor directory stops discovery below that directory.
|
||||
directory = path.parent
|
||||
while directory != root:
|
||||
directory = directory.parent
|
||||
if directory not in ancestor_projects:
|
||||
has_project = False
|
||||
with _path_errors(directory), os.scandir(internal_path(directory)) as entries:
|
||||
with os.scandir(internal_path(directory)) as entries:
|
||||
for entry in entries:
|
||||
sibling = Path(strip_extended_prefix(entry.path))
|
||||
if sibling.suffix.casefold() != ".prj" or any(sibling.is_relative_to(b) for b in excluded):
|
||||
continue
|
||||
with _path_errors(sibling):
|
||||
details = entry.stat(follow_symlinks=False)
|
||||
_reject_reparse(details, sibling)
|
||||
if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling):
|
||||
has_project = True
|
||||
break
|
||||
details = entry.stat(follow_symlinks=False)
|
||||
_reject_reparse(details, sibling)
|
||||
if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling):
|
||||
has_project = True
|
||||
break
|
||||
ancestor_projects[directory] = has_project
|
||||
if ancestor_projects[directory]:
|
||||
raise TaskCenterError("project_selection", "selected project is hidden by an ancestor project")
|
||||
with _path_errors(path):
|
||||
selected.add(canonical_path(path, strict=True))
|
||||
selected.add(canonical_path(path, strict=True))
|
||||
return tuple(sorted(selected, key=lambda path: str(path).casefold()))
|
||||
|
||||
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
"""Hold a data-root lock while the GUI owns its database and layout."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
import errno
|
||||
import os
|
||||
import time
|
||||
|
||||
from PySide6.QtNetwork import QLocalServer, QLocalSocket
|
||||
|
||||
from .path_access import internal_path
|
||||
from .task_queue import _os_lock
|
||||
|
||||
|
||||
class InstanceUnavailable(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@contextmanager
|
||||
def gui_instance(data_root):
|
||||
root = internal_path(data_root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
# OS locks release on process death. Keep the file so every contender locks the same inode.
|
||||
with (root / '.gui-instance.lock').open('a+b') as handle:
|
||||
identity = os.fstat(handle.fileno())
|
||||
endpoint = f'DxPartReplace-{identity.st_dev:x}-{identity.st_ino:x}'
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
try:
|
||||
_os_lock(handle, True)
|
||||
break
|
||||
except OSError as error:
|
||||
if error.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
|
||||
raise
|
||||
if _activate(endpoint):
|
||||
yield None
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise InstanceUnavailable('此数据目录已在使用,现有窗口暂未响应。')
|
||||
time.sleep(.05)
|
||||
yield endpoint
|
||||
|
||||
|
||||
def _activate(endpoint):
|
||||
socket = QLocalSocket()
|
||||
socket.connectToServer(endpoint)
|
||||
if not socket.waitForConnected(100):
|
||||
return False
|
||||
if os.name == 'nt':
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
pid = wintypes.DWORD()
|
||||
get_pipe_pid = ctypes.windll.kernel32.GetNamedPipeServerProcessId
|
||||
get_pipe_pid.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
|
||||
if get_pipe_pid(int(socket.socketDescriptor()), ctypes.byref(pid)):
|
||||
ctypes.windll.user32.AllowSetForegroundWindow(pid.value)
|
||||
socket.write(b'activate\n')
|
||||
socket.flush()
|
||||
return (socket.bytesAvailable() > 0 or socket.waitForReadyRead(1000)) and socket.readAll() == b'1'
|
||||
|
||||
|
||||
def listen_for_activation(endpoint, activate):
|
||||
server = QLocalServer()
|
||||
server.setSocketOptions(QLocalServer.SocketOption.UserAccessOption)
|
||||
if os.name != 'nt':
|
||||
QLocalServer.removeServer(endpoint) # The lock owner can remove a crashed owner's socket.
|
||||
if not server.listen(endpoint):
|
||||
raise RuntimeError(server.errorString())
|
||||
|
||||
def accept():
|
||||
while server.hasPendingConnections():
|
||||
socket = server.nextPendingConnection()
|
||||
|
||||
def respond(socket=socket):
|
||||
if socket.canReadLine() and socket.readLine() == b'activate\n':
|
||||
activate()
|
||||
socket.write(b'1')
|
||||
socket.flush()
|
||||
socket.disconnectFromServer()
|
||||
|
||||
socket.disconnected.connect(socket.deleteLater)
|
||||
socket.readyRead.connect(respond)
|
||||
respond()
|
||||
|
||||
server.newConnection.connect(accept)
|
||||
return server
|
||||
@@ -3,8 +3,6 @@ from datetime import datetime
|
||||
import json
|
||||
import re
|
||||
|
||||
from ..errors import ProjectPathError
|
||||
|
||||
ERROR_TEXT = {
|
||||
"dsh_startup": "DSH助手启动失败,请检查发布包中的运行时和 Node.js。",
|
||||
'user_forced_stop': '操作已强制中断,结果待核验。',
|
||||
@@ -59,8 +57,6 @@ ERROR_TEXT = {
|
||||
|
||||
|
||||
def format_operation_error(error):
|
||||
if isinstance(error, ProjectPathError):
|
||||
return f'{error.message}\n错误代码:{error.code} · 错误编号:{error.error_id}'
|
||||
title = ERROR_TEXT.get(error.code, '操作未完成')
|
||||
report = getattr(error, 'bom_report', None)
|
||||
if report is not None:
|
||||
|
||||
@@ -19,8 +19,6 @@ from .workers import ServiceWorker
|
||||
from .operation_state import OperationPhase
|
||||
from .command_menu import CommandMenu
|
||||
from .icons import icon
|
||||
from .messages import format_operation_error
|
||||
from ..errors import ProjectPathError
|
||||
from ..bom_import_state import BomImportMachine, BomImportPhase, BomImportState
|
||||
from ..bom_pending import retained_bom_rows
|
||||
|
||||
@@ -46,9 +44,6 @@ class DirectoryTaskDialog(QDialog):
|
||||
self.scan = QPushButton('读取工程', objectName='readTaskProjects')
|
||||
self.projects = QListWidget(objectName='taskProjectCandidates')
|
||||
self.summary = QLabel('先读取工程,再勾选需要创建任务的项目。')
|
||||
self.summary.setWordWrap(True)
|
||||
self.summary.setTextFormat(Qt.TextFormat.PlainText)
|
||||
self.summary.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText('创建任务')
|
||||
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False)
|
||||
@@ -142,10 +137,7 @@ class DirectoryTaskDialog(QDialog):
|
||||
if self._closed:
|
||||
return
|
||||
self._scanned_root = None
|
||||
if isinstance(error, ProjectPathError):
|
||||
self.summary.setText(format_operation_error(error))
|
||||
else:
|
||||
self.summary.setText(getattr(error, 'message', str(error)))
|
||||
self.summary.setText(getattr(error, 'message', str(error)))
|
||||
|
||||
def _finished(self):
|
||||
self._worker = None
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
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}]
|
||||
@@ -3,8 +3,7 @@ import test_accuracy_vbs_guards as guards
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['', 'snapshot', 'identity', 'transaction', 'native',
|
||||
'native_unresolved', 'prior_staged_write', 'save_requested',
|
||||
'save_committed', 'close'])
|
||||
'save_requested', 'save_committed', 'close'])
|
||||
def test_safe_pause_cannot_interrupt_verified_failure_cleanup(tmp_path, fault):
|
||||
output = guards.run_vbs(tmp_path, ['QPProgress', 'QPDiscardFailedBatchProject',
|
||||
'QPCloseBatchProject', 'QPReadUtf8'], '''
|
||||
@@ -34,8 +33,6 @@ Set QP_Fso=CreateObject("Scripting.FileSystemObject")
|
||||
QP_Root="''' + str(tmp_path) + '''":QP_AttemptToken="token":QP_ProgressSequence=0
|
||||
QP_BatchMode=True:QP_OwnedProject=True:QP_OwnedProjectPath="board.prj"
|
||||
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_BatchSaveCommitted=''' + str(fault == 'save_committed') + '''
|
||||
Class FakeApp
|
||||
@@ -88,8 +85,8 @@ End Sub
|
||||
Sub QPLog(ByVal Root,ByVal Level,ByVal Message)
|
||||
End Sub
|
||||
''')
|
||||
paused_before = fault not in {'native', 'native_unresolved'}
|
||||
paused_after = fault not in {'native', 'native_unresolved', 'transaction'}
|
||||
paused_before = fault != 'native'
|
||||
paused_after = fault not in {'native', 'transaction'}
|
||||
assert output.splitlines()[-1] == f'result:{paused_before}:{not fault}:{bool(fault)}:{paused_after}'
|
||||
|
||||
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
from contextlib import closing
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QDialogButtonBox
|
||||
|
||||
from dx_productivity.trial_task_center import project_tasks
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
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.ui.messages import format_operation_error
|
||||
from dx_productivity.trial_task_center.ui.project_plan import DirectoryTaskDialog
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def service(tmp_path):
|
||||
log = configure_logging(tmp_path / 'data')
|
||||
with closing(TaskStore(tmp_path / 'tasks.db')) as store:
|
||||
yield TaskCenterService(store, log), store, log.application_log_path
|
||||
|
||||
|
||||
def deny_directory_listing(folder, request):
|
||||
if os.name != 'nt':
|
||||
pytest.skip('requires a Windows filesystem ACL')
|
||||
import ntsecuritycon
|
||||
import win32api
|
||||
import win32con
|
||||
import win32security
|
||||
|
||||
flag = win32security.DACL_SECURITY_INFORMATION
|
||||
path = str(folder)
|
||||
original = win32security.GetFileSecurity(path, flag)
|
||||
token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
|
||||
try:
|
||||
sid = win32security.GetTokenInformation(token, win32security.TokenUser)[0]
|
||||
finally:
|
||||
token.Close()
|
||||
dacl = win32security.ACL()
|
||||
dacl.AddAccessDeniedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_LIST_DIRECTORY, sid)
|
||||
dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, sid)
|
||||
descriptor = win32security.SECURITY_DESCRIPTOR()
|
||||
descriptor.SetSecurityDescriptorDacl(True, dacl, False)
|
||||
request.addfinalizer(lambda: win32security.SetFileSecurity(path, flag, original))
|
||||
win32security.SetFileSecurity(path, flag, descriptor)
|
||||
with pytest.raises(PermissionError) as failure, os.scandir(folder):
|
||||
pytest.fail('directory ACL did not deny enumeration')
|
||||
assert failure.value.winerror == 5
|
||||
print('Windows ACL produced WinError 5')
|
||||
|
||||
|
||||
def assert_operator_error(text, path, code, advice):
|
||||
print(text)
|
||||
assert str(path) in text
|
||||
assert code in text and 'DXT-' in text
|
||||
assert advice in text
|
||||
assert 'Traceback' not in text
|
||||
assert '发生未处理异常' not in text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(('case', 'code', 'advice'), [
|
||||
('missing', 'path_missing', '移动或删除'),
|
||||
('file', 'path_not_directory', '请选择工程目录'),
|
||||
('file_parent', 'path_not_directory', '请选择工程目录'),
|
||||
('denied', 'path_denied', '读取权限'),
|
||||
])
|
||||
def test_directory_dialog_shows_actionable_path_error(qtbot, tmp_path, request, service, case, code, advice):
|
||||
api, store, log = service
|
||||
folder = tmp_path / case
|
||||
requested = folder
|
||||
if case in {'file', 'file_parent'}:
|
||||
folder.touch()
|
||||
if case == 'file_parent':
|
||||
requested = folder / 'subfolder'
|
||||
if case == 'denied':
|
||||
folder.mkdir()
|
||||
deny_directory_listing(folder, request)
|
||||
|
||||
dialog = DirectoryTaskDialog(api)
|
||||
qtbot.addWidget(dialog)
|
||||
dialog.directory.setText(str(requested))
|
||||
dialog.show()
|
||||
qtbot.mouseClick(dialog.scan, Qt.MouseButton.LeftButton)
|
||||
qtbot.waitUntil(lambda: dialog._worker is None, timeout=5000)
|
||||
assert dialog.directory.isEnabled()
|
||||
assert not dialog.buttons.button(QDialogButtonBox.StandardButton.Ok).isEnabled()
|
||||
assert_operator_error(dialog.summary.text(), requested, code, advice)
|
||||
assert store.list_tasks() == ()
|
||||
contents = log.read_text(encoding='utf-8')
|
||||
assert f'operation=scan_project_directory code={code}' in contents
|
||||
assert 'Traceback' not in contents
|
||||
|
||||
|
||||
def test_moved_project_fails_after_scan_without_creating_partial_tasks(qtbot, tmp_path, service):
|
||||
api, store, log = service
|
||||
root = tmp_path / 'projects'
|
||||
root.mkdir()
|
||||
for name in ('one.prj', 'two.prj'):
|
||||
(root / name).write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
|
||||
dialog = DirectoryTaskDialog(api)
|
||||
qtbot.addWidget(dialog)
|
||||
dialog.directory.setText(str(root))
|
||||
dialog.show()
|
||||
qtbot.mouseClick(dialog.scan, Qt.MouseButton.LeftButton)
|
||||
create = dialog.buttons.button(QDialogButtonBox.StandardButton.Ok)
|
||||
qtbot.waitUntil(create.isEnabled, timeout=5000)
|
||||
moved = root / 'two.prj'
|
||||
moved.rename(root / 'relocated.prj')
|
||||
qtbot.mouseClick(create, Qt.MouseButton.LeftButton)
|
||||
|
||||
with pytest.raises(TaskCenterError) as failure:
|
||||
api.create_project_tasks(dialog.values()[0], selected_paths=dialog.values()[1])
|
||||
assert_operator_error(format_operation_error(failure.value), moved, 'path_missing', '移动或删除')
|
||||
assert store.list_tasks() == ()
|
||||
contents = log.read_text(encoding='utf-8')
|
||||
assert 'operation=create_project_tasks code=path_missing' in contents
|
||||
assert 'Traceback' not in contents
|
||||
|
||||
|
||||
def test_unexpected_scan_fault_remains_traceable_in_application_log(tmp_path, monkeypatch, service):
|
||||
api, _, log = service
|
||||
|
||||
def fail(*args, **kwargs):
|
||||
raise RuntimeError('injected non-filesystem failure')
|
||||
|
||||
monkeypatch.setattr(project_tasks, '_validated_root', fail)
|
||||
with pytest.raises(TaskCenterError) as failure:
|
||||
api.scan_project_directory(tmp_path)
|
||||
assert failure.value.code == 'unhandled_exception'
|
||||
contents = log.read_text(encoding='utf-8')
|
||||
assert 'operation=scan_project_directory code=unhandled_exception' in contents
|
||||
assert 'Traceback' in contents and failure.value.error_id in contents
|
||||
@@ -1,84 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
|
||||
|
||||
_SOURCE = Path(__file__).resolve().parents[2] / 'src'
|
||||
_APP = 'dx_productivity.trial_task_center.application'
|
||||
|
||||
|
||||
def _wait_for(predicate, description):
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(.05)
|
||||
raise AssertionError(description)
|
||||
|
||||
|
||||
def test_concurrent_gui_launches_activate_one_owner_and_recover_after_kill(tmp_path):
|
||||
root = tmp_path / 'Shared Root'
|
||||
independent = tmp_path / 'Independent Root'
|
||||
root.mkdir()
|
||||
store = TaskStore(root / 'task-center.db')
|
||||
try:
|
||||
task = store.create_task('Existing task')
|
||||
finally:
|
||||
store.close()
|
||||
processes = []
|
||||
env = os.environ | {'PYTHONPATH': str(_SOURCE), 'QT_QPA_PLATFORM': 'offscreen'}
|
||||
|
||||
def launch(path, *arguments):
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, '-m', _APP, '--data-root', str(path), *arguments],
|
||||
env=env,
|
||||
)
|
||||
processes.append(process)
|
||||
return process
|
||||
|
||||
def log(path):
|
||||
logfile = path / 'logs/application.log'
|
||||
return logfile.read_text(encoding='utf-8') if logfile.exists() else ''
|
||||
|
||||
try:
|
||||
alias = root.with_name(root.name.upper()) if os.name == 'nt' else root
|
||||
contenders = [launch(root), launch(alias), launch(root), launch(alias)]
|
||||
_wait_for(lambda: sum(p.poll() is not None for p in contenders) >= 3,
|
||||
'Three concurrent launches should exit after handing off to one GUI')
|
||||
owners = [p for p in contenders if p.poll() is None]
|
||||
assert len(owners) == 1
|
||||
assert [p.returncode for p in contenders if p not in owners] == [0, 0, 0]
|
||||
_wait_for(lambda: log(root).count('instance_conflict') == 3,
|
||||
'The GUI should handle and log all three activation requests')
|
||||
assert log(root).count('application_start ') == 1
|
||||
|
||||
other = launch(independent)
|
||||
_wait_for(lambda: 'application_start ' in log(independent), 'Different root should start independently')
|
||||
assert other.poll() is None and owners[0].poll() is None
|
||||
|
||||
helper = launch(root, '--native-helper')
|
||||
assert helper.wait(timeout=60) == 2 # The helper validates its own required snapshot.
|
||||
assert log(root).count('instance_conflict') == 3
|
||||
|
||||
owners[0].kill()
|
||||
owners[0].wait(timeout=10)
|
||||
assert launch(root, '--smoke-test').wait(timeout=60) == 0
|
||||
assert log(root).count('application_start ') == 2
|
||||
assert log(root).count('application_clean_shutdown') == 1
|
||||
assert other.poll() is None
|
||||
store = TaskStore(root / 'task-center.db')
|
||||
try:
|
||||
assert [record.task_id for record in store.list_tasks()] == [task.task_id]
|
||||
finally:
|
||||
store.close()
|
||||
finally:
|
||||
for process in processes:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=10)
|
||||
@@ -152,7 +152,6 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk
|
||||
elif code == 0xF5 and handle == 1695:
|
||||
submits.append(handle)
|
||||
raise RuntimeError('native submit reached')
|
||||
return 1, 1
|
||||
gui = SimpleNamespace(error=RuntimeError, GetAncestor=lambda *args: 1, EnumWindows=enum_windows,
|
||||
EnumChildWindows=lambda *args: None, IsWindowVisible=lambda handle: True,
|
||||
GetClassName=lambda handle: {2: '#32770', 3: 'SysListView32', 4: 'Edit'}.get(handle, 'Main'),
|
||||
@@ -180,7 +179,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, 'replacement_command_from_resources', lambda *args: 33977)
|
||||
monkeypatch.setattr(native_helper, 'wait_for', lambda callback, *args, **kwargs: callback())
|
||||
monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args, **kwargs: callback())
|
||||
monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args: callback())
|
||||
monkeypatch.setattr(native_helper, 'wait_for_native_target', lambda callback, *args: callback())
|
||||
report = {}
|
||||
with pytest.raises(ValueError if fail_at else RuntimeError, match='重新读取目标封装' if fail_at else 'native submit reached'):
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Verify the original issue 33 evidence and summarize queues without running enclosed scripts."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from zipfile import ZipFile
|
||||
|
||||
|
||||
def summarize(path):
|
||||
with path.open('rb') as stream:
|
||||
sha = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
if sha != '1ac99eac3cf79bbf1f011d1d5fe833e92b98fba2c01546b3cfaf55a90b82d5b3':
|
||||
raise ValueError('Expected the original 1.3.2 field bundle from issue 33')
|
||||
queues = {}
|
||||
batches = {}
|
||||
with ZipFile(path) as archive:
|
||||
manifest = next(n for n in archive.namelist() if n.endswith('/SHA256SUMS.txt'))
|
||||
prefix = manifest.rsplit('/', 1)[0] + '/'
|
||||
entries = archive.read(manifest).decode('utf-8-sig').splitlines()
|
||||
for line in entries:
|
||||
digest, member = line.split(None, 1)
|
||||
with archive.open(prefix + member.strip().replace('\\', '/')) as stream:
|
||||
if hashlib.file_digest(stream, 'sha256').hexdigest() != digest.lower():
|
||||
raise ValueError('File checksum mismatch: ' + member)
|
||||
for member in archive.namelist():
|
||||
if '/data_full132/task-queues/' in member and member.endswith('.json'):
|
||||
queue = json.loads(archive.read(member))
|
||||
queues[Path(member).stem] = dict(
|
||||
total=len(queue['task_ids']), phase=queue['phase'],
|
||||
states=dict(Counter(row['state'] for row in queue['entries'].values())),
|
||||
isolated=list(queue.get('isolated_tasks', {})))
|
||||
if '/data_full132/batch-resources/' in member and member.endswith('/business-result.json'):
|
||||
result = json.loads(archive.read(member))
|
||||
fields = (result['payload'].get('result') or {}).get('fields', {})
|
||||
if 'queue_id' in fields:
|
||||
batches[result['batch_id']] = {key: fields.get(key) for key in
|
||||
('queue_id', 'paused', 'current_task_id')}
|
||||
return dict(sha256=sha, verified_files=len(entries), queues=queues, batch_results=batches)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('bundle', type=Path)
|
||||
print(json.dumps(summarize(parser.parse_args().bundle), ensure_ascii=False, indent=2))
|
||||
Reference in new issue
Block a user