fix: handle owned CAD error dialogs and unblock verified shutdown
This commit is contained in:
1 parent
08ddf4cd6a
commit
75ee8bd33a
9 files changed
+560
-11
No files matched your search
@@ -41,6 +41,7 @@ jobs:
|
||||
tests/packaging/test_self_extracting_release.py
|
||||
tests/trial_task_center/test_bom_template_contract.py
|
||||
tests/trial_task_center/test_bom_import_review.py
|
||||
tests/v1_1/test_cad_dialogs.py
|
||||
--junitxml=build/ci-results.xml --tb=short
|
||||
- name: Windows release scope
|
||||
run: |
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# CAD 弹窗与资源释放补丁
|
||||
|
||||
基于 `08ddf4c`,参考 `docs/reviews/2026-10-19-native-snapshot.md`:曾因 CAD 预定义 Vd 枚举被脚本重复声明,弹出编译错误框;定向确认错误框后 CAD 才能正常退出。该次异常记录仍保持 `clean=false`。
|
||||
|
||||
## 实际行为
|
||||
|
||||
- 从私有桌面枚举自有且仍存活的 CAD PID,只读取该进程的可见标准对话框。使用有超时的窗口文本读取,不切换输入桌面、不发送全局鼠标键盘输入。采样限制为每次约 0.5 秒、最多 8 个对话框、最多 64 个子控件;不完整快照不能授权点击。
|
||||
- 目前自动确认范围仅为已知 VBScript 编译错误、匹配标题、单一且可用的“确定/OK”按钮。先原子保存标题、正文、按钮、句柄、PID、会话标识和阶段;发送消息前重新枚举并比对完整快照,避免旧 HWND 被复用。每个快照最多请求一次确认。
|
||||
- 保存、覆盖、许可、其他未知提示均记录为 `manual_required`,不自动点击。证据写入失败也不能授权点击。
|
||||
- 启动、工程关闭检查点、Quit 和 CAD 退出等待均检查弹窗。会话就绪后另有不调用 COM 的独立监测线程,业务线程被 COM 模态等待阻塞时仍能处理上述已知错误框;关闭前停止该线程。
|
||||
- 生产 `BatchCadRuntime` 的桌面租约同步接入监测与动作,限定当前 generation 及本 lease 的存活进程。旧代次和其他 PID 不能继承该权限。
|
||||
- 编译错误即使已确认关闭,也保持失败;证据最多 100 条,达到上限仍锁存致命错误,不点击无法记录的新对话框。
|
||||
- Quit 超时后保留原进程与保护标记。人工处理弹窗后,只有 CAD 和原 Quit helper 都已实际退出,等待才自动结束;不重复 Quit、不自动重做替换、不把超时后的结果标记为正常成功。
|
||||
- `cad-dialogs-<session-token>.json` 和会话概要进入现有脱敏诊断导出,包括批次 `generation-N` 子目录。证据以文本和控件信息为主,本轮没有增加截图或新的界面按钮。
|
||||
|
||||
## 定向验证
|
||||
|
||||
1. 修改前现有 `test_isolated_cad.py`:**34 passed**。
|
||||
2. 新增弹窗测试先复现缺失逻辑;退出阶段集成用例先复现“错误框未处理”和“进程已退出仍必须点强制结束”。随后修复并通过。
|
||||
3. 弹窗、隔离会话、用户停止、诊断导出的阶段性定向验证:**79 passed**。
|
||||
4. 生产批次租约、证据上限修正后的弹窗与 batch runtime 定向验证:**55 passed**。
|
||||
5. 最终 `python -m pytest -q tests/v1_1/test_cad_dialogs.py --tb=short`:**21 passed**,包括外国 PID、旧 generation、控件句柄复用、写盘失败、重复点击防护、启动致命错误、人工解除后退出、记录上限、两种目录诊断导出等独立用例。
|
||||
|
||||
上述范围重叠,不累加。21 项中包含 3 个真实 Win32 私有桌面 MessageBox 样本:已知脚本错误可关闭、保存提示保持不动、真实 BatchCadRuntime 租约下主线程等待时由后台监测解除已知错误框。样本使用独立 Python 进程,未启动真实 CAD,也未打开或修改工程。
|
||||
|
||||
独立只读复核发现证据上限可能漏记致命错误,已修正并以先失败后通过的用例验证;增量复核通过。现有保存证明、实例身份、强制结束授权与不确定状态保护保持生效。
|
||||
|
||||
本轮未执行真实 DxDesigner 换料、PCB、安装包构建或整库重复回归。Linux CI 加入本文件的可移植用例;原生 Win32 样本在非 Windows 上跳过,本机结果不能代替远端 Linux 检查结果。
|
||||
@@ -61,6 +61,20 @@ class _DesktopLease:
|
||||
self.owner._track(process)
|
||||
return process
|
||||
|
||||
def inspect_dialogs(self, pid):
|
||||
if self.desktop is None or self.generation != self.owner.generation:
|
||||
return ()
|
||||
inspect = getattr(self.desktop, 'inspect_dialogs', None)
|
||||
if inspect is None or not any(process.pid == pid and process.poll() is None for process in self.processes):
|
||||
return ()
|
||||
return inspect(pid)
|
||||
|
||||
def acknowledge_dialog(self, dialog):
|
||||
if (self.desktop is None or self.generation != self.owner.generation or
|
||||
not any(process.pid == dialog['pid'] and process.poll() is None for process in self.processes)):
|
||||
raise WorkerMonitorError('stale or unavailable batch dialog owner')
|
||||
self.desktop.acknowledge_dialog(dialog)
|
||||
|
||||
def close(self):
|
||||
errors, remaining, records = [], [], []
|
||||
for process in reversed(self.processes):
|
||||
@@ -435,7 +449,8 @@ class BatchCadRuntime:
|
||||
self.record['cad_shutdown'] = {key: cad_record[key] for key in (
|
||||
'state', 'clean', 'cad_exit_code', 'quit_helper_exit_code', 'cleanup_errors',
|
||||
'shutdown_seconds', 'orderly_shutdown', 'diagnostic_errors', 'forced_termination',
|
||||
'forced_root_termination', 'forced_descendant_pids', 'termination_reason') if key in cad_record}
|
||||
'forced_root_termination', 'forced_descendant_pids', 'termination_reason',
|
||||
'dialog_supervision') if key in cad_record}
|
||||
if self.desktop is not None:
|
||||
try:
|
||||
self.desktop.close()
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Bounded, COM-independent observations of modal dialogs on an owned desktop."""
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import json
|
||||
import time
|
||||
from threading import RLock
|
||||
|
||||
from .batch_resources import write_record
|
||||
|
||||
|
||||
def _text(handle):
|
||||
user = ctypes.WinDLL('user32', use_last_error=True)
|
||||
send = user.SendMessageTimeoutW
|
||||
send.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM,
|
||||
wintypes.UINT, wintypes.UINT, ctypes.POINTER(ctypes.c_size_t)]
|
||||
send.restype = wintypes.LPARAM
|
||||
buffer, result = ctypes.create_unicode_buffer(2048), ctypes.c_size_t()
|
||||
if not send(handle, 0x000D, len(buffer), ctypes.addressof(buffer), 0x0002, 50, ctypes.byref(result)):
|
||||
raise OSError('dialog text unavailable or unresponsive')
|
||||
if result.value >= len(buffer) - 1:
|
||||
raise OSError('dialog text exceeds observation limit')
|
||||
return buffer.value
|
||||
|
||||
|
||||
def inspect_owned_dialogs(api, desktop_name, pid):
|
||||
import win32gui
|
||||
import win32process
|
||||
|
||||
result = []
|
||||
deadline = time.monotonic() + .5
|
||||
for window in api._desktop_windows(desktop_name):
|
||||
if window['pid'] != pid or window['class'] != '#32770' or not win32gui.IsWindowVisible(window['hwnd']):
|
||||
continue
|
||||
handle = window['hwnd']
|
||||
row = dict(window, title='', text='', buttons=[], complete=True)
|
||||
labels, children = [], []
|
||||
try:
|
||||
row['title'] = _text(handle)
|
||||
win32gui.EnumChildWindows(handle, lambda child, _: children.append(child), None)
|
||||
for child in children:
|
||||
if time.monotonic() >= deadline or len(children) > 64:
|
||||
row['complete'] = False
|
||||
break
|
||||
if not win32gui.IsWindowVisible(child):
|
||||
continue
|
||||
if win32process.GetWindowThreadProcessId(child)[1] != pid:
|
||||
row['complete'] = False
|
||||
continue
|
||||
text = _text(child)
|
||||
if win32gui.GetClassName(child).casefold() == 'button':
|
||||
row['buttons'].append({'hwnd': int(child), 'id': win32gui.GetDlgCtrlID(child),
|
||||
'text': text, 'enabled': bool(win32gui.IsWindowEnabled(child))})
|
||||
elif text:
|
||||
labels.append(text)
|
||||
except Exception as error:
|
||||
row.update(complete=False, read_error=str(error))
|
||||
row['text'] = '\n'.join(labels)[:8192]
|
||||
result.append(row)
|
||||
if len(result) >= 8 or time.monotonic() >= deadline:
|
||||
break
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def acknowledge_owned_dialog(api, desktop_name, pid, expected):
|
||||
import win32gui
|
||||
|
||||
# Re-enumerate the private desktop and compare the complete fingerprint;
|
||||
# a recycled HWND or changed prompt cannot inherit the earlier decision.
|
||||
current = next((row for row in inspect_owned_dialogs(api, desktop_name, pid)
|
||||
if row == expected), None)
|
||||
if current is None or not _script_error(current):
|
||||
raise OSError('dialog changed before acknowledgement')
|
||||
win32gui.PostMessage(current['buttons'][0]['hwnd'], 0x00F5, 0, 0) # BM_CLICK, no global input
|
||||
|
||||
|
||||
def _script_error(row):
|
||||
title = row['title'].strip().casefold()
|
||||
body = row['text'].casefold()
|
||||
buttons = row['buttons']
|
||||
return (row.get('complete') is True and title in {'script error', 'microsoft vbscript', 'dxdesigner', '脚本错误'}
|
||||
and any(marker in body for marker in ('microsoft vbscript compilation error', 'microsoft vbscript 编译器错误'))
|
||||
and len(buttons) == 1 and buttons[0]['id'] in {1, 2} and buttons[0]['enabled']
|
||||
and buttons[0]['text'].replace('&', '').strip().casefold() in {'ok', '确定', '确定(o)'})
|
||||
|
||||
|
||||
class CadDialogGuard:
|
||||
def __init__(self, desktop, process, evidence_path, token):
|
||||
self.desktop, self.process = desktop, process
|
||||
self.evidence_path, self.token = evidence_path, token
|
||||
self.records, self.seen = [], set()
|
||||
self.blocking = []
|
||||
self.failure = ''
|
||||
self._lock = RLock()
|
||||
|
||||
def poll(self, phase):
|
||||
with self._lock:
|
||||
self._poll(phase)
|
||||
|
||||
def _poll(self, phase):
|
||||
inspect = getattr(self.desktop, 'inspect_dialogs', None)
|
||||
if inspect is None or self.process.poll() is not None:
|
||||
self.blocking = []
|
||||
return
|
||||
rows = [row for row in inspect(self.process.pid)
|
||||
if row['pid'] == self.process.pid and row['class'] == '#32770']
|
||||
self.blocking = [row['title'] or '未命名弹窗' for row in rows]
|
||||
for row in rows:
|
||||
key = json.dumps(row, ensure_ascii=False, sort_keys=True)
|
||||
action = 'acknowledge_script_error' if _script_error(row) else 'manual_required'
|
||||
if action == 'acknowledge_script_error':
|
||||
self.failure = 'CAD script error: ' + row['text'][:1000]
|
||||
if key in self.seen or len(self.records) >= 100:
|
||||
continue
|
||||
record = dict(row, phase=phase, action=action, observed_at=time.time())
|
||||
self.records.append(record)
|
||||
self._save() # No automatic button action without durable evidence.
|
||||
self.seen.add(key)
|
||||
if action == 'acknowledge_script_error':
|
||||
self.desktop.acknowledge_dialog(row)
|
||||
|
||||
def _save(self):
|
||||
write_record(self.evidence_path, {'version': 1, 'session_token': self.token,
|
||||
'cad_pid': self.process.pid, 'dialogs': self.records})
|
||||
|
||||
def summary(self):
|
||||
with self._lock:
|
||||
return {'evidence_path': str(self.evidence_path), 'dialogs_seen': len(self.records),
|
||||
'blocked': bool(self.blocking), 'blocking_titles': list(self.blocking), 'error': self.failure}
|
||||
@@ -52,6 +52,9 @@ def _scrub_json(value):
|
||||
|
||||
|
||||
def _allowed(parts):
|
||||
if re.fullmatch(r'cad-dialogs-[a-f0-9]{32}\.json', parts[-1]):
|
||||
return ((len(parts) == 4 and parts[0] == 'batch-resources' and re.fullmatch(r'generation-\d+', parts[2])) or
|
||||
any(value in parts for value in ('quick-run', 'quickrun', 'quick-run-history')))
|
||||
if (len(parts) == 5 and parts[0] == 'tasks' and parts[2] == 'quick-run-history'
|
||||
and re.fullmatch(r'bom-import-[A-Za-z0-9-]+', parts[3])):
|
||||
return parts[-1] == 'source-map.json'
|
||||
|
||||
@@ -7,12 +7,14 @@ import subprocess
|
||||
import sys
|
||||
import time
|
||||
from traceback import clear_frames
|
||||
from threading import Event, Thread
|
||||
from uuid import uuid4
|
||||
|
||||
from .cad_identity import CadBinding, current_desktop_name, verify_application, project_file_path
|
||||
from .isolated_desktop import PrivateDesktop
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
from .path_access import internal_path, canonical_path, retry_sharing_violation
|
||||
from .cad_dialogs import CadDialogGuard
|
||||
|
||||
|
||||
class PrivateCadStartupError(WorkerMonitorError):
|
||||
@@ -98,6 +100,10 @@ class IsolatedCadSession:
|
||||
self.abort_event = abort_event
|
||||
self.stop_control = stop_control
|
||||
self.record = {'desktop': self.desktop.name, 'token': self.token, 'state': 'starting'}
|
||||
self._dialogs = None
|
||||
self._dialog_monitor_error = ''
|
||||
self._dialog_stop = Event()
|
||||
self._dialog_thread = None
|
||||
|
||||
def _record(self, **values):
|
||||
self.record.update(values)
|
||||
@@ -118,6 +124,8 @@ class IsolatedCadSession:
|
||||
self._check_abort()
|
||||
self.desktop.__enter__()
|
||||
self.cad = self.desktop.start_process((str(_designer_executable()),))
|
||||
self._dialogs = CadDialogGuard(self.desktop, self.cad,
|
||||
self.root / ('cad-dialogs-' + self.token + '.json'), self.token)
|
||||
self._record(cad_pid=self.cad.pid)
|
||||
bootstrap = self.root / ('cad-binding-' + self.token + '.json')
|
||||
environment = dict(os.environ, DXPART_DESKTOP=self.desktop.name,
|
||||
@@ -129,16 +137,18 @@ class IsolatedCadSession:
|
||||
deadline = time.monotonic() + 120
|
||||
while probe.poll() is None:
|
||||
self._check_abort()
|
||||
self._poll_dialogs('startup')
|
||||
cad_exit = self.cad.poll()
|
||||
if cad_exit is not None:
|
||||
raise WorkerMonitorError(f'owned private CAD exited during startup: exit code {cad_exit}')
|
||||
if time.monotonic() >= deadline:
|
||||
raise WorkerMonitorError('private CAD bootstrap timed out')
|
||||
raise WorkerMonitorError('private CAD bootstrap timed out' + self._dialog_description())
|
||||
time.sleep(0.05)
|
||||
code = probe.poll()
|
||||
if code:
|
||||
failure_type = CadIdentityConflict if code == PRIVATE_CAD_IDENTITY_EXIT_CODE else WorkerMonitorError
|
||||
raise failure_type('private CAD startup failed: ' + probe.stderr.read().decode('utf-8', errors='replace'))
|
||||
self._poll_dialogs('startup')
|
||||
finally:
|
||||
probe.close()
|
||||
try:
|
||||
@@ -151,8 +161,10 @@ class IsolatedCadSession:
|
||||
raise CadIdentityConflict('private CAD bootstrap identity evidence is invalid: ' + str(failure)) from failure
|
||||
self.binding = binding
|
||||
self._record(state='ready', guid=self.binding.guid, startup_seconds=time.monotonic() - self.started)
|
||||
self._start_dialog_monitor()
|
||||
return self
|
||||
except Exception as error:
|
||||
self._stop_dialog_monitor()
|
||||
try:
|
||||
self.desktop.close()
|
||||
except Exception as failure:
|
||||
@@ -167,6 +179,54 @@ class IsolatedCadSession:
|
||||
if self.abort_event is not None and self.abort_event.is_set():
|
||||
raise WorkerMonitorError('private CAD startup was cancelled before execution')
|
||||
|
||||
def _start_dialog_monitor(self):
|
||||
if getattr(self.desktop, 'inspect_dialogs', None) is None:
|
||||
return
|
||||
def monitor():
|
||||
while not self._dialog_stop.wait(.2):
|
||||
self._poll_dialogs('running')
|
||||
self._dialog_thread = Thread(target=monitor, name='owned-cad-dialogs', daemon=True)
|
||||
self._dialog_thread.start()
|
||||
|
||||
def _stop_dialog_monitor(self):
|
||||
self._dialog_stop.set()
|
||||
if self._dialog_thread is not None:
|
||||
self._dialog_thread.join(3)
|
||||
if self._dialog_thread.is_alive():
|
||||
self._dialog_monitor_error = 'CAD dialog monitor did not stop within its budget'
|
||||
|
||||
def _poll_dialogs(self, phase):
|
||||
if self._dialogs is None:
|
||||
return
|
||||
try:
|
||||
self._dialogs.poll(phase)
|
||||
except Exception as error:
|
||||
self._dialog_monitor_error = str(error)
|
||||
self.record['dialog_supervision'] = dict(self._dialogs.summary(), monitor_error=self._dialog_monitor_error)
|
||||
if phase in {'startup', 'checkpoint'} and self._dialogs.failure:
|
||||
raise WorkerMonitorError(self._dialogs.failure + self._dialog_description())
|
||||
|
||||
def _dialog_description(self):
|
||||
if self._dialogs is None or not self._dialogs.records:
|
||||
return ''
|
||||
summary = self._dialogs.summary()
|
||||
titles = ' / '.join(summary['blocking_titles']) or '已记录弹窗'
|
||||
return f';CAD 弹窗:{titles};详情:{summary["evidence_path"]}'
|
||||
|
||||
def _wait_process(self, process, timeout, phase):
|
||||
if getattr(self.desktop, 'inspect_dialogs', None) is None:
|
||||
return process.wait(timeout=timeout)
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
self._poll_dialogs(phase)
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise subprocess.TimeoutExpired(getattr(process, 'args', phase), timeout)
|
||||
try:
|
||||
return process.wait(timeout=min(.25, remaining))
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
|
||||
def start_worker(self, command, *, extra_environment=None, **options):
|
||||
if self.binding is None or self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned private CAD is unavailable')
|
||||
@@ -187,7 +247,7 @@ class IsolatedCadSession:
|
||||
process = self.start_worker(_helper_command('checkpoint', evidence, self.cad.pid),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
code = process.wait(timeout=20)
|
||||
code = self._wait_process(process, 20, 'checkpoint')
|
||||
if code:
|
||||
failure_type = CadIdentityConflict if code == PRIVATE_CAD_IDENTITY_EXIT_CODE else WorkerMonitorError
|
||||
raise failure_type('project close checkpoint failed: ' +
|
||||
@@ -206,6 +266,7 @@ class IsolatedCadSession:
|
||||
return result
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
self._stop_dialog_monitor()
|
||||
closing_started = time.monotonic()
|
||||
cleanup_errors = []
|
||||
diagnostic_errors = []
|
||||
@@ -250,20 +311,25 @@ class IsolatedCadSession:
|
||||
if self.cad is not None and self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned CAD exited before the authorized quit request')
|
||||
if self.cad is not None and self.binding is not None:
|
||||
self._poll_dialogs('closing')
|
||||
closing = self.desktop.start_process(_helper_command('quit', self.root / 'private-desktop.json', self.cad.pid),
|
||||
env=_child_environment(self.binding.environment()), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
quit_code = closing.wait(timeout=20)
|
||||
quit_code = self._wait_process(closing, 20, 'closing')
|
||||
exit_codes['quit_helper_exit_code'] = quit_code
|
||||
if quit_code:
|
||||
raise WorkerMonitorError('owned CAD refused orderly exit: ' + closing.stderr.read().decode('utf-8', errors='replace'))
|
||||
cad_code = self.cad.wait(timeout=15)
|
||||
cad_code = self._wait_process(self.cad, 15, 'closing')
|
||||
exit_codes['cad_exit_code'] = cad_code
|
||||
if cad_code != 0:
|
||||
raise WorkerMonitorError('owned CAD returned a nonzero exit code after quit')
|
||||
self.record['orderly_shutdown'] = True
|
||||
except Exception as failure:
|
||||
remember('orderly_shutdown', failure)
|
||||
remember('orderly_shutdown', WorkerMonitorError(str(failure) + self._dialog_description())
|
||||
if self._dialog_description() else failure)
|
||||
finally:
|
||||
if self._dialogs is not None and (self._dialogs.failure or self._dialog_monitor_error):
|
||||
remember('cad_dialog', WorkerMonitorError(
|
||||
(self._dialogs.failure or self._dialog_monitor_error) + self._dialog_description()))
|
||||
if error is not None or failures:
|
||||
# Evidence failure must never prevent the identity-checked Quit
|
||||
# above or release of the handles we own below.
|
||||
@@ -277,10 +343,14 @@ class IsolatedCadSession:
|
||||
if cad_running:
|
||||
# A refused/timed-out Quit may still be saving or closing.
|
||||
# Keep both CAD and its helper owned and alive until the
|
||||
# interactive caller confirms force, including ordinary stop.
|
||||
# caller confirms force or both retained processes exit.
|
||||
from .stop_control import wait_for_resolution
|
||||
def owned_processes_exited():
|
||||
self._poll_dialogs('closing')
|
||||
return self.cad.poll() is not None and (closing is None or closing.poll() is not None)
|
||||
try:
|
||||
wait_for_resolution(self.stop_control, self.root, failure_message())
|
||||
wait_for_resolution(self.stop_control, self.root, failure_message(),
|
||||
resolved=owned_processes_exited)
|
||||
except WorkerMonitorError as failure:
|
||||
force_event = getattr(self.stop_control, 'force_event', None)
|
||||
if force_event is None or not force_event.is_set():
|
||||
|
||||
@@ -536,6 +536,19 @@ class PrivateDesktop:
|
||||
def __exit__(self, *_exc: object) -> None:
|
||||
self.close()
|
||||
|
||||
def inspect_dialogs(self, pid):
|
||||
from .cad_dialogs import inspect_owned_dialogs
|
||||
if self._handle is None or not any(process.pid == pid and process.poll() is None for process in self._processes):
|
||||
return ()
|
||||
return inspect_owned_dialogs(self._api, self.name, pid)
|
||||
|
||||
def acknowledge_dialog(self, dialog):
|
||||
from .cad_dialogs import acknowledge_owned_dialog
|
||||
pid = dialog['pid']
|
||||
if self._handle is None or not any(process.pid == pid and process.poll() is None for process in self._processes):
|
||||
raise TaskCenterError('private_desktop', 'dialog process is no longer owned and alive')
|
||||
acknowledge_owned_dialog(self._api, self.name, pid, dialog)
|
||||
|
||||
def _create(self) -> None:
|
||||
if os.name != "nt" and self._api is None:
|
||||
return
|
||||
|
||||
@@ -42,11 +42,12 @@ def protect_interruption(root, reason):
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def wait_for_resolution(control, root, error):
|
||||
"""Interactive owners retain a possibly changed project until explicit force.
|
||||
def wait_for_resolution(control, root, error, *, resolved=None):
|
||||
"""Retain uncertain work until explicit force or an owned-exit proof.
|
||||
|
||||
The GUI-side supervisor can also terminate its own Job after durable force
|
||||
evidence. Ordinary cancellation never releases this wait.
|
||||
evidence. Ordinary cancellation never releases this wait; an optional
|
||||
observer may prove all retained processes exited without clearing uncertainty.
|
||||
"""
|
||||
if not isinstance(control, StopControl):
|
||||
return
|
||||
@@ -71,6 +72,9 @@ def wait_for_resolution(control, root, error):
|
||||
resolution_error=str(error), stop_requested=True, safe_stop=False)
|
||||
_publish_progress(root / 'worker-progress.json', record)
|
||||
while True:
|
||||
if resolved is not None and resolved():
|
||||
control.waiting_for_resolution = False
|
||||
return
|
||||
if control.force_event.wait(.1):
|
||||
try:
|
||||
protect()
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
"""Owned modal-dialog samples; no CAD, project modifications, or PCB."""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def script_dialog(**changes):
|
||||
row = {'hwnd': 10, 'pid': 123, 'class': '#32770', 'title': 'Script Error',
|
||||
'text': 'Microsoft VBScript compilation error\nName redefined: VdFoo', 'complete': True,
|
||||
'buttons': [{'hwnd': 11, 'id': 1, 'text': 'OK', 'enabled': True}]}
|
||||
return dict(row, **changes)
|
||||
|
||||
|
||||
def test_known_script_error_is_recorded_before_acknowledgement_and_remains_failure(tmp_path):
|
||||
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
|
||||
path = tmp_path / 'cad-dialogs.json'
|
||||
rows, acknowledged = [script_dialog()], []
|
||||
def acknowledge(row):
|
||||
assert json.loads(path.read_text(encoding='utf-8'))['dialogs'][0]['action'] == 'acknowledge_script_error'
|
||||
acknowledged.append(row['hwnd'])
|
||||
rows.clear()
|
||||
desktop = SimpleNamespace(inspect_dialogs=lambda pid: tuple(rows), acknowledge_dialog=acknowledge)
|
||||
guard = CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: None), path, 'session')
|
||||
guard.poll('closing')
|
||||
guard.poll('closing')
|
||||
assert acknowledged == [10]
|
||||
assert 'compilation error' in guard.failure
|
||||
assert guard.summary()['evidence_path'] == str(path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('row', [
|
||||
script_dialog(pid=999),
|
||||
script_dialog(title='Save Changes', text='Save changes to Board.prj?'),
|
||||
script_dialog(title='License Error', text='License unavailable'),
|
||||
script_dialog(title='DxDesigner', text='Unknown warning'),
|
||||
script_dialog(complete=False),
|
||||
script_dialog(buttons=[{'hwnd': 11, 'id': 1, 'text': 'OK', 'enabled': True},
|
||||
{'hwnd': 12, 'id': 2, 'text': 'Cancel', 'enabled': True}]),
|
||||
])
|
||||
def test_other_prompts_and_foreign_windows_are_never_automatically_clicked(tmp_path, row):
|
||||
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
|
||||
path = tmp_path / 'cad-dialogs.json'
|
||||
desktop = SimpleNamespace(inspect_dialogs=lambda pid: (row,),
|
||||
acknowledge_dialog=lambda _: pytest.fail('unsafe/foreign prompt clicked'))
|
||||
guard = CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: None), path, 'session')
|
||||
guard.poll('startup')
|
||||
if row['pid'] == 123:
|
||||
assert guard.summary()['blocked']
|
||||
assert json.loads(path.read_text(encoding='utf-8'))['dialogs'][0]['action'] == 'manual_required'
|
||||
else:
|
||||
assert not path.exists()
|
||||
|
||||
|
||||
def test_evidence_failure_prevents_automatic_acknowledgement(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import cad_dialogs
|
||||
desktop = SimpleNamespace(inspect_dialogs=lambda pid: (script_dialog(),),
|
||||
acknowledge_dialog=lambda _: pytest.fail('unrecorded prompt clicked'))
|
||||
guard = cad_dialogs.CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: None),
|
||||
tmp_path / 'cad-dialogs.json', 'session')
|
||||
monkeypatch.setattr(cad_dialogs, 'write_record', lambda *_: (_ for _ in ()).throw(OSError('disk unavailable')))
|
||||
with pytest.raises(OSError, match='disk unavailable'):
|
||||
guard.poll('closing')
|
||||
|
||||
|
||||
def test_dialogs_are_not_repeatedly_clicked_when_they_do_not_close(tmp_path):
|
||||
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
|
||||
acknowledged = []
|
||||
desktop = SimpleNamespace(inspect_dialogs=lambda pid: (script_dialog(),),
|
||||
acknowledge_dialog=lambda row: acknowledged.append(row['hwnd']))
|
||||
guard = CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: None),
|
||||
tmp_path / 'cad-dialogs.json', 'session')
|
||||
for _ in range(5):
|
||||
guard.poll('closing')
|
||||
assert acknowledged == [10]
|
||||
assert guard.summary()['blocked']
|
||||
|
||||
|
||||
def test_guard_ignores_a_completed_process(tmp_path):
|
||||
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
|
||||
desktop = SimpleNamespace(inspect_dialogs=lambda pid: pytest.fail('exited PID inspected'))
|
||||
guard = CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: 0),
|
||||
tmp_path / 'cad-dialogs.json', 'session')
|
||||
guard.poll('closing')
|
||||
|
||||
|
||||
def test_evidence_limit_still_latches_fatal_error_without_unrecorded_click(tmp_path):
|
||||
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
|
||||
rows = [script_dialog(title='Unknown', text='initial')]
|
||||
desktop = SimpleNamespace(inspect_dialogs=lambda pid: tuple(rows),
|
||||
acknowledge_dialog=lambda row: pytest.fail('evidence limit cannot authorize another click'))
|
||||
guard = CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: None),
|
||||
tmp_path / 'cad-dialogs.json', 'session')
|
||||
for number in range(100):
|
||||
rows[0] = script_dialog(title='Unknown', text=str(number))
|
||||
guard.poll('running')
|
||||
rows[0] = script_dialog()
|
||||
guard.poll('closing')
|
||||
assert guard.failure and len(guard.records) == 100
|
||||
|
||||
|
||||
def test_batch_desktop_lease_delegates_dialogs_only_for_its_current_owned_process(tmp_path):
|
||||
from dx_productivity.trial_task_center.batch_runtime import _DesktopLease
|
||||
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
|
||||
calls = []
|
||||
desktop = SimpleNamespace(inspect_dialogs=lambda pid: calls.append(pid) or (script_dialog(),),
|
||||
acknowledge_dialog=lambda row: calls.append('ack'))
|
||||
owner = SimpleNamespace(generation=1)
|
||||
lease = _DesktopLease(owner, tmp_path)
|
||||
lease.desktop, lease.generation = desktop, 1
|
||||
lease.processes = [SimpleNamespace(pid=123, poll=lambda: None)]
|
||||
assert lease.inspect_dialogs(123) == (script_dialog(),)
|
||||
lease.acknowledge_dialog(script_dialog())
|
||||
assert not lease.inspect_dialogs(999)
|
||||
owner.generation = 2
|
||||
assert not lease.inspect_dialogs(123)
|
||||
with pytest.raises(WorkerMonitorError, match='stale'):
|
||||
lease.acknowledge_dialog(script_dialog())
|
||||
assert calls == [123, 'ack']
|
||||
|
||||
|
||||
def test_session_acknowledges_known_error_then_quits_without_claiming_success(tmp_path, monkeypatch):
|
||||
from test_isolated_cad import fake_desktop
|
||||
from dx_productivity.trial_task_center import isolated_cad as runtime
|
||||
events, cad = fake_desktop(monkeypatch, tmp_path)
|
||||
session = runtime.IsolatedCadSession(tmp_path)
|
||||
session.__enter__()
|
||||
rows = [script_dialog()]
|
||||
session.desktop.inspect_dialogs = lambda pid: tuple(rows)
|
||||
session.desktop.acknowledge_dialog = lambda row: rows.clear()
|
||||
with pytest.raises(runtime.WorkerMonitorError, match='script error'):
|
||||
session.__exit__(None, None, None)
|
||||
assert not rows and events.count('quit') == 1
|
||||
assert cad.poll() == 0 and session.record['orderly_shutdown']
|
||||
assert session.record['clean'] is False
|
||||
assert (tmp_path / 'uncertain.flag').exists()
|
||||
|
||||
|
||||
def test_startup_script_error_is_acknowledged_and_cannot_enter_project_work(tmp_path, monkeypatch):
|
||||
from test_isolated_cad import fake_desktop
|
||||
from dx_productivity.trial_task_center import isolated_cad as runtime
|
||||
events, cad = fake_desktop(monkeypatch, tmp_path)
|
||||
rows = [script_dialog()]
|
||||
monkeypatch.setattr(runtime.PrivateDesktop, 'inspect_dialogs', lambda self, pid: tuple(rows), raising=False)
|
||||
monkeypatch.setattr(runtime.PrivateDesktop, 'acknowledge_dialog', lambda self, row: rows.clear(), raising=False)
|
||||
with pytest.raises(runtime.PrivateCadStartupError, match='compilation error'):
|
||||
with runtime.IsolatedCadSession(tmp_path):
|
||||
pytest.fail('acknowledging a fatal popup must not authorize project work')
|
||||
assert not rows and cad.poll() is not None
|
||||
assert ('release', False) in events
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Win32 action boundary')
|
||||
def test_changed_prompt_or_recycled_window_handle_is_not_acknowledged(tmp_path, monkeypatch):
|
||||
import win32gui
|
||||
from dx_productivity.trial_task_center import cad_dialogs
|
||||
expected = script_dialog()
|
||||
monkeypatch.setattr(cad_dialogs, 'inspect_owned_dialogs',
|
||||
lambda *_: (script_dialog(title='Save Changes', text='Save changes?'),))
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', lambda *_: pytest.fail('changed HWND clicked'))
|
||||
with pytest.raises(OSError, match='changed'):
|
||||
cad_dialogs.acknowledge_owned_dialog(None, 'dx-owned', 123, expected)
|
||||
|
||||
|
||||
def test_protected_wait_finishes_when_user_dismisses_dialog_and_owned_processes_exit(tmp_path, monkeypatch):
|
||||
from threading import Event, Thread
|
||||
from test_isolated_cad import fake_desktop
|
||||
from dx_productivity.trial_task_center import isolated_cad as runtime
|
||||
from dx_productivity.trial_task_center.stop_control import StopControl
|
||||
from dx_productivity.trial_task_center import worker_monitor
|
||||
events, cad = fake_desktop(monkeypatch, tmp_path, cad_exit_code=None)
|
||||
control = StopControl()
|
||||
session = runtime.IsolatedCadSession(tmp_path, stop_control=control)
|
||||
session.__enter__()
|
||||
rows = [script_dialog(title='Save Changes', text='Save changes to Board.prj?')]
|
||||
session.desktop.inspect_dialogs = lambda pid: tuple(rows)
|
||||
session.desktop.acknowledge_dialog = lambda row: pytest.fail('save prompt clicked')
|
||||
start = session.desktop.start_process
|
||||
def start_quit(command, **kwargs):
|
||||
process = start(command, **kwargs)
|
||||
if command[0] == 'quit':
|
||||
process.wait = lambda timeout: (_ for _ in ()).throw(subprocess.TimeoutExpired('quit', timeout))
|
||||
process.poll = lambda: None if rows else 0
|
||||
return process
|
||||
session.desktop.start_process = start_quit
|
||||
# Exercise timeout recovery without waiting for the normal 20 second budget.
|
||||
clock = [0.0]
|
||||
monkeypatch.setattr(runtime.time, 'monotonic', lambda: clock[0])
|
||||
session.desktop.inspect_dialogs = lambda pid: (clock.__setitem__(0, clock[0] + 21) or tuple(rows))
|
||||
waiting, finished = Event(), Event()
|
||||
publish = worker_monitor._publish_progress
|
||||
def observe(path, snapshot):
|
||||
publish(path, snapshot)
|
||||
if snapshot.get('stage') == 'awaiting_reconciliation':
|
||||
waiting.set()
|
||||
monkeypatch.setattr(worker_monitor, '_publish_progress', observe)
|
||||
errors = []
|
||||
def close():
|
||||
try:
|
||||
session.__exit__(None, None, None)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
finally:
|
||||
finished.set()
|
||||
thread = Thread(target=close)
|
||||
thread.start()
|
||||
try:
|
||||
assert waiting.wait(2)
|
||||
assert not finished.is_set() and cad.poll() is None
|
||||
rows.clear() # The operator handled the unknown prompt.
|
||||
cad.returncode = 0
|
||||
assert finished.wait(2), 'completed owned processes must release without requiring force'
|
||||
assert not control.force_event.is_set()
|
||||
assert errors and session.record['clean'] is False
|
||||
assert events.count('quit') == 1 and (tmp_path / 'uncertain.flag').exists()
|
||||
finally:
|
||||
control.request_force()
|
||||
thread.join(3)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Native owned private-desktop MessageBox samples')
|
||||
@pytest.mark.parametrize('known', [True, False])
|
||||
def test_real_private_desktop_messagebox_is_handled_without_touching_input_desktop(tmp_path, known):
|
||||
import sys
|
||||
import time
|
||||
from uuid import uuid4
|
||||
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
|
||||
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
|
||||
text = 'Microsoft VBScript compilation error\nName redefined: VdFoo' if known else 'Save changes to Board.prj?'
|
||||
title = 'Script Error' if known else 'Save Changes'
|
||||
code = 'import ctypes; ctypes.windll.user32.MessageBoxW(None, ' + repr(text) + ', ' + repr(title) + ', 0)'
|
||||
with PrivateDesktop('dx-' + uuid4().hex, enabled=True) as desktop:
|
||||
process = desktop.start_process((sys.executable, '-c', code))
|
||||
guard = CadDialogGuard(desktop, process, tmp_path / 'cad-dialogs.json', 'sample')
|
||||
deadline = time.monotonic() + 10
|
||||
while not (guard.failure if known else guard.summary()['dialogs_seen']) and time.monotonic() < deadline:
|
||||
guard.poll('closing')
|
||||
time.sleep(.05)
|
||||
assert guard.summary()['dialogs_seen'] >= 1
|
||||
if known:
|
||||
assert guard.records[-1]['action'] == 'acknowledge_script_error', guard.records
|
||||
assert process.wait(timeout=3) == 0
|
||||
assert guard.failure
|
||||
else:
|
||||
assert process.poll() is None
|
||||
assert guard.summary()['blocked']
|
||||
assert desktop.cleanup_record['desktop_confirmation']['released']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('directory', ['tasks/task/quick-run', 'batch-resources/batch/generation-1'])
|
||||
def test_dialog_evidence_is_in_diagnostic_bundle_and_scrubbed(tmp_path, directory):
|
||||
import zipfile
|
||||
from dx_productivity.trial_task_center.diagnostics_bundle import export_diagnostic_bundle
|
||||
path = tmp_path / 'data' / directory / ('cad-dialogs-' + 'a' * 32 + '.json')
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text(json.dumps({'text': 'C:/Users/Alice/Board/script.vbs'}), encoding='utf-8')
|
||||
bundle = export_diagnostic_bundle(tmp_path / 'data', tmp_path / 'diagnostics.zip')
|
||||
with zipfile.ZipFile(bundle) as archive:
|
||||
content = archive.read(path.relative_to(tmp_path / 'data').as_posix()).decode()
|
||||
assert 'Alice' not in content and '<USER_HOME>' in content
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Native modal dialog while the business thread waits')
|
||||
def test_dialog_is_serviced_while_business_thread_is_blocked(tmp_path):
|
||||
import sys
|
||||
from dx_productivity.trial_task_center import isolated_cad as runtime
|
||||
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime, _DesktopLease
|
||||
code = "import ctypes; ctypes.windll.user32.MessageBoxW(None, 'Microsoft VBScript compilation error', 'Script Error', 0)"
|
||||
with BatchCadRuntime(tmp_path / 'runtime', 'dialog-sample') as batch:
|
||||
lease = _DesktopLease(batch, tmp_path)
|
||||
lease.__enter__()
|
||||
process = lease.start_process((sys.executable, '-c', code))
|
||||
session = runtime.IsolatedCadSession(tmp_path, desktop=lease)
|
||||
session.cad = process
|
||||
session._dialogs = CadDialogGuard(lease, process, tmp_path / 'cad-dialogs.json', session.token)
|
||||
session._start_dialog_monitor()
|
||||
try:
|
||||
assert process.wait(timeout=5) == 0 # No polling from this blocked thread.
|
||||
assert session._dialogs.failure
|
||||
finally:
|
||||
session._stop_dialog_monitor()
|
||||
lease.close()
|
||||
assert not session._dialog_thread.is_alive()
|
||||
assert batch.desktop.cleanup_record['desktop_confirmation']['released']
|
||||
Reference in new issue
Block a user