Files
cbb-refresh-verify-795/src/cbb_refresh_verify/dialog_agent.py
T

552 lines
24 KiB
Python

"""Private-desktop dialog agent with bounded, in-memory loopback IPC."""
from __future__ import annotations
from dataclasses import asdict, dataclass
import json
import socket
from collections import deque
from pathlib import Path
import subprocess
import sys
import time
from uuid import uuid4
from .dialog_models import (
DialogPhase,
WindowSnapshot,
compatible_window_identity,
stable_fingerprint,
)
from .dialog_probe import WindowProbe, WindowProbeError
SCHEMA_VERSION = 1
class DialogAgentProtocolError(RuntimeError):
pass
@dataclass(frozen=True)
class ActionResult:
channel: str = ""
accepted_controls: tuple[int, ...] = ()
error_code: str = ""
detail: str = ""
def to_record(self):
return asdict(self)
@classmethod
def from_record(cls, record):
values = dict(record or {})
values["accepted_controls"] = tuple(values.get("accepted_controls", ()))
return cls(**values)
@dataclass(frozen=True)
class AgentPaths:
config: Path
port: int
token: str
@classmethod
def from_config(cls, config_path: Path) -> "AgentPaths":
config_path = Path(config_path)
document = json.loads(config_path.read_text(encoding="utf-8"))
if document.get("schema_version") != SCHEMA_VERSION:
raise DialogAgentProtocolError("Unsupported dialog-agent schema")
return cls(config_path, int(document["port"]), str(document["token"]))
class JsonChannel:
"""One connection, newline-framed JSON, no polling traffic written to disk."""
def __init__(self, connection):
self.connection = connection
self.buffer = b""
def send(self, document, timeout_seconds=2.0):
self.connection.settimeout(timeout_seconds)
payload = json.dumps(document, ensure_ascii=False).encode("utf-8") + b"\n"
self.connection.sendall(payload)
def receive(self, timeout_seconds):
deadline = time.monotonic() + timeout_seconds
while b"\n" not in self.buffer:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("dialog-agent receive timed out")
self.connection.settimeout(remaining)
data = self.connection.recv(65536)
if not data:
raise EOFError("dialog-agent disconnected")
self.buffer += data
if len(self.buffer) > 8 * 1024 * 1024:
raise DialogAgentProtocolError("dialog-agent message too large")
line, self.buffer = self.buffer.split(b"\n", 1)
return json.loads(line.decode("utf-8"))
def close(self):
self.connection.close()
def dialog_agent_command(config_path: Path):
if getattr(sys, "frozen", False):
return [sys.executable, "--dialog-agent", str(config_path)]
return [sys.executable, "-m", "cbb_refresh_verify", "--dialog-agent", str(config_path)]
class DialogActionExecutor:
def __init__(self, *, win32gui=None, win32con=None, uia_wrapper=None):
if win32gui is None:
import win32gui as win32gui_module
win32gui = win32gui_module
if win32con is None:
import win32con as win32con_module
win32con = win32con_module
self.win32gui = win32gui
self.win32con = win32con
self.uia_wrapper = uia_wrapper or self._default_uia_wrapper
@staticmethod
def _default_uia_wrapper(handle):
from pywinauto import Desktop
return Desktop(backend="uia").window(handle=handle).wrapper_object()
@staticmethod
def _target(snapshot: WindowSnapshot, target: dict):
candidates = tuple(control for control in snapshot.controls if control.enabled)
if "control_id" in target:
candidates = tuple(c for c in candidates if c.control_id == int(target["control_id"]))
if "automation_id" in target:
candidates = tuple(c for c in candidates if c.automation_id == str(target["automation_id"]))
if "control_type" in target:
candidates = tuple(c for c in candidates
if c.control_type.casefold() == str(target["control_type"]).casefold())
if "name_contains" in target:
token = str(target["name_contains"]).casefold()
candidates = tuple(c for c in candidates if token in c.name.casefold())
if not target:
candidates = tuple(c for c in candidates
if c.class_name.casefold() == "button"
and c.control_id in {1, 6})
return candidates[0] if len(candidates) == 1 else None
@staticmethod
def _license_target(snapshot: WindowSnapshot):
selectors = tuple(
control for control in snapshot.controls
if control.enabled and (
"selectionitem" in {value.casefold() for value in control.patterns}
or control.control_type.casefold() == "listitem"
)
)
if any(control.selected or control.checked for control in selectors):
confirmations = tuple(
control for control in snapshot.controls
if control.enabled and control.class_name.casefold() == "button"
and control.control_id == 1
)
return confirmations[0] if len(confirmations) == 1 else None
unselected = tuple(control for control in selectors
if not control.selected and not control.checked)
if len(unselected) == 1:
return unselected[0]
# Some EE7.9 installations expose the license chooser as a GXWND
# pane without exposing any selectable child. Clicking that pane (or
# its group button) is a no-op; the dialog's default license is
# accepted by the real OK control instead. Prefer that confirmation
# target whenever no SelectionItem/ListItem was found.
confirmations = tuple(
control for control in snapshot.controls
if control.enabled and control.class_name.casefold() == "button"
and control.control_id == 1
)
if len(confirmations) == 1:
return confirmations[0]
opener = tuple(
control for control in snapshot.controls
if control.enabled and control.class_name.casefold() == "button"
and control.control_id == 5225
)
return opener[0] if len(opener) == 1 else None
@staticmethod
def _restore_database_target(snapshot: WindowSnapshot):
"""Select the user-saved database before confirming restoration."""
controls = tuple(control for control in snapshot.controls if control.enabled)
marker = ("last user saved database", "最后一次用户保存", "最后保存", "用户保存")
choice = next(
(control for control in controls
if control.control_type.casefold() in {"radiobutton", "button", "listitem"}
and any(token in control.name.casefold() for token in marker)
and not (control.selected or control.checked)),
None,
)
if choice is not None:
return choice
return next(
(control for control in controls
if control.class_name.casefold() == "button"
and control.control_id == 1),
None,
)
def _private_mouse_click(self, target, parent_hwnd: int):
"""Click a custom control on the companion's private desktop.
GX/MFC controls can ignore a zero-coordinate posted click even though
the message is accepted. Use the control's center in client coordinates
and synchronously deliver the message so the owner processes it before
the postcondition probe runs. No foreground activation or real cursor
movement is involved.
"""
left = top = right = bottom = 0
try:
rect = self.win32gui.GetClientRect(target.handle)
left, top, right, bottom = (int(value) for value in rect)
except Exception:
try:
rect = self.win32gui.GetWindowRect(target.handle)
left, top, right, bottom = (int(value) for value in rect)
right, bottom = right - left, bottom - top
left, top = 0, 0
except Exception:
# Preserve the legacy message-only fallback for probe/test
# backends that cannot provide geometry.
left = top = right = bottom = 0
x = max(0, (right - left) // 2)
y = max(0, (bottom - top) // 2)
lparam = (y << 16) | (x & 0xFFFF)
down = 0x0201 # WM_LBUTTONDOWN
up = 0x0202 # WM_LBUTTONUP
send_message = getattr(self.win32gui, "SendMessage", None)
if send_message is not None:
send_message(target.handle, down, 1, lparam)
send_message(target.handle, up, 0, lparam)
else:
self.win32gui.PostMessage(target.handle, down, 1, lparam)
self.win32gui.PostMessage(target.handle, up, 0, lparam)
# Some owner-drawn buttons do not synthesize BN_CLICKED from mouse
# messages. Forward the equivalent command to the dialog owner.
if send_message is not None and parent_hwnd:
send_message(parent_hwnd, 0x0111, int(target.control_id), target.handle)
def perform(self, snapshot: WindowSnapshot, action: dict) -> ActionResult:
channels = tuple(action.get("channels", ()))
action_name = action.get("action")
if action_name == 'user_confirmed_pcb_open':
try:
from .pcb_open_consent import validate_action_window
if channels != ('win32_button_click',):
raise ValueError('PCB_OPEN_ACTION_CHANNEL_CHANGED')
validate_action_window(snapshot, action)
except Exception as error:
return ActionResult(error_code='DATABASE_RECOVERY_REQUIRED', detail=str(error))
if action_name == 'user_selected_pcb_version':
try:
from .pcb_restore_prompt import validate_action_window
if channels != ('win32_button_click',):
raise ValueError('PCB_VERSION_ACTION_CHANNEL_MISMATCH')
validate_action_window(snapshot, action)
except Exception as error:
return ActionResult(error_code='PCB_VERSION_CHOICE_REQUIRED', detail=str(error))
if action_name == 'post_repair_local_read_write':
try:
from .post_repair_consent import validate_action_window
validate_action_window(snapshot, action)
if channels != ('win32_button_click',) or action.get('target') != {'control_id': 6}:
raise ValueError('POST_REPAIR_ACTION_MISMATCH')
except Exception as error:
return ActionResult(error_code='DATABASE_RECOVERY_REQUIRED', detail=str(error))
if action_name == "accept_license":
target = self._license_target(snapshot)
elif action_name == "restore_last_saved":
target = self._restore_database_target(snapshot)
else:
target = self._target(snapshot, dict(action.get("target", {})))
if target is None:
return ActionResult(error_code="ACTION_TARGET_NOT_UNIQUE",
detail="没有找到唯一且可用的目标控件")
if action_name == "restore_last_saved" and target.control_id != 1:
# EE7.9's custom radio button can block a UIA SelectionItem call
# on Win10. BM_CLICK is asynchronous and keeps the agent
# responsive; UIA remains an explicit fallback if Win32 fails.
channels = ("win32_button_click",
*(channel for channel in channels
if channel != "win32_button_click"))
for channel in channels:
if channel == "interface":
continue
if channel.startswith("uia_"):
try:
patterns = {value.casefold() for value in target.patterns}
if channel == "uia_select" and "selectionitem" not in patterns:
continue
if channel == "uia_toggle" and "toggle" not in patterns:
continue
if channel == "uia_invoke" and not (
"invoke" in patterns or target.class_name.casefold() == "button"):
continue
wrapper = self.uia_wrapper(target.handle)
if channel == "uia_invoke":
wrapper.invoke()
elif channel == "uia_select":
wrapper.select()
elif channel == "uia_toggle":
wrapper.toggle()
else:
continue
return ActionResult(channel=channel, accepted_controls=(target.control_id,))
except Exception:
continue
if channel == "win32_button_click" and target.class_name.casefold() == "button":
try:
self.win32gui.PostMessage(
target.handle, getattr(self.win32con, "BM_CLICK", 0x00F5), 0, 0)
return ActionResult(channel=channel, accepted_controls=(target.control_id,))
except Exception:
continue
if channel == "win32_mouse_click" and action.get("action") == "accept_license":
try:
self._private_mouse_click(target, snapshot.hwnd)
return ActionResult(channel=channel, accepted_controls=(target.control_id,))
except Exception:
continue
return ActionResult(error_code="ACTION_CHANNEL_FAILED",
detail=f"动作通道均失败: {', '.join(channels)}")
class DialogAgentServer:
def __init__(self, paths: AgentPaths, *, probe, executor=None, poll_seconds=0.02):
self.paths = paths
self.probe = probe
self.executor = executor or DialogActionExecutor()
self.poll_seconds = max(0.005, float(poll_seconds))
self.sequence = 0
self.requests = deque(maxlen=1)
self.responses = deque(maxlen=1)
connection = socket.create_connection(("127.0.0.1", paths.port), timeout=10)
connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.channel = JsonChannel(connection)
self.channel.send({"token": paths.token}, timeout_seconds=10)
self.observed_snapshots = {}
self.observed_pids = None
@classmethod
def from_config(cls, config_path: Path, *, probe, executor=None):
return cls(AgentPaths.from_config(config_path), probe=probe, executor=executor)
def _response(self, request, **values):
self.sequence += 1
response = {
"schema_version": SCHEMA_VERSION,
"request_id": request.get("request_id", ""),
"sequence": self.sequence,
**values,
}
self.channel.send(response)
self.responses.append(response)
def _handle(self, request):
self.requests.append(request)
if request.get("schema_version") != SCHEMA_VERSION:
self._response(request, error_code="DIALOG_PROTOCOL_ERROR", detail="schema_version 不匹配")
return
try:
phase = DialogPhase(request["phase"])
if request.get("op") == "observe":
pids = request.get('pids')
if pids is not None and (not isinstance(pids, list)
or any(type(pid) is not int or pid <= 0 for pid in pids)):
raise ValueError('DIALOG_PID_SCOPE_INVALID')
self.observed_pids = set(pids) if pids is not None else None
snapshots = (self.probe.capture(phase, pids=self.observed_pids) if pids is not None
else self.probe.capture(phase))
if pids is not None:
snapshots = tuple(w for w in snapshots if w.pid in self.observed_pids)
self.observed_snapshots.clear()
for snapshot in snapshots:
self.observed_snapshots[stable_fingerprint(snapshot)] = snapshot
self._response(request, result=[item.to_record() for item in snapshots])
return
if request.get("op") == "perform":
expected = self.observed_snapshots.get(request.get("fingerprint"))
if (expected is None or int(request.get('hwnd', 0)) != expected.hwnd
or self.observed_pids is not None and (expected.pid not in self.observed_pids
or not self.probe.matches_identity(expected))):
self._response(request, result=ActionResult(
error_code="STALE_DIALOG",
detail="窗口已消失或指纹已变化",
).to_record())
return
else:
# The supervisor just observed this exact fingerprint. A
# second full child/UIA scan can block on EE7.9's native
# license dialog, so execute against that validated
# snapshot instead of rescanning it synchronously.
snapshot = expected
result = self.executor.perform(snapshot, dict(request.get("action", {})))
self._response(request, result=result.to_record())
return
self._response(request, error_code="DIALOG_PROTOCOL_ERROR", detail="未知 op")
except WindowProbeError as error:
self._response(request, error_code=error.error_code, detail=error.detail)
except Exception as error:
self._response(request, error_code="DIALOG_AGENT_ERROR", detail=str(error))
def serve_once(self) -> bool:
try:
request = self.channel.receive(self.poll_seconds)
except TimeoutError:
return False
self._handle(request)
return True
def serve_forever(self) -> int:
try:
while True:
self.serve_once()
except (EOFError, ConnectionError, OSError):
return 0
finally:
self.channel.close()
class DialogAgentClient:
def __init__(self, paths: AgentPaths, listener, *, timeout_seconds: float = 2.0):
self.paths = paths
self.listener = listener
self.channel = None
self.timeout_seconds = max(0.1, float(timeout_seconds))
self.last_sequence = 0
@classmethod
def prepare(cls, root: Path, *, desktop_name: str, timeout_seconds=2.0):
root = Path(root)
root.mkdir(parents=True, exist_ok=True)
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
listener.bind(("127.0.0.1", 0))
listener.listen(1)
paths = AgentPaths(root / "dialog-agent.json", listener.getsockname()[1], uuid4().hex)
paths.config.write_text(json.dumps({
"schema_version": SCHEMA_VERSION, "transport": "loopback_memory",
"desktop_name": desktop_name, "port": paths.port, "token": paths.token,
}, ensure_ascii=False), encoding="utf-8")
return cls(paths, listener, timeout_seconds=timeout_seconds)
except Exception:
listener.close()
raise
@classmethod
def start(cls, worker, root: Path, *, timeout_seconds: float = 2.0, stop=None):
client = cls.prepare(root, desktop_name=worker.name, timeout_seconds=timeout_seconds)
try:
from .defaults import DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS
worker.start_companion(dialog_agent_command(client.paths.config))
# Frozen imports can exceed ten seconds; PCB remains behind its gate.
client._accept(timeout_seconds=DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS, stop=stop)
return client
except Exception:
client.close()
raise
def _accept(self, timeout_seconds, *, stop=None):
if self.channel is not None:
return
deadline = time.monotonic() + timeout_seconds
while True:
if stop is not None and stop.is_set():
raise InterruptedError('VERIFY_CANCELLED: 弹窗代理启动已取消,未启动 PCB')
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError('dialog-agent startup timed out')
self.listener.settimeout(min(.2, remaining))
try:
connection, _address = self.listener.accept()
break
except socket.timeout:
continue
channel = JsonChannel(connection)
try:
connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError('dialog-agent handshake timed out')
hello = channel.receive(min(self.timeout_seconds, remaining))
if hello.get("token") != self.paths.token:
raise DialogAgentProtocolError("dialog-agent authentication failed")
if stop is not None and stop.is_set():
raise InterruptedError('VERIFY_CANCELLED: 弹窗代理启动已取消,未启动 PCB')
self.channel = channel
except Exception:
channel.close()
raise
finally:
self.listener.close()
def _request(self, op: str, phase: DialogPhase, **values):
try:
self._accept(self.timeout_seconds)
request_id = uuid4().hex
self.channel.send({
"schema_version": SCHEMA_VERSION, "request_id": request_id,
"op": op, "phase": phase.value, **values,
}, self.timeout_seconds)
response = self.channel.receive(self.timeout_seconds)
except (OSError, EOFError) as error:
raise DialogAgentProtocolError(f"DIALOG_PROTOCOL_TIMEOUT_OR_DISCONNECT: {op}: {error}") from error
if response.get("schema_version") != SCHEMA_VERSION:
raise DialogAgentProtocolError("响应 schema_version 不匹配")
if response.get("request_id") != request_id:
raise DialogAgentProtocolError("响应 request_id 不匹配")
sequence = int(response.get("sequence", 0))
if sequence <= self.last_sequence:
raise DialogAgentProtocolError("响应 sequence 非单调递增")
self.last_sequence = sequence
if response.get("error_code"):
raise DialogAgentProtocolError(f"{response['error_code']}: {response.get('detail', '')}")
return response.get("result")
def observe(self, phase: DialogPhase, *, pids=None) -> tuple[WindowSnapshot, ...]:
result = self._request("observe", phase, **({'pids': sorted(pids)} if pids is not None else {}))
return tuple(WindowSnapshot.from_record(item) for item in (result or ()))
def perform(self, *, hwnd: int, fingerprint: str, action: dict,
phase: DialogPhase) -> ActionResult:
result = self._request(
"perform", phase, hwnd=int(hwnd), fingerprint=str(fingerprint), action=dict(action))
return ActionResult.from_record(result)
def close(self):
if self.channel is not None:
self.channel.close()
self.listener.close()
class _CurrentDesktop:
@staticmethod
def EnumDesktopWindows():
import win32gui
handles = []
def collect(handle, _context):
handles.append(int(handle))
return True
win32gui.EnumWindows(collect, None)
return tuple(handles)
def dialog_agent_main(config_path: Path) -> int:
import pythoncom
pythoncom.CoInitialize()
try:
probe = WindowProbe(desktop=_CurrentDesktop())
return DialogAgentServer.from_config(config_path, probe=probe).serve_forever()
finally:
pythoncom.CoUninitialize()