"""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'] # Explicitly dismiss our disposable sample after proving no automatic click. dialog, = guard.summary()['current_dialogs'] guard.manual_action(dialog, dialog['buttons'][0]['hwnd']) assert process.wait(timeout=3) == 0 assert desktop.cleanup_record['desktop_confirmation']['released'] assert not any(row.get('forced_termination') for row in desktop.cleanup_record['processes']) @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 '' 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']