From a0fc255edbf87cd176894fe4aa49865d8e131143 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 23:45:43 -0500 Subject: [PATCH 01/14] test(flow): report the native field read's refusal when the approval halts before its request --- .../tests/e2e/test_windows_hosted_governed.py | 79 ++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-) diff --git a/packages/flow/tests/e2e/test_windows_hosted_governed.py b/packages/flow/tests/e2e/test_windows_hosted_governed.py index a5ba26a077..0e32fd17ed 100644 --- a/packages/flow/tests/e2e/test_windows_hosted_governed.py +++ b/packages/flow/tests/e2e/test_windows_hosted_governed.py @@ -348,7 +348,7 @@ def _print_diagnostics(phase: str, record: dict[str, Any]) -> None: """Print the halts and the form-state probe in full; pytest's assertion message shortens a long dict.""" - for key in ("halts", "form_state_probe"): + for key in ("halts", "form_state_probe", "projection_probe"): print(f"{phase} {key}: {json.dumps(record.get(key), default=str)}") @@ -426,6 +426,82 @@ def _form_state_probe(backend, run_dir: Path, frame_png: bytes) -> dict[str, Any return out +def _projection_probe(backend, run_dir: Path) -> dict[str, Any]: + """Why the approval's native field read refused, when no request exists. + + Diagnostics only. A halt before the approval request leaves no request + file and no save frame, so :func:`_form_state_probe` cannot run. This + records the window lookup under the earlier steps' points, the agent's + closed refusal receipt for that window (stage, channel, reason, the + walk ordinal; never field text), and a type-only census of the window's + UIA tree in the agent's walk order (no names or values). + """ + + from openadapt_flow.backends.windows_backend import CLIENT_VALUE_READ_CONTRACT + + out: dict[str, Any] = {} + try: + report = _report(run_dir) + save = report.results[-1].step_id + points = [ + (int(r.resolution.point[0]), int(r.resolution.point[1])) + for r in report.results + if r.step_id != save and r.resolution is not None + ] + roots = [backend.window_root_at(x, y) for x, y in points] + out["root_at"] = roots + named = {root for root in roots if root is not None} + if len(named) != 1 or None in roots: + out["window"] = "not one window" + return out + hwnd, pid = next(iter(named)) + typed = backend._post_typed_read( + "/window/form-fields", + {"hwnd": hwnd, "pid": pid, "value_contract": CLIENT_VALUE_READ_CONTRACT}, + ) + payload = typed.payload or {} + out["refusal"] = payload.get("refusal") + out["field_kinds"] = [f.get("kind") for f in payload.get("fields") or []] + out["census"] = _type_census(hwnd) + except Exception as exc: # noqa: BLE001 - diagnostics never fail the test + out["probe_error"] = f"{type(exc).__name__}: {exc}" + return out + + +def _type_census(hwnd: int, limit: int = 120) -> list[Any]: + """``[ordinal, depth, type, has_hwnd, value_pattern, children]`` per node. + + Preorder, the order the agent's walk pops nodes (its ordinal counts + from 1). Type and capability only: no names, values or text. + """ + + import uiautomation as auto # noqa: PLC0415 - Windows-only diagnostics + + rows: list[Any] = [] + with auto.UIAutomationInitializerInThread(): + window = auto.ControlFromHandle(hwnd) + stack = [(c, 1) for c in reversed(window.GetChildren())] + while stack and len(rows) < limit: + control, depth = stack.pop() + children = control.GetChildren() + try: + value = control.GetPropertyValueEx(30043, 1) + except Exception as exc: # noqa: BLE001 + value = type(exc).__name__ + rows.append( + [ + len(rows) + 1, + depth, + control.ControlTypeName, + int(control.NativeWindowHandle or 0) > 0, + value if isinstance(value, bool) else repr(type(value)), + len(children), + ] + ) + stack.extend((c, depth + 1) for c in reversed(children)) + return rows + + def _request_frame(run_dir: Path) -> bytes: requests = sorted((run_dir / "item-approval").glob("request-*.json")) request = json.loads(requests[-1].read_text(encoding="utf-8")) @@ -640,6 +716,7 @@ def run_case(run_id: str, wait_s: int): ) except Exception as exc: # noqa: BLE001 - diagnostics never fail the test evidence["approved"]["form_state_probe"] = {"probe_error": repr(exc)} + evidence["approved"]["projection_probe"] = _projection_probe(backend, run_dir) _print_diagnostics("approved", evidence["approved"]) assert person.errors == [], evidence["approved"] assert done.returncode == 0, ( From 036937bda9173ad9c512cf6bbc9802e7c30e3a84 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 23:47:06 -0500 Subject: [PATCH 02/14] test(flow): a windowless grid cell's value refuses the native field projection --- .../flow/tests/test_approval_form_fields.py | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 80a1706a9a..28ae424dc2 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -770,6 +770,37 @@ def test_the_agent_refuses_a_window_uia_cannot_open(monkeypatch): assert perform("window-form-fields", {"hwnd": 7, "pid": 11})["window"] is None +@pytest.mark.parametrize("cell_hwnd", ["none", "grid"], ids=["no-hwnd", "grid-hwnd"]) +def test_a_windowless_grid_cell_value_refuses_the_projection(monkeypatch, cell_hwnd): + # A WinForms DataGridView draws its cells itself: each cell is a UIA + # DataItem with a value pattern but no window of its own (handle 0), or + # at most the grid's. WM_GETTEXT cannot read the cell, so its value has + # no second, independent source. The projection refuses; the cell is + # neither passed as proven, nor masked, nor left to OCR (#2291). The + # fixture's other controls each own a handle, which is why the hosted + # Patient Notes approval was the first to meet this. + cells = [ + _Control("DataItemControl", bounds=(20, 140, 220, 180), value="Neil"), + _Control("DataItemControl", bounds=(220, 140, 420, 180), value="Sorenson"), + ] + row = _Control( + "CustomControl", bounds=(20, 140, 620, 180), selected=True, children=cells + ) + grid = _Control("TableControl", bounds=(20, 60, 630, 280), children=[row]) + search = _Control("EditControl", bounds=(20, 20, 500, 43), value="Neil") + perform = _agent(monkeypatch, _window(search, grid)) + shared = 0 if cell_hwnd == "none" else grid.NativeWindowHandle + for control in (row, *cells): + control.NativeWindowHandle = shared + # The grid's own window text is not the cell's value. + control.native_override = "" + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert answer["window"] is None and answer["fields"] == [] + refusal = answer["refusal"] + assert (refusal["stage"], refusal["channel"]) == ("observation", "value") + assert refusal["reason"] == "bound_identity_unavailable" + + @pytest.mark.parametrize( "control_type,source", [ From 9bb59cb4df8d6a98c997358b979750d819d45d4c Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 23:58:27 -0500 Subject: [PATCH 03/14] fix(flow): bind a screen fault to the engine's own capture of the signed frame, and name the differing receipt keys --- .../runtime/replay/qualification_faults.py | 45 +++++- packages/flow/tests/test_qualify_windows.py | 130 ++++++++++++++++++ 2 files changed, 172 insertions(+), 3 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py b/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py index 869f08edf9..b1cbec5beb 100644 --- a/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py +++ b/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py @@ -204,8 +204,15 @@ def _validate_fault_mutation( "after_input_sha256": after_input_sha256, } actual = receipt.model_dump(mode="python") - if any(actual.get(key) != value for key, value in expected.items()): - raise RuntimeError("qualification_fault_receipt_binding_invalid") + differing = sorted( + key for key, value in expected.items() if actual.get(key) != value + ) + if differing: + # Key names only: the bound values are digests and identifiers + # this message must not carry into a report. + raise RuntimeError( + "qualification_fault_receipt_binding_invalid: " + ",".join(differing) + ) if context.before_input_sha256 == after_input_sha256: raise RuntimeError("qualification_fault_input_unchanged") trusted_key = self._qualification_fault_public_key @@ -249,7 +256,9 @@ def _apply_screen_fault_mutation( return before_png if mutation.replace_effect_verifier: raise RuntimeError("qualification_screen_fault_replaced_verifier") - after_png = capture_frame() + after_png = _observe_signed_frame( + capture_frame, mutation.receipt.after_input_sha256 + ) self._validate_fault_mutation( context, mutation.receipt, @@ -403,3 +412,33 @@ def _require_qualification_environment_current(self) -> None: raise StructuralResolutionRefused( "qualification environment changed before input" ) + + +#: How long the engine looks for the frame a screen-fault receipt signed. +SIGNED_FRAME_ATTEMPTS = 30 +SIGNED_FRAME_INTERVAL_S = 0.1 + + +def _observe_signed_frame(capture: Callable[[], bytes], signed_sha256: str) -> bytes: + """The engine's own capture of the frame the fault receipt signed. + + The driver signs a settled frame; the engine then captures the screen + itself and binds the detector's input to that capture. One capture is + not enough on a native desktop: a text caret that blinks every ~0.5 s + can toggle between the driver's frame and the engine's, so identical + staging reads as a different frame. The engine captures again, a bounded + number of times, until its own frame's bytes equal the signed digest. + Only exact equality ends the wait early; otherwise the last capture is + returned and the receipt check refuses it, so a frame the driver did not + sign is never treated as staged. + """ + + import time + + frame = capture() + for _ in range(SIGNED_FRAME_ATTEMPTS - 1): + if sha256_bytes(frame) == signed_sha256: + break + time.sleep(SIGNED_FRAME_INTERVAL_S) + frame = capture() + return frame diff --git a/packages/flow/tests/test_qualify_windows.py b/packages/flow/tests/test_qualify_windows.py index 871c3b8aed..6b71baf822 100644 --- a/packages/flow/tests/test_qualify_windows.py +++ b/packages/flow/tests/test_qualify_windows.py @@ -243,3 +243,133 @@ def test_native_environment_refuses_agent_without_real_keyboard_receipts(): } with pytest.raises(ValueError, match="native keyboard lease"): surfaces.environment_payload(native, native_config()) + + +class _FaultHost: + """The replayer's screen-fault path, with the run's binding stubbed.""" + + def __init__(self, driver, backend): + from openadapt_flow.runtime.replay.qualification_faults import ( + QualificationFaultInjection, + ) + + self._mixin = QualificationFaultInjection + self.backend = backend + self.qualification_fault_driver = driver + self.governed_authorization = SimpleNamespace( + qualification_fault_driver_id=driver.driver_id, + qualification_fault_driver_contract_sha256=driver.contract_sha256, + qualification_fault_driver_key_id=driver.attestation_key_id, + ) + self._qualification_fault_public_key = driver.public_key_base64 + self._qualification_fault_mutations = [] + + def _qualification_fault_context(self, **_kwargs): + return _ambiguity(self.backend) + + def __getattr__(self, name): + return getattr(self._mixin, name).__get__(self) + + def apply(self, before): + return self._mixin._apply_screen_fault_mutation( + self, + gate="target_resolution", + step=SimpleNamespace(id="s3"), + before_png=before, + effect_verifier=None, + ) + + +def _ambiguity(backend=None): + context = _context("ambiguity", backend=backend) + context.gate = "target_resolution" + return context + + +def _native_save_workflow(): + workflow = _workflow() + workflow.steps[-1].anchor.structural = StructuralLocator( + automation_id="commit", role="button" + ) + return workflow + + +def _screens(frames, then): + shots = list(frames) + return lambda: shots.pop(0) if shots else then + + +def test_a_caret_blink_after_staging_still_binds_the_signed_frame(monkeypatch): + # Hosted Windows, fault-ambiguity trial 3: the driver signed a settled + # frame, then the caret in the note box toggled before the engine's own + # capture, and identical staging read as a receipt for another frame. + # The engine now captures until its frame is the one signed. + from openadapt_flow.runtime.replay import qualification_faults as faults + + monkeypatch.setattr(faults, "SIGNED_FRAME_INTERVAL_S", 0.0) + caret_on, caret_off = b"overlay, caret on", b"overlay, caret off" + backend = SimpleNamespace( + stage_qualification_fault=lambda kind, locator, **kw: "owned-id", + clear_qualification_fault=lambda _id: None, + # Driver settles on caret_on (three equal frames), the engine's + # first two captures see caret_off, its third caret_on again. + screenshot=_screens([caret_on] * 3 + [caret_off] * 2, caret_on), + ) + host = _FaultHost(WindowsFaultDriver(_native_save_workflow()), backend) + assert host.apply(b"before") == caret_on + assert len(host._qualification_fault_mutations) == 1 + + +def test_a_frame_the_driver_did_not_sign_is_never_staged(monkeypatch): + from openadapt_flow.runtime.replay import qualification_faults as faults + + monkeypatch.setattr(faults, "SIGNED_FRAME_INTERVAL_S", 0.0) + signed, other = b"overlay as signed", b"something else on screen" + backend = SimpleNamespace( + stage_qualification_fault=lambda kind, locator, **kw: "owned-id", + clear_qualification_fault=lambda _id: None, + screenshot=_screens([signed] * 3, other), + ) + host = _FaultHost(WindowsFaultDriver(_native_save_workflow()), backend) + with pytest.raises(RuntimeError) as raised: + host.apply(b"before") + # The refusal names the differing key, never a bound value. + assert str(raised.value) == ( + "qualification_fault_receipt_binding_invalid: after_input_sha256" + ) + assert hashlib.sha256(signed).hexdigest() not in str(raised.value) + assert host._qualification_fault_mutations == [] + + +def test_a_receipt_bound_to_another_run_names_only_the_differing_keys(): + from openadapt_flow.runtime.replay.qualification_faults import ( + QualificationFaultInjection, + ) + + driver = WindowsFaultDriver(_native_save_workflow()) + frame = b"overlay" + backend = SimpleNamespace( + stage_qualification_fault=lambda kind, locator, **kw: "owned-id", + clear_qualification_fault=lambda _id: None, + screenshot=lambda: frame, + ) + receipt = driver.mutate(_ambiguity(backend)).receipt + host = _FaultHost(driver, backend) + context = SimpleNamespace( + **{ + **vars(_ambiguity()), + "run_id_sha256": "b" * 64, + "gate": "identity_verification", + } + ) + with pytest.raises(RuntimeError) as raised: + QualificationFaultInjection._validate_fault_mutation( + host, + context, + receipt, + after_input_sha256=hashlib.sha256(frame).hexdigest(), + ) + assert str(raised.value) == ( + "qualification_fault_receipt_binding_invalid: gate,run_id_sha256" + ) + assert host._qualification_fault_mutations == [] From 405dc5eff0efe3b6f1dcc4ff778b7d283a07098f Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 00:32:37 -0500 Subject: [PATCH 04/14] fix(flow): read a windowless, read-only control's UIA value into the approval digest as unverified, never masked or complete --- packages/flow/docs/APPROVAL_MODES.md | 8 + .../approval_mode/form_state.py | 29 +- .../approval_mode/item_approval.py | 11 +- .../approval_mode/window_fields.py | 19 +- .../backends/win_agent/native_value.py | 115 +++++++ .../backends/win_agent/server.py | 115 ++++++- .../tests/e2e/test_windows_hosted_governed.py | 7 +- .../flow/tests/test_approval_form_fields.py | 299 ++++++++++++++++-- 8 files changed, 566 insertions(+), 37 deletions(-) diff --git a/packages/flow/docs/APPROVAL_MODES.md b/packages/flow/docs/APPROVAL_MODES.md index 5ad161e9c6..95b8e2ad45 100644 --- a/packages/flow/docs/APPROVAL_MODES.md +++ b/packages/flow/docs/APPROVAL_MODES.md @@ -81,6 +81,14 @@ openadapt-flow item-approval decline RUN_DIR ... --reason wrong_values is gone, another of the app's windows reaches outside that frame, or a monitor sits left of or above the primary one (the window's frame and the screenshot's pixels would then be offset), it reads the whole screen. + Each text box, label and button that has its own window is read by its + value, proved complete by two independent sources. A control drawn by its + parent, with no window of its own (a grid cell or column header, a title + bar), can't be proved that way. When it is read-only and not a password + field, its UI Automation value is read twice, must match, and enters the + digest as its own kind; the screen text there is still read too. Any + other control without a proof stops the item. See + [Limits](LIMITS.md#windows-approval-controls-without-their-own-window). Elsewhere it reads the words on the screen. An API step prepares its request again instead; a request whose digest changed stops the item before the save, and the GUI steps don't run in its place. diff --git a/packages/flow/openadapt_flow/approval_mode/form_state.py b/packages/flow/openadapt_flow/approval_mode/form_state.py index d512b63d0e..599663b18e 100644 --- a/packages/flow/openadapt_flow/approval_mode/form_state.py +++ b/packages/flow/openadapt_flow/approval_mode/form_state.py @@ -24,6 +24,13 @@ caret blinking in a text box, a hovered title-bar button or a selection highlight that dims when the window loses focus then reads the same every time, while a changed value changes the digest through either channel. +- A control with no window of its own (a grid cell or column header, a + title bar) has no second source to prove its value complete. When it is + read-only and not a password field, its UI Automation value, read twice + and equal, enters the digest as ``uia_only_unverified``; its pixels are + never painted out, so OCR still reads them, and the read is never a + complete value. Limit: a provider that truncates the value could hide a + suffix that changes while OCR sees nothing change either. Only a digest leaves this module. The digest stays in the run directory; it never enters the report or anything sent to Cloud. @@ -37,7 +44,11 @@ import re from typing import Any, Optional, Sequence -from openadapt_flow.approval_mode.window_fields import valid_form_field +from openadapt_flow.approval_mode.window_fields import ( + UIA_ONLY_UNVERIFIED, + UNMASKED_KINDS, + valid_form_field, +) #: (kind, "sha256:") FormState = tuple[str, str] @@ -209,11 +220,12 @@ def window_fields_state( rows.append( [kind, [fx, fy, fw, fh], text, state, proof, field["value_identity"]] ) - # State, container and empty values leave pixels visible. Only - # complete nonempty leaves or visible labels authorize a mask. + # State, container, unverified and empty values leave pixels + # visible. Only complete nonempty leaves or visible labels + # authorize a mask. inside = ( None - if kind in {"state", "value"} or not text + if kind in UNMASKED_KINDS or not text else _clamp((fx - x0, fy - y0, fw, fh), w, h) ) if inside is not None: @@ -226,9 +238,14 @@ def window_fields_state( return None if not words and not any(row[2] for row in rows): return None - return _digest( - "window_fields", {"window": list(window), "fields": rows, "words": words} + # A read that includes an unverified (windowless) value is its own kind, + # so its digest never equals one from a read that proved every value. + kind = ( + "window_fields_uia_only_unverified" + if any(row[0] == UIA_ONLY_UNVERIFIED for row in rows) + else "window_fields" ) + return _digest(kind, {"window": list(window), "fields": rows, "words": words}) def capture_form_state( diff --git a/packages/flow/openadapt_flow/approval_mode/item_approval.py b/packages/flow/openadapt_flow/approval_mode/item_approval.py index 630d8b4e1d..234ddbe3e6 100644 --- a/packages/flow/openadapt_flow/approval_mode/item_approval.py +++ b/packages/flow/openadapt_flow/approval_mode/item_approval.py @@ -245,9 +245,18 @@ class ItemApprovalRequest(BaseModel): #: text on the screen where the application exposes no form controls, #: or (``window_fields``) the app window's controls read by value through #: the platform's accessibility API with the rest of it read by OCR. + #: ``window_fields_uia_only_unverified`` is that read when it includes a + #: windowless control's unverified UIA value (never equal to a fully + #: proved read). #: ``api_request`` when the save is an API step: the digest is then the #: exact request, the record and the record check (``api_request``). - form_state_kind: Literal["dom", "screen_text", "window_fields", "api_request"] + form_state_kind: Literal[ + "dom", + "screen_text", + "window_fields", + "window_fields_uia_only_unverified", + "api_request", + ] form_state_sha256: str = Field(pattern=PREFIXED_SHA256_PATTERN) created_at: str expires_at: str diff --git a/packages/flow/openadapt_flow/approval_mode/window_fields.py b/packages/flow/openadapt_flow/approval_mode/window_fields.py index 70f1a4b22f..bd1d0d9a0b 100644 --- a/packages/flow/openadapt_flow/approval_mode/window_fields.py +++ b/packages/flow/openadapt_flow/approval_mode/window_fields.py @@ -9,7 +9,15 @@ FIELD_KEYS = frozenset( {"kind", "rect", "text", "state", "value_proof", "value_identity"} ) -FIELD_KINDS = frozenset({"title_bar", "edit", "value", "text", "state"}) +#: A windowless, read-only control's UIA value read twice (no second source). +#: It enters the approval digest only, never masks pixels, and never counts +#: as a complete value or as read-back evidence. +UIA_ONLY_UNVERIFIED = "uia_only_unverified" +FIELD_KINDS = frozenset( + {"title_bar", "edit", "value", "text", "state", UIA_ONLY_UNVERIFIED} +) +#: Kinds whose rectangle is never painted out of the OCR read. +UNMASKED_KINDS = frozenset({"state", "value", UIA_ONLY_UNVERIFIED}) FIELD_STATES = frozenset({None, "on", "off", "indeterminate", "selected", "unselected"}) # The host checks the format it understands, independently of the deployed @@ -64,7 +72,9 @@ def valid_form_field(field: Any, *, pid: int | None = None) -> bool: ``text`` without a value proof is the established visible-label channel; value-backed cells must carry a proof. Containers and empty values enter - the digest but leave their pixels visible. A proof is observation metadata, + the digest but leave their pixels visible. ``uia_only_unverified`` (a + windowless control's value) never carries a proof, never masks, and is + never a complete value. A proof is observation metadata, not a signature or caller-provided authorization. """ try: @@ -83,7 +93,10 @@ def valid_form_field(field: Any, *, pid: int | None = None) -> bool: or rect[2] <= 0 or rect[3] <= 0 or (kind in {"edit", "value"} and (proof is None or state is not None)) - or (kind in {"title_bar", "state"} and proof is not None) + or ( + kind in {"title_bar", "state", UIA_ONLY_UNVERIFIED} + and proof is not None + ) or (kind == "state" and (text != "" or state is None)) ): return False diff --git a/packages/flow/openadapt_flow/backends/win_agent/native_value.py b/packages/flow/openadapt_flow/backends/win_agent/native_value.py index db5c8e7252..013b8e997e 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -574,6 +574,121 @@ def native() -> NativeRead: return CompleteValue(False, None, "value_observation_unavailable", None) +@dataclass(frozen=True) +class UnverifiedValue: + """A windowless, read-only control's UIA value, read twice. Never complete. + + A control drawn by its parent (a DataGridView cell or column header, a + title bar) has no window of its own, so there is no second source to + read it from: no ``WM_GETTEXT`` and no :class:`ValueProof`. This class + carries what UI Automation says, read twice under the same identity + guard and equal byte for byte. It is evidence that the provider's value + did not change, never that the value is complete: a provider that + truncates could hide a suffix that changes while both reads still agree. + Only the approval form-state digest may use it, never masked, so OCR + still reads the control's pixels. It is not read-back evidence, an edit + baseline, or anything that yields VERIFIED, and it has no proof to pass + :func:`valid_value_proof`. + """ + + value: str | None + reason: str | None + + @property + def complete(self) -> bool: + """Always False: there is no independent second source.""" + return False + + @property + def proof(self) -> None: + """Always None: no :class:`ValueProof` exists for this read.""" + return None + + +def _windowless_identity(control: Any) -> tuple[int, tuple[int, ...]]: + hwnd, pid = control.NativeWindowHandle, control.ProcessId + runtime = control.GetRuntimeId() + if ( + type(hwnd) is not int + or hwnd != 0 + or not _positive_int(pid) + or not isinstance(runtime, (tuple, list)) + or not 1 <= len(runtime) <= 64 + or any(type(item) is not int for item in runtime) + ): + raise ValueUnavailable("windowless_identity_unavailable") + return pid, tuple(runtime) + + +def observe_uia_only_value( + control: Any, + *, + identity: Callable[[], str | None], + clock: Callable[[], float] = time.monotonic, +) -> UnverifiedValue: + """Read a windowless, read-only, non-password control's UIA value twice. + + The control must have no native window of its own (``NativeWindowHandle`` + exactly 0); a control with a window must prove its value through + :func:`observe_complete_value` instead. The sensitivity guard runs + first and is the last check before every provider access, exactly as for + a complete read, so a password or unknown status refuses. The + ValuePattern must say read-only before and after each read. Both reads + are bracketed by the caller's bound scope (``identity``) and must agree. + Anything else returns ``value=None`` with a fixed reason; no provider + text or exception crosses this boundary. + """ + try: + require_non_sensitive_value(control) + deadline = clock() + 5.0 + binding = identity() + if not isinstance(binding, str) or not 1 <= len(binding) <= 256: + raise ValueUnavailable("bound_identity_unavailable") + bound = _windowless_identity(control) + + def guard(*, scope: bool = False) -> None: + if clock() >= deadline: + raise ValueUnavailable("value_observation_deadline") + if (scope and identity() != binding) or _windowless_identity( + control + ) != bound: + raise ValueUnavailable("value_identity_changed") + # This MUST be last, as in observe_complete_value. + require_non_sensitive_value(control) + + def uia() -> str: + guard() + method = control.GetValuePattern + guard() + pattern = method() + guard() + read_only = getattr(pattern, "IsReadOnly", None) + guard() + if read_only is not True: + raise ValueUnavailable("value_not_read_only") + value = getattr(pattern, "Value", None) + guard() + if not isinstance(value, str): + raise ValueUnavailable("value_pattern_unavailable") + if len(utf16_bytes(value)) // 2 > MAX_UTF16_UNITS: + raise ValueUnavailable("value_exceeds_limit") + if getattr(pattern, "IsReadOnly", None) is not True: + raise ValueUnavailable("value_readability_changed") + guard(scope=True) + return value + + first = uia() + second = uia() + guard(scope=True) + if utf16_bytes(first) != utf16_bytes(second): + raise ValueUnavailable("value_observation_changed") + return UnverifiedValue(first, None) + except ValueUnavailable as exc: + return UnverifiedValue(None, str(exc)) + except Exception: + return UnverifiedValue(None, "value_observation_unavailable") + + def valid_value_proof(value: str, proof: object) -> bool: """Strict shared wire validation; a legacy complete flag is insufficient.""" if not isinstance(proof, dict) or set(proof) != set( diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 9c9f1a1460..275b275bb9 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -3013,6 +3013,65 @@ def _form_value_identity( return None +def _form_windowless_identity( + control: object, window: object, hwnd: int, scope: Callable[[], bool] +) -> Optional[str]: + """Fresh scope of a control with no window of its own, or None. + + The same scope :func:`_form_value_identity` binds (the bound window, the + process, the RuntimeId chain up to the window, geometry, type, on + screen), except that the control cannot be reopened from its own handle: + it must have none. A control with a handle is not windowless and gets + no answer here. + """ + try: + if not scope() or _control_value(window, "NativeWindowHandle", None) != hwnd: + return None + native = _control_value(control, "NativeWindowHandle", None) + if type(native) is not int or native != 0: + return None + pid = _control_value(window, "ProcessId", None) + root_id, field_id = _runtime_id(window), _runtime_id(control) + if ( + not root_id + or not field_id + or not isinstance(pid, int) + or isinstance(pid, bool) + or _control_value(control, "ProcessId", None) != pid + ): + return None + chain = [] + node: Any = control + for _ in range(_MAX_UIA_DEPTH): + runtime = _runtime_id(node) + if not runtime or _control_value(node, "ProcessId", None) != pid: + return None + chain.append(runtime) + if runtime == root_id: + break + node = node.GetParentControl() + else: + return None + bounds = _bounds(control) + if bounds is None or _control_value(control, "IsOffscreen", None) is not False: + return None + return hashlib.sha256( + json.dumps( + [ + "windowless", + hwnd, + pid, + chain, + bounds, + _control_value(control, "ControlTypeName", None), + ], + separators=(",", ":"), + ).encode("utf-8") + ).hexdigest() + except Exception: # noqa: BLE001 - a missing scope is never complete + return None + + @dataclass(frozen=True) class _FormStateObservation: complete: bool @@ -3121,6 +3180,8 @@ def _rect(bounds: list[int]) -> list[int]: "provider_native_value_disagreement", "value_observation_unavailable", "value_identity_changed", + "windowless_identity_unavailable", + "value_not_read_only", } ) # One closed model binds reason to its stage/channel. No free-text diagnostic @@ -3420,7 +3481,59 @@ def append_state() -> None: } ) - if on_screen and exposes and bounds is not None: + native_handle = ( + _control_value(control, "NativeWindowHandle", None) + if on_screen and exposes and bounds is not None + else None + ) + if type(native_handle) is int and native_handle == 0: + # No window of its own (a grid cell or column header, a title + # bar): no second source can prove its value complete. A + # read-only, non-password value read twice through UIA enters the + # digest as its own kind, never masked, so OCR still reads its + # pixels, and never counts as complete (UnverifiedValue). + # Limit: a provider that truncates could hide a suffix that + # changes while OCR also sees nothing change. + def windowless(c: object = control) -> Optional[str]: + return _form_windowless_identity(c, window, hwnd, scope) + + bound_scope = windowless() + unverified = _native_value_api().observe_uia_only_value( + control, identity=windowless + ) + if unverified.value is None: + reason = ( + unverified.reason + if type(unverified.reason) is str + and unverified.reason in _FORM_REFUSAL_REASONS + else "value_unavailable" + ) + return _form_refused("observation", "value", reason, visited) + if bound_scope is None: + return _form_refused( + "observation", + "value_identity", + "value_identity_unavailable", + visited, + ) + if windowless() != bound_scope: + return _form_refused( + "observation", "value_identity", "value_identity_changed", visited + ) + assert bounds is not None + fields.append( + { + "kind": "uia_only_unverified", + "rect": _rect(bounds), + "text": unverified.value, + "state": state, + "value_proof": None, + "value_identity": None, + } + ) + if not children: + continue + elif on_screen and exposes and bounds is not None: # A real value capability owns a complete-value obligation on ANY # control type. Containers and generic value controls stay unmasked; # no Edit/Document or nominal label type may hide an unread value. diff --git a/packages/flow/tests/e2e/test_windows_hosted_governed.py b/packages/flow/tests/e2e/test_windows_hosted_governed.py index 0e32fd17ed..23e70ca746 100644 --- a/packages/flow/tests/e2e/test_windows_hosted_governed.py +++ b/packages/flow/tests/e2e/test_windows_hosted_governed.py @@ -469,7 +469,7 @@ def _projection_probe(backend, run_dir: Path) -> dict[str, Any]: def _type_census(hwnd: int, limit: int = 120) -> list[Any]: - """``[ordinal, depth, type, has_hwnd, value_pattern, children]`` per node. + """``[ordinal, depth, type, has_hwnd, value_pattern, children, password]``. Preorder, the order the agent's walk pops nodes (its ordinal counts from 1). Type and capability only: no names, values or text. @@ -488,6 +488,10 @@ def _type_census(hwnd: int, limit: int = 120) -> list[Any]: value = control.GetPropertyValueEx(30043, 1) except Exception as exc: # noqa: BLE001 value = type(exc).__name__ + try: + password = control.GetPropertyValueEx(30019, 1) + except Exception as exc: # noqa: BLE001 + password = type(exc).__name__ rows.append( [ len(rows) + 1, @@ -496,6 +500,7 @@ def _type_census(hwnd: int, limit: int = 120) -> list[Any]: int(control.NativeWindowHandle or 0) > 0, value if isinstance(value, bool) else repr(type(value)), len(children), + password if isinstance(password, bool) else "not-bool", ] ) stack.extend((c, depth + 1) for c in reversed(children)) diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 28ae424dc2..23ac6318af 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -515,7 +515,9 @@ def GetPropertyValueEx(self, property_id, ignore_default): def GetValuePattern(self): if self._value is None: raise RuntimeError("no value pattern") - return SimpleNamespace(Value=self._value, IsReadOnly=False) + return SimpleNamespace( + Value=self._value, IsReadOnly=getattr(self, "read_only", False) + ) def GetSelectionItemPattern(self): if self._selected is None: @@ -770,35 +772,265 @@ def test_the_agent_refuses_a_window_uia_cannot_open(monkeypatch): assert perform("window-form-fields", {"hwnd": 7, "pid": 11})["window"] is None -@pytest.mark.parametrize("cell_hwnd", ["none", "grid"], ids=["no-hwnd", "grid-hwnd"]) -def test_a_windowless_grid_cell_value_refuses_the_projection(monkeypatch, cell_hwnd): - # A WinForms DataGridView draws its cells itself: each cell is a UIA - # DataItem with a value pattern but no window of its own (handle 0), or - # at most the grid's. WM_GETTEXT cannot read the cell, so its value has - # no second, independent source. The projection refuses; the cell is - # neither passed as proven, nor masked, nor left to OCR (#2291). The - # fixture's other controls each own a handle, which is why the hosted - # Patient Notes approval was the first to meet this. +def _windowless(control_type, value, *, read_only=True, **kwargs): + """A control drawn by its parent: UIA value, no window of its own.""" + control = _Control(control_type, value=value, **kwargs) + control.NativeWindowHandle = 0 + control.read_only = read_only + return control + + +def _census_window(): + """The hosted Patient Notes window as UIA showed it (run 46355293928): + the grid's header row and data row, and the title bar, have no window + of their own; the text boxes, buttons and labels each have one.""" + + headers = [ + _windowless( + "HeaderControl", name, bounds=(20 + 200 * i, 60, 220 + 200 * i, 100) + ) + for i, name in enumerate(("first", "last", "dob")) + ] cells = [ - _Control("DataItemControl", bounds=(20, 140, 220, 180), value="Neil"), - _Control("DataItemControl", bounds=(220, 140, 420, 180), value="Sorenson"), + _windowless( + "DataItemControl", value, bounds=(20 + 200 * i, 100, 220 + 200 * i, 140) + ) + for i, value in enumerate(("Neil", "Sorenson", "1984-03-12")) ] - row = _Control( - "CustomControl", bounds=(20, 140, 620, 180), selected=True, children=cells + header_row = _Control("CustomControl", bounds=(20, 60, 620, 100), children=headers) + data_row = _Control( + "CustomControl", bounds=(20, 100, 620, 140), selected=True, children=cells + ) + for row in (header_row, data_row): + row.NativeWindowHandle = 0 + grid = _Control( + "TableControl", bounds=(20, 60, 630, 280), children=[header_row, data_row] + ) + title = _windowless( + "TitleBarControl", + "Patient Notes - Benchmark Harness", + bounds=(0, 0, 1024, 30), + children=[ + _Control("ButtonControl", bounds=(900, 0, 940, 30), name="Minimize"), + _Control("ButtonControl", bounds=(980, 0, 1020, 30), name="Close"), + ], + ) + for button in title._children: + button.NativeWindowHandle = 0 + window = _window( + _Control("EditControl", bounds=(20, 30, 500, 53), value="Neil"), + _Control("ButtonControl", bounds=(510, 28, 610, 58), name="searchButton"), + grid, + _Control("TextControl", bounds=(20, 295, 220, 317), name="Clinical note:"), + _Control("EditControl", bounds=(20, 320, 610, 440), value="BP 128/82"), + _Control("ButtonControl", bounds=(510, 450, 610, 484), name="saveButton"), + title, + ) + return window, headers, cells, title + + +def test_the_patient_notes_census_projects_its_windowless_values_unverified( + monkeypatch, +): + # #2291 made every value-capable control prove its value through a second + # source on its own window. The grid's three column headers and three + # cells and the title bar have no window, so the whole read refused + # (bound_identity_unavailable) and every governed approval on this app + # halted. Their UIA values now enter the digest as their own kind, + # unmasked and never complete; every control with a window still proves. + window, headers, cells, title = _census_window() + perform = _agent(monkeypatch, window) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert answer["refusal"] is None + fields = answer["fields"] + unverified = [f for f in fields if f["kind"] == "uia_only_unverified"] + assert [f["text"] for f in unverified] == [ + "first", + "last", + "dob", + "Neil", + "Sorenson", + "1984-03-12", + "Patient Notes - Benchmark Harness", + ] + assert all( + f["value_proof"] is None and f["value_identity"] is None for f in unverified ) - grid = _Control("TableControl", bounds=(20, 60, 630, 280), children=[row]) - search = _Control("EditControl", bounds=(20, 20, 500, 43), value="Neil") - perform = _agent(monkeypatch, _window(search, grid)) - shared = 0 if cell_hwnd == "none" else grid.NativeWindowHandle - for control in (row, *cells): - control.NativeWindowHandle = shared - # The grid's own window text is not the cell's value. - control.native_override = "" + edits = [f for f in fields if f["kind"] == "edit"] + assert [f["text"] for f in edits] == ["Neil", "BP 128/82"] + assert all(valid_value_proof(f["text"], f["value_proof"]) for f in edits) + # The title bar's buttons still read by name under it. + assert ("text", "Close") in [(f["kind"], f["text"]) for f in fields] + + +@pytest.mark.parametrize( + "control_type", ["HeaderControl", "DataItemControl", "TitleBarControl"] +) +def test_each_windowless_kind_is_unverified_and_never_masked(monkeypatch, control_type): + control = _windowless(control_type, "shown", bounds=(20, 140, 220, 180)) + perform = _agent(monkeypatch, _window(control)) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert _without_proofs(answer["fields"]) == [ + { + "kind": "uia_only_unverified", + "rect": [20, 140, 200, 40], + "text": "shown", + "state": None, + } + ] + # Its pixels stay in the OCR read: nothing is painted over its rect. + seen = [] + + def ocr(png): + with Image.open(io.BytesIO(png)) as image: + seen.append(image.convert("RGB").getpixel((100, 160))) + return [] + + frame = io.BytesIO() + Image.new("RGB", SIZE, (10, 20, 30)).save(frame, format="PNG") + state = window_fields_state( + SimpleNamespace(ocr=ocr), + frame.getvalue(), + {"bounds": (0, 0, 1024, 720), "fields": answer["fields"]}, + ) + assert seen == [(10, 20, 30)] + assert state is not None and state[0] == "window_fields_uia_only_unverified" + + +def _refusal(monkeypatch, control): + perform = _agent(monkeypatch, _window(control)) answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) assert answer["window"] is None and answer["fields"] == [] - refusal = answer["refusal"] - assert (refusal["stage"], refusal["channel"]) == ("observation", "value") - assert refusal["reason"] == "bound_identity_unavailable" + return answer["refusal"]["reason"] + + +@pytest.mark.parametrize( + "password", + [True, _UNSUPPORTED_PROPERTY, None], + ids=["password", "status-unsupported", "status-missing"], +) +def test_a_windowless_password_or_unknown_status_still_refuses(monkeypatch, password): + # The sensitivity guard runs before any probe of the control; a password + # or an unknown status refuses at the first one, before any value read. + class Unread(_Control): + def GetValuePattern(self): + raise AssertionError("no value read on a sensitive control") + + control = Unread("DataItemControl", value="secret", password=password) + control.NativeWindowHandle = 0 + control.read_only = True + assert _refusal(monkeypatch, control) in { + "visibility_unknown", + "password_or_password_status_unavailable", + } + + +def test_a_windowless_editable_value_still_refuses(monkeypatch): + control = _windowless("DataItemControl", "Neil", read_only=False) + assert _refusal(monkeypatch, control) == "value_not_read_only" + + +def test_two_windowless_reads_that_disagree_refuse(monkeypatch): + class Flicker(_Control): + reads = 0 + + def GetValuePattern(self): + self.reads += 1 + return SimpleNamespace( + Value="Neil" if self.reads == 1 else "Neil Sorenson", IsReadOnly=True + ) + + control = Flicker("DataItemControl", value="Neil") + control.NativeWindowHandle = 0 + assert _refusal(monkeypatch, control) == "value_observation_changed" + + +def test_a_cell_sharing_its_grids_window_still_needs_a_proof(monkeypatch): + # Only a control with no window at all is windowless. A cell that reports + # its grid's window still owes a complete-value proof, and the grid's + # window text is not the cell's value. + cell = _Control("DataItemControl", bounds=(20, 140, 220, 180), value="Neil") + cell.read_only = True + grid = _Control("TableControl", bounds=(20, 60, 630, 280), children=[cell]) + perform = _agent(monkeypatch, _window(grid)) + cell.NativeWindowHandle = grid.NativeWindowHandle + cell.native_override = "" + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert answer["window"] is None + assert answer["refusal"]["reason"] == "bound_identity_unavailable" + + +def test_an_unverified_value_is_never_a_complete_value_or_read_back(monkeypatch): + import openadapt_flow.backends.win_agent.native_value as native + from openadapt_flow.approval_mode.window_fields import ( + valid_form_field, + valid_value_observation, + ) + + cell = _windowless("DataItemControl", "Neil", bounds=(20, 140, 220, 180)) + cell.AutomationId = "cell" + window = _window(cell) + perform = _agent(monkeypatch, window) + unverified = native.observe_uia_only_value(cell, identity=lambda: "scope") + assert unverified.value == "Neil" + assert unverified.complete is False and unverified.proof is None + assert not valid_value_proof("Neil", unverified.proof) + assert not valid_value_observation("Neil", unverified.proof, None) + # The complete-value reader, which read-back and edit baselines use, + # still refuses the same control. + assert not native.observe_complete_value(cell, identity=lambda: "scope").complete + sys.modules["uiautomation"].GetRootControl = lambda: window + read = perform("read", {"locator": {"automation_id": "cell"}}) + assert not read.get("complete") + # The wire format refuses an unverified field that claims a proof. + field = { + "kind": "uia_only_unverified", + "rect": [20, 140, 200, 40], + "text": "Neil", + "state": None, + "value_proof": _proof("Neil"), + "value_identity": "a" * 64, + } + assert not valid_form_field(field) + assert valid_form_field({**field, "value_proof": None, "value_identity": None}) + + +def test_an_unverified_read_never_matches_a_proved_one(): + frame = io.BytesIO() + Image.new("RGB", SIZE, "white").save(frame, format="PNG") + no_words = SimpleNamespace(ocr=lambda _png: []) + base = { + "rect": [20, 140, 200, 40], + "text": "Neil", + "state": None, + "value_proof": None, + "value_identity": None, + } + unverified = window_fields_state( + no_words, + frame.getvalue(), + { + "bounds": (0, 0, 1024, 720), + "fields": [{**base, "kind": "uia_only_unverified"}], + }, + ) + proved = window_fields_state( + no_words, + frame.getvalue(), + { + "bounds": (0, 0, 1024, 720), + "fields": [ + { + **base, + "kind": "edit", + "value_proof": _proof("Neil"), + "value_identity": "a" * 64, + } + ], + }, + ) + assert unverified is not None and proved is not None + assert unverified[0] != proved[0] and unverified[1] != proved[1] @pytest.mark.parametrize( @@ -1000,3 +1232,20 @@ def test_an_unreadable_title_never_hides_the_title_bar(monkeypatch): window.Name = "" perform = _agent(monkeypatch, window) assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["fields"] == [] + + +def test_a_password_status_that_appears_between_reads_refuses(monkeypatch): + import openadapt_flow.backends.win_agent.native_value as native + + class Turns(_Control): + def GetValuePattern(self): + # After the first read, the provider starts reporting a password. + self.IsPassword = True + return SimpleNamespace(Value="Neil", IsReadOnly=True) + + cell = Turns("DataItemControl", value="Neil") + cell.NativeWindowHandle = 0 + _agent(monkeypatch, _window(cell)) + observed = native.observe_uia_only_value(cell, identity=lambda: "scope") + assert observed.value is None + assert observed.reason == "password_or_password_status_unavailable" From 72123f53c16f768481496c8fef80fe587cb42875 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 00:32:37 -0500 Subject: [PATCH 05/14] fix(flow): record a stale-identity fault receipt on the engine's plain frame when the lease refuses, on an exact digest match only --- packages/flow/docs/LIMITS.md | 21 ++++ .../runtime/replay/qualification_faults.py | 41 ++++++- packages/flow/tests/test_qualify_windows.py | 111 +++++++++++++++++- 3 files changed, 168 insertions(+), 5 deletions(-) diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index a01bf6395d..751684484d 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -25,6 +25,27 @@ are part of the qualification boundary, so this does not qualify arbitrary fresh workers. A script-hosted application's own code is covered by its declared version, not the host executable's hash. +## Windows approval: controls without their own window + +Before a save, an approval on Windows reads the app window to check that +nothing changed while the person decided. A text box or label with its own +window is read through two independent sources that must agree, so a value +cut short by the app's accessibility provider stops the item. A control drawn +by its parent, such as a grid cell, a grid column header or the title bar, +has no second source. Its UI Automation value is read twice and must match, +and the screen text over it is still read. If the provider cuts that value +short, a change in the hidden part that also leaves the visible text the same +is not detected. This value is used only for that check: it is never a +complete value, read-back evidence or the basis of a VERIFIED result. An +editable control, a password field, a control whose password status is +unknown, or one whose two reads differ still stops the item. + +A native Windows stale-identity fault covers the whole screen, so the +keyboard lease that checks the target refuses and the save halts. The fault +receipt then binds to the engine's own plain screenshot, and only when its +SHA-256 equals the frame the fault driver signed. Otherwise no receipt is +recorded and the campaign rejects the case. + ## Validated on Every published result used synthetic patients, claims and records. diff --git a/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py b/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py index b1cbec5beb..bbef7626e5 100644 --- a/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py +++ b/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py @@ -256,9 +256,20 @@ def _apply_screen_fault_mutation( return before_png if mutation.replace_effect_verifier: raise RuntimeError("qualification_screen_fault_replaced_verifier") - after_png = _observe_signed_frame( - capture_frame, mutation.receipt.after_input_sha256 - ) + signed = mutation.receipt.after_input_sha256 + try: + after_png = _observe_signed_frame(capture_frame, signed) + except StructuralResolutionRefused: + # The detector's own capture refused (a native keyboard lease + # whose target the staged fault covers): that refusal is the halt. + # The driver then signed the engine's plain screenshot instead. + # Record the receipt only if the engine's own plain capture has + # exactly that digest; either way the refusal stands unchanged. + # (A bound method is a new object per lookup: compare the + # argument, not ``capture_frame``, to tell the paths apart.) + if capture is not None: + self._record_fault_on_plain_frame(context, mutation.receipt) + raise self._validate_fault_mutation( context, mutation.receipt, @@ -266,6 +277,30 @@ def _apply_screen_fault_mutation( ) return after_png + def _record_fault_on_plain_frame( + self, context: QualificationFaultContext, receipt: FaultMutationReceipt + ) -> None: + """Bind ``receipt`` to the engine's own plain screenshot, or nothing. + + Only an exact SHA-256 match with the signed frame records it, through + the same receipt checks as any staged fault. A mismatch, an + unavailable capture or a failed check records nothing. Never raises: + the caller re-raises the detector's refusal, which this must not + replace. + """ + + try: + frame = _observe_signed_frame( + self.backend.screenshot, receipt.after_input_sha256 + ) + if sha256_bytes(frame) != receipt.after_input_sha256: + return + self._validate_fault_mutation( + context, receipt, after_input_sha256=sha256_bytes(frame) + ) + except Exception: # noqa: BLE001 - nothing recorded; the halt stands + return + def _bind_surface_qualification_environment( self, workflow: Workflow, surface_id: str ) -> Optional[str]: diff --git a/packages/flow/tests/test_qualify_windows.py b/packages/flow/tests/test_qualify_windows.py index 6b71baf822..a9fe2835b9 100644 --- a/packages/flow/tests/test_qualify_windows.py +++ b/packages/flow/tests/test_qualify_windows.py @@ -264,19 +264,32 @@ def __init__(self, driver, backend): self._qualification_fault_public_key = driver.public_key_base64 self._qualification_fault_mutations = [] + context_kind = "ambiguity" + detector_capture = None + def _qualification_fault_context(self, **_kwargs): + if self.context_kind == "stale_identity": + context = _context("stale_identity", backend=self.backend) + context.gate = "actuation_revalidation" + context.capture_frame = self.detector_capture + return context return _ambiguity(self.backend) def __getattr__(self, name): return getattr(self._mixin, name).__get__(self) - def apply(self, before): + def apply(self, before, capture=None): return self._mixin._apply_screen_fault_mutation( self, - gate="target_resolution", + gate=( + "actuation_revalidation" + if self.context_kind == "stale_identity" + else "target_resolution" + ), step=SimpleNamespace(id="s3"), before_png=before, effect_verifier=None, + capture=capture, ) @@ -373,3 +386,97 @@ def test_a_receipt_bound_to_another_run_names_only_the_differing_keys(): "qualification_fault_receipt_binding_invalid: gate,run_id_sha256" ) assert host._qualification_fault_mutations == [] + + +def _refusing_lease(): + from openadapt_flow.backend import StructuralResolutionRefused + + def capture(): + raise StructuralResolutionRefused( + "native keyboard lease observation unavailable" + ) + + return capture + + +@pytest.mark.parametrize("plain_matches", [True, False], ids=["match", "differs"]) +def test_a_stale_surface_that_refuses_the_lease_keeps_the_halt( + monkeypatch, plain_matches +): + # Hosted Windows, fault-stale-identity: the staged overlay covers the + # focused note box, so the consequential click's revalidation capture + # (a native keyboard lease) refuses. That refusal is the halt. The driver + # then signs the plain screenshot. The receipt is recorded only when the + # engine's own plain capture has exactly that digest; the refusal stands + # either way, unchanged. + from openadapt_flow.backend import StructuralResolutionRefused + from openadapt_flow.runtime.replay import qualification_faults as faults + + monkeypatch.setattr(faults, "SIGNED_FRAME_INTERVAL_S", 0.0) + signed, other = b"stale surface as signed", b"a different frame" + backend = SimpleNamespace( + stage_qualification_fault=lambda kind, locator, **kw: "owned-id", + clear_qualification_fault=lambda _id: None, + # The driver settles on ``signed``; the engine then sees ``signed`` + # again or only ``other``. + screenshot=_screens([signed] * 3, signed if plain_matches else other), + ) + host = _FaultHost(WindowsFaultDriver(_native_save_workflow()), backend) + host.context_kind = "stale_identity" + host.detector_capture = lease = _refusing_lease() + with pytest.raises(StructuralResolutionRefused) as raised: + host.apply(b"before", capture=lease) + assert str(raised.value) == "native keyboard lease observation unavailable" + recorded = host._qualification_fault_mutations + if plain_matches: + assert len(recorded) == 1 + assert recorded[0].after_input_sha256 == hashlib.sha256(signed).hexdigest() + assert recorded[0].fault_kind == "stale_identity" + else: + assert recorded == [] + + +def test_a_rejected_stale_surface_case_has_no_receipt_to_certify(monkeypatch): + # The campaign certifies a fault case only from the run report's exact + # signed receipt; with the digests apart the report has none, so the + # case evidence is refused ("requires exactly one fault_receipt"). + from openadapt_flow.backend import StructuralResolutionRefused + from openadapt_flow.runtime.replay import qualification_faults as faults + + monkeypatch.setattr(faults, "SIGNED_FRAME_INTERVAL_S", 0.0) + backend = SimpleNamespace( + stage_qualification_fault=lambda kind, locator, **kw: "owned-id", + clear_qualification_fault=lambda _id: None, + screenshot=_screens([b"signed"] * 3, b"moved on"), + ) + host = _FaultHost(WindowsFaultDriver(_native_save_workflow()), backend) + host.context_kind = "stale_identity" + host.detector_capture = lease = _refusing_lease() + with pytest.raises(StructuralResolutionRefused): + host.apply(b"before", capture=lease) + assert host._qualification_fault_mutations == [] + + +def test_a_plain_capture_refusal_is_never_rebound(monkeypatch): + # Without a separate detector capture there is nothing to fall back to: + # a refusal from the plain screenshot itself records nothing. + from openadapt_flow.backend import StructuralResolutionRefused + from openadapt_flow.runtime.replay import qualification_faults as faults + + monkeypatch.setattr(faults, "SIGNED_FRAME_INTERVAL_S", 0.0) + shots = [b"signed"] * 3 + + def screenshot(): + if shots: + return shots.pop(0) + raise StructuralResolutionRefused("plain capture refused") + + backend = SimpleNamespace( + stage_qualification_fault=lambda kind, locator, **kw: "owned-id", + clear_qualification_fault=lambda _id: None, + screenshot=screenshot, + ) + host = _FaultHost(WindowsFaultDriver(_native_save_workflow()), backend) + with pytest.raises(StructuralResolutionRefused): + host.apply(b"before") + assert host._qualification_fault_mutations == [] From 9df0f136ee30f30b47563ed49ac2cd924a3952da Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 01:18:34 -0500 Subject: [PATCH 06/14] fix(flow): read windowlessness from the raw UIA element, and report which windowless identity check fails --- .../backends/win_agent/native_value.py | 29 ++++++++- .../backends/win_agent/server.py | 15 +++-- .../tests/e2e/test_windows_hosted_governed.py | 59 +++++++++++++++++++ .../flow/tests/test_approval_form_fields.py | 33 +++++++++++ 4 files changed, 125 insertions(+), 11 deletions(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/native_value.py b/packages/flow/openadapt_flow/backends/win_agent/native_value.py index 013b8e997e..c1fb477603 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -605,12 +605,35 @@ def proof(self) -> None: return None +_NO_ELEMENT = object() + + +def has_no_native_window(control: Any) -> bool: + """True only when UI Automation answers that the control has no window. + + Read from the raw element: uiautomation's ``NativeWindowHandle`` + property also answers 0 when the read itself fails, and a failed read + must never make a windowed control look windowless. A COM null (None) + or 0 is no window; an error or any other answer is not. + """ + try: + element: Any = getattr(control, "Element", _NO_ELEMENT) + if element is _NO_ELEMENT: + # Not a uiautomation Control (an in-process provider or a test + # double): only an exact integer 0 counts. + raw = control.NativeWindowHandle + return type(raw) is int and raw == 0 + raw = element.CurrentNativeWindowHandle + except Exception: + return False + return raw is None or (type(raw) is int and raw == 0) + + def _windowless_identity(control: Any) -> tuple[int, tuple[int, ...]]: - hwnd, pid = control.NativeWindowHandle, control.ProcessId + pid = control.ProcessId runtime = control.GetRuntimeId() if ( - type(hwnd) is not int - or hwnd != 0 + not has_no_native_window(control) or not _positive_int(pid) or not isinstance(runtime, (tuple, list)) or not 1 <= len(runtime) <= 64 diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 275b275bb9..5fed7e71ce 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -3027,8 +3027,7 @@ def _form_windowless_identity( try: if not scope() or _control_value(window, "NativeWindowHandle", None) != hwnd: return None - native = _control_value(control, "NativeWindowHandle", None) - if type(native) is not int or native != 0: + if not _native_value_api().has_no_native_window(control): return None pid = _control_value(window, "ProcessId", None) root_id, field_id = _runtime_id(window), _runtime_id(control) @@ -3481,12 +3480,12 @@ def append_state() -> None: } ) - native_handle = ( - _control_value(control, "NativeWindowHandle", None) - if on_screen and exposes and bounds is not None - else None - ) - if type(native_handle) is int and native_handle == 0: + if ( + on_screen + and exposes + and bounds is not None + and _native_value_api().has_no_native_window(control) + ): # No window of its own (a grid cell or column header, a title # bar): no second source can prove its value complete. A # read-only, non-password value read twice through UIA enters the diff --git a/packages/flow/tests/e2e/test_windows_hosted_governed.py b/packages/flow/tests/e2e/test_windows_hosted_governed.py index 23e70ca746..10de7eccda 100644 --- a/packages/flow/tests/e2e/test_windows_hosted_governed.py +++ b/packages/flow/tests/e2e/test_windows_hosted_governed.py @@ -463,6 +463,7 @@ def _projection_probe(backend, run_dir: Path) -> dict[str, Any]: out["refusal"] = payload.get("refusal") out["field_kinds"] = [f.get("kind") for f in payload.get("fields") or []] out["census"] = _type_census(hwnd) + out["windowless_checks"] = _windowless_checks(hwnd) except Exception as exc: # noqa: BLE001 - diagnostics never fail the test out["probe_error"] = f"{type(exc).__name__}: {exc}" return out @@ -507,6 +508,64 @@ def _type_census(hwnd: int, limit: int = 120) -> list[Any]: return rows +def _windowless_checks(hwnd: int, limit: int = 8) -> list[Any]: + """Each windowless value control's identity checks, as booleans only. + + The agent binds a control with no window of its own by its process, its + RuntimeId chain up to the window, its geometry and being on screen + (``_form_windowless_identity``). This records which of those hold for + each such control, to show which one a refusal came from. + """ + + import uiautomation as auto # noqa: PLC0415 - Windows-only diagnostics + + from openadapt_flow.backends.win_agent import native_value + from openadapt_flow.backends.win_agent import server as agent + + rows: list[Any] = [] + with auto.UIAutomationInitializerInThread(): + window = auto.ControlFromHandle(hwnd) + pid = window.ProcessId + root_id = agent._runtime_id(window) + stack = list(reversed(window.GetChildren())) + while stack and len(rows) < limit: + control = stack.pop() + stack.extend(reversed(control.GetChildren())) + if not native_value.has_no_native_window(control): + continue + try: + if control.GetPropertyValueEx(30043, 1) is not True: + continue + except Exception: # noqa: BLE001 + continue + chain_ok, node = False, control + for _ in range(agent._MAX_UIA_DEPTH): + runtime = agent._runtime_id(node) + if not runtime or getattr(node, "ProcessId", None) != pid: + break + if runtime == root_id: + chain_ok = True + break + node = node.GetParentControl() + offscreen = getattr(control, "IsOffscreen", None) + rows.append( + { + "type": control.ControlTypeName, + "pid_matches": control.ProcessId == pid, + "runtime_id": bool(agent._runtime_id(control)), + "chain_reaches_window": chain_ok, + "bounds": agent._bounds(control) is not None, + "offscreen_is_false": offscreen is False, + "offscreen_type": type(offscreen).__name__, + "identity": agent._form_windowless_identity( + control, window, hwnd, lambda: True + ) + is not None, + } + ) + return rows + + def _request_frame(run_dir: Path) -> bytes: requests = sorted((run_dir / "item-approval").glob("request-*.json")) request = json.loads(requests[-1].read_text(encoding="utf-8")) diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 23ac6318af..202ac04348 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -1249,3 +1249,36 @@ def GetValuePattern(self): observed = native.observe_uia_only_value(cell, identity=lambda: "scope") assert observed.value is None assert observed.reason == "password_or_password_status_unavailable" + + +def test_a_failed_handle_read_never_makes_a_control_windowless(monkeypatch): + # uiautomation's NativeWindowHandle answers 0 when the COM read fails. + # The agent reads the raw element instead, so a windowed control whose + # handle it cannot read still owes a full proof. + import openadapt_flow.backends.win_agent.native_value as native + + class Element: + def __init__(self, raw): + self.raw = raw + + @property + def CurrentNativeWindowHandle(self): # noqa: N802 - UIA naming + if isinstance(self.raw, Exception): + raise self.raw + return self.raw + + cell = _windowless("DataItemControl", "Neil", bounds=(20, 140, 220, 180)) + for raw, windowless in ( + (None, True), + (0, True), + (OSError("COM"), False), + (5, False), + ): + cell.Element = Element(raw) + assert native.has_no_native_window(cell) is windowless + cell.Element = Element(OSError("COM")) + # It takes the strict path, which has no proof for it, and refuses. + assert _refusal(monkeypatch, cell) in { + "bound_identity_unavailable", + "native_identity_unavailable", + } From efa57343a0e32d350ee11d98aebc3c8fded5b9f5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 01:23:49 -0500 Subject: [PATCH 07/14] test(flow): stage the Windows stale-identity fault as a click-through surface, and keep occlusion as its own native refusal check --- .../win_agent/qualification_faults.py | 44 +++++++++++++++---- .../backends/win_agent/server.py | 3 ++ .../backends/windows_backend.py | 10 ++--- .../test_windows_qualification_campaign.py | 22 ++++++++++ .../test_windows_qualification_faults.py | 26 +++++++++-- 5 files changed, 87 insertions(+), 18 deletions(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/qualification_faults.py b/packages/flow/openadapt_flow/backends/win_agent/qualification_faults.py index d9c2aa9b9f..53a1c0d591 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/qualification_faults.py +++ b/packages/flow/openadapt_flow/backends/win_agent/qualification_faults.py @@ -26,14 +26,32 @@ Add-Type -ReferencedAssemblies System.Windows.Forms -TypeDefinition @' using System.Windows.Forms; public class QualificationOverlay : Form { + // A stale surface changes the pixels over the app while the same control + // stays under the point: layered and transparent to hit testing, so + // UI Automation and the keyboard lease still find the app's control. + public static bool ClickThrough; + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern bool SetLayeredWindowAttributes(System.IntPtr h, uint k, byte a, uint f); protected override bool ShowWithoutActivation { get { return true; } } protected override CreateParams CreateParams { - get { var cp = base.CreateParams; cp.ExStyle |= 0x08000000; return cp; } + get { + var cp = base.CreateParams; + cp.ExStyle |= 0x08000000; + if (ClickThrough) { cp.ExStyle |= 0x00080000 | 0x00000020; } + return cp; + } + } + protected override void OnHandleCreated(System.EventArgs e) { + base.OnHandleCreated(e); + // Fully opaque (alpha 255, LWA_ALPHA): nothing under it, such as a + // blinking caret, shows through and changes the frame. + if (ClickThrough) { SetLayeredWindowAttributes(Handle, 0, 255, 2); } } } '@ [Console]::InputEncoding = [Text.Encoding]::UTF8 $c = [Console]::In.ReadToEnd() | ConvertFrom-Json +[QualificationOverlay]::ClickThrough = ($c.kind -eq 'stale_identity') $f = New-Object QualificationOverlay $f.FormBorderStyle = 'None' $f.ShowInTaskbar = $false @@ -44,7 +62,7 @@ $x = [int]$c.bounds[0]; $y = [int]$c.bounds[1] $w = [Math]::Max(120, [int]$c.bounds[2] - $x) $h = [Math]::Max(40, [int]$c.bounds[3] - $y) -if ($c.kind -eq 'stale_identity') { +if ($c.kind -eq 'stale_identity' -or $c.kind -eq 'occlusion') { $f.Bounds = [Windows.Forms.SystemInformation]::VirtualScreen $l = New-Object Windows.Forms.Label $l.Name = 'qualification-stale-surface' @@ -114,6 +132,12 @@ def __init__(self, code: str) -> None: super().__init__(code) +#: Overlays the agent stages. ``occlusion`` is not a campaign fault: it is +#: the opaque full-screen overlay that covers the target and hit testing, +#: kept so native tests still prove that an occluded keyboard lease refuses. +STAGED_KINDS = frozenset({"ambiguity", "wrong_identity", "stale_identity", "occlusion"}) + + def validate_identity_offset( value: object, kind: str ) -> tuple[int, int, int, int] | None: @@ -212,11 +236,7 @@ def stage( *, identity_offset: tuple[int, int, int, int] | None = None, ) -> dict[str, Any]: - if not isinstance(kind, str) or kind not in { - "ambiguity", - "wrong_identity", - "stale_identity", - }: + if not isinstance(kind, str) or kind not in STAGED_KINDS: raise FaultStagingError("qualification_unknown_fault") try: offset = validate_identity_offset(identity_offset, kind) @@ -300,7 +320,15 @@ def stage( while time.monotonic() < deadline: if process.poll() is not None: raise FaultStagingError("qualification_overlay_exited") - if kind == "ambiguity": + if kind == "stale_identity": + # Click-through: the same control is still under the + # point, and only the pixels changed. + observed = self._uia("element-identity-at", target_point) + changed = ( + observed.get("status") == "ok" + and observed.get("identity") == identity + ) + elif kind == "ambiguity": observed = self._uia("find", {"locator": locator}) changed = ( observed.get("status") == "ok" diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 5fed7e71ce..dfa2294d89 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -4620,10 +4620,13 @@ def do_POST(self) -> None: # noqa: N802 - stdlib naming label="qualification fault", ) kind_value = data["kind"] + # "occlusion" is a native test overlay, not a + # campaign fault (see qualification_faults). if not isinstance(kind_value, str) or kind_value not in { "ambiguity", "wrong_identity", "stale_identity", + "occlusion", }: raise AgentRequestError( 400, "invalid_schema", "unknown qualification fault" diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index 98dcdeb297..acacad7f0c 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -1407,16 +1407,14 @@ def stage_qualification_fault( identity_offset: tuple[int, int, int, int] | None = None, ) -> str: """Stage one opt-in native test fault; absence never counts as success.""" - if not isinstance(kind, str) or kind not in { - "ambiguity", - "wrong_identity", - "stale_identity", - }: - raise ValueError("unknown Windows qualification fault") from openadapt_flow.backends.win_agent.qualification_faults import ( + STAGED_KINDS, validate_identity_offset, ) + if not isinstance(kind, str) or kind not in STAGED_KINDS: + raise ValueError("unknown Windows qualification fault") + offset = validate_identity_offset(identity_offset, kind) payload: dict[str, Any] = { "kind": kind, diff --git a/packages/flow/tests/e2e/test_windows_qualification_campaign.py b/packages/flow/tests/e2e/test_windows_qualification_campaign.py index 731a870883..eca52686e1 100644 --- a/packages/flow/tests/e2e/test_windows_qualification_campaign.py +++ b/packages/flow/tests/e2e/test_windows_qualification_campaign.py @@ -148,6 +148,28 @@ def after_run(ctx, current_backend, report): assert report.execution_outcome == "HALTED" assert after == expected + # Occlusion, kept apart from the stale-identity fault (now a + # click-through surface): an opaque overlay over the focused field + # and hit testing makes the native keyboard lease refuse before any + # input, and nothing is saved. + from openadapt_flow.backend import StructuralResolutionRefused + + reset() + assert save.anchor is not None and save.anchor.structural is not None + occlusion = backend.stage_qualification_fault( + "occlusion", save.anchor.structural + ) + try: + with pytest.raises( + StructuralResolutionRefused, + match="native keyboard lease observation unavailable", + ): + backend.guarded_keyboard_frame() + finally: + backend.clear_qualification_fault(occlusion) + assert host.rows() == baseline + evidence["occlusion_refused_before_input"] = True + result = qualify( bundle, config, diff --git a/packages/flow/tests/test_windows_qualification_faults.py b/packages/flow/tests/test_windows_qualification_faults.py index 68bdfa5bff..1050fbceb9 100644 --- a/packages/flow/tests/test_windows_qualification_faults.py +++ b/packages/flow/tests/test_windows_qualification_faults.py @@ -10,6 +10,7 @@ from openadapt_flow.backends.win_agent import AgentConfig, create_server from openadapt_flow.backends.win_agent.qualification_faults import ( + STAGED_KINDS, FaultStagingError, QualificationFaultController, ) @@ -50,7 +51,7 @@ class Surface: process = None def launch(self, payload): - assert payload["kind"] in {"ambiguity", "wrong_identity", "stale_identity"} + assert payload["kind"] in STAGED_KINDS self.staged = True self.process = Process() return self.process @@ -79,9 +80,20 @@ def controller(self): ) -@pytest.mark.parametrize("kind", ["ambiguity", "wrong_identity", "stale_identity"]) +# A stale surface is click-through: the same control stays under the point +# (UIA unchanged) while the pixels change. Every other overlay changes both. +CHANGES_UIA = { + "ambiguity": True, + "wrong_identity": True, + "occlusion": True, + "stale_identity": False, +} + + +@pytest.mark.parametrize("kind", sorted(CHANGES_UIA)) def test_staging_requires_changed_surface_and_uia_then_cleans_only_its_process(kind): surface = Surface() + surface.change_uia = CHANGES_UIA[kind] controller = surface.controller() receipt = controller.stage(kind, LOCATOR) assert receipt["kind"] == kind @@ -94,10 +106,16 @@ def test_staging_requires_changed_surface_and_uia_then_cleans_only_its_process(k @pytest.mark.parametrize("missing", ["change_pixels", "change_uia"]) -@pytest.mark.parametrize("kind", ["ambiguity", "wrong_identity", "stale_identity"]) +@pytest.mark.parametrize("kind", sorted(CHANGES_UIA)) def test_unobserved_mutation_declines_and_removes_overlay(kind, missing): surface = Surface() - setattr(surface, missing, False) + surface.change_uia = CHANGES_UIA[kind] + if missing == "change_pixels": + surface.change_pixels = False + else: + # The UIA side does the opposite of what this overlay must show: a + # stale surface that covers the control, or a fault that left it. + surface.change_uia = not CHANGES_UIA[kind] with pytest.raises(FaultStagingError, match="not_observed"): surface.controller().stage(kind, LOCATOR) assert surface.process.stopped From 035e63f9759c69dee541fd1df2b50b6e47286a63 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 01:59:43 -0500 Subject: [PATCH 08/14] test(flow): a stale-identity surface shows another record in the recorded identity box; report the windowless RuntimeId shape --- .../win_agent/qualification_faults.py | 26 ++++++++++++++++--- .../flow/openadapt_flow/qualify/windows.py | 14 +++++++--- .../tests/e2e/test_windows_hosted_governed.py | 10 +++++++ packages/flow/tests/test_qualify_windows.py | 1 + .../test_windows_qualification_faults.py | 17 +++++++++--- 5 files changed, 57 insertions(+), 11 deletions(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/qualification_faults.py b/packages/flow/openadapt_flow/backends/win_agent/qualification_faults.py index 53a1c0d591..c9a4915ad0 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/qualification_faults.py +++ b/packages/flow/openadapt_flow/backends/win_agent/qualification_faults.py @@ -63,7 +63,21 @@ $w = [Math]::Max(120, [int]$c.bounds[2] - $x) $h = [Math]::Max(40, [int]$c.bounds[3] - $y) if ($c.kind -eq 'stale_identity' -or $c.kind -eq 'occlusion') { - $f.Bounds = [Windows.Forms.SystemInformation]::VirtualScreen + $screen = [Windows.Forms.SystemInformation]::VirtualScreen + $f.Bounds = $screen + if ($c.kind -eq 'stale_identity' -and $null -ne $c.identity_bounds) { + # Another record where the verified one was shown. + $identity = New-Object Windows.Forms.Label + $identity.Name = 'qualification-stale-identity' + $identity.Text = 'Different record 8675309 2040-12-31' + $identity.AccessibleName = $identity.Text + $identity.Location = New-Object Drawing.Point(([int]$c.identity_bounds[0] - $screen.X), ([int]$c.identity_bounds[1] - $screen.Y)) + $identity.Size = New-Object Drawing.Size(([int]$c.identity_bounds[2] - [int]$c.identity_bounds[0]), ([int]$c.identity_bounds[3] - [int]$c.identity_bounds[1])) + $identity.Font = New-Object Drawing.Font('Segoe UI', 12) + $identity.BackColor = [Drawing.Color]::White + $identity.ForeColor = [Drawing.Color]::Black + $f.Controls.Add($identity) + } $l = New-Object Windows.Forms.Label $l.Name = 'qualification-stale-surface' $l.AccessibleName = 'Qualification stale surface' @@ -145,13 +159,13 @@ def validate_identity_offset( if value is None: return None if ( - kind != "wrong_identity" + kind not in {"wrong_identity", "stale_identity"} or not isinstance(value, (tuple, list)) or len(value) != 4 or any(isinstance(v, bool) or not isinstance(v, int) for v in value) ): raise ValueError( - "identity_offset requires four integer coordinates for wrong_identity" + "identity_offset requires four integer coordinates for an identity fault" ) dx, dy, width, height = value if ( @@ -242,6 +256,8 @@ def stage( offset = validate_identity_offset(identity_offset, kind) except ValueError as exc: raise FaultStagingError("qualification_invalid_identity_offset") from exc + if kind == "stale_identity" and offset is None: + raise FaultStagingError("qualification_invalid_identity_offset") if self._active is not None: raise FaultStagingError("qualification_mutation_active") before = self._uia("find", {"locator": locator}) @@ -344,7 +360,9 @@ def stage( and observed.get("identity") is not None and observed["identity"] != identity ) - if changed and identity_point is not None: + if changed and identity_point is not None and kind != "stale_identity": + # A click-through stale surface leaves the app's elements + # under both points; only the pixels show another record. at_region = self._uia("element-identity-at", identity_point) changed = ( at_region.get("status") == "ok" diff --git a/packages/flow/openadapt_flow/qualify/windows.py b/packages/flow/openadapt_flow/qualify/windows.py index 204648dc7e..fb63188eb9 100644 --- a/packages/flow/openadapt_flow/qualify/windows.py +++ b/packages/flow/openadapt_flow/qualify/windows.py @@ -26,10 +26,12 @@ ).hexdigest() WINDOWS_FAULT_DRIVER_ID = "openadapt.qualify.windows-faults" WINDOWS_FAULT_DRIVER_CONTRACT_SHA256 = hashlib.sha256( - b"openadapt.qualify.windows-faults/v2\n" + b"openadapt.qualify.windows-faults/v3\n" b"opt-in authenticated real UIA/physical overlays from the recorded locator; " b"ambiguity@target_resolution; wrong_identity@recorded_identifier_region; " - b"stale_identity@actuation_revalidation; weak_effect@effect_strength; " + b"stale_identity@actuation_revalidation as a click-through opaque surface " + b"showing another record in the recorded identifier region; " + b"weak_effect@effect_strength; " b"missing_effect@effect_verifier; owned cleanup" ).hexdigest() @@ -102,11 +104,15 @@ def _screen_fault(self, context: Any) -> str | None: ): self.declined = "native_save_locator_unavailable" return None - if context.fault_kind == "wrong_identity" and anchor.identifier_region is None: + # Both identity faults show another record in the recorded identity + # box: wrong_identity over the app, stale_identity click-through (the + # same control stays under the point, the record on screen changed). + identity_faults = {"wrong_identity", "stale_identity"} + if context.fault_kind in identity_faults and anchor.identifier_region is None: self.declined = "native_identity_region_unavailable" return None try: - if context.fault_kind == "wrong_identity": + if context.fault_kind in identity_faults: assert anchor.identifier_region is not None x, y, width, height = anchor.identifier_region click_x, click_y = anchor.click_point diff --git a/packages/flow/tests/e2e/test_windows_hosted_governed.py b/packages/flow/tests/e2e/test_windows_hosted_governed.py index 10de7eccda..9a903df42a 100644 --- a/packages/flow/tests/e2e/test_windows_hosted_governed.py +++ b/packages/flow/tests/e2e/test_windows_hosted_governed.py @@ -548,9 +548,19 @@ def _windowless_checks(hwnd: int, limit: int = 8) -> list[Any]: break node = node.GetParentControl() offscreen = getattr(control, "IsOffscreen", None) + try: + raw = control.GetRuntimeId() + runtime_shape: Any = { + "type": type(raw).__name__, + "length": len(raw) if raw is not None else None, + "item_types": sorted({type(item).__name__ for item in raw or ()}), + } + except Exception as exc: # noqa: BLE001 + runtime_shape = {"error": type(exc).__name__} rows.append( { "type": control.ControlTypeName, + "runtime_shape": runtime_shape, "pid_matches": control.ProcessId == pid, "runtime_id": bool(agent._runtime_id(control)), "chain_reaches_window": chain_ok, diff --git a/packages/flow/tests/test_qualify_windows.py b/packages/flow/tests/test_qualify_windows.py index a9fe2835b9..d227598bed 100644 --- a/packages/flow/tests/test_qualify_windows.py +++ b/packages/flow/tests/test_qualify_windows.py @@ -304,6 +304,7 @@ def _native_save_workflow(): workflow.steps[-1].anchor.structural = StructuralLocator( automation_id="commit", role="button" ) + workflow.steps[-1].anchor.identifier_region = (10, 10, 100, 30) return workflow diff --git a/packages/flow/tests/test_windows_qualification_faults.py b/packages/flow/tests/test_windows_qualification_faults.py index 1050fbceb9..f13ca21ad6 100644 --- a/packages/flow/tests/test_windows_qualification_faults.py +++ b/packages/flow/tests/test_windows_qualification_faults.py @@ -90,12 +90,18 @@ def controller(self): } +def _offset(kind): + """A stale surface always carries the recorded identity box (wrong + identity's own region checks have their own tests below).""" + return {"identity_offset": (-40, -20, 120, 20)} if kind == "stale_identity" else {} + + @pytest.mark.parametrize("kind", sorted(CHANGES_UIA)) def test_staging_requires_changed_surface_and_uia_then_cleans_only_its_process(kind): surface = Surface() surface.change_uia = CHANGES_UIA[kind] controller = surface.controller() - receipt = controller.stage(kind, LOCATOR) + receipt = controller.stage(kind, LOCATOR, **_offset(kind)) assert receipt["kind"] == kind assert len(receipt["mutation_id"]) == 32 with pytest.raises(FaultStagingError, match="not_owned"): @@ -117,10 +123,15 @@ def test_unobserved_mutation_declines_and_removes_overlay(kind, missing): # stale surface that covers the control, or a fault that left it. surface.change_uia = not CHANGES_UIA[kind] with pytest.raises(FaultStagingError, match="not_observed"): - surface.controller().stage(kind, LOCATOR) + surface.controller().stage(kind, LOCATOR, **_offset(kind)) assert surface.process.stopped +def test_a_stale_surface_needs_the_recorded_identity_box(): + with pytest.raises(FaultStagingError, match="invalid_identity_offset"): + Surface().controller().stage("stale_identity", LOCATOR) + + def test_incomplete_census_never_launches_a_fault(): surface = Surface() surface.truncated = True @@ -330,7 +341,7 @@ def test_changed_save_label_cannot_attest_unchanged_record_identity(): ("wrong_identity", [32769, 0, 1, 1]), ("wrong_identity", [0, 0, 1, 1, 1]), ("ambiguity", [0, 0, 120, 20]), - ("stale_identity", [0, 0, 120, 20]), + ("occlusion", [0, 0, 120, 20]), ], ) def test_identity_rectangle_schema_refuses_unbounded_and_unrelated_mutations( From 7e0559581a48c9682123d1c90633f159efcc98d4 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 02:55:47 -0500 Subject: [PATCH 09/14] fix(flow): bind a windowless grid cell with no RuntimeId by its structural path, as its own digest-only kind --- packages/flow/docs/LIMITS.md | 11 +- .../approval_mode/form_state.py | 16 +- .../approval_mode/item_approval.py | 4 +- .../approval_mode/window_fields.py | 21 +- .../backends/win_agent/native_value.py | 29 ++- .../backends/win_agent/server.py | 132 +++++++++++- .../flow/tests/test_approval_form_fields.py | 202 ++++++++++++++++++ 7 files changed, 390 insertions(+), 25 deletions(-) diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index 751684484d..2009f2164b 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -35,8 +35,15 @@ by its parent, such as a grid cell, a grid column header or the title bar, has no second source. Its UI Automation value is read twice and must match, and the screen text over it is still read. If the provider cuts that value short, a change in the hidden part that also leaves the visible text the same -is not detected. This value is used only for that check: it is never a -complete value, read-back evidence or the basis of a VERIFIED result. An +is not detected. Some providers give such a control no RuntimeId at all +(WinForms grid cells and column headers). That control is then bound by its +path: each element up to an ancestor that has a RuntimeId, by type, position +and index among its siblings, read again before and after each of the two +reads. If a provider swaps in another element with the same type, position +and index, the check reads it as the same control; a changed value still +shows in the two reads or in the screen text. A scroll or resize between the +reads stops the item. These values are used only for that check: they are +never complete values, read-back evidence or the basis of a VERIFIED result. An editable control, a password field, a control whose password status is unknown, or one whose two reads differ still stops the item. diff --git a/packages/flow/openadapt_flow/approval_mode/form_state.py b/packages/flow/openadapt_flow/approval_mode/form_state.py index 599663b18e..00b73606f3 100644 --- a/packages/flow/openadapt_flow/approval_mode/form_state.py +++ b/packages/flow/openadapt_flow/approval_mode/form_state.py @@ -30,7 +30,11 @@ and equal, enters the digest as ``uia_only_unverified``; its pixels are never painted out, so OCR still reads them, and the read is never a complete value. Limit: a provider that truncates the value could hide a - suffix that changes while OCR sees nothing change either. + suffix that changes while OCR sees nothing change either. A control whose + provider gives no RuntimeId (WinForms grid cells and headers) is bound by + its structural path up to an ancestor that has one, and reads as + ``uia_only_structural``; a provider that swaps in another element with + the same type, bounds and index reads as the same control. Only a digest leaves this module. The digest stays in the run directory; it never enters the report or anything sent to Cloud. @@ -45,6 +49,7 @@ from typing import Any, Optional, Sequence from openadapt_flow.approval_mode.window_fields import ( + UIA_ONLY_STRUCTURAL, UIA_ONLY_UNVERIFIED, UNMASKED_KINDS, valid_form_field, @@ -240,9 +245,14 @@ def window_fields_state( return None # A read that includes an unverified (windowless) value is its own kind, # so its digest never equals one from a read that proved every value. + # The weakest binding in the read names it: a structural-path value, + # then a RuntimeId-bound one, then a read that proved every value. + kinds = {row[0] for row in rows} kind = ( - "window_fields_uia_only_unverified" - if any(row[0] == UIA_ONLY_UNVERIFIED for row in rows) + "window_fields_uia_only_structural" + if UIA_ONLY_STRUCTURAL in kinds + else "window_fields_uia_only_unverified" + if UIA_ONLY_UNVERIFIED in kinds else "window_fields" ) return _digest(kind, {"window": list(window), "fields": rows, "words": words}) diff --git a/packages/flow/openadapt_flow/approval_mode/item_approval.py b/packages/flow/openadapt_flow/approval_mode/item_approval.py index 234ddbe3e6..c0d7594bfe 100644 --- a/packages/flow/openadapt_flow/approval_mode/item_approval.py +++ b/packages/flow/openadapt_flow/approval_mode/item_approval.py @@ -247,7 +247,8 @@ class ItemApprovalRequest(BaseModel): #: the platform's accessibility API with the rest of it read by OCR. #: ``window_fields_uia_only_unverified`` is that read when it includes a #: windowless control's unverified UIA value (never equal to a fully - #: proved read). + #: proved read); ``window_fields_uia_only_structural`` when one of those + #: values is bound by its structural path (no RuntimeId). #: ``api_request`` when the save is an API step: the digest is then the #: exact request, the record and the record check (``api_request``). form_state_kind: Literal[ @@ -255,6 +256,7 @@ class ItemApprovalRequest(BaseModel): "screen_text", "window_fields", "window_fields_uia_only_unverified", + "window_fields_uia_only_structural", "api_request", ] form_state_sha256: str = Field(pattern=PREFIXED_SHA256_PATTERN) diff --git a/packages/flow/openadapt_flow/approval_mode/window_fields.py b/packages/flow/openadapt_flow/approval_mode/window_fields.py index bd1d0d9a0b..d18f392210 100644 --- a/packages/flow/openadapt_flow/approval_mode/window_fields.py +++ b/packages/flow/openadapt_flow/approval_mode/window_fields.py @@ -13,11 +13,17 @@ #: It enters the approval digest only, never masks pixels, and never counts #: as a complete value or as read-back evidence. UIA_ONLY_UNVERIFIED = "uia_only_unverified" -FIELD_KINDS = frozenset( - {"title_bar", "edit", "value", "text", "state", UIA_ONLY_UNVERIFIED} +#: The same read for a control whose provider gives no RuntimeId (WinForms +#: grid cells and headers), bound by its structural path instead. Weaker +#: than a RuntimeId binding: a same-type, same-bounds, same-index swap reads +#: as the same control. Digest only, never masked, never complete. +UIA_ONLY_STRUCTURAL = "uia_only_structural" +UNVERIFIED_KINDS = frozenset({UIA_ONLY_UNVERIFIED, UIA_ONLY_STRUCTURAL}) +FIELD_KINDS = frozenset({"title_bar", "edit", "value", "text", "state"}) | ( + UNVERIFIED_KINDS ) #: Kinds whose rectangle is never painted out of the OCR read. -UNMASKED_KINDS = frozenset({"state", "value", UIA_ONLY_UNVERIFIED}) +UNMASKED_KINDS = frozenset({"state", "value"}) | UNVERIFIED_KINDS FIELD_STATES = frozenset({None, "on", "off", "indeterminate", "selected", "unselected"}) # The host checks the format it understands, independently of the deployed @@ -73,8 +79,8 @@ def valid_form_field(field: Any, *, pid: int | None = None) -> bool: ``text`` without a value proof is the established visible-label channel; value-backed cells must carry a proof. Containers and empty values enter the digest but leave their pixels visible. ``uia_only_unverified`` (a - windowless control's value) never carries a proof, never masks, and is - never a complete value. A proof is observation metadata, + windowless control's value) and ``uia_only_structural`` never + carry a proof, never mask, and are never complete values. A proof is observation metadata, not a signature or caller-provided authorization. """ try: @@ -93,10 +99,7 @@ def valid_form_field(field: Any, *, pid: int | None = None) -> bool: or rect[2] <= 0 or rect[3] <= 0 or (kind in {"edit", "value"} and (proof is None or state is not None)) - or ( - kind in {"title_bar", "state", UIA_ONLY_UNVERIFIED} - and proof is not None - ) + or (kind in {"title_bar", "state"} | UNVERIFIED_KINDS and proof is not None) or (kind == "state" and (text != "" or state is None)) ): return False diff --git a/packages/flow/openadapt_flow/backends/win_agent/native_value.py b/packages/flow/openadapt_flow/backends/win_agent/native_value.py index c1fb477603..7c2a05d72d 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -629,15 +629,24 @@ def has_no_native_window(control: Any) -> bool: return raw is None or (type(raw) is int and raw == 0) -def _windowless_identity(control: Any) -> tuple[int, tuple[int, ...]]: +def _windowless_identity( + control: Any, *, structural: bool +) -> tuple[int, tuple[int, ...]]: + """The control's process and RuntimeId, re-read for every guard. + + A RuntimeId-bound read needs a real RuntimeId (1..64 integers). A + structural read is for a control whose provider gives an empty RuntimeId + (WinForms DataGridView cells and headers); it must stay exactly empty, so + a control that has a RuntimeId never falls back to the structural path. + """ pid = control.ProcessId runtime = control.GetRuntimeId() if ( not has_no_native_window(control) or not _positive_int(pid) or not isinstance(runtime, (tuple, list)) - or not 1 <= len(runtime) <= 64 or any(type(item) is not int for item in runtime) + or (len(runtime) != 0 if structural else not 1 <= len(runtime) <= 64) ): raise ValueUnavailable("windowless_identity_unavailable") return pid, tuple(runtime) @@ -647,6 +656,7 @@ def observe_uia_only_value( control: Any, *, identity: Callable[[], str | None], + structural: bool = False, clock: Callable[[], float] = time.monotonic, ) -> UnverifiedValue: """Read a windowless, read-only, non-password control's UIA value twice. @@ -657,9 +667,11 @@ def observe_uia_only_value( first and is the last check before every provider access, exactly as for a complete read, so a password or unknown status refuses. The ValuePattern must say read-only before and after each read. Both reads - are bracketed by the caller's bound scope (``identity``) and must agree. - Anything else returns ``value=None`` with a fixed reason; no provider - text or exception crosses this boundary. + are bracketed by the caller's bound scope (``identity``), re-read before + and after each read, and must agree. ``structural`` is for a control with + an empty RuntimeId: the caller's scope is then its structural path, and + the RuntimeId must stay empty. Anything else returns ``value=None`` with a + fixed reason; no provider text or exception crosses this boundary. """ try: require_non_sensitive_value(control) @@ -667,20 +679,21 @@ def observe_uia_only_value( binding = identity() if not isinstance(binding, str) or not 1 <= len(binding) <= 256: raise ValueUnavailable("bound_identity_unavailable") - bound = _windowless_identity(control) + bound = _windowless_identity(control, structural=structural) def guard(*, scope: bool = False) -> None: if clock() >= deadline: raise ValueUnavailable("value_observation_deadline") if (scope and identity() != binding) or _windowless_identity( - control + control, structural=structural ) != bound: raise ValueUnavailable("value_identity_changed") # This MUST be last, as in observe_complete_value. require_non_sensitive_value(control) def uia() -> str: - guard() + # The bound scope is re-read before and after each value read. + guard(scope=True) method = control.GetValuePattern guard() pattern = method() diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index dfa2294d89..5624c7ede0 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -3013,6 +3013,116 @@ def _form_value_identity( return None +def _raw_runtime(control: object) -> Optional[tuple[int, ...]]: + """The provider's RuntimeId exactly: a tuple (possibly empty), or None. + + Unlike :func:`_runtime_id`, an unreadable or malformed answer is None, + never an empty RuntimeId, so a read failure cannot select the structural + path. + """ + try: + method = getattr(control, "GetRuntimeId") + value = method() + except Exception: # noqa: BLE001 - unreadable is not empty + return None + if not isinstance(value, (tuple, list)) or len(value) > 64: + return None + if any(type(item) is not int for item in value): + return None + return tuple(value) + + +def _child_index(parent: object, node: object, auto: Any) -> Optional[int]: + """The one position of ``node`` among ``parent``'s children, or None.""" + try: + same = auto.ControlsAreSame + children = list(parent.GetChildren()) # type: ignore[attr-defined] + matches = [i for i, child in enumerate(children) if same(child, node)] + except Exception: # noqa: BLE001 - an unknown position is no path + return None + return matches[0] if len(matches) == 1 else None + + +def _form_windowless_path( + control: object, window: object, hwnd: int, scope: Callable[[], bool], auto: Any +) -> Optional[str]: + """Fresh structural path of a windowless control with no RuntimeId. + + WinForms gives DataGridView cells and column headers an empty RuntimeId, + so they cannot be bound the way :func:`_form_windowless_identity` binds + a control. Each node from the control up to the bound window contributes + its RuntimeId when it has one, else its control type, bounds and its one + index among its parent's children. The path must reach an ancestor with + a real RuntimeId and end at the bound window (hwnd and process). The + caller re-reads it before and after each value read; any difference + (a scroll, a resize, a new row) refuses. + + Limit: a provider that swaps in another element with the same type, + bounds and index reads as the same path. This binding serves only the + approval digest's change detection (``uia_only_structural``); it is + never used for actions, focus, read-back, edit baselines or VERIFIED. + """ + try: + if not scope() or _control_value(window, "NativeWindowHandle", None) != hwnd: + return None + if not _native_value_api().has_no_native_window(control): + return None + pid = _control_value(window, "ProcessId", None) + root_id = _raw_runtime(window) + if not root_id or not isinstance(pid, int) or isinstance(pid, bool): + return None + if _raw_runtime(control) != (): + return None + path: list[Any] = [] + anchored = False + node: Any = control + for _ in range(_MAX_UIA_DEPTH): + if _control_value(node, "ProcessId", None) != pid: + return None + runtime = _raw_runtime(node) + if runtime is None: + return None + if runtime == root_id: + path.append(["window", list(runtime)]) + break + parent = node.GetParentControl() + if parent is None: + return None + if runtime: + anchored = anchored or node is not control + path.append(["runtime", list(runtime)]) + else: + index = _child_index(parent, node, auto) + node_bounds = _bounds(node) + node_type = _control_value(node, "ControlTypeName", None) + if index is None or node_bounds is None or not node_type: + return None + path.append(["path", node_type, node_bounds, index]) + node = parent + else: + return None + if not anchored: + return None + bounds = _bounds(control) + if bounds is None or _control_value(control, "IsOffscreen", None) is not False: + return None + return hashlib.sha256( + json.dumps( + [ + "windowless-structural", + hwnd, + pid, + path, + bounds, + _control_value(control, "ControlTypeName", None), + ], + separators=(",", ":"), + ).encode("utf-8") + ).hexdigest() + except Exception: # noqa: BLE001 - a missing scope is never complete + return None + + def _form_windowless_identity( control: object, window: object, hwnd: int, scope: Callable[[], bool] ) -> Optional[str]: @@ -3493,12 +3603,28 @@ def append_state() -> None: # pixels, and never counts as complete (UnverifiedValue). # Limit: a provider that truncates could hide a suffix that # changes while OCR also sees nothing change. + # A RuntimeId binds the read to the element. A provider that + # gives none (WinForms grid cells and headers) is bound by its + # structural path instead; an unreadable RuntimeId refuses, and a + # control with one never falls back to the path. + own_runtime = _raw_runtime(control) + if own_runtime is None: + return _form_refused( + "observation", + "value_identity", + "value_identity_unavailable", + visited, + ) + structural = len(own_runtime) == 0 + def windowless(c: object = control) -> Optional[str]: + if structural: + return _form_windowless_path(c, window, hwnd, scope, auto) return _form_windowless_identity(c, window, hwnd, scope) bound_scope = windowless() unverified = _native_value_api().observe_uia_only_value( - control, identity=windowless + control, identity=windowless, structural=structural ) if unverified.value is None: reason = ( @@ -3522,7 +3648,9 @@ def windowless(c: object = control) -> Optional[str]: assert bounds is not None fields.append( { - "kind": "uia_only_unverified", + "kind": ( + "uia_only_structural" if structural else "uia_only_unverified" + ), "rect": _rect(bounds), "text": unverified.value, "state": state, diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 202ac04348..d2e1464386 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -623,6 +623,7 @@ def read(self, owner, *, guard): monkeypatch.setattr(native, "Win32TextReader", Reader) auto = types.SimpleNamespace( ControlFromHandle=lambda hwnd: controls.get(hwnd), + ControlsAreSame=lambda first, second: first is second, UIAutomationInitializerInThread=_Init, ) monkeypatch.setitem(sys.modules, "uiautomation", auto) @@ -1282,3 +1283,204 @@ def CurrentNativeWindowHandle(self): # noqa: N802 - UIA naming "bound_identity_unavailable", "native_identity_unavailable", } + + +def _no_runtime(*controls): + """WinForms gives DataGridView rows, cells and headers no RuntimeId.""" + for control in controls: + control.GetRuntimeId = lambda: () + + +def _structural_grid(cell): + row = _Control( + "CustomControl", bounds=(20, 140, 620, 180), selected=True, children=[cell] + ) + row.NativeWindowHandle = 0 + grid = _Control("TableControl", bounds=(20, 60, 630, 280), children=[row]) + _no_runtime(row, cell) + return grid, row + + +def test_a_grid_cell_without_a_runtime_id_binds_by_its_path_under_the_grid( + monkeypatch, +): + window, headers, cells, title = _census_window() + grid = window._children[2] + _no_runtime(*headers, *cells, *grid._children) + perform = _agent(monkeypatch, window) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert answer["refusal"] is None + kinds = [(f["kind"], f["text"]) for f in answer["fields"]] + assert [text for kind, text in kinds if kind == "uia_only_structural"] == [ + "first", + "last", + "dob", + "Neil", + "Sorenson", + "1984-03-12", + ] + # The title bar has a RuntimeId and keeps the RuntimeId binding. + assert ("uia_only_unverified", "Patient Notes - Benchmark Harness") in kinds + frame = io.BytesIO() + Image.new("RGB", SIZE, "white").save(frame, format="PNG") + state = window_fields_state( + SimpleNamespace(ocr=lambda _png: []), + frame.getvalue(), + {"bounds": (0, 0, 1024, 720), "fields": answer["fields"]}, + ) + assert state is not None and state[0] == "window_fields_uia_only_structural" + + +def test_a_path_with_no_runtime_id_up_to_the_window_refuses(monkeypatch): + cell = _windowless("DataItemControl", "Neil", bounds=(20, 140, 220, 180)) + grid, row = _structural_grid(cell) + _no_runtime(grid) + assert _refusal(monkeypatch, grid) == "bound_identity_unavailable" + + +def test_bounds_that_change_between_the_two_reads_refuse(monkeypatch): + class Scrolls(_Control): + reads = 0 + + def GetValuePattern(self): + self.reads += 1 + if self.reads == 2: + # The grid scrolled: the row moved between the two reads. + row.BoundingRectangle = _Rect(20, 180, 620, 220) + return SimpleNamespace(Value="Neil", IsReadOnly=True) + + cell = Scrolls("DataItemControl", bounds=(20, 140, 220, 180), value="Neil") + cell.NativeWindowHandle = 0 + grid, row = _structural_grid(cell) + assert _refusal(monkeypatch, grid) == "value_identity_changed" + + +def test_two_structural_reads_that_disagree_refuse(monkeypatch): + class Flicker(_Control): + reads = 0 + + def GetValuePattern(self): + self.reads += 1 + value = "Neil" if self.reads == 1 else "Neil Sorenson" + return SimpleNamespace(Value=value, IsReadOnly=True) + + cell = Flicker("DataItemControl", bounds=(20, 140, 220, 180), value="Neil") + cell.NativeWindowHandle = 0 + grid, _row = _structural_grid(cell) + assert _refusal(monkeypatch, grid) == "value_observation_changed" + + +@pytest.mark.parametrize( + "password", + [True, _UNSUPPORTED_PROPERTY, None], + ids=["password", "status-unsupported", "status-missing"], +) +def test_a_structural_password_or_unknown_status_cell_refuses(monkeypatch, password): + class Unread(_Control): + def GetValuePattern(self): + raise AssertionError("no value read on a sensitive control") + + cell = Unread( + "DataItemControl", bounds=(20, 140, 220, 180), value="x", password=password + ) + cell.NativeWindowHandle = 0 + cell.read_only = True + grid, _row = _structural_grid(cell) + assert _refusal(monkeypatch, grid) in { + "visibility_unknown", + "password_or_password_status_unavailable", + } + + +def test_an_unreadable_runtime_id_never_falls_back_to_the_path(monkeypatch): + cell = _windowless("DataItemControl", "Neil", bounds=(20, 140, 220, 180)) + grid, _row = _structural_grid(cell) + + def unreadable(): + raise OSError("provider failed") + + cell.GetRuntimeId = unreadable + assert _refusal(monkeypatch, grid) == "value_identity_unavailable" + + +def test_a_runtime_id_that_disappears_mid_read_refuses(monkeypatch): + # A control read with its RuntimeId keeps needing it: if the provider + # stops giving one between the reads, the read refuses. + class Loses(_Control): + reads = 0 + + def GetValuePattern(self): + self.reads += 1 + if self.reads == 2: + self.GetRuntimeId = lambda: () + return SimpleNamespace(Value="Neil", IsReadOnly=True) + + cell = Loses("DataItemControl", bounds=(20, 140, 220, 180), value="Neil") + cell.NativeWindowHandle = 0 + assert _refusal(monkeypatch, cell) in { + "value_identity_changed", + "windowless_identity_unavailable", + } + + +def test_a_structural_value_is_never_a_proof_or_read_back(monkeypatch): + import openadapt_flow.backends.win_agent.native_value as native + from openadapt_flow.approval_mode.window_fields import ( + valid_form_field, + valid_value_observation, + ) + + cell = _windowless("DataItemControl", "Neil", bounds=(20, 140, 220, 180)) + cell.AutomationId = "cell" + grid, _row = _structural_grid(cell) + window = _window(grid) + perform = _agent(monkeypatch, window) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + field = next(f for f in answer["fields"] if f["kind"] == "uia_only_structural") + assert field["value_proof"] is None and field["value_identity"] is None + assert not valid_value_proof(field["text"], field["value_proof"]) + assert not valid_value_observation(field["text"], field["value_proof"], None) + assert not valid_form_field({**field, "value_proof": _proof("Neil")}) + observed = native.observe_uia_only_value( + cell, identity=lambda: "scope", structural=True + ) + assert observed.value == "Neil" and not observed.complete and observed.proof is None + assert not native.observe_complete_value(cell, identity=lambda: "scope").complete + sys.modules["uiautomation"].GetRootControl = lambda: window + assert not perform("read", {"locator": {"automation_id": "cell"}}).get("complete") + + +def test_the_three_window_read_kinds_never_compare_equal(): + frame = io.BytesIO() + Image.new("RGB", SIZE, "white").save(frame, format="PNG") + no_words = SimpleNamespace(ocr=lambda _png: []) + base = { + "rect": [20, 140, 200, 40], + "text": "Neil", + "state": None, + "value_proof": None, + "value_identity": None, + } + states = [ + window_fields_state( + no_words, + frame.getvalue(), + {"bounds": (0, 0, 1024, 720), "fields": [field]}, + ) + for field in ( + {**base, "kind": "uia_only_structural"}, + {**base, "kind": "uia_only_unverified"}, + { + **base, + "kind": "edit", + "value_proof": _proof("Neil"), + "value_identity": "a" * 64, + }, + ) + ] + assert [state[0] for state in states] == [ + "window_fields_uia_only_structural", + "window_fields_uia_only_unverified", + "window_fields", + ] + assert len({state[1] for state in states}) == 3 From f05e0cef52bd770b23abda755d8f62289fe74f56 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 03:29:25 -0500 Subject: [PATCH 10/14] test(flow): report which windowless value read stage fails --- .../tests/e2e/test_windows_hosted_governed.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/packages/flow/tests/e2e/test_windows_hosted_governed.py b/packages/flow/tests/e2e/test_windows_hosted_governed.py index 9a903df42a..776475126b 100644 --- a/packages/flow/tests/e2e/test_windows_hosted_governed.py +++ b/packages/flow/tests/e2e/test_windows_hosted_governed.py @@ -557,9 +557,35 @@ def _windowless_checks(hwnd: int, limit: int = 8) -> list[Any]: } except Exception as exc: # noqa: BLE001 runtime_shape = {"error": type(exc).__name__} + value_read: dict[str, Any] = {} + try: + stage = "GetValuePattern" + pattern = control.GetValuePattern() + value_read["pattern"] = type(pattern).__name__ + stage = "IsReadOnly" + read_only = pattern.IsReadOnly + value_read["read_only"] = ( + read_only + if isinstance(read_only, bool) + else type(read_only).__name__ + ) + stage = "Value" + value = pattern.Value + value_read["value"] = ( + {"length": len(value)} + if isinstance(value, str) + else type(value).__name__ + ) + except Exception as exc: # noqa: BLE001 + value_read["error"] = [stage, type(exc).__name__] rows.append( { "type": control.ControlTypeName, + "value_read": value_read, + "structural_identity": agent._form_windowless_path( + control, window, hwnd, lambda: True, auto + ) + is not None, "runtime_shape": runtime_shape, "pid_matches": control.ProcessId == pid, "runtime_id": bool(agent._runtime_id(control)), From 4b05d94854ae5ba31e01c2e66411d02b02f87555 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 04:07:31 -0500 Subject: [PATCH 11/14] fix(flow): read a windowless value through GetPattern when the control class has no GetValuePattern --- .../backends/win_agent/native_value.py | 13 ++++++++-- .../tests/e2e/test_windows_hosted_governed.py | 8 ++++++- .../flow/tests/test_approval_form_fields.py | 24 +++++++++++++++++++ 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/native_value.py b/packages/flow/openadapt_flow/backends/win_agent/native_value.py index 7c2a05d72d..a6f52b0070 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -16,6 +16,7 @@ MAX_UTF16_UNITS = 65536 PROOF_SCHEMA = "openadapt.native-value-completeness/v3" IS_PASSWORD_PROPERTY = 30019 +VALUE_PATTERN_ID = 10002 # Win32 EDIT password evidence: the ES_PASSWORD style and EM_GETPASSWORDCHAR. ES_PASSWORD = 0x0020 EM_GETPASSWORDCHAR = 0x00D2 @@ -694,10 +695,18 @@ def guard(*, scope: bool = False) -> None: def uia() -> str: # The bound scope is re-read before and after each value read. guard(scope=True) - method = control.GetValuePattern + # uiautomation gives only some control classes GetValuePattern + # (not HeaderControl or TitleBarControl); every control has the + # generic GetPattern, which answers None when unsupported. + method = getattr(control, "GetValuePattern", None) guard() - pattern = method() + if callable(method): + pattern = method() + else: + pattern = control.GetPattern(VALUE_PATTERN_ID) guard() + if pattern is None: + raise ValueUnavailable("value_pattern_unavailable") read_only = getattr(pattern, "IsReadOnly", None) guard() if read_only is not True: diff --git a/packages/flow/tests/e2e/test_windows_hosted_governed.py b/packages/flow/tests/e2e/test_windows_hosted_governed.py index 776475126b..ccd64f4d4e 100644 --- a/packages/flow/tests/e2e/test_windows_hosted_governed.py +++ b/packages/flow/tests/e2e/test_windows_hosted_governed.py @@ -558,9 +558,15 @@ def _windowless_checks(hwnd: int, limit: int = 8) -> list[Any]: except Exception as exc: # noqa: BLE001 runtime_shape = {"error": type(exc).__name__} value_read: dict[str, Any] = {} + try: + legacy = control.GetLegacyIAccessiblePattern() + value_read["legacy_read_only"] = bool(int(legacy.State) & 0x40) + except Exception as exc: # noqa: BLE001 + value_read["legacy_read_only"] = type(exc).__name__ try: stage = "GetValuePattern" - pattern = control.GetValuePattern() + getter = getattr(control, "GetValuePattern", None) + pattern = getter() if callable(getter) else control.GetPattern(10002) value_read["pattern"] = type(pattern).__name__ stage = "IsReadOnly" read_only = pattern.IsReadOnly diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index d2e1464386..229a56039e 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -1484,3 +1484,27 @@ def test_the_three_window_read_kinds_never_compare_equal(): "window_fields", ] assert len({state[1] for state in states}) == 3 + + +@pytest.mark.parametrize("control_type", ["HeaderControl", "TitleBarControl"]) +def test_a_control_class_without_get_value_pattern_reads_through_get_pattern( + monkeypatch, control_type +): + # uiautomation's HeaderControl and TitleBarControl have no + # GetValuePattern; the generic GetPattern(ValuePattern) reads them. + import openadapt_flow.backends.win_agent.native_value as native + + class Generic(_Control): + GetValuePattern = None # type: ignore[assignment] + + def GetPattern(self, pattern_id): + assert pattern_id == native.VALUE_PATTERN_ID + return SimpleNamespace(Value=self._value, IsReadOnly=True) + + control = Generic(control_type, bounds=(20, 140, 220, 180), value="first") + control.NativeWindowHandle = 0 + perform = _agent(monkeypatch, _window(control)) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert [(f["kind"], f["text"]) for f in answer["fields"]] == [ + ("uia_only_unverified", "first") + ] From 41431aad9f3f32d4071341cdedd915ea76de3d73 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 04:10:37 -0500 Subject: [PATCH 12/14] fix(flow): admit an editable-flagged windowless grid cell, header or title bar as digest-only approval evidence --- packages/flow/docs/LIMITS.md | 8 ++- .../backends/win_agent/native_value.py | 20 +++++-- .../backends/win_agent/server.py | 51 +++++++++++++++- .../flow/tests/test_approval_form_fields.py | 59 +++++++++++++++++++ 4 files changed, 131 insertions(+), 7 deletions(-) diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index 2009f2164b..a43eb01f9c 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -42,8 +42,12 @@ and index among its siblings, read again before and after each of the two reads. If a provider swaps in another element with the same type, position and index, the check reads it as the same control; a changed value still shows in the two reads or in the screen text. A scroll or resize between the -reads stops the item. These values are used only for that check: they are -never complete values, read-back evidence or the basis of a VERIFIED result. An +reads stops the item. A grid or list cell, a header or the title bar is +included even when its provider reports it as editable (WinForms does so +for a read-only grid); a text box never is. These values are used only for +that check: they are never complete values, read-back evidence or the basis +of a VERIFIED result. Read-back, not the approval check, verifies what a +save wrote. An editable control, a password field, a control whose password status is unknown, or one whose two reads differ still stops the item. diff --git a/packages/flow/openadapt_flow/backends/win_agent/native_value.py b/packages/flow/openadapt_flow/backends/win_agent/native_value.py index a6f52b0070..550dc16f0d 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -658,6 +658,7 @@ def observe_uia_only_value( *, identity: Callable[[], str | None], structural: bool = False, + allow_editable: bool = False, clock: Callable[[], float] = time.monotonic, ) -> UnverifiedValue: """Read a windowless, read-only, non-password control's UIA value twice. @@ -671,8 +672,12 @@ def observe_uia_only_value( are bracketed by the caller's bound scope (``identity``), re-read before and after each read, and must agree. ``structural`` is for a control with an empty RuntimeId: the caller's scope is then its structural path, and - the RuntimeId must stay empty. Anything else returns ``value=None`` with a - fixed reason; no provider text or exception crosses this boundary. + the RuntimeId must stay empty. ``allow_editable`` (only for a grid or + list cell, a header or a title bar; the caller decides that scope) also + accepts a ValuePattern that says editable, as long as the flag is the + same at every check; it adds a value to the digest and never makes one + complete. Anything else returns ``value=None`` with a fixed reason; no + provider text or exception crosses this boundary. """ try: require_non_sensitive_value(control) @@ -709,19 +714,26 @@ def uia() -> str: raise ValueUnavailable("value_pattern_unavailable") read_only = getattr(pattern, "IsReadOnly", None) guard() - if read_only is not True: + if type(read_only) is not bool: + raise ValueUnavailable("read_only_or_read_only_status_unavailable") + if not read_only and not allow_editable: raise ValueUnavailable("value_not_read_only") + if readability and readability[0] is not read_only: + # The flag flipped between the two reads. + raise ValueUnavailable("value_readability_changed") + readability.append(read_only) value = getattr(pattern, "Value", None) guard() if not isinstance(value, str): raise ValueUnavailable("value_pattern_unavailable") if len(utf16_bytes(value)) // 2 > MAX_UTF16_UNITS: raise ValueUnavailable("value_exceeds_limit") - if getattr(pattern, "IsReadOnly", None) is not True: + if getattr(pattern, "IsReadOnly", None) is not read_only: raise ValueUnavailable("value_readability_changed") guard(scope=True) return value + readability: list[bool] = [] first = uia() second = uia() guard(scope=True) diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 5624c7ede0..0469c06bfc 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -3013,6 +3013,52 @@ def _form_value_identity( return None +#: Windowless elements whose ValuePattern may say editable and still enter +#: the approval digest (WinForms reports a read-only DataGridView's cells as +#: editable). Never an Edit, Document or ComboBox, nor anything with a window. +_WINDOWLESS_CELL_TYPES = frozenset( + {"DataItemControl", "ListItemControl", "HeaderControl", "HeaderItemControl"} +) +_CELL_CONTAINER_TYPES = frozenset({"DataGridControl", "ListControl", "TableControl"}) + + +def _windowless_cell_in_scope( + control: object, window: object, structural: bool +) -> bool: + """Whether an editable-flagged windowless value may be digest evidence. + + A grid or list cell or header, read by its structural path, whose first + ancestor with a RuntimeId is a grid, list or table; or the window's own + title bar. Anything else must say read-only. The value only adds change + detection to the approval digest: it is never complete, never read-back + evidence, and read-back, not the digest, verifies what a save wrote. + """ + try: + control_type = _control_value(control, "ControlTypeName", None) + if control_type == "TitleBarControl": + parent = control.GetParentControl() # type: ignore[attr-defined] + root = _raw_runtime(window) + return not structural and bool(root) and _raw_runtime(parent) == root + if not structural or control_type not in _WINDOWLESS_CELL_TYPES: + return False + node: Any = control + for _ in range(_MAX_UIA_DEPTH): + node = node.GetParentControl() + if node is None: + return False + runtime = _raw_runtime(node) + if runtime is None: + return False + if runtime: + return ( + _control_value(node, "ControlTypeName", None) + in _CELL_CONTAINER_TYPES + ) + return False + except Exception: # noqa: BLE001 - unknown scope keeps read-only required + return False + + def _raw_runtime(control: object) -> Optional[tuple[int, ...]]: """The provider's RuntimeId exactly: a tuple (possibly empty), or None. @@ -3624,7 +3670,10 @@ def windowless(c: object = control) -> Optional[str]: bound_scope = windowless() unverified = _native_value_api().observe_uia_only_value( - control, identity=windowless, structural=structural + control, + identity=windowless, + structural=structural, + allow_editable=_windowless_cell_in_scope(control, window, structural), ) if unverified.value is None: reason = ( diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 229a56039e..61f6040c46 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -1508,3 +1508,62 @@ def GetPattern(self, pattern_id): assert [(f["kind"], f["text"]) for f in answer["fields"]] == [ ("uia_only_unverified", "first") ] + + +def test_an_editable_grid_cell_binds_as_digest_only_evidence(monkeypatch): + # WinForms reports a read-only DataGridView's cells as editable + # (ValuePattern.IsReadOnly False). A windowless grid cell under a grid + # with a RuntimeId still enters the digest, unmasked and never complete. + cell = _windowless( + "DataItemControl", "Neil", read_only=False, bounds=(20, 140, 220, 180) + ) + grid, _row = _structural_grid(cell) + perform = _agent(monkeypatch, _window(grid)) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert [(f["kind"], f["text"]) for f in answer["fields"]] == [ + ("state", ""), + ("uia_only_structural", "Neil"), + ] + + +@pytest.mark.parametrize("control_type", ["EditControl", "DocumentControl"]) +def test_an_editable_windowless_text_box_in_a_grid_still_needs_a_complete_read( + monkeypatch, control_type +): + box = _windowless(control_type, "Neil", read_only=False, bounds=(20, 140, 220, 180)) + grid, _row = _structural_grid(box) + assert _refusal(monkeypatch, grid) == "value_not_read_only" + + +def test_an_editable_cell_outside_a_grid_list_or_table_refuses(monkeypatch): + cell = _windowless( + "DataItemControl", "Neil", read_only=False, bounds=(20, 140, 220, 180) + ) + _row_grid, row = _structural_grid(cell) + pane = _Control("PaneControl", bounds=(20, 60, 630, 280), children=[row]) + assert _refusal(monkeypatch, pane) == "value_not_read_only" + + +def test_a_cell_whose_read_only_flag_flips_between_reads_refuses(monkeypatch): + class Flips(_Control): + reads = 0 + + def GetValuePattern(self): + self.reads += 1 + return SimpleNamespace(Value="Neil", IsReadOnly=self.reads == 1) + + cell = Flips("DataItemControl", bounds=(20, 140, 220, 180), value="Neil") + cell.NativeWindowHandle = 0 + grid, _row = _structural_grid(cell) + assert _refusal(monkeypatch, grid) == "value_readability_changed" + + +def test_an_editable_title_bar_of_the_window_binds(monkeypatch): + title = _windowless( + "TitleBarControl", "Patient Notes", read_only=False, bounds=(0, 0, 1024, 30) + ) + perform = _agent(monkeypatch, _window(title)) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert [(f["kind"], f["text"]) for f in answer["fields"]] == [ + ("uia_only_unverified", "Patient Notes") + ] From a2047e691dd8f8b07d9ae9fde8579914a336ef0f Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 09:41:11 -0500 Subject: [PATCH 13/14] fix(flow): read windowless provider probes through an explicit not-checked value, not an except-return The verdict-fold check counted eight new except-Exception handlers that return a default. The agent's server.py and native_value.py run as copied stdlib files and cannot import openadapt_flow.verdict, so each now goes through one probe that maps any provider exception to NOT_CHECKED, the same rule as verdict.observe; every caller maps it to the refusal it returned before. The replay fallback uses verdict.observe itself. Behaviour is unchanged. --- .../backends/win_agent/native_value.py | 67 +++++++++++++++-- .../backends/win_agent/server.py | 73 ++++++++++++++----- .../runtime/replay/qualification_faults.py | 8 +- 3 files changed, 121 insertions(+), 27 deletions(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/native_value.py b/packages/flow/openadapt_flow/backends/win_agent/native_value.py index 550dc16f0d..31d9aeb8f0 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -11,7 +11,7 @@ import time from dataclasses import asdict, dataclass from enum import Enum -from typing import Any, Callable, Protocol +from typing import Any, Callable, Protocol, TypeVar MAX_UTF16_UNITS = 65536 PROOF_SCHEMA = "openadapt.native-value-completeness/v3" @@ -609,6 +609,36 @@ def proof(self) -> None: _NO_ELEMENT = object() +_T = TypeVar("_T") + + +class _NotChecked: + """What a provider read that raised hands back: nothing was read.""" + + __slots__ = () + + def __repr__(self) -> str: + return "NOT_CHECKED" + + +#: A probe that raised. It is never a value; every caller maps it to its own +#: refusal (None, not windowless, a fixed reason). +NOT_CHECKED = _NotChecked() + + +def probe(read: Callable[[], _T]) -> _T | _NotChecked: + """Run one accessibility-provider read; any ``Exception`` is NOT_CHECKED. + + The agent runs from copied stdlib files, so it cannot import + ``openadapt_flow.verdict.observe``; this is the same rule. A failure + never becomes a default value here, and no exception text crosses it. + """ + try: + return read() + except Exception: # noqa: BLE001 - every provider failure is NOT_CHECKED + return NOT_CHECKED + + def has_no_native_window(control: Any) -> bool: """True only when UI Automation answers that the control has no window. @@ -617,7 +647,8 @@ def has_no_native_window(control: Any) -> bool: must never make a windowed control look windowless. A COM null (None) or 0 is no window; an error or any other answer is not. """ - try: + + def read() -> bool: element: Any = getattr(control, "Element", _NO_ELEMENT) if element is _NO_ELEMENT: # Not a uiautomation Control (an in-process provider or a test @@ -625,9 +656,9 @@ def has_no_native_window(control: Any) -> bool: raw = control.NativeWindowHandle return type(raw) is int and raw == 0 raw = element.CurrentNativeWindowHandle - except Exception: - return False - return raw is None or (type(raw) is int and raw == 0) + return raw is None or (type(raw) is int and raw == 0) + + return probe(read) is True def _windowless_identity( @@ -679,6 +710,30 @@ def observe_uia_only_value( complete. Anything else returns ``value=None`` with a fixed reason; no provider text or exception crosses this boundary. """ + result = probe( + lambda: _read_uia_only_value( + control, + identity=identity, + structural=structural, + allow_editable=allow_editable, + clock=clock, + ) + ) + if isinstance(result, UnverifiedValue): + return result + # COM/ctypes/provider errors never expose a partial value or a Name. + return UnverifiedValue(None, "value_observation_unavailable") + + +def _read_uia_only_value( + control: Any, + *, + identity: Callable[[], str | None], + structural: bool, + allow_editable: bool, + clock: Callable[[], float], +) -> UnverifiedValue: + """:func:`observe_uia_only_value` without its provider-error boundary.""" try: require_non_sensitive_value(control) deadline = clock() + 5.0 @@ -742,8 +797,6 @@ def uia() -> str: return UnverifiedValue(first, None) except ValueUnavailable as exc: return UnverifiedValue(None, str(exc)) - except Exception: - return UnverifiedValue(None, "value_observation_unavailable") def valid_value_proof(value: str, proof: object) -> bool: diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index aa2b571ed3..092335a58f 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -99,7 +99,7 @@ from dataclasses import dataclass from datetime import datetime, timezone from http.server import BaseHTTPRequestHandler, HTTPServer -from typing import Any, Callable, Optional +from typing import Any, Callable, Optional, TypeVar # PNG magic used to validate/return frames. _PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" @@ -588,6 +588,34 @@ def require_foreground() -> None: return _delivery_receipt("physical_scroll", native=False) +class _NotChecked: + """What a provider read that raised hands back: nothing was read.""" + + __slots__ = () + + def __repr__(self) -> str: + return "NOT_CHECKED" + + +#: A probe that raised. It is never a value; every caller maps it to its own +#: refusal. (Same rule as native_value.probe; this file runs copied, alone.) +NOT_CHECKED = _NotChecked() +_T = TypeVar("_T") + + +def _probe(read: Callable[[], _T]) -> _T | _NotChecked: + """Run one accessibility-provider read; any ``Exception`` is NOT_CHECKED. + + The agent runs from copied stdlib files, so it cannot import + ``openadapt_flow.verdict.observe``; this is the same rule. A failure + never becomes a default value here, and no exception text crosses it. + """ + try: + return read() + except Exception: # noqa: BLE001 - every provider failure is NOT_CHECKED + return NOT_CHECKED + + def _control_value(control: object, attr: str, default: object = "") -> object: try: return getattr(control, attr, default) @@ -3034,7 +3062,8 @@ def _windowless_cell_in_scope( detection to the approval digest: it is never complete, never read-back evidence, and read-back, not the digest, verifies what a save wrote. """ - try: + + def read() -> bool: control_type = _control_value(control, "ControlTypeName", None) if control_type == "TitleBarControl": parent = control.GetParentControl() # type: ignore[attr-defined] @@ -3056,8 +3085,9 @@ def _windowless_cell_in_scope( in _CELL_CONTAINER_TYPES ) return False - except Exception: # noqa: BLE001 - unknown scope keeps read-only required - return False + + # An unknown scope keeps read-only required. + return _probe(read) is True def _raw_runtime(control: object) -> Optional[tuple[int, ...]]: @@ -3067,10 +3097,9 @@ def _raw_runtime(control: object) -> Optional[tuple[int, ...]]: never an empty RuntimeId, so a read failure cannot select the structural path. """ - try: - method = getattr(control, "GetRuntimeId") - value = method() - except Exception: # noqa: BLE001 - unreadable is not empty + value = _probe(lambda: getattr(control, "GetRuntimeId")()) + if isinstance(value, _NotChecked): + # Unreadable is not empty. return None if not isinstance(value, (tuple, list)) or len(value) > 64: return None @@ -3081,11 +3110,15 @@ def _raw_runtime(control: object) -> Optional[tuple[int, ...]]: def _child_index(parent: object, node: object, auto: Any) -> Optional[int]: """The one position of ``node`` among ``parent``'s children, or None.""" - try: + + def read() -> list[int]: same = auto.ControlsAreSame children = list(parent.GetChildren()) # type: ignore[attr-defined] - matches = [i for i, child in enumerate(children) if same(child, node)] - except Exception: # noqa: BLE001 - an unknown position is no path + return [i for i, child in enumerate(children) if same(child, node)] + + matches = _probe(read) + if isinstance(matches, _NotChecked): + # An unknown position is no path. return None return matches[0] if len(matches) == 1 else None @@ -3109,7 +3142,8 @@ def _form_windowless_path( approval digest's change detection (``uia_only_structural``); it is never used for actions, focus, read-back, edit baselines or VERIFIED. """ - try: + + def read() -> Optional[str]: if not scope() or _control_value(window, "NativeWindowHandle", None) != hwnd: return None if not _native_value_api().has_no_native_window(control): @@ -3166,8 +3200,10 @@ def _form_windowless_path( separators=(",", ":"), ).encode("utf-8") ).hexdigest() - except Exception: # noqa: BLE001 - a missing scope is never complete - return None + + # A missing scope is never complete. + result = _probe(read) + return None if isinstance(result, _NotChecked) else result def _form_windowless_identity( @@ -3181,7 +3217,8 @@ def _form_windowless_identity( it must have none. A control with a handle is not windowless and gets no answer here. """ - try: + + def read() -> Optional[str]: if not scope() or _control_value(window, "NativeWindowHandle", None) != hwnd: return None if not _native_value_api().has_no_native_window(control): @@ -3224,8 +3261,10 @@ def _form_windowless_identity( separators=(",", ":"), ).encode("utf-8") ).hexdigest() - except Exception: # noqa: BLE001 - a missing scope is never complete - return None + + # A missing scope is never complete. + result = _probe(read) + return None if isinstance(result, _NotChecked) else result @dataclass(frozen=True) diff --git a/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py b/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py index bbef7626e5..cbb243ca1d 100644 --- a/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py +++ b/packages/flow/openadapt_flow/runtime/replay/qualification_faults.py @@ -21,6 +21,7 @@ sha256_bytes, verify_fault_mutation_receipt, ) +from openadapt_flow.verdict import observe if TYPE_CHECKING: from typing import Callable, Literal, Optional @@ -289,7 +290,7 @@ def _record_fault_on_plain_frame( replace. """ - try: + def record() -> None: frame = _observe_signed_frame( self.backend.screenshot, receipt.after_input_sha256 ) @@ -298,8 +299,9 @@ def _record_fault_on_plain_frame( self._validate_fault_mutation( context, receipt, after_input_sha256=sha256_bytes(frame) ) - except Exception: # noqa: BLE001 - nothing recorded; the halt stands - return + + # An Errored observation records nothing; the halt stands either way. + observe(record) def _bind_surface_qualification_environment( self, workflow: Workflow, surface_id: str From 8b2ea9cfe1b879410a9ac09c5505910d6ad080a6 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 09:43:55 -0500 Subject: [PATCH 14/14] test(flow): every windowless probe maps a provider error to the refusal it returned before --- .../flow/tests/test_approval_form_fields.py | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 61f6040c46..115e7d2ae0 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -1567,3 +1567,52 @@ def test_an_editable_title_bar_of_the_window_binds(monkeypatch): assert [(f["kind"], f["text"]) for f in answer["fields"]] == [ ("uia_only_unverified", "Patient Notes") ] + + +def test_every_windowless_probe_maps_a_provider_error_to_its_refusal(monkeypatch): + # Each windowless read goes through one probe; a provider error is + # NOT_CHECKED, and every caller turns it into the refusal it returned + # before (None, not windowless, not in scope, a fixed reason). + import openadapt_flow.backends.win_agent.native_value as native + from openadapt_flow.backends.win_agent import server + + def boom(*_args, **_kwargs): + raise OSError("COM") + + assert native.probe(boom) is native.NOT_CHECKED + assert server._probe(boom) is server.NOT_CHECKED + assert native.probe(lambda: 0) == 0 and server._probe(lambda: ()) == () + + cell = _windowless("DataItemControl", "Neil", bounds=(20, 140, 220, 180)) + cell.AutomationId = "cell" + window = _window(cell) + _agent(monkeypatch, window) + + # Read failures: an unreadable RuntimeId is never the empty one. + broken = SimpleNamespace(GetRuntimeId=boom, GetChildren=boom, GetParentControl=boom) + assert server._raw_runtime(broken) is None + assert server._child_index(broken, cell, SimpleNamespace()) is None + same_raises = SimpleNamespace(ControlsAreSame=boom) + assert server._child_index(window, cell, same_raises) is None + + # An unknown scope keeps read-only required. + orphan = _windowless("DataItemControl", "Neil", bounds=(20, 140, 220, 180)) + orphan.GetParentControl = boom + assert server._windowless_cell_in_scope(orphan, window, True) is False + title = _windowless("TitleBarControl", "Notes", bounds=(0, 0, 640, 30)) + title.GetParentControl = boom + assert server._windowless_cell_in_scope(title, window, False) is False + + # A scope that cannot be read is never a binding. + hwnd = window.NativeWindowHandle + assert server._form_windowless_path(cell, window, hwnd, boom, None) is None + assert server._form_windowless_identity(cell, window, hwnd, boom) is None + + # A provider error mid-read is a fixed reason, never a value. + cell.GetValuePattern = boom + failed = native.observe_uia_only_value(cell, identity=lambda: "scope") + assert failed.value is None + assert failed.reason == "value_observation_unavailable" + assert native.observe_uia_only_value(cell, identity=boom).reason == ( + "value_observation_unavailable" + )