diff --git a/docs/plans/2026-10-15-bom-live-roundtrip.md b/docs/plans/2026-10-15-bom-live-roundtrip.md new file mode 100644 index 0000000..acec703 --- /dev/null +++ b/docs/plans/2026-10-15-bom-live-roundtrip.md @@ -0,0 +1,11 @@ +# BOM 真人流程与重复执行 + +沿用当前 1.1.2 开发版和 11 列模板;用户已授权实现与在副本上实际替换。原 CAD PID 18732、原工程及原始 BOM 不操作;及时提交推送,不打包发布。 + +1. 导入反馈:提供结构化校验报告,显示总行数、校验通过/失败/未检查行数、工程、Excel 行号和原因。严格原 API 保持拒绝整批部分写入;UI 走报告入口,有错误时不保存或默默执行部分替换,修正后重新导入。 +2. 完成任务:显式“开始新一轮”保留旧命令、快照、计划和日志,重置运行状态并清除已过期目标基线,重新采集当前工程再编辑和执行;不解除中断/不确定状态。批规则编辑需兼顾同批仍完成的成员,以明确的新一轮范围保证一致性。 +3. 长路径:分别核对证据目录、Excel 路径、实际工程路径;通过真实 WSH 检查和实际 CAD 试验发现限制后修复。身份验证始终使用原始工程身份,运行别名不得让工程串位。 +4. 原生真人流程脚本:Qt 弹窗选择创建任务、导出默认模板、修改模板实际单元格、失败导入报告、成功导入预览、保存、点击执行、原生 Replace Part 保存回读;开始新一轮后再次导入与替换;用独立原生读取核对选中与未选中位号,检查私有桌面及自有 CAD 释放。 +5. 自动回归覆盖报告、事务、重跑状态和长路径身份;真实验证记录步骤耗时、路径长度、日志、前后器件和截图,报告任何实际限制。 + +并行所有权:报告代理持有 bom_plan.py/bom_batch.py/new bom_import_report.py/ui/project_plan.py;重跑代理持有 service.py/store reset helper/ui/main_window.py/run_panel.py/execution_state.py;主代理持有路径兼容、VBS 与真实探针,并接入报告服务 API。不得并行启动 CAD。 diff --git a/integration/dxdesigner795/QuickPartReplace.vbs b/integration/dxdesigner795/QuickPartReplace.vbs index 10df295..76a8d04 100644 --- a/integration/dxdesigner795/QuickPartReplace.vbs +++ b/integration/dxdesigner795/QuickPartReplace.vbs @@ -35,6 +35,7 @@ Dim QP_NcSyncSummary Dim QP_SessionMode, QP_SessionToken, QP_SessionProject, QP_MonitorJobId Dim QP_OwnedProjectPath, QP_SessionWaiting, QP_SessionExternalChange Dim QP_CheckpointSchematic, QP_CheckpointSheet +Dim QP_ProjectAccess, QP_AccessProject Dim FailureState, CloseError Set QP_Fso = CreateObject("Scripting.FileSystemObject") QP_RootTemplate = "%LOCALAPPDATA%\DxProductivity\trial-task-center\quick-run" @@ -520,6 +521,7 @@ Function QPConfirmedProjectPath() Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed sheet columns are incomplete" If (Len(QP_TargetSchematic) = 0) <> (Len(QP_TargetSheet) = 0) Then _ Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed sheet identity is incomplete" + TargetPath = QPProjectAccessPath(TargetPath) If Not QP_Fso.FileExists(TargetPath) Then _ Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed project file does not exist: " & TargetPath If LCase(QP_Fso.GetExtensionName(TargetPath)) <> "prj" Then _ @@ -2498,7 +2500,7 @@ Function QPProjectPath() If Len(Trim(ProjectPath)) = 0 Then Err.Raise vbObjectError + 827, "QuickPartReplace", "no active project" End If - QPProjectPath = ProjectPath + QPProjectPath = QPCanonicalPath(ProjectPath) End Function Function QPSheetIdentity() @@ -2929,8 +2931,49 @@ Function QPDecode(ByVal Value) End Function Function QPCanonicalPath(ByVal Value) - QPCanonicalPath = LCase(Replace(QP_Fso.GetAbsolutePathName(CStr(Value)), _ - "/", "\")) + Dim Identity + QPEnsureProjectAccess + Identity = LCase(Replace(QP_Fso.GetAbsolutePathName(CStr(Value)), "/", "\")) + If QP_AccessProject.Exists(Identity) Then Identity = QP_AccessProject(Identity) + QPCanonicalPath = Identity +End Function + +Sub QPEnsureProjectAccess() + Dim Path, Lines, Fields, Index, Canonical, Access + If IsObject(QP_ProjectAccess) Then Exit Sub + Set QP_ProjectAccess = CreateObject("Scripting.Dictionary") + Set QP_AccessProject = CreateObject("Scripting.Dictionary") + QP_ProjectAccess.CompareMode = 1 + QP_AccessProject.CompareMode = 1 + Path = QP_Fso.BuildPath(QP_Root, "project-access.tsv") + If Not QP_Fso.FileExists(Path) Then Exit Sub + Lines = Split(QPReadUtf8(Path), vbLf) + If Replace(Lines(0), vbCr, "") <> "project_path" & vbTab & "access_path" Then _ + Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "invalid project access header" + For Index = 1 To UBound(Lines) + If Len(Replace(Lines(Index), vbCr, "")) > 0 Then + Fields = Split(Replace(Lines(Index), vbCr, ""), vbTab) + If UBound(Fields) <> 1 Then _ + Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "invalid project access row" + Canonical = LCase(Replace(QP_Fso.GetAbsolutePathName(Fields(0)), "/", "\")) + Access = LCase(Replace(QP_Fso.GetAbsolutePathName(Fields(1)), "/", "\")) + If QP_ProjectAccess.Exists(Canonical) Or QP_AccessProject.Exists(Access) Then _ + Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "duplicate project access identity" + QP_ProjectAccess.Add Canonical, Fields(1) + QP_AccessProject.Add Access, Canonical + End If + Next +End Sub + +Function QPProjectAccessPath(ByVal Value) + Dim Identity + QPEnsureProjectAccess + Identity = LCase(Replace(QP_Fso.GetAbsolutePathName(CStr(Value)), "/", "\")) + If QP_ProjectAccess.Exists(Identity) Then + QPProjectAccessPath = QP_ProjectAccess(Identity) + Else + QPProjectAccessPath = Value + End If End Function Sub QPRaiseCaptured(ByVal Number, ByVal Source, ByVal Description, ByVal Fallback) diff --git a/src/dx_productivity/trial_task_center/cad_identity.py b/src/dx_productivity/trial_task_center/cad_identity.py index 8cf2bcf..ad57687 100644 --- a/src/dx_productivity/trial_task_center/cad_identity.py +++ b/src/dx_productivity/trial_task_center/cad_identity.py @@ -66,3 +66,12 @@ def verify_application(app, binding=None, *, require_view=True): if not handle or window_pid(handle) != binding.pid: raise ValueError('CAD view PID does not match its owned session') return binding + + +def project_file_path(app): + """COM type libraries expose this getter as either a property or a method.""" + value = app.GetProjectData().GetProjectFilePath + value = value() if callable(value) else value + if not isinstance(value, str): + raise ValueError('CAD returned an invalid project path') + return value diff --git a/src/dx_productivity/trial_task_center/isolated_cad.py b/src/dx_productivity/trial_task_center/isolated_cad.py index d7060df..b79d971 100644 --- a/src/dx_productivity/trial_task_center/isolated_cad.py +++ b/src/dx_productivity/trial_task_center/isolated_cad.py @@ -8,7 +8,7 @@ import sys import time from uuid import uuid4 -from .cad_identity import CadBinding, current_desktop_name, verify_application +from .cad_identity import CadBinding, current_desktop_name, verify_application, project_file_path from .isolated_desktop import PrivateDesktop from .worker_monitor import WorkerMonitorError @@ -227,7 +227,7 @@ def native_action(action, evidence, expected_pid): # ActiveViewHandle can retain a destroyed/reused HWND after closing # the last project. The private ROT/GUID binds this empty instance. verify_application(app, binding, require_view=False) - if app.GetProjectData().GetProjectFilePath(): + if project_file_path(app): raise ValueError('owned CAD still has a project open; no implicit save or discard') app.Quit() else: diff --git a/src/dx_productivity/trial_task_center/legacy_paths.py b/src/dx_productivity/trial_task_center/legacy_paths.py index 6943216..4a94ee4 100644 --- a/src/dx_productivity/trial_task_center/legacy_paths.py +++ b/src/dx_productivity/trial_task_center/legacy_paths.py @@ -3,6 +3,7 @@ from __future__ import annotations import atexit import ctypes +import csv import hashlib import os from pathlib import Path @@ -87,6 +88,8 @@ atexit.register(cleanup_worker_aliases) def worker_paths(script: Path, root: Path) -> tuple[str, str]: + if os.name == 'nt': + _prepare_project_access(root) if os.name != 'nt' or _fits(root): return str(script), str(root) canonical = root.resolve(strict=True) @@ -99,3 +102,55 @@ def worker_paths(script: Path, root: Path) -> tuple[str, str]: raise TaskCenterError('quick_run_path_length', f'无法建立长路径兼容入口:{error};尚未启动 CAD 操作。') from error return str(alias / script.name), str(alias) + + +def _prepare_project_access(root: Path): + """Keep command identities canonical while giving legacy CAD short entry paths.""" + command = root / 'command.tsv' + if not command.is_file(): + return + rows = [] + with command.open(encoding='utf-8-sig', newline='') as stream: + for row in csv.DictReader(stream, delimiter='\t'): + value = row.get('project_path') + if not value: + continue + project = Path(value).resolve(strict=False) + if (_fits(project.parent) and len(str(project)) < 260) or not project.is_file(): + continue + short = _short_path(project) + if short and _fits(Path(short).parent) and len(short) < 260: + access = Path(short) + else: + access = _aliases.alias(project.parent) / project.name + if not _fits(access.parent) or len(str(access)) >= 260 or access.resolve(strict=True) != project: + raise TaskCenterError('quick_run_path_length', '工程短路径入口不能与原工程身份对应,未启动 CAD 操作。') + pair = (str(project), str(access)) + if pair not in rows: + rows.append(pair) + target = root / 'project-access.tsv' + if rows or target.exists(): + temporary = target.with_suffix('.tmp') + with temporary.open('w', encoding='utf-8', newline='') as stream: + writer = csv.writer(stream, delimiter='\t', lineterminator='\n') + writer.writerow(('project_path', 'access_path')) + writer.writerows(rows) + temporary.replace(target) + + +def validate_project_access(root: Path): + """Reject disappeared/redirected entry paths before and after a native worker.""" + target = Path(root) / 'project-access.tsv' + if not target.is_file(): + return + with target.open(encoding='utf-8-sig', newline='') as stream: + reader = csv.DictReader(stream, delimiter='\t') + if reader.fieldnames != ['project_path', 'access_path']: + raise TaskCenterError('target_identity', '工程路径入口清单格式已改变') + for row in reader: + try: + same = Path(row['access_path']).resolve(strict=True) == Path(row['project_path']).resolve(strict=True) + except (OSError, ValueError, KeyError): + same = False + if not same: + raise TaskCenterError('target_identity', '工程短路径入口已失效或指向其他工程,拒绝使用采集或替换结果') diff --git a/src/dx_productivity/trial_task_center/native_helper.py b/src/dx_productivity/trial_task_center/native_helper.py index 9716400..7bc26c6 100644 --- a/src/dx_productivity/trial_task_center/native_helper.py +++ b/src/dx_productivity/trial_task_center/native_helper.py @@ -205,7 +205,7 @@ def attach(): api = win32com.client.gencache.EnsureModule( "{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0) app = api.IVdApp(win32com.client.GetActiveObject("Viewdraw.Application")._oleobj_) - from .cad_identity import verify_application + from .cad_identity import verify_application, project_file_path verify_application(app) return app, api @@ -228,9 +228,9 @@ def components_on_sheet(app, api): def check_active_context(app, metadata): - from .cad_identity import verify_application + from .cad_identity import verify_application, project_file_path verify_application(app) - if os.path.normcase(os.path.abspath(app.GetProjectData().GetProjectFilePath())) != os.path.normcase(os.path.abspath(metadata[1])): + if Path(project_file_path(app)).resolve() != Path(metadata[1]).resolve(): raise ValueError("Active project changed") if f"{app.ActiveView.GetName(0)}:{app.ActiveView.Block.SheetNum}" != metadata[4]: raise ValueError("Active sheet changed") diff --git a/src/dx_productivity/trial_task_center/quick_run.py b/src/dx_productivity/trial_task_center/quick_run.py index 883e152..e68325e 100644 --- a/src/dx_productivity/trial_task_center/quick_run.py +++ b/src/dx_productivity/trial_task_center/quick_run.py @@ -1707,9 +1707,13 @@ def _cached_native_helper_launch_arguments(frozen: bool, executable: str) -> tup def _run_process(command: tuple[str, ...], timeout: int, *, abort_event=None) -> subprocess.CompletedProcess[str]: from .isolated_cad import run_isolated_process + from .legacy_paths import validate_project_access - return run_isolated_process(command, timeout, - **({'abort_event': abort_event, 'cooperative_abort': True} if abort_event is not None else {})) + validate_project_access(Path(command[3])) + result = run_isolated_process(command, timeout, + **({'abort_event': abort_event, 'cooperative_abort': True} if abort_event is not None else {})) + validate_project_access(Path(command[3])) + return result def _log_text(value: str) -> str: diff --git a/tests/v1_1/test_com_project_path.py b/tests/v1_1/test_com_project_path.py new file mode 100644 index 0000000..bfbbf46 --- /dev/null +++ b/tests/v1_1/test_com_project_path.py @@ -0,0 +1,20 @@ +from types import SimpleNamespace +import pytest + +from dx_productivity.trial_task_center import isolated_cad + + +@pytest.mark.parametrize('as_property', [True, False]) +def test_private_quit_accepts_property_or_method_project_path(monkeypatch, tmp_path, as_property): + import win32com.client + data = SimpleNamespace(GetProjectFilePath='' if as_property else lambda: '') + quit_calls = [] + app = SimpleNamespace(GetProjectData=lambda: data, Quit=lambda: quit_calls.append(1)) + monkeypatch.setattr(win32com.client, 'GetActiveObject', lambda _: app) + monkeypatch.setattr(isolated_cad, 'current_desktop_name', lambda: 'dx-' + 'a' * 32) + monkeypatch.setattr(isolated_cad, 'verify_application', lambda *args, **kwargs: None) + for name, value in {'DXPART_DESKTOP': 'dx-' + 'a' * 32, 'DXPART_SESSION_TOKEN': 'a' * 32, + 'DXPART_CAD_PID': '123', 'DXPART_CAD_GUID': 'guid'}.items(): + monkeypatch.setenv(name, value) + assert isolated_cad.native_action('quit', tmp_path / 'unused.json', 123) == 0 + assert quit_calls == [1] diff --git a/tests/v1_1/test_project_long_paths.py b/tests/v1_1/test_project_long_paths.py new file mode 100644 index 0000000..9134059 --- /dev/null +++ b/tests/v1_1/test_project_long_paths.py @@ -0,0 +1,90 @@ +from pathlib import Path +from types import SimpleNamespace +import re +import subprocess + +import pytest + +from dx_productivity.trial_task_center import legacy_paths, native_helper + + +def long_project(tmp_path): + folder = tmp_path / ('design-' + 'x' * 78) / ('revision-' + 'y' * 78) + folder.mkdir(parents=True) + project = folder / 'board.prj' + project.write_text('project') + assert len(str(project)) > 260 + return project + + +def test_worker_prepares_project_access_without_changing_command_identity(tmp_path, monkeypatch): + project = long_project(tmp_path) + root = tmp_path / 'worker' + root.mkdir() + script = root / 'worker.vbs' + script.write_text('runtime') + command = f'job_id\tproject_path\njob\t{project}\n' + (root / 'command.tsv').write_text(command, encoding='utf-8') + monkeypatch.setattr(legacy_paths, '_short_path', lambda _: None) + pool = legacy_paths._AliasPool() + monkeypatch.setattr(legacy_paths, '_aliases', pool) + try: + legacy_paths.worker_paths(script, root) + mapping = (root / 'project-access.tsv').read_text(encoding='utf-8').splitlines() + assert mapping[0] == 'project_path\taccess_path' + canonical, access = mapping[1].split('\t') + assert Path(canonical) == project.resolve() + assert len(access) < 160 and Path(access).resolve() == project.resolve() + assert (root / 'command.tsv').read_text(encoding='utf-8') == command + vbs = tmp_path / 'access-check.vbs' + vbs.write_text('Set f=CreateObject("Scripting.FileSystemObject")\nWScript.Echo CStr(f.FileExists(WScript.Arguments(0)))\n') + result = subprocess.run((r'C:\Windows\SysWOW64\cscript.exe', '//nologo', str(vbs), access), capture_output=True,text=True) + assert result.stdout.strip() == 'True' + finally: + assert not pool.close() + + +def test_native_context_accepts_same_project_via_junction_and_rejects_foreign(tmp_path, monkeypatch): + from dx_productivity.trial_task_center import cad_identity + project = long_project(tmp_path) + pool = legacy_paths._AliasPool() + monkeypatch.setattr(cad_identity, 'verify_application', lambda _: None) + try: + alias = pool.alias(project.parent) / project.name + app = SimpleNamespace(GetProjectData=lambda: SimpleNamespace(GetProjectFilePath=lambda: str(alias)), + ActiveView=SimpleNamespace(GetName=lambda _: 'MAIN', Block=SimpleNamespace(SheetNum='1'))) + metadata = ('job', str(project), 'OLD', 'NEW', 'MAIN:1') + native_helper.check_active_context(app, metadata) + with pytest.raises(ValueError, match='Active project changed'): + native_helper.check_active_context(app, ('job', str(tmp_path / 'foreign.prj'), 'OLD', 'NEW', 'MAIN:1')) + finally: + assert not pool.close() + + +def test_redirected_project_entry_is_rejected_before_native_launch(tmp_path, monkeypatch): + import _winapi + from dx_productivity.trial_task_center import quick_run + from dx_productivity.trial_task_center.errors import TaskCenterError + project = long_project(tmp_path) + other = tmp_path / 'other' + other.mkdir() + (other / project.name).write_text('foreign') + root = tmp_path / 'evidence' + root.mkdir() + pool = legacy_paths._AliasPool() + try: + access = pool.alias(project.parent) + (root / 'project-access.tsv').write_text(f'project_path\taccess_path\n{project}\t{access / project.name}\n') + access.rmdir() + _winapi.CreateJunction(str(other), str(access)) + from dx_productivity.trial_task_center import isolated_cad + monkeypatch.setattr(isolated_cad, 'run_isolated_process', lambda *a, **k: pytest.fail('foreign project launch')) + with pytest.raises(TaskCenterError) as error: + quick_run._run_process(('cscript', '//nologo', 'worker', str(root)), 1) + assert error.value.code == 'target_identity' + finally: + # Restore the original binding before asking pool cleanup to remove it. + if access.is_junction(): + access.rmdir() + _winapi.CreateJunction(str(project.parent), str(access)) + assert not pool.close()