import threading from cbb_refresh_verify import application from cbb_refresh_verify.dialog_agent import ( ActionResult, DialogActionExecutor, DialogAgentClient, DialogAgentServer, ) from cbb_refresh_verify.dialog_models import ( ControlSnapshot, DialogPhase, WindowSnapshot, stable_fingerprint, compatible_window_identity, ) def snapshot(title="Prompt"): return WindowSnapshot( hwnd=10, pid=20, process_name="ExpeditionPCB.exe", process_role="pcb", window_class="GXWND", title=title, phase=DialogPhase.PCB_STARTING, controls=(ControlSnapshot(11, 1, "Button", "OK", control_type="Button"),), ) class FakeProbe: def __init__(self, value): self.value = value def capture(self, phase): return (self.value,) if self.value is not None else () def capture_one(self, hwnd, phase): return self.value if self.value is not None and self.value.hwnd == hwnd else None class FakeExecutor: def __init__(self): self.calls = [] def perform(self, snapshot_value, action): self.calls.append((snapshot_value, action)) return ActionResult(channel="uia_invoke", accepted_controls=(1,)) def running_protocol(tmp_path, probe, executor=None): client = DialogAgentClient.prepare(tmp_path, desktop_name="test", timeout_seconds=2) server = DialogAgentServer.from_config(client.paths.config, probe=probe, executor=executor) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() return client, server, thread def test_agent_correlates_observe_response_by_request_id(tmp_path): client, server, thread = running_protocol(tmp_path, FakeProbe(snapshot())) try: reply = client.observe(DialogPhase.PCB_STARTING) finally: client.close() thread.join(timeout=2) assert reply[0].window_class == "GXWND" assert server.requests[0]["request_id"] == server.responses[0]["request_id"] assert server.responses[0]["sequence"] == 1 def test_agent_rejects_stale_action_fingerprint(tmp_path): executor = FakeExecutor() client, _server, thread = running_protocol(tmp_path, FakeProbe(snapshot("Changed")), executor) try: result = client.perform( hwnd=10, fingerprint=stable_fingerprint(snapshot("Old")), action={"channels": ["uia_invoke"], "action": "confirm"}, phase=DialogPhase.PCB_STARTING, ) finally: client.close() thread.join(timeout=2) assert result.error_code == "STALE_DIALOG" assert executor.calls == [] def test_agent_perform_uses_observed_snapshot_when_refresh_probe_blocks(tmp_path): class BlockingRefreshProbe(FakeProbe): def capture_one(self, hwnd, phase): raise RuntimeError("refresh probe blocked by native license dialog") executor = FakeExecutor() value = snapshot() client, server, thread = running_protocol( tmp_path, BlockingRefreshProbe(value), executor ) try: observed = client.observe(DialogPhase.PCB_STARTING) result = client.perform( hwnd=value.hwnd, fingerprint=stable_fingerprint(observed[0]), action={"channels": ["uia_invoke"], "action": "confirm"}, phase=DialogPhase.PCB_STARTING, ) finally: client.close() thread.join(timeout=2) assert result.accepted_controls == (1,) assert executor.calls == [(value, {"channels": ["uia_invoke"], "action": "confirm"})] def test_window_identity_allows_control_tree_changes_during_initialization(): original = snapshot('') changed = WindowSnapshot( hwnd=original.hwnd, pid=original.pid, process_name=original.process_name, process_role=original.process_role, window_class=original.window_class, title=original.title, phase=original.phase, controls=original.controls + ( ControlSnapshot(12, 2, 'Button', 'Cancel', control_type='Button'), ), ) assert compatible_window_identity(original, changed) def test_hidden_agent_route_runs_before_qt(monkeypatch, tmp_path): called = [] monkeypatch.setattr( "cbb_refresh_verify.dialog_agent.dialog_agent_main", lambda path: called.append(path) or 17, ) code = application.main(["--dialog-agent", str(tmp_path / "agent.json")]) assert code == 17 assert called == [tmp_path / "agent.json"] def test_desktop_worker_companion_uses_same_desktop_and_job(monkeypatch): import cbb_refresh_verify.desktop_worker as module starts = [] assignments = [] class Startup: lpDesktop = "" class Handle: def Close(self): pass monkeypatch.setattr(module.win32process, "STARTUPINFO", Startup) monkeypatch.setattr( module.win32process, "CreateProcess", lambda *args: starts.append(args) or (Handle(), Handle(), 321, 1), ) monkeypatch.setattr( module.win32job, "AssignProcessToJobObject", lambda job, handle: assignments.append((job, handle)), ) worker = module.DesktopWorker.__new__(module.DesktopWorker) worker.name = "PrivateDesk" worker.job = object() worker.job_bound = True worker.companions = [] pid = worker.start_companion(["python", "--dialog-agent", "config.json"]) assert pid == 321 assert starts[0][-1].lpDesktop == "winsta0\\PrivateDesk" assert assignments and len(worker.companions) == 1 def test_license_action_selects_unique_uia_license_before_ok(): selected = [] class Wrapper: def select(self): selected.append('license') controls = ( ControlSnapshot(11, 1522, 'GXWND', 'Product license', control_type='ListItem', patterns=('SelectionItem',)), ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button', patterns=('Invoke',)), ) value = snapshot() value = WindowSnapshot(**{**value.__dict__, 'controls': controls}) executor = DialogActionExecutor(uia_wrapper=lambda _handle: Wrapper()) result = executor.perform(value, { 'action': 'accept_license', 'channels': ['uia_select', 'uia_invoke', 'win32_button_click'], }) assert result.channel == 'uia_select' assert result.accepted_controls == (1522,) assert selected == ['license'] def test_license_action_invokes_ok_only_after_selection(): invoked = [] class Wrapper: def invoke(self): invoked.append('ok') controls = ( ControlSnapshot(11, 1522, 'GXWND', 'Product license', control_type='ListItem', selected=True, patterns=('SelectionItem',)), ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button', patterns=('Invoke',)), ) value = snapshot() value = WindowSnapshot(**{**value.__dict__, 'controls': controls}) executor = DialogActionExecutor(uia_wrapper=lambda _handle: Wrapper()) result = executor.perform(value, { 'action': 'accept_license', 'channels': ['uia_select', 'uia_invoke', 'win32_button_click'], }) assert result.channel == 'uia_invoke' assert result.accepted_controls == (1,) assert invoked == ['ok'] def test_license_selector_can_use_targeted_private_window_message(): messages = [] class Gui: def PostMessage(self, hwnd, message, wparam, lparam): messages.append((hwnd, message, wparam, lparam)) value = snapshot('') controls = ( ControlSnapshot(11, 5225, 'Button', 'Select the desired product license', control_type='Button'), ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button'), ) value = WindowSnapshot(**{**value.__dict__, 'controls': controls}) executor = DialogActionExecutor(win32gui=Gui(), uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable'))) result = executor.perform(value, { 'action': 'accept_license', 'channels': ['win32_mouse_click'], }) assert result.channel == 'win32_mouse_click' assert result.accepted_controls == (1,) assert [item[0] for item in messages] == [12, 12] def test_license_selector_sends_center_click_and_parent_command_for_custom_button(): posted = [] sent = [] class Gui: def GetWindowRect(self, hwnd): assert hwnd == 12 return (100, 200, 180, 240) def PostMessage(self, hwnd, message, wparam, lparam): posted.append((hwnd, message, wparam, lparam)) def SendMessage(self, hwnd, message, wparam, lparam): sent.append((hwnd, message, wparam, lparam)) value = snapshot('') controls = ( ControlSnapshot(11, 5225, 'Button', 'Select the desired product license', control_type='Button'), ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button'), ) value = WindowSnapshot(**{**value.__dict__, 'hwnd': 99, 'controls': controls}) executor = DialogActionExecutor(win32gui=Gui(), uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable'))) result = executor.perform(value, { 'action': 'accept_license', 'channels': ['win32_mouse_click'], }) assert result.channel == 'win32_mouse_click' assert result.accepted_controls == (1,) assert posted == [] assert sent == [(12, 0x0201, 1, (20 << 16) | 40), (12, 0x0202, 0, (20 << 16) | 40), (99, 0x0111, 1, 12)] def test_license_action_targets_ok_when_license_pane_has_no_selectable_item(): controls = ( ControlSnapshot(11, 5225, 'Button', 'Select the desired product license', control_type='Group'), ControlSnapshot(12, 1522, 'GXWND', 'Select the desired product license', control_type='Pane'), ControlSnapshot(13, 1, 'Button', 'OK', control_type='Button'), ) value = snapshot('') value = WindowSnapshot(**{**value.__dict__, 'controls': controls}) executor = DialogActionExecutor( win32gui=type('Gui', (), {'PostMessage': lambda *_args: None})(), uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable')), ) result = executor.perform(value, { 'action': 'accept_license', 'channels': ['win32_mouse_click'], }) assert result.accepted_controls == (1,) def test_license_ok_button_prefers_nonblocking_win32_button_click(): class Gui: def __init__(self): self.messages = [] def PostMessage(self, hwnd, message, wparam, lparam): self.messages.append((hwnd, message, wparam, lparam)) value = snapshot('') controls = ( ControlSnapshot(11, 5225, 'Button', 'Select the desired product license', control_type='Button'), ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button'), ) value = WindowSnapshot(**{**value.__dict__, 'controls': controls}) gui = Gui() executor = DialogActionExecutor( win32gui=gui, uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable')), ) result = executor.perform(value, { 'action': 'accept_license', 'channels': ['interface', 'uia_select', 'uia_invoke', 'win32_button_click', 'win32_mouse_click'], }) assert result.channel == 'win32_button_click' assert result.accepted_controls == (1,) assert gui.messages and gui.messages[0][0] == 12 def test_database_restoration_selects_last_user_saved_before_ok(): selected = [] posted = [] class Wrapper: def select(self): selected.append('last-saved') class Gui: def PostMessage(self, hwnd, message, wparam, lparam): posted.append((hwnd, message, wparam, lparam)) controls = ( ControlSnapshot(11, 6213, 'Button', 'Load the last user saved database dated 2026/9/24 22:52.', control_type='RadioButton', patterns=('SelectionItem',)), ControlSnapshot(12, 6206, 'Button', 'Load the autosave database dated 2026/9/24 22:52.', control_type='RadioButton', selected=True, patterns=('SelectionItem',)), ControlSnapshot(13, 1, 'Button', 'OK', control_type='Button', patterns=('Invoke',)), ) value = snapshot('Database Restoration') value = WindowSnapshot(**{**value.__dict__, 'controls': controls}) executor = DialogActionExecutor(win32gui=Gui(), uia_wrapper=lambda _handle: Wrapper()) result = executor.perform(value, { 'action': 'restore_last_saved', 'channels': ['uia_select', 'win32_button_click', 'uia_invoke'], }) assert result.channel == 'win32_button_click' assert result.accepted_controls == (6213,) assert selected == [] assert posted and posted[0][0] == 11 def test_agent_polling_does_not_write_request_response_capture_files(tmp_path): client, server, thread = running_protocol(tmp_path, FakeProbe(snapshot())) try: for _ in range(80): assert client.observe(DialogPhase.PCB_STARTING)[0].hwnd == 10 assert not list(tmp_path.glob('*.jsonl')) assert len(server.requests) <= 1 assert len(server.responses) <= 1 finally: client.close() thread.join(timeout=2) assert not thread.is_alive() def test_agent_start_failure_releases_listener(tmp_path): import pytest class FailedWorker: name = 'test' def start_companion(self, command): raise RuntimeError('cannot create companion') with pytest.raises(RuntimeError, match='cannot create companion'): DialogAgentClient.start(FailedWorker(), tmp_path) def _slow_start_client(tmp_path, monkeypatch, *, delay, stop=None): import socket from types import SimpleNamespace from cbb_refresh_verify import dialog_agent as module client = DialogAgentClient.prepare(tmp_path, desktop_name='test') client.listener.close() elapsed = [0.0] class Listener: closed = False def settimeout(self, timeout): self.timeout = timeout def accept(self): if elapsed[0] < delay: elapsed[0] += self.timeout if stop is not None and elapsed[0] >= .4: stop.set() raise socket.timeout() return SimpleNamespace(setsockopt=lambda *a: None), None def close(self): self.closed = True class Channel: def __init__(self, connection): pass def receive(self, timeout): return {'token': client.paths.token} def send(self, *a): pass def close(self): pass client.listener = Listener() monkeypatch.setattr(module, 'JsonChannel', Channel) monkeypatch.setattr(module.time, 'monotonic', lambda: elapsed[0]) monkeypatch.setattr(DialogAgentClient, 'prepare', classmethod(lambda cls, *a, **k: client)) worker = SimpleNamespace(name='test', start_companion=lambda command: None) return client, worker, elapsed def test_frozen_agent_can_initialize_after_the_old_ten_second_deadline(tmp_path, monkeypatch): client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=12) assert DialogAgentClient.start(worker, tmp_path) is client assert elapsed[0] >= 12 and client.channel is not None assert client.timeout_seconds == 2 # Normal IPC does not inherit the startup budget. def test_agent_startup_wait_responds_to_cancel_without_starting_pcb(tmp_path, monkeypatch): import pytest from threading import Event stop = Event() client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=100, stop=stop) with pytest.raises(InterruptedError, match='VERIFY_CANCELLED'): DialogAgentClient.start(worker, tmp_path, stop=stop) assert elapsed[0] < 1 and client.listener.closed def test_agent_startup_still_has_an_absolute_deadline(tmp_path, monkeypatch): import pytest client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=100) with pytest.raises(TimeoutError): DialogAgentClient.start(worker, tmp_path) assert 29 <= elapsed[0] <= 31 and client.listener.closed def test_cancellation_during_authenticated_handshake_never_releases_startup(tmp_path, monkeypatch): import pytest from threading import Event from cbb_refresh_verify import dialog_agent as module stop = Event() client, worker, _ = _slow_start_client(tmp_path, monkeypatch, delay=0) class Channel: def __init__(self, connection): pass def receive(self, timeout): stop.set() return {'token': client.paths.token} def close(self): pass monkeypatch.setattr(module, 'JsonChannel', Channel) with pytest.raises(InterruptedError, match='VERIFY_CANCELLED'): DialogAgentClient.start(worker, tmp_path, stop=stop) assert client.channel is None and client.listener.closed def test_memory_channel_timeout_is_bounded_and_partial_packets_survive(): import socket import pytest from cbb_refresh_verify.dialog_agent import JsonChannel a, b = socket.socketpair() channel = JsonChannel(a) try: b.sendall(b'{"value":') with pytest.raises(TimeoutError): channel.receive(.05) b.sendall(b'17}\n') assert channel.receive(.5) == {'value': 17} b.close() with pytest.raises(EOFError): channel.receive(.5) finally: channel.close() b.close() def test_loopback_connection_rejects_wrong_agent_token(tmp_path): import socket import pytest from cbb_refresh_verify.dialog_agent import JsonChannel, DialogAgentProtocolError client = DialogAgentClient.prepare(tmp_path, desktop_name='test', timeout_seconds=2) wrong = JsonChannel(socket.create_connection(('127.0.0.1', client.paths.port), timeout=1)) try: wrong.send({'token': 'not-the-agent'}) with pytest.raises(DialogAgentProtocolError, match='authentication failed'): client.observe(DialogPhase.PCB_STARTING) finally: wrong.close() client.close()