From 6742b1a43791d734d9e52135f4b55464804911d6 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 16:59:28 -0500 Subject: [PATCH 01/34] fix(approval): read a desktop approval's text fields by value, not by OCR (#2189) On the hosted Windows governed run, two reads of an unchanged Patient Notes window gave different OCR words: the caret in the search box split "Neil", and the title bar's close button read once and not the next time. Every resumed approval halted on form_changed_after_approval. The win_agent gains a typed read, window-form-fields (capability window_form_fields_v1): the approval window's frame, its title bar and every on-screen text field whose UI Automation value it can read. The approval's form state then reads those fields by value, paints their pixels out of the window crop and reads the rest of the window by OCR, with the characters joined so OCR's word boundaries do not matter. A changed value changes the digest through either channel; a request and a recheck read through different channels never match. The agent answers no window when the app shows any other window or the walk is incomplete, and the window is then read by OCR as before. --- .../approval_mode/form_state.py | 128 ++++- .../backends/win_agent/server.py | 151 ++++++ .../backends/windows_backend.py | 106 +++- .../flow/openadapt_flow/runtime/replayer.py | 5 +- .../flow/tests/test_approval_form_fields.py | 503 ++++++++++++++++++ 5 files changed, 874 insertions(+), 19 deletions(-) create mode 100644 packages/flow/tests/test_approval_form_fields.py diff --git a/packages/flow/openadapt_flow/approval_mode/form_state.py b/packages/flow/openadapt_flow/approval_mode/form_state.py index 26a0f18357..de15f12791 100644 --- a/packages/flow/openadapt_flow/approval_mode/form_state.py +++ b/packages/flow/openadapt_flow/approval_mode/form_state.py @@ -16,6 +16,13 @@ is read, in reading order and with its frame in the digest, so text elsewhere on the screen that changes by itself (a clock in a taskbar, a notification) is not mistaken for an edited form. +- When the backend can also read that window's text fields through the + platform's accessibility API (``approval_form_fields``: UI Automation on + Windows), each field and the title bar is read by its value and painted + out of the OCR read, and the rest of the window is still read by OCR. A + caret blinking in a text box or a hovered title-bar button then reads the + same every time, while a changed value changes the digest through either + channel. Only a digest leaves this module. The digest stays in the run directory; it never enters the report or anything sent to Cloud. @@ -154,17 +161,80 @@ def screen_text_state( return _digest("screen_text", {"rows": rows}) +def _clamp(region: Region, width: int, height: int) -> Optional[Region]: + x, y, w, h = region + left, top = max(0, x), max(0, y) + right, bottom = min(width, x + w), min(height, y + h) + if right <= left or bottom <= top: + return None + return (left, top, right - left, bottom - top) + + +def window_fields_state( + vision: Any, frame_png: bytes, window_fields: dict[str, Any] +) -> Optional[FormState]: + """The window's fields by value, and the rest of it by OCR, or ``None``. + + ``window_fields`` is a backend's ``approval_form_fields`` answer: the + window's frame and its title bar and text fields, each with its screen + rectangle and text. Every field rectangle is painted out of the window + crop before OCR, so what OCR reads there (a caret, a hovered button) + cannot vary between reads; the field's own value stands in for it. The + frame, each field's kind, rectangle and value, and the remaining + characters in reading order are all in the digest. ``None`` when nothing was read. + """ + + from PIL import Image, ImageDraw + + try: + bounds = tuple(int(v) for v in window_fields["bounds"]) + fields = list(window_fields["fields"]) + with Image.open(io.BytesIO(frame_png)) as image: + window = _clamp(bounds, *image.size) # type: ignore[arg-type] + if window is None: + return None + x0, y0, w, h = window + crop = image.convert("RGB").crop((x0, y0, x0 + w, y0 + h)) + draw = ImageDraw.Draw(crop) + rows: list[Any] = [] + for field in fields: + kind, text = str(field["kind"]), str(field["text"]) + fx, fy, fw, fh = (int(v) for v in field["rect"]) + rows.append([kind, [fx, fy, fw, fh], text]) + inside = _clamp((fx - x0, fy - y0, fw, fh), w, h) + if inside is not None: + ix, iy, iw, ih = inside + draw.rectangle((ix, iy, ix + iw - 1, iy + ih - 1), fill="white") + out = io.BytesIO() + crop.save(out, format="PNG") + words = _words(vision, out.getvalue()) + except Exception: # noqa: BLE001 - unreadable is not "unchanged" + return None + if not words and not any(row[2] for row in rows): + return None + # OCR's word boundaries move with what else is on the screen ("Benchmark + # Harness" reads as one word or two), so the words are joined: the + # characters and their reading order are what the person saw. + return _digest( + "window_fields", + {"window": list(window), "fields": rows, "text": "".join(words)}, + ) + + def capture_form_state( backend: Any, vision: Any, frame_png: Optional[bytes] = None, regions: Optional[Sequence[Region]] = None, + window_fields: Optional[dict[str, Any]] = None, ) -> Optional[FormState]: """The best available field state for this backend, or ``None``. A backend may provide ``form_state()`` returning JSON-serializable data; a browser backend is read through its page; any other backend falls back - to the words on the screen, in ``regions`` when they are given. + to the screen: the app window's fields by value and the rest by OCR when + ``window_fields`` is given, else the words in ``regions`` (or on the + whole screen). """ custom = getattr(backend, "form_state", None) @@ -180,6 +250,8 @@ def capture_form_state( frame_png = backend.screenshot() except Exception: # noqa: BLE001 return None + if window_fields is not None: + return window_fields_state(vision, frame_png, window_fields) return screen_text_state(vision, frame_png, regions) @@ -229,10 +301,64 @@ def approval_window_regions( return [(left, top, right - left, bottom - top)] +def approval_window_fields( + backend: Any, save_step: Optional[str], results: Sequence[Any] = () +) -> Optional[dict[str, Any]]: + """The backend's ``approval_form_fields`` answer for the approval's + window, or ``None`` (and the caller reads the window by OCR alone). + + The same window :func:`approval_window_regions` names; the save step is + left out and the earlier steps' points name the window on a resumed run. + Never raises. + """ + + fields_of = getattr(backend, "approval_form_fields", None) + if not callable(fields_of): + return None + try: + points = [ + (int(prior.resolution.point[0]), int(prior.resolution.point[1])) + for prior in results + if prior.step_id != save_step and prior.resolution is not None + ] + answer = fields_of(save_step, points) + except Exception: # noqa: BLE001 - no answer is OCR alone + return None + if not isinstance(answer, dict) or set(answer) != {"bounds", "fields"}: + return None + return answer + + +def approval_form_state( + backend: Any, + vision: Any, + frame_png: Optional[bytes], + save_step: Optional[str], + results: Sequence[Any] = (), +) -> Optional[FormState]: + """The approval's form state for ``save_step``, or ``None``. + + The app window's fields by value where the backend can read them, + otherwise the window (or the whole screen) by OCR. A request and its + recheck that read through different channels get different kinds, so + the save halts. + """ + + if frame_png is not None: + fields = approval_window_fields(backend, save_step, results) + if fields is not None: + return capture_form_state(backend, vision, frame_png, window_fields=fields) + regions = approval_window_regions(backend, frame_png, save_step, results) + return capture_form_state(backend, vision, frame_png, regions) + + __all__ = [ "FormState", + "approval_form_state", + "approval_window_fields", "approval_window_regions", "capture_form_state", + "window_fields_state", "dom_form_state", "screen_text_state", ] diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index f81f8849a0..879485900e 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -2232,8 +2232,157 @@ def _window_operation( return {"status": "ok", "window": owned} +#: Control types whose on-screen text is their UIA value: an approval reads +#: the value and leaves their pixels out of the OCR (a caret blinks there). +_FORM_VALUE_TYPES = frozenset({"EditControl", "DocumentControl"}) +_MAX_FORM_FIELDS = 256 + + +def _form_field_value(control: object) -> tuple[bool, Optional[str]]: + """``(readable, value)`` of a text field through its Value pattern.""" + method = _control_value(control, "GetValuePattern", None) + if not callable(method): + return False, None + try: + pattern = method() + value = getattr(pattern, "Value", None) if pattern is not None else None + except Exception: # noqa: BLE001 - pattern not supported + return False, None + if not isinstance(value, str): + return False, None + return True, value[:_MAX_READ_TEXT] + + +def _window_form_fields( + auto: Any, hwnd: int +) -> tuple[Optional[list[dict[str, Any]]], bool]: + """The window's title bar and on-screen text fields, in tree order. + + Each field is ``{"kind", "rect": [x, y, w, h], "text"}``: ``title_bar`` + with the window's title, ``edit`` with the field's value. A field whose + value cannot be read (a password box, an unsupported pattern) or that is + off screen is left out, so its pixels stay in the caller's OCR read. + ``(None, False)`` when UIA cannot open the window; ``truncated`` when the + walk hit its bounds. + """ + from_handle = getattr(auto, "ControlFromHandle", None) + if not callable(from_handle): + return None, False + try: + window = from_handle(hwnd) + except Exception: # noqa: BLE001 - provider failure is no answer + return None, False + if window is None: + return None, False + title = " ".join(str(_control_value(window, "Name", "") or "").split()) + fields: list[dict[str, Any]] = [] + stack: list[tuple[Any, int]] = [(c, 1) for c in reversed(_children(window))] + visited = 0 + while stack: + control, depth = stack.pop() + visited += 1 + if visited > _MAX_UIA_NODES or len(fields) > _MAX_FORM_FIELDS: + return fields, True + control_type = str(_control_value(control, "ControlTypeName", "")) + bounds = _bounds(control) + if control_type == "TitleBarControl": + if bounds is not None: + fields.append( + { + "kind": "title_bar", + "rect": [ + bounds[0], + bounds[1], + bounds[2] - bounds[0], + bounds[3] - bounds[1], + ], + "text": title[:_MAX_READ_TEXT], + } + ) + continue + if control_type in _FORM_VALUE_TYPES: + offscreen = _control_value(control, "IsOffscreen", True) + readable, value = _form_field_value(control) + if bounds is not None and offscreen is False and readable: + fields.append( + { + "kind": "edit", + "rect": [ + bounds[0], + bounds[1], + bounds[2] - bounds[0], + bounds[3] - bounds[1], + ], + "text": value, + } + ) + continue + if depth < _MAX_UIA_DEPTH: + stack.extend((c, depth + 1) for c in reversed(_children(control))) + return fields, False + + +def _window_form_fields_operation( + payload: dict[str, Any], user32: Any, auto_loader: Callable[[], Any] +) -> dict[str, Any]: + """``window-form-fields``: the window's frame (as ``window-bounds``) and + its text fields' values, for an approval's form state. + + Answers ``window: None`` whenever the read could hide something on the + screen: the window is not one ``window-bounds`` names, the app shows any + other window (it could sit over a field whose pixels the caller leaves + out), or UIA cannot read the window completely. + """ + framed = _window_operation("window-bounds", payload, user32) + window = framed.get("window") + if window is None: + return {"status": "ok", "window": None, "fields": []} + hwnd, pid = window["hwnd"], window["pid"] + for candidate in user32.top_level_windows(): + if candidate == hwnd or user32.pid_of(candidate) != pid: + continue + if not user32.is_visible(candidate): + continue + cloaked = user32.is_cloaked(candidate) + if cloaked is None or not cloaked: + return {"status": "ok", "window": None, "fields": []} + auto = auto_loader() + with auto.UIAutomationInitializerInThread(): + fields, truncated = _window_form_fields(auto, hwnd) + if fields is None or truncated: + return {"status": "ok", "window": None, "fields": []} + return {"status": "ok", "window": window, "fields": fields} + + +def _load_uiautomation() -> Any: + try: + import uiautomation as auto # noqa: PLC0415 - Windows-only, lazy + except Exception as exc: # noqa: BLE001 + raise AgentRequestError( + 503, "uia_unavailable", "UI Automation is unavailable" + ) from exc + if os.name == "nt": + import comtypes.client # noqa: PLC0415 + + comtypes.client.gen_dir = None + return auto + + def _perform_uia(operation: str, payload: dict[str, Any]) -> dict[str, Any]: """Perform one typed UIA operation on one COM-affine server thread.""" + if operation == "window-form-fields": + if os.name != "nt": + raise AgentRequestError(503, "uia_unavailable", "Win32 is unavailable") + try: + return _window_form_fields_operation( + payload, _user32_factory(), _load_uiautomation + ) + except AgentRequestError: + raise + except Exception as exc: # noqa: BLE001 - bounded, never a crash + raise AgentRequestError( + 503, "uia_unavailable", "window state is unavailable" + ) from exc if operation in _WINDOW_OPERATIONS: if os.name != "nt": raise AgentRequestError(503, "uia_unavailable", "Win32 is unavailable") @@ -2866,6 +3015,7 @@ def do_GET(self) -> None: # noqa: N802 - stdlib naming "uia_v1", "uia_read_v1", "window_bounds_v1", + "window_form_fields_v1", "uia_authoring_tree_v1", *( ["legacy_waa_input_v1"] @@ -2908,6 +3058,7 @@ def do_POST(self) -> None: # noqa: N802 - stdlib naming "/window/root-at": ("uia", "window-root-at"), "/window/owned-over": ("uia", "owned-window-over"), "/window/bounds": ("uia", "window-bounds"), + "/window/form-fields": ("uia", "window-form-fields"), "/uia/text-at-point": ("uia", "text-at-point"), "/uia/focused-field-label": ("uia", "focused-field-label"), "/uia/identity-candidates-at": ("uia", "identity-candidates-at"), diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index 82ba18bd3c..1a90d34f55 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -232,6 +232,26 @@ def _pixel_box(value: object) -> Optional[dict[str, int]]: return {k: int(value[k]) for k in ("x", "y", "w", "h")} +def _window_frame( + window: Any, hwnd: int, pid: int +) -> Optional[tuple[int, int, int, int]]: + """The ``bounds`` of a typed window answer for exactly ``(hwnd, pid)``.""" + if not isinstance(window, dict) or set(window) != {"hwnd", "pid", "bounds"}: + return None + bounds = window["bounds"] + if ( + window["hwnd"] != hwnd + or window["pid"] != pid + or not isinstance(bounds, list) + or len(bounds) != 4 + or any(isinstance(v, bool) or not isinstance(v, int) for v in bounds) + or bounds[2] <= 0 + or bounds[3] <= 0 + ): + return None + return (bounds[0], bounds[1], bounds[2], bounds[3]) + + def _window_pair(raw: object) -> Optional[tuple[int, int]]: """``(hwnd, pid)`` from an agent's ``{hwnd, pid}``, or None when off-shape.""" if not isinstance(raw, dict) or set(raw) != {"hwnd", "pid"}: @@ -1005,6 +1025,19 @@ def approval_form_region( verified, when steps were seen in different windows, when the window is gone, or when the agent cannot say. Never raises. """ + found = self._approval_window(exclude_step, points) + if found is None: + return None + hwnd, pid = found + typed = self._post_typed_read("/window/bounds", {"hwnd": hwnd, "pid": pid}) + window = typed.payload.get("window") if typed.payload is not None else None + return _window_frame(window, hwnd, pid) + + def _approval_window( + self, exclude_step: Optional[str], points: Sequence[tuple[int, int]] + ) -> Optional[tuple[int, int]]: + """``(hwnd, pid)`` of the one window the run's verified steps (apart + from ``exclude_step``) were in, or None.""" captures = { capture for step_id, capture in self._verified_windows.items() @@ -1023,23 +1056,64 @@ def approval_form_region( captures = {c for c in found if c is not None} if len(captures) != 1: return None - hwnd, pid = next(iter(captures)) - typed = self._post_typed_read("/window/bounds", {"hwnd": hwnd, "pid": pid}) - window = typed.payload.get("window") if typed.payload is not None else None - if not isinstance(window, dict) or set(window) != {"hwnd", "pid", "bounds"}: - return None - bounds = window["bounds"] - if ( - window["hwnd"] != hwnd - or window["pid"] != pid - or not isinstance(bounds, list) - or len(bounds) != 4 - or any(isinstance(v, bool) or not isinstance(v, int) for v in bounds) - or bounds[2] <= 0 - or bounds[3] <= 0 - ): + return next(iter(captures)) + + def approval_form_fields( + self, + exclude_step: Optional[str] = None, + points: Sequence[tuple[int, int]] = (), + ) -> Optional[dict[str, Any]]: + """The approval window's frame and its text fields, read through UI + Automation, for an approval's form state. + + Returns ``{"bounds": (x, y, w, h), "fields": [{"kind", "rect", + "text"}, ...]}``: the same window :meth:`approval_form_region` names, + its title bar and every on-screen text field whose value UIA reads, + in tree order. The caller reads those fields by value and the rest of + the window by OCR, so a blinking caret or a hovered title-bar button + no longer changes the digest. None when the agent cannot say, when + the app shows another window, or on any doubt. Never raises. + """ + try: + found = self._approval_window(exclude_step, points) + if found is None: + return None + hwnd, pid = found + typed = self._post_typed_read( + "/window/form-fields", {"hwnd": hwnd, "pid": pid} + ) + payload = typed.payload + if payload is None or set(payload) != {"status", "window", "fields"}: + return None + bounds = _window_frame(payload["window"], hwnd, pid) + fields = payload["fields"] + if bounds is None or not isinstance(fields, list): + return None + checked: list[dict[str, Any]] = [] + for field in fields: + if not isinstance(field, dict) or set(field) != { + "kind", + "rect", + "text", + }: + return None + rect, text = field["rect"], field["text"] + if ( + field["kind"] not in ("title_bar", "edit") + or not isinstance(text, str) + or not isinstance(rect, list) + or len(rect) != 4 + or any(isinstance(v, bool) or not isinstance(v, int) for v in rect) + or rect[2] <= 0 + or rect[3] <= 0 + ): + return None + checked.append( + {"kind": field["kind"], "rect": tuple(rect), "text": text} + ) + return {"bounds": bounds, "fields": checked} + except Exception: # noqa: BLE001 - no answer is no fields return None - return (bounds[0], bounds[1], bounds[2], bounds[3]) def window_root_at(self, x: int, y: int) -> Optional[tuple[int, int]]: """``(hwnd, pid)`` of the foreground app's top-level window at (x, y). diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 6993034d1b..ddc6d7489b 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -13129,8 +13129,9 @@ def _approval_form_state( try: results = getattr(self._approval_report, "results", ()) step, backend = self._approval_form_step_id, self.backend - regions = fs.approval_window_regions(backend, frame_png, step, results) - return fs.capture_form_state(backend, self.vision, frame_png, regions) + return fs.approval_form_state( + backend, self.vision, frame_png, step, results + ) except Exception: # noqa: BLE001 - unreadable is never "unchanged" return None diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py new file mode 100644 index 0000000000..fca7cd960f --- /dev/null +++ b/packages/flow/tests/test_approval_form_fields.py @@ -0,0 +1,503 @@ +"""A desktop approval reads the app's text fields by value (#2189). + +On the hosted Windows governed run, two reads of an unchanged Patient Notes +window gave different OCR words: the caret in the search box split "Neil" +into "i n", and the title bar's close button read as "x" once and not the +next time. Every resumed approval then halted on a form that had not +changed. Real OCR on rendered frames here: a caret or a title-bar glyph must +not change the digest, while a changed value still must, whether it is in a +text field (read through UI Automation) or anywhere else in the window (read +by OCR). +""" + +from __future__ import annotations + +import io +import sys +import types +from types import SimpleNamespace + +import pytest +from PIL import Image, ImageDraw, ImageFont + +import openadapt_flow.vision as vision +from openadapt_flow.approval_mode.form_state import ( + approval_form_state, + approval_window_fields, + screen_text_state, + window_fields_state, +) +from openadapt_flow.backends.windows_backend import WindowsBackend + +SIZE = (1024, 768) +WINDOW = (0, 0, 1024, 720) +TITLE_BAR = (0, 0, 1024, 30) +SEARCH = (20, 44, 480, 26) +NOTE = (20, 340, 600, 120) + + +def _font(size: int): + for name in ("DejaVuSans.ttf", "Arial.ttf", "/System/Library/Fonts/Helvetica.ttc"): + try: + return ImageFont.truetype(name, size) + except OSError: + continue + return ImageFont.load_default() + + +def _frame( + *, + search: str = "Neil", + caret: bool = False, + close_hover: bool = False, + banner: str = "Patient: Neil Sorenson (1984-03-12)", + note: str = "BP 128/82; follow-up in 2 weeks", + clock: str = "7:27 PM", +) -> bytes: + image = Image.new("RGB", SIZE, "white") + draw = ImageDraw.Draw(image) + font = _font(20) + draw.text((8, 4), "Patient Notes - Benchmark Harness", fill="black", font=font) + if close_hover: + draw.rectangle((976, 0, 1023, 29), fill=(232, 17, 35)) + draw.text((992, 3), "X", fill="white", font=font) + else: + draw.text((994, 3), "x", fill="black", font=font) + draw.rectangle( + (SEARCH[0], SEARCH[1], SEARCH[0] + SEARCH[2], SEARCH[1] + SEARCH[3]), + outline="gray", + ) + draw.text((SEARCH[0] + 4, SEARCH[1] + 2), search, fill="black", font=font) + if caret: + draw.line( + (SEARCH[0] + 44, SEARCH[1] + 4, SEARCH[0] + 44, SEARCH[1] + 22), + fill="black", + width=2, + ) + draw.text((20, 110), "Neil Sorenson 1984-03-12", fill="black", font=font) + draw.text((20, 300), banner, fill="black", font=font) + draw.rectangle( + (NOTE[0], NOTE[1], NOTE[0] + NOTE[2], NOTE[1] + NOTE[3]), outline="gray" + ) + draw.text((NOTE[0] + 4, NOTE[1] + 4), note, fill="black", font=font) + draw.text((20, 500), "Save Note", fill="black", font=font) + draw.rectangle((0, 720, SIZE[0], SIZE[1]), fill=(32, 32, 32)) + draw.text((900, 732), clock, fill="white", font=font) + out = io.BytesIO() + image.save(out, format="PNG") + return out.getvalue() + + +def _fields(*, search: str = "Neil", note: str = "BP 128/82; follow-up in 2 weeks"): + return { + "bounds": WINDOW, + "fields": [ + { + "kind": "title_bar", + "rect": TITLE_BAR, + "text": "Patient Notes - Benchmark Harness", + }, + {"kind": "edit", "rect": SEARCH, "text": search}, + {"kind": "edit", "rect": NOTE, "text": note}, + ], + } + + +def _state(fields=None, **frame): + return window_fields_state(vision, _frame(**frame), fields or _fields()) + + +def test_the_issue_reproduces_with_ocr_alone(): + # The old read: OCR of the whole window. A caret is enough to change it. + plain = screen_text_state(vision, _frame(), [WINDOW]) + assert plain is not None + assert screen_text_state(vision, _frame(caret=True), [WINDOW]) != plain + + +def test_a_caret_or_a_title_bar_glyph_leaves_the_form_unchanged(): + before = _state() + assert before is not None and before[0] == "window_fields" + assert _state(caret=True) == before + assert _state(close_hover=True) == before + assert _state(caret=True, close_hover=True, clock="7:28 PM") == before + + +@pytest.mark.parametrize( + "fields,frame", + [ + ( + _fields(note="BP 138/82; follow-up in 2 weeks"), + {"note": "BP 138/82; follow-up in 2 weeks"}, + ), + (_fields(note="BP 138/82; follow-up in 2 weeks"), {}), + (_fields(search="Nell"), {"search": "Nell"}), + (None, {"banner": "Patient: Neil Sorensen (1983-01-19)"}), + ], + ids=["note-value", "note-value-not-yet-painted", "search-value", "banner-by-ocr"], +) +def test_a_changed_value_changes_the_form(fields, frame): + before = _state() + after = _state(fields, **frame) + assert before is not None and after is not None + assert before != after + + +def test_a_moved_field_or_window_changes_the_form(): + before = _state() + moved = _fields() + moved["fields"][2] = {**moved["fields"][2], "rect": (20, 341, 600, 120)} + assert _state(moved) != before + window = {**_fields(), "bounds": (0, 0, 1024, 719)} + assert _state(window) != before + + +def test_a_field_covers_only_its_own_pixels(): + # A field rectangle that the agent reported over the banner would hide + # the banner from OCR; its rectangle is then part of the digest, and + # its value must be read. The banner change still shows through the + # other channel: a different field set is a different digest. + covering = _fields() + covering["fields"].append({"kind": "edit", "rect": (20, 296, 500, 30), "text": ""}) + assert _state(covering) != _state() + + +def test_a_window_that_reads_nothing_is_unreadable(): + blank = io.BytesIO() + Image.new("RGB", SIZE, "white").save(blank, format="PNG") + empty = {"bounds": WINDOW, "fields": []} + assert window_fields_state(vision, blank.getvalue(), empty) is None + off = {"bounds": (2000, 0, 10, 10), "fields": []} + assert window_fields_state(vision, _frame(), off) is None + + +_RESULTS = [ + SimpleNamespace(step_id="s1", resolution=SimpleNamespace(point=(40, 50))), + SimpleNamespace(step_id="save", resolution=SimpleNamespace(point=(9, 9))), +] + + +def test_fields_are_read_for_the_window_without_the_save_step(): + asked = [] + + def fields(exclude_step, points): + asked.append((exclude_step, points)) + return _fields() + + backend = SimpleNamespace( + approval_form_fields=fields, + approval_form_region=lambda *_a: (0, 0, 1024, 720), + ) + frame = _frame() + state = approval_form_state(backend, vision, frame, "save", _RESULTS) + assert asked == [("save", [(40, 50)])] + assert state == window_fields_state(vision, frame, _fields()) + + +@pytest.mark.parametrize( + "answer", + [None, "fields", {"bounds": WINDOW}, {"bounds": WINDOW, "fields": [], "x": 1}], + ids=["none", "not-a-dict", "missing", "extra"], +) +def test_without_fields_the_window_is_read_by_ocr(answer): + backend = SimpleNamespace( + approval_form_fields=lambda *_a: answer, + approval_form_region=lambda *_a: WINDOW, + ) + frame = _frame() + assert approval_window_fields(backend, "save", _RESULTS) is None + assert approval_form_state(backend, vision, frame, "save", _RESULTS) == ( + screen_text_state(vision, frame, [WINDOW]) + ) + + +def test_a_request_and_recheck_through_different_channels_never_match(): + frame = _frame() + by_fields = approval_form_state( + SimpleNamespace(approval_form_fields=lambda *_a: _fields()), + vision, + frame, + "save", + ) + by_ocr = approval_form_state( + SimpleNamespace(approval_form_region=lambda *_a: WINDOW), + vision, + frame, + "save", + ) + assert by_fields is not None and by_ocr is not None + assert by_fields[0] != by_ocr[0] and by_fields != by_ocr + + +# -- WindowsBackend ----------------------------------------------------------- + + +def _windows_backend(captures, answer): + backend = object.__new__(WindowsBackend) + backend._verified_windows = dict(captures) + backend._conflicted_windows = set() + sent = [] + + def post(path, payload): + sent.append((path, payload)) + return SimpleNamespace(payload=answer) + + backend._post_typed_read = post + return backend, sent + + +_GOOD = { + "status": "ok", + "window": {"hwnd": 7, "pid": 10, "bounds": [0, 0, 1024, 720]}, + "fields": [ + {"kind": "title_bar", "rect": [0, 0, 1024, 30], "text": "Patient Notes"}, + {"kind": "edit", "rect": [20, 44, 480, 26], "text": "Neil"}, + ], +} + + +def test_the_windows_backend_reads_the_fields_of_its_one_window(): + backend, sent = _windows_backend({"s1": (7, 10), "save": (99, 10)}, _GOOD) + answer = backend.approval_form_fields("save") + assert sent == [("/window/form-fields", {"hwnd": 7, "pid": 10})] + assert answer == { + "bounds": (0, 0, 1024, 720), + "fields": [ + {"kind": "title_bar", "rect": (0, 0, 1024, 30), "text": "Patient Notes"}, + {"kind": "edit", "rect": (20, 44, 480, 26), "text": "Neil"}, + ], + } + + +def _bad(**change): + answer = {**_GOOD, "fields": [dict(f) for f in _GOOD["fields"]]} + for key, value in change.items(): + if key.startswith("field_"): + answer["fields"][1][key[len("field_") :]] = value + else: + answer[key] = value + return answer + + +@pytest.mark.parametrize( + "captures,answer", + [ + ({}, _GOOD), + ({"s1": (7, 10), "s2": (8, 10)}, _GOOD), + ({"s1": (7, 10)}, None), + ({"s1": (7, 10)}, {**_GOOD, "window": None}), + ( + {"s1": (7, 10)}, + {**_GOOD, "window": {"hwnd": 8, "pid": 10, "bounds": [0, 0, 9, 9]}}, + ), + ({"s1": (7, 10)}, {**_GOOD, "extra": 1}), + ({"s1": (7, 10)}, _bad(fields="x")), + ({"s1": (7, 10)}, _bad(field_kind="button")), + ({"s1": (7, 10)}, _bad(field_text=None)), + ({"s1": (7, 10)}, _bad(field_rect=[20, 44, True, 26])), + ({"s1": (7, 10)}, _bad(field_rect=[20, 44, 0, 26])), + ({"s1": (7, 10)}, _bad(field_extra=1)), + ], + ids=[ + "none-verified", + "two-windows", + "no-answer", + "no-window", + "other-window", + "extra-key", + "fields-not-a-list", + "unknown-kind", + "no-text", + "bool-rect", + "empty-rect", + "extra-field-key", + ], +) +def test_the_windows_backend_refuses_doubtful_fields(captures, answer): + backend, _sent = _windows_backend(captures, answer) + assert backend.approval_form_fields("save") is None + + +# -- win_agent ---------------------------------------------------------------- + + +class _Rect: + def __init__(self, left, top, right, bottom): + self.left, self.top, self.right, self.bottom = left, top, right, bottom + + +class _Control: + def __init__( + self, + control_type, + *, + bounds=(0, 0, 10, 10), + value=None, + offscreen=False, + name="", + children=(), + ): + self.ControlTypeName = control_type + self.BoundingRectangle = _Rect(*bounds) + self.IsOffscreen = offscreen + self.Name = name + self._value = value + self._children = list(children) + + def GetChildren(self): + return self._children + + def GetValuePattern(self): + if self._value is None: + raise RuntimeError("no value pattern") + return SimpleNamespace(Value=self._value) + + +class _Desktop: + def __init__(self, extra_windows=()): + self.windows = {7: (10, (0, 0, 1024, 720), True, False)} + for hwnd, entry in extra_windows: + self.windows[hwnd] = entry + + def per_monitor_dpi(self): + return True + + def virtual_origin(self): + return (0, 0) + + def top_level_windows(self): + return list(self.windows) + + def is_window(self, hwnd): + return hwnd in self.windows + + def pid_of(self, hwnd): + return self.windows[hwnd][0] + + def rect(self, hwnd): + return self.windows[hwnd][1] + + def is_visible(self, hwnd): + return self.windows[hwnd][2] + + def is_cloaked(self, hwnd): + return self.windows[hwnd][3] + + +class _Init: + def __enter__(self): + return self + + def __exit__(self, *a): + return None + + +def _window(*children): + return _Control( + "WindowControl", + bounds=(0, 0, 1024, 720), + name="Patient Notes", + children=children, + ) + + +def _agent(monkeypatch, window, desktop=None): + # Only the agent module sees Windows; pytest's own paths stay POSIX. + import os + + import openadapt_flow.backends.win_agent.server as agent_server + + monkeypatch.setattr( + agent_server, "os", types.SimpleNamespace(**{**vars(os), "name": "nt"}) + ) + monkeypatch.setattr(agent_server, "_user32_factory", lambda: desktop or _Desktop()) + auto = types.SimpleNamespace( + ControlFromHandle=lambda hwnd: window if hwnd == 7 else None, + UIAutomationInitializerInThread=_Init, + ) + monkeypatch.setitem(sys.modules, "uiautomation", auto) + client = types.SimpleNamespace(gen_dir="unset") + monkeypatch.setitem(sys.modules, "comtypes", types.SimpleNamespace(client=client)) + monkeypatch.setitem(sys.modules, "comtypes.client", client) + return agent_server._perform_uia + + +def test_the_agent_reads_the_title_bar_and_every_readable_text_field(monkeypatch): + window = _window( + _Control( + "TitleBarControl", + bounds=(0, 0, 1024, 30), + children=[_Control("ButtonControl", name="Close")], + ), + _Control( + "PaneControl", + bounds=(0, 30, 1024, 720), + children=[ + _Control("EditControl", bounds=(20, 44, 500, 70), value="Neil"), + _Control( + "EditControl", + bounds=(20, 80, 500, 100), + value="hidden", + offscreen=True, + ), + _Control( + "EditControl", bounds=(20, 110, 500, 130) + ), # password: no value + _Control( + "DocumentControl", bounds=(20, 340, 620, 460), value="BP 128/82" + ), + _Control( + "TextControl", bounds=(20, 300, 500, 320), name="Patient: Neil" + ), + ], + ), + ) + perform = _agent(monkeypatch, window) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert answer["window"] == {"hwnd": 7, "pid": 10, "bounds": [0, 0, 1024, 720]} + assert answer["fields"] == [ + {"kind": "title_bar", "rect": [0, 0, 1024, 30], "text": "Patient Notes"}, + {"kind": "edit", "rect": [20, 44, 480, 26], "text": "Neil"}, + {"kind": "edit", "rect": [20, 340, 600, 120], "text": "BP 128/82"}, + ] + + +@pytest.mark.parametrize( + "extra", + [ + [(8, (10, (100, 100, 300, 200), True, False))], + [(8, (10, (100, 100, 300, 200), True, None))], + ], + ids=["another-app-window", "cloak-unknown"], +) +def test_the_agent_refuses_when_the_app_shows_another_window(monkeypatch, extra): + window = _window(_Control("EditControl", bounds=(20, 44, 500, 70), value="Neil")) + perform = _agent(monkeypatch, window, _Desktop(extra)) + assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["window"] is None + + +def test_the_agent_ignores_hidden_or_cloaked_windows_and_other_apps(monkeypatch): + window = _window(_Control("EditControl", bounds=(20, 44, 500, 70), value="Neil")) + desktop = _Desktop( + [ + (8, (10, (100, 100, 300, 200), False, False)), + (9, (10, (100, 100, 300, 200), True, True)), + (11, (99, (0, 720, 1024, 768), True, False)), + ] + ) + perform = _agent(monkeypatch, window, desktop) + assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["window"] is not None + + +def test_the_agent_refuses_a_walk_it_cannot_finish(monkeypatch): + import openadapt_flow.backends.win_agent.server as agent_server + + monkeypatch.setattr(agent_server, "_MAX_UIA_NODES", 2) + window = _window(*[_Control("PaneControl") for _ in range(5)]) + perform = _agent(monkeypatch, window) + assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["window"] is None + + +def test_the_agent_refuses_a_window_uia_cannot_open(monkeypatch): + perform = _agent(monkeypatch, None) + assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["window"] is None + assert perform("window-form-fields", {"hwnd": 7, "pid": 11})["window"] is None From c4ac87a2242cae4a1225a80e995611d9bbbae9e0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 16:59:52 -0500 Subject: [PATCH 02/34] ci: run the approval form-fields tests on the Windows runner --- .github/workflows/desktop-replay.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/desktop-replay.yml b/.github/workflows/desktop-replay.yml index 9185099a0e..35c98243f7 100644 --- a/.github/workflows/desktop-replay.yml +++ b/.github/workflows/desktop-replay.yml @@ -35,6 +35,7 @@ on: - packages/flow/tests/test_check_it_dry_run_apps.py - packages/flow/tests/native_apps/check_it_gtk.py - packages/flow/tests/test_approval_form_window.py + - packages/flow/tests/test_approval_form_fields.py - packages/flow/benchmark/rdp_pool/** - packages/flow/pyproject.toml - packages/flow/uv.lock @@ -88,7 +89,8 @@ jobs: run: | mkdir -p runs pytest -v -rs -p no:cacheprovider tests/test_windows_attempt_ledger.py \ - tests/test_approval_form_window.py --junitxml=runs/windows-guards-junit.xml + tests/test_approval_form_window.py tests/test_approval_form_fields.py \ + --junitxml=runs/windows-guards-junit.xml - name: Record, compile and replay, judged from the record env: OAFLOW_WINDOWS_HOSTED_E2E: "1" From 07200ddd6f9f486356ccc6e2376c7c118c0c3ff9 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 17:13:12 -0500 Subject: [PATCH 03/34] test: drop the OCR-only reproduction, whose result depends on the platform's fonts --- packages/flow/tests/test_approval_form_fields.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index fca7cd960f..222d8aa1ef 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -107,13 +107,6 @@ def _state(fields=None, **frame): return window_fields_state(vision, _frame(**frame), fields or _fields()) -def test_the_issue_reproduces_with_ocr_alone(): - # The old read: OCR of the whole window. A caret is enough to change it. - plain = screen_text_state(vision, _frame(), [WINDOW]) - assert plain is not None - assert screen_text_state(vision, _frame(caret=True), [WINDOW]) != plain - - def test_a_caret_or_a_title_bar_glyph_leaves_the_form_unchanged(): before = _state() assert before is not None and before[0] == "window_fields" From 7504306b0724eea8a9a1e1387e582c0b1a4988bf Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 17:24:45 -0500 Subject: [PATCH 04/34] fix(approval): read labels, buttons and grid cells by value too; keep OCR words A selected grid row's cell read as "n" in one crop and "neil" in the next, and its highlight dims when the window loses focus while the item waits. Leaf labels and buttons are now read by their UIA name and leaf list and grid cells by their value (never by a positional name), with toggle and selection state; all are painted out of the OCR. A row's selection state is read without painting it out. The residual OCR keeps its word list: joined characters would hash "12 | 5" and "1 | 25" alike. The governed e2e probe now records the field read and whether it reproduces the request. --- .../approval_mode/form_state.py | 30 ++-- .../backends/win_agent/server.py | 119 ++++++++++++--- .../backends/windows_backend.py | 31 ++-- .../tests/e2e/test_windows_hosted_governed.py | 20 +++ .../flow/tests/test_approval_form_fields.py | 143 +++++++++++++++--- 5 files changed, 277 insertions(+), 66 deletions(-) diff --git a/packages/flow/openadapt_flow/approval_mode/form_state.py b/packages/flow/openadapt_flow/approval_mode/form_state.py index de15f12791..7c51a138b8 100644 --- a/packages/flow/openadapt_flow/approval_mode/form_state.py +++ b/packages/flow/openadapt_flow/approval_mode/form_state.py @@ -16,13 +16,14 @@ is read, in reading order and with its frame in the digest, so text elsewhere on the screen that changes by itself (a clock in a taskbar, a notification) is not mistaken for an edited form. -- When the backend can also read that window's text fields through the +- When the backend can also read that window's controls through the platform's accessibility API (``approval_form_fields``: UI Automation on - Windows), each field and the title bar is read by its value and painted + Windows), each text field, label, button, list or grid cell and the title + bar is read by its value (with its toggle or selection state) and painted out of the OCR read, and the rest of the window is still read by OCR. A - caret blinking in a text box or a hovered title-bar button then reads the - same every time, while a changed value changes the digest through either - channel. + 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. Only a digest leaves this module. The digest stays in the run directory; it never enters the report or anything sent to Cloud. @@ -180,8 +181,8 @@ def window_fields_state( rectangle and text. Every field rectangle is painted out of the window crop before OCR, so what OCR reads there (a caret, a hovered button) cannot vary between reads; the field's own value stands in for it. The - frame, each field's kind, rectangle and value, and the remaining - characters in reading order are all in the digest. ``None`` when nothing was read. + frame, each field's kind, rectangle, value and state, and the remaining + words in reading order are all in the digest. ``None`` when nothing was read. """ from PIL import Image, ImageDraw @@ -200,8 +201,13 @@ def window_fields_state( for field in fields: kind, text = str(field["kind"]), str(field["text"]) fx, fy, fw, fh = (int(v) for v in field["rect"]) - rows.append([kind, [fx, fy, fw, fh], text]) - inside = _clamp((fx - x0, fy - y0, fw, fh), w, h) + state = field.get("state") + rows.append([kind, [fx, fy, fw, fh], text, state]) + # A ``state`` entry (a selected grid row) carries no text: its + # pixels stay in the OCR read. + inside = ( + None if kind == "state" else _clamp((fx - x0, fy - y0, fw, fh), w, h) + ) if inside is not None: ix, iy, iw, ih = inside draw.rectangle((ix, iy, ix + iw - 1, iy + ih - 1), fill="white") @@ -212,12 +218,8 @@ def window_fields_state( return None if not words and not any(row[2] for row in rows): return None - # OCR's word boundaries move with what else is on the screen ("Benchmark - # Harness" reads as one word or two), so the words are joined: the - # characters and their reading order are what the person saw. return _digest( - "window_fields", - {"window": list(window), "fields": rows, "text": "".join(words)}, + "window_fields", {"window": list(window), "fields": rows, "words": words} ) diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 879485900e..21ba0f58f5 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -2235,11 +2235,33 @@ def _window_operation( #: Control types whose on-screen text is their UIA value: an approval reads #: the value and leaves their pixels out of the OCR (a caret blinks there). _FORM_VALUE_TYPES = frozenset({"EditControl", "DocumentControl"}) -_MAX_FORM_FIELDS = 256 +#: Leaf controls whose on-screen text is their UIA name by convention +#: (labels, buttons), and leaf items whose on-screen text is their UIA value +#: (list and grid cells; their name is often a position such as "first Row +#: 0", so they count only with a value). Both are read and painted out too, +#: so a selection highlight or a focus change cannot change how OCR reads +#: them. +_FORM_NAMED_TYPES = frozenset( + { + "TextControl", + "ButtonControl", + "CheckBoxControl", + "RadioButtonControl", + "TabItemControl", + "HeaderItemControl", + "HyperlinkControl", + "MenuItemControl", + } +) +_FORM_ITEM_TYPES = frozenset( + {"ListItemControl", "DataItemControl", "TreeItemControl", "CustomControl"} +) +_MAX_FORM_FIELDS = 512 +_TOGGLE_STATES = {0: "off", 1: "on", 2: "indeterminate"} def _form_field_value(control: object) -> tuple[bool, Optional[str]]: - """``(readable, value)`` of a text field through its Value pattern.""" + """``(readable, value)`` of a control through its Value pattern.""" method = _control_value(control, "GetValuePattern", None) if not callable(method): return False, None @@ -2253,17 +2275,50 @@ def _form_field_value(control: object) -> tuple[bool, Optional[str]]: return True, value[:_MAX_READ_TEXT] +def _form_field_state(control: object, control_type: str) -> Optional[str]: + """A check box's toggle state, or whether an item is selected; else None.""" + if control_type in ("CheckBoxControl", "RadioButtonControl"): + method = _control_value(control, "GetTogglePattern", None) + if callable(method): + try: + state = getattr(method(), "ToggleState", None) + except Exception: # noqa: BLE001 - pattern not supported + state = None + if state in _TOGGLE_STATES: + return _TOGGLE_STATES[state] + method = _control_value(control, "GetSelectionItemPattern", None) + if callable(method): + try: + selected = getattr(method(), "IsSelected", None) + except Exception: # noqa: BLE001 - pattern not supported + selected = None + if isinstance(selected, bool): + return "selected" if selected else "unselected" + return None + + +def _rect(bounds: list[int]) -> list[int]: + return [bounds[0], bounds[1], bounds[2] - bounds[0], bounds[3] - bounds[1]] + + def _window_form_fields( auto: Any, hwnd: int ) -> tuple[Optional[list[dict[str, Any]]], bool]: - """The window's title bar and on-screen text fields, in tree order. - - Each field is ``{"kind", "rect": [x, y, w, h], "text"}``: ``title_bar`` - with the window's title, ``edit`` with the field's value. A field whose - value cannot be read (a password box, an unsupported pattern) or that is - off screen is left out, so its pixels stay in the caller's OCR read. - ``(None, False)`` when UIA cannot open the window; ``truncated`` when the - walk hit its bounds. + """The window's controls whose text UIA reads, in tree order. + + Each entry is ``{"kind", "rect": [x, y, w, h], "text", "state"}``: + + - ``title_bar``, with the window's title; + - ``edit``, a text field with its value; + - ``text``, a leaf label or button with its value or name, or a leaf + list or grid cell with its value, and ``state`` its toggle or + selection state; + - ``state``, a container (a grid row) whose selection state UIA reads: + it carries no text and its pixels stay in the caller's OCR read. + + A control that is off screen, or whose text cannot be read or is empty, + is left out, so its pixels stay in the OCR read. ``(None, False)`` when + UIA cannot open the window; ``truncated`` when the walk hit its bounds. """ from_handle = getattr(auto, "ControlFromHandle", None) if not callable(from_handle): @@ -2285,40 +2340,54 @@ def _window_form_fields( return fields, True control_type = str(_control_value(control, "ControlTypeName", "")) bounds = _bounds(control) + on_screen = _control_value(control, "IsOffscreen", True) is False if control_type == "TitleBarControl": if bounds is not None: fields.append( { "kind": "title_bar", - "rect": [ - bounds[0], - bounds[1], - bounds[2] - bounds[0], - bounds[3] - bounds[1], - ], + "rect": _rect(bounds), "text": title[:_MAX_READ_TEXT], + "state": None, } ) continue if control_type in _FORM_VALUE_TYPES: - offscreen = _control_value(control, "IsOffscreen", True) readable, value = _form_field_value(control) - if bounds is not None and offscreen is False and readable: + if bounds is not None and on_screen and readable: fields.append( { "kind": "edit", - "rect": [ - bounds[0], - bounds[1], - bounds[2] - bounds[0], - bounds[3] - bounds[1], - ], + "rect": _rect(bounds), "text": value, + "state": None, } ) continue + children = _children(control) + state = _form_field_state(control, control_type) + if not children and control_type in _FORM_NAMED_TYPES | _FORM_ITEM_TYPES: + readable, value = _form_field_value(control) + text = value if readable and value else None + if text is None and control_type in _FORM_NAMED_TYPES: + name = " ".join(str(_control_value(control, "Name", "") or "").split()) + text = name[:_MAX_READ_TEXT] or None + if bounds is not None and on_screen and text: + fields.append( + { + "kind": "text", + "rect": _rect(bounds), + "text": text, + "state": state, + } + ) + continue + if state is not None and bounds is not None and on_screen: + fields.append( + {"kind": "state", "rect": _rect(bounds), "text": "", "state": state} + ) if depth < _MAX_UIA_DEPTH: - stack.extend((c, depth + 1) for c in reversed(_children(control))) + stack.extend((c, depth + 1) for c in reversed(children)) return fields, False diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index 1a90d34f55..a09bbc3629 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -232,6 +232,14 @@ def _pixel_box(value: object) -> Optional[dict[str, int]]: return {k: int(value[k]) for k in ("x", "y", "w", "h")} +#: The approval form-field read's contract (win_agent ``window-form-fields``). +_FIELD_KEYS = frozenset({"kind", "rect", "text", "state"}) +_FIELD_KINDS = frozenset({"title_bar", "edit", "text", "state"}) +_FIELD_STATES = frozenset( + {None, "on", "off", "indeterminate", "selected", "unselected"} +) + + def _window_frame( window: Any, hwnd: int, pid: int ) -> Optional[tuple[int, int, int, int]]: @@ -1067,9 +1075,10 @@ def approval_form_fields( Automation, for an approval's form state. Returns ``{"bounds": (x, y, w, h), "fields": [{"kind", "rect", - "text"}, ...]}``: the same window :meth:`approval_form_region` names, - its title bar and every on-screen text field whose value UIA reads, - in tree order. The caller reads those fields by value and the rest of + "text", "state"}, ...]}``: the same window + :meth:`approval_form_region` names, and its title bar, text fields, + labels, buttons and cells whose text UIA reads (with toggle and + selection state), in tree order. The caller reads those fields by value and the rest of the window by OCR, so a blinking caret or a hovered title-bar button no longer changes the digest. None when the agent cannot say, when the app shows another window, or on any doubt. Never raises. @@ -1091,15 +1100,12 @@ def approval_form_fields( return None checked: list[dict[str, Any]] = [] for field in fields: - if not isinstance(field, dict) or set(field) != { - "kind", - "rect", - "text", - }: + if not isinstance(field, dict) or set(field) != _FIELD_KEYS: return None rect, text = field["rect"], field["text"] if ( - field["kind"] not in ("title_bar", "edit") + field["kind"] not in _FIELD_KINDS + or field["state"] not in _FIELD_STATES or not isinstance(text, str) or not isinstance(rect, list) or len(rect) != 4 @@ -1109,7 +1115,12 @@ def approval_form_fields( ): return None checked.append( - {"kind": field["kind"], "rect": tuple(rect), "text": text} + { + "kind": field["kind"], + "rect": tuple(rect), + "text": text, + "state": field["state"], + } ) return {"bounds": bounds, "fields": checked} except Exception: # noqa: BLE001 - no answer is no fields diff --git a/packages/flow/tests/e2e/test_windows_hosted_governed.py b/packages/flow/tests/e2e/test_windows_hosted_governed.py index d4ffd6d6ef..4bd6945772 100644 --- a/packages/flow/tests/e2e/test_windows_hosted_governed.py +++ b/packages/flow/tests/e2e/test_windows_hosted_governed.py @@ -390,6 +390,26 @@ def _form_state_probe(backend, run_dir: Path, frame_png: bytes) -> dict[str, Any from openadapt_flow.approval_mode.form_state import _crop out["window_words"] = _words(vision, _crop(frame_png, clamped)) + # The read the replayer makes first: the window's controls through + # UI Automation, painted out of the OCR (synthetic data only). + from openadapt_flow.approval_mode.form_state import approval_form_state + + fields = backend.approval_form_fields(request["step_id"], points) + out["fields"] = ( + None + if fields is None + else [ + [f["kind"], list(f["rect"]), f["text"], f["state"]] + for f in fields["fields"] + ] + ) + out["fields_matches"] = ( + approval_form_state( + backend, vision, frame_png, request["step_id"], report.results + ) + == expected + ) + out["request_kind"] = expected[0] except Exception as exc: # noqa: BLE001 - diagnostics never fail the test out["probe_error"] = f"{type(exc).__name__}: {exc}" return out diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 222d8aa1ef..81625808e6 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -34,6 +34,8 @@ TITLE_BAR = (0, 0, 1024, 30) SEARCH = (20, 44, 480, 26) NOTE = (20, 340, 600, 120) +ROW = (20, 100, 600, 40) +CELLS = [(20, 100, 200, 40), (220, 100, 200, 40), (420, 100, 200, 40)] def _font(size: int): @@ -53,6 +55,8 @@ def _frame( banner: str = "Patient: Neil Sorenson (1984-03-12)", note: str = "BP 128/82; follow-up in 2 weeks", clock: str = "7:27 PM", + row_fill: tuple[int, int, int] = (0, 120, 215), + dose: str = "Dose: 12 | 5", ) -> bytes: image = Image.new("RGB", SIZE, "white") draw = ImageDraw.Draw(image) @@ -74,7 +78,11 @@ def _frame( fill="black", width=2, ) - draw.text((20, 110), "Neil Sorenson 1984-03-12", fill="black", font=font) + # The selected grid row: its highlight dims when the window loses focus. + draw.rectangle((ROW[0], ROW[1], ROW[0] + ROW[2], ROW[1] + ROW[3]), fill=row_fill) + for (cx, _cy, _cw, _ch), cell in zip(CELLS, ("Neil", "Sorenson", "1984-03-12")): + draw.text((cx + 4, ROW[1] + 8), cell, fill="white", font=font) + draw.text((20, 600), dose, fill="black", font=font) draw.text((20, 300), banner, fill="black", font=font) draw.rectangle( (NOTE[0], NOTE[1], NOTE[0] + NOTE[2], NOTE[1] + NOTE[3]), outline="gray" @@ -88,7 +96,16 @@ def _frame( return out.getvalue() -def _fields(*, search: str = "Neil", note: str = "BP 128/82; follow-up in 2 weeks"): +def _fields( + *, + search: str = "Neil", + note: str = "BP 128/82; follow-up in 2 weeks", + selected: str = "selected", +): + cells = [ + {"kind": "text", "rect": rect, "text": text, "state": None} + for rect, text in zip(CELLS, ("Neil", "Sorenson", "1984-03-12")) + ] return { "bounds": WINDOW, "fields": [ @@ -96,9 +113,12 @@ def _fields(*, search: str = "Neil", note: str = "BP 128/82; follow-up in 2 week "kind": "title_bar", "rect": TITLE_BAR, "text": "Patient Notes - Benchmark Harness", + "state": None, }, - {"kind": "edit", "rect": SEARCH, "text": search}, - {"kind": "edit", "rect": NOTE, "text": note}, + {"kind": "edit", "rect": SEARCH, "text": search, "state": None}, + {"kind": "state", "rect": ROW, "text": "", "state": selected}, + *cells, + {"kind": "edit", "rect": NOTE, "text": note, "state": None}, ], } @@ -115,6 +135,12 @@ def test_a_caret_or_a_title_bar_glyph_leaves_the_form_unchanged(): assert _state(caret=True, close_hover=True, clock="7:28 PM") == before +def test_a_dimmed_selection_highlight_leaves_the_form_unchanged(): + # The window lost focus while the item waited: the selected row turns + # grey, its cells read the same through UIA. + assert _state(row_fill=(204, 204, 204)) == _state() + + @pytest.mark.parametrize( "fields,frame", [ @@ -125,8 +151,17 @@ def test_a_caret_or_a_title_bar_glyph_leaves_the_form_unchanged(): (_fields(note="BP 138/82; follow-up in 2 weeks"), {}), (_fields(search="Nell"), {"search": "Nell"}), (None, {"banner": "Patient: Neil Sorensen (1983-01-19)"}), + (None, {"dose": "Dose: 1 | 25"}), + (_fields(selected="unselected"), {}), + ], + ids=[ + "note-value", + "note-value-not-yet-painted", + "search-value", + "banner-by-ocr", + "adjacent-numbers-by-ocr", + "selection", ], - ids=["note-value", "note-value-not-yet-painted", "search-value", "banner-by-ocr"], ) def test_a_changed_value_changes_the_form(fields, frame): before = _state() @@ -138,7 +173,7 @@ def test_a_changed_value_changes_the_form(fields, frame): def test_a_moved_field_or_window_changes_the_form(): before = _state() moved = _fields() - moved["fields"][2] = {**moved["fields"][2], "rect": (20, 341, 600, 120)} + moved["fields"][-1] = {**moved["fields"][-1], "rect": (20, 341, 600, 120)} assert _state(moved) != before window = {**_fields(), "bounds": (0, 0, 1024, 719)} assert _state(window) != before @@ -150,7 +185,9 @@ def test_a_field_covers_only_its_own_pixels(): # its value must be read. The banner change still shows through the # other channel: a different field set is a different digest. covering = _fields() - covering["fields"].append({"kind": "edit", "rect": (20, 296, 500, 30), "text": ""}) + covering["fields"].append( + {"kind": "edit", "rect": (20, 296, 500, 30), "text": "", "state": None} + ) assert _state(covering) != _state() @@ -242,8 +279,14 @@ def post(path, payload): "status": "ok", "window": {"hwnd": 7, "pid": 10, "bounds": [0, 0, 1024, 720]}, "fields": [ - {"kind": "title_bar", "rect": [0, 0, 1024, 30], "text": "Patient Notes"}, - {"kind": "edit", "rect": [20, 44, 480, 26], "text": "Neil"}, + { + "kind": "title_bar", + "rect": [0, 0, 1024, 30], + "text": "Patient Notes", + "state": None, + }, + {"kind": "edit", "rect": [20, 44, 480, 26], "text": "Neil", "state": None}, + {"kind": "state", "rect": [20, 100, 600, 40], "text": "", "state": "selected"}, ], } @@ -255,8 +298,19 @@ def test_the_windows_backend_reads_the_fields_of_its_one_window(): assert answer == { "bounds": (0, 0, 1024, 720), "fields": [ - {"kind": "title_bar", "rect": (0, 0, 1024, 30), "text": "Patient Notes"}, - {"kind": "edit", "rect": (20, 44, 480, 26), "text": "Neil"}, + { + "kind": "title_bar", + "rect": (0, 0, 1024, 30), + "text": "Patient Notes", + "state": None, + }, + {"kind": "edit", "rect": (20, 44, 480, 26), "text": "Neil", "state": None}, + { + "kind": "state", + "rect": (20, 100, 600, 40), + "text": "", + "state": "selected", + }, ], } @@ -289,6 +343,7 @@ def _bad(**change): ({"s1": (7, 10)}, _bad(field_rect=[20, 44, True, 26])), ({"s1": (7, 10)}, _bad(field_rect=[20, 44, 0, 26])), ({"s1": (7, 10)}, _bad(field_extra=1)), + ({"s1": (7, 10)}, _bad(field_state="maybe")), ], ids=[ "none-verified", @@ -303,6 +358,7 @@ def _bad(**change): "bool-rect", "empty-rect", "extra-field-key", + "unknown-state", ], ) def test_the_windows_backend_refuses_doubtful_fields(captures, answer): @@ -328,7 +384,11 @@ def __init__( offscreen=False, name="", children=(), + selected=None, + toggle=None, ): + self._selected = selected + self._toggle = toggle self.ControlTypeName = control_type self.BoundingRectangle = _Rect(*bounds) self.IsOffscreen = offscreen @@ -344,6 +404,16 @@ def GetValuePattern(self): raise RuntimeError("no value pattern") return SimpleNamespace(Value=self._value) + def GetSelectionItemPattern(self): + if self._selected is None: + raise RuntimeError("no selection item pattern") + return SimpleNamespace(IsSelected=self._selected) + + def GetTogglePattern(self): + if self._toggle is None: + raise RuntimeError("no toggle pattern") + return SimpleNamespace(ToggleState=self._toggle) + class _Desktop: def __init__(self, extra_windows=()): @@ -415,6 +485,18 @@ def _agent(monkeypatch, window, desktop=None): def test_the_agent_reads_the_title_bar_and_every_readable_text_field(monkeypatch): + row = _Control( + "CustomControl", + bounds=(20, 140, 620, 180), + selected=True, + children=[ + _Control("DataItemControl", bounds=(20, 140, 220, 180), value="Neil"), + _Control("DataItemControl", bounds=(220, 140, 420, 180), value=""), + # A cell whose only text is its position name: not read, so its + # pixels stay in the OCR. + _Control("DataItemControl", bounds=(420, 140, 620, 180), name="dob Row 0"), + ], + ) window = _window( _Control( "TitleBarControl", @@ -432,15 +514,23 @@ def test_the_agent_reads_the_title_bar_and_every_readable_text_field(monkeypatch value="hidden", offscreen=True, ), - _Control( - "EditControl", bounds=(20, 110, 500, 130) - ), # password: no value + # A password box: no value, so its pixels stay in the OCR. + _Control("EditControl", bounds=(20, 110, 500, 130)), + row, _Control( "DocumentControl", bounds=(20, 340, 620, 460), value="BP 128/82" ), _Control( "TextControl", bounds=(20, 300, 500, 320), name="Patient: Neil" ), + _Control( + "CheckBoxControl", + bounds=(20, 470, 200, 490), + name="Urgent", + toggle=1, + ), + # A pane with no text of its own is not a field. + _Control("PaneControl", bounds=(700, 40, 900, 90)), ], ), ) @@ -448,9 +538,28 @@ def test_the_agent_reads_the_title_bar_and_every_readable_text_field(monkeypatch answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) assert answer["window"] == {"hwnd": 7, "pid": 10, "bounds": [0, 0, 1024, 720]} assert answer["fields"] == [ - {"kind": "title_bar", "rect": [0, 0, 1024, 30], "text": "Patient Notes"}, - {"kind": "edit", "rect": [20, 44, 480, 26], "text": "Neil"}, - {"kind": "edit", "rect": [20, 340, 600, 120], "text": "BP 128/82"}, + { + "kind": "title_bar", + "rect": [0, 0, 1024, 30], + "text": "Patient Notes", + "state": None, + }, + {"kind": "edit", "rect": [20, 44, 480, 26], "text": "Neil", "state": None}, + {"kind": "state", "rect": [20, 140, 600, 40], "text": "", "state": "selected"}, + {"kind": "text", "rect": [20, 140, 200, 40], "text": "Neil", "state": None}, + { + "kind": "edit", + "rect": [20, 340, 600, 120], + "text": "BP 128/82", + "state": None, + }, + { + "kind": "text", + "rect": [20, 300, 480, 20], + "text": "Patient: Neil", + "state": None, + }, + {"kind": "text", "rect": [20, 470, 180, 20], "text": "Urgent", "state": "on"}, ] From c74f5dff3fdec1127ddfac6d2b56d1907539baf9 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 17:38:08 -0500 Subject: [PATCH 05/34] fix(approval): accept the window_fields form-state kind in an approval request --- .../flow/openadapt_flow/approval_mode/item_approval.py | 6 ++++-- packages/flow/tests/test_approval_mode_item_approval.py | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/flow/openadapt_flow/approval_mode/item_approval.py b/packages/flow/openadapt_flow/approval_mode/item_approval.py index 4fb2693500..a7a8c01a10 100644 --- a/packages/flow/openadapt_flow/approval_mode/item_approval.py +++ b/packages/flow/openadapt_flow/approval_mode/item_approval.py @@ -241,10 +241,12 @@ class ItemApprovalRequest(BaseModel): screenshot: str = Field(min_length=1, max_length=256) screenshot_sha256: str = Field(pattern=_HEX_SHA256) #: How the field state was read: the page's own form controls, or the - #: text on the screen where the application exposes no form controls. + #: 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. #: ``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", "api_request"] + form_state_kind: Literal["dom", "screen_text", "window_fields", "api_request"] form_state_sha256: str = Field(pattern=PREFIXED_SHA256_PATTERN) created_at: str expires_at: str diff --git a/packages/flow/tests/test_approval_mode_item_approval.py b/packages/flow/tests/test_approval_mode_item_approval.py index fbcdd2a458..64c9b9bc33 100644 --- a/packages/flow/tests/test_approval_mode_item_approval.py +++ b/packages/flow/tests/test_approval_mode_item_approval.py @@ -94,6 +94,14 @@ def test_a_request_is_two_private_files_and_waits(tmp_path): assert "form_state_sha256" not in summary +def test_a_desktop_window_read_by_its_fields_is_a_request_kind(tmp_path): + # A desktop approval that read the app window's controls by value (#2189). + store = ItemApprovalStore(tmp_path / "run") + request = _open(store, form_state=("window_fields", "sha256:" + "2" * 64)) + assert request.form_state_kind == "window_fields" + assert store.read_request(request.request_id) == request + + def test_an_approval_is_recorded_once_and_used_once(tmp_path): store = ItemApprovalStore(tmp_path / "run") request = _open(store) From 571ffdd46dfdc629d2d51e68dafe656fd23f97cb Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 17:45:19 -0500 Subject: [PATCH 06/34] docs: approval reads the window's controls by value (#2189); rebuild llms-full.txt --- CAPABILITIES.md | 2 +- llms-full.txt | 9 ++++++++- packages/flow/CHANGELOG.md | 23 +++++++++++++++++++++++ packages/flow/docs/LIMITS.md | 7 +++++++ 4 files changed, 39 insertions(+), 2 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 73a5c32284..9e834cfa1a 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -230,7 +230,7 @@ improvising or retrying when something is off. | Surface | Status | Evidence | Where | | --- | --- | --- | --- | | Web (Playwright, Chromium) | Released | Real apps on local test copies (OpenEMR, Odoo, Frappe Lending, openIMIS) and Medplum; CI runs in-tree apps on every build | [SURFACES.md](packages/flow/docs/SURFACES.md) | -| Native Windows (UI Automation) | Released | Synthetic (a WinForms test app in a Windows 11 VM, 3 of 3 trials); CI on a GitHub-hosted Windows runner on every change to the Windows path and nightly: record, compile and replay of the WinForms Patient Notes app through the real win_agent, judged from its SQLite record, with a near-identical sibling roster that must not be written, and a non-gating governed run of the same workflow under the Standard profile with a person's signed approval, a hold and a resume, whose resume currently stops before the save on a false form change (fail-closed, nothing written; [#2189](https://github.com/OpenAdaptAI/OpenAdapt/issues/2189)), followed by a gating check that fails the job on any sibling, held or unverified write ([desktop-replay.yml](.github/workflows/desktop-replay.yml)); on a real Windows 11 ARM machine, record, compile and replay of the same kind of WinForms test form with an owned confirm dialog, 3 of 3 trials, each also refusing a target covered by another app's window and one blocked by a modal dialog before any input | [SURFACES.md](packages/flow/docs/SURFACES.md) | +| Native Windows (UI Automation) | Released | Synthetic (a WinForms test app in a Windows 11 VM, 3 of 3 trials); CI on a GitHub-hosted Windows runner on every change to the Windows path and nightly: record, compile and replay of the WinForms Patient Notes app through the real win_agent, judged from its SQLite record, with a near-identical sibling roster that must not be written, and a non-gating governed run of the same workflow under the Standard profile with a person's signed approval, a hold and a resume, whose resume completes the save (`VERIFIED`, the note on the target row only) now that the approval reads the window's text fields, labels and grid cells by value through UI Automation and only the rest by OCR ([#2189](https://github.com/OpenAdaptAI/OpenAdapt/issues/2189), [#2291](https://github.com/OpenAdaptAI/OpenAdapt/pull/2291)), followed by a gating check that fails the job on any sibling, held or unverified write ([desktop-replay.yml](.github/workflows/desktop-replay.yml)); on a real Windows 11 ARM machine, record, compile and replay of the same kind of WinForms test form with an owned confirm dialog, 3 of 3 trials, each also refusing a target covered by another app's window and one blocked by a modal dialog before any input | [SURFACES.md](packages/flow/docs/SURFACES.md) | | Native macOS (Accessibility) | Released | Synthetic (TextEdit, 3 of 3 file effects, driving the backend directly); a real third-party app, calibre (Qt, SQLite library): record, compile (certified under `clinical-write`) and a `standard` run checked against the library's database, `VERIFIED` with only the target book changed; a same-title book by another author stopped at the identity check and two identical books were refused as ambiguous, each with nothing written ([benchmark/macos_native](packages/flow/benchmark/macos_native/README.md)) | [SURFACES.md](packages/flow/docs/SURFACES.md) | | Native Linux (AT-SPI, X11) | Released | Real AT-SPI in CI (`flow-linux-atspi`, Xvfb with a window manager): a GTK3 fixture (3 verified effects, 3 ambiguous and 3 stale targets refused) and a GTK3 chart app with SQLite: record, compile (certified under `clinical-write`), a `standard` run `VERIFIED` against the database, another patient's chart and a look-alike chart stopped before the save, and a repaired notice admitted on its AT-SPI element identity ([benchmark/repair_every_backend](packages/flow/benchmark/repair_every_backend/README.md)) | [LINUX_NATIVE.md](packages/flow/docs/desktop/LINUX_NATIVE.md) | | RDP (pixels; Aardwolf or headless FreeRDP with a session pool) | Released | A Windows 11 VM over Aardwolf RDP, 3 of 3 (transport and input), plus a FreeRDP batch; through the stock Remote Desktop client on a real H.264/AVC444 session, 105 scripted runs on two apps (OpenEMR in Edge and a WinForms test app): 55 saves confirmed in the database, 0 wrong-record saves, 40 false stops ranked by cause | [SURFACES.md](packages/flow/docs/SURFACES.md), `backends/xfreerdp.py`, [benchmark/rdp_avc_real](packages/flow/benchmark/rdp_avc_real/README.md) | diff --git a/llms-full.txt b/llms-full.txt index c43236290b..fb3c601d5c 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -664,7 +664,7 @@ improvising or retrying when something is off. | Surface | Status | Evidence | Where | | --- | --- | --- | --- | | Web (Playwright, Chromium) | Released | Real apps on local test copies (OpenEMR, Odoo, Frappe Lending, openIMIS) and Medplum; CI runs in-tree apps on every build | [SURFACES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SURFACES.md) | -| Native Windows (UI Automation) | Released | Synthetic (a WinForms test app in a Windows 11 VM, 3 of 3 trials); CI on a GitHub-hosted Windows runner on every change to the Windows path and nightly: record, compile and replay of the WinForms Patient Notes app through the real win_agent, judged from its SQLite record, with a near-identical sibling roster that must not be written, and a non-gating governed run of the same workflow under the Standard profile with a person's signed approval, a hold and a resume, whose resume currently stops before the save on a false form change (fail-closed, nothing written; [#2189](https://github.com/OpenAdaptAI/OpenAdapt/issues/2189)), followed by a gating check that fails the job on any sibling, held or unverified write ([desktop-replay.yml](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/.github/workflows/desktop-replay.yml)); on a real Windows 11 ARM machine, record, compile and replay of the same kind of WinForms test form with an owned confirm dialog, 3 of 3 trials, each also refusing a target covered by another app's window and one blocked by a modal dialog before any input | [SURFACES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SURFACES.md) | +| Native Windows (UI Automation) | Released | Synthetic (a WinForms test app in a Windows 11 VM, 3 of 3 trials); CI on a GitHub-hosted Windows runner on every change to the Windows path and nightly: record, compile and replay of the WinForms Patient Notes app through the real win_agent, judged from its SQLite record, with a near-identical sibling roster that must not be written, and a non-gating governed run of the same workflow under the Standard profile with a person's signed approval, a hold and a resume, whose resume completes the save (`VERIFIED`, the note on the target row only) now that the approval reads the window's text fields, labels and grid cells by value through UI Automation and only the rest by OCR ([#2189](https://github.com/OpenAdaptAI/OpenAdapt/issues/2189), [#2291](https://github.com/OpenAdaptAI/OpenAdapt/pull/2291)), followed by a gating check that fails the job on any sibling, held or unverified write ([desktop-replay.yml](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/.github/workflows/desktop-replay.yml)); on a real Windows 11 ARM machine, record, compile and replay of the same kind of WinForms test form with an owned confirm dialog, 3 of 3 trials, each also refusing a target covered by another app's window and one blocked by a modal dialog before any input | [SURFACES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SURFACES.md) | | Native macOS (Accessibility) | Released | Synthetic (TextEdit, 3 of 3 file effects, driving the backend directly); a real third-party app, calibre (Qt, SQLite library): record, compile (certified under `clinical-write`) and a `standard` run checked against the library's database, `VERIFIED` with only the target book changed; a same-title book by another author stopped at the identity check and two identical books were refused as ambiguous, each with nothing written ([benchmark/macos_native](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/macos_native/README.md)) | [SURFACES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SURFACES.md) | | Native Linux (AT-SPI, X11) | Released | Real AT-SPI in CI (`flow-linux-atspi`, Xvfb with a window manager): a GTK3 fixture (3 verified effects, 3 ambiguous and 3 stale targets refused) and a GTK3 chart app with SQLite: record, compile (certified under `clinical-write`), a `standard` run `VERIFIED` against the database, another patient's chart and a look-alike chart stopped before the save, and a repaired notice admitted on its AT-SPI element identity ([benchmark/repair_every_backend](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/repair_every_backend/README.md)) | [LINUX_NATIVE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/desktop/LINUX_NATIVE.md) | | RDP (pixels; Aardwolf or headless FreeRDP with a session pool) | Released | A Windows 11 VM over Aardwolf RDP, 3 of 3 (transport and input), plus a FreeRDP batch; through the stock Remote Desktop client on a real H.264/AVC444 session, 105 scripted runs on two apps (OpenEMR in Edge and a WinForms test app): 55 saves confirmed in the database, 0 wrong-record saves, 40 false stops ranked by cause | [SURFACES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SURFACES.md), `backends/xfreerdp.py`, [benchmark/rdp_avc_real](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/rdp_avc_real/README.md) | @@ -2218,6 +2218,13 @@ What is not: - Values chosen by clicking (not typing), drag and drop, and WebSocket traffic are checked only by the write adapter or the read-back, if at all. - The instruction detector on approval forms is a heuristic display aid. +- On Windows, a desktop approval reads the app window's text fields, labels, + buttons and grid cells by their UI Automation value or name and paints them + out of the OCR read. It trusts that a standard control draws the text UI + Automation reports; a control that paints other text under the same + rectangle would hide a change there. Custom-drawn text that UI Automation + does not expose stays in the OCR read, and any other window of the app + sends the whole window back to OCR alone. - No live model has been run against these fixtures yet; the live-model test is off by default because it costs money. diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index ddddd858db..9ac3d8461f 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -15,6 +15,29 @@ +## Unreleased + +### Fixes + +- A desktop approval no longer halts on a form that did not change + ([#2189](https://github.com/OpenAdaptAI/OpenAdapt/issues/2189)). On the + hosted Windows governed run, two reads of the same Patient Notes window + gave different OCR words (the caret in the search box, the title bar's + close button, a selected grid row), so every resumed approval stopped + with `form_changed_after_approval`. The win_agent has a new typed read, + `window-form-fields` (capability `window_form_fields_v1`): the approval + window's frame, its title bar, and every on-screen text field, label, + button and list or grid cell whose text UI Automation reads, with toggle + and selection state. The approval's form state (kind `window_fields`) + reads those controls by value, paints them out of the window crop, and + reads the rest of the window by OCR. A changed value still changes the + digest through either channel. Cells count only by value, never by a + positional name. The agent answers no window when the app shows any other + window or the walk is incomplete, and the window is then read by OCR as + before; a request and a recheck read through different channels never + match. The governed run now resumes to `VERIFIED` with the note on the + target row only. + ## v3.3.0 (2026-11-19) ### Fixes diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index b0beaa4619..3c053141dd 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -946,6 +946,13 @@ What is not: - Values chosen by clicking (not typing), drag and drop, and WebSocket traffic are checked only by the write adapter or the read-back, if at all. - The instruction detector on approval forms is a heuristic display aid. +- On Windows, a desktop approval reads the app window's text fields, labels, + buttons and grid cells by their UI Automation value or name and paints them + out of the OCR read. It trusts that a standard control draws the text UI + Automation reports; a control that paints other text under the same + rectangle would hide a change there. Custom-drawn text that UI Automation + does not expose stays in the OCR read, and any other window of the app + sends the whole window back to OCR alone. - No live model has been run against these fixtures yet; the live-model test is off by default because it costs money. From 4ad70c763cd0abf6a3954766a3f1326d82bf62e3 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 19:26:51 -0500 Subject: [PATCH 07/34] fix(approval): preserve complete evidence for masked controls --- .../backends/win_agent/server.py | 36 +++++-- .../flow/openadapt_flow/runtime/replayer.py | 6 +- .../flow/tests/test_approval_form_fields.py | 94 +++++++++++++++++++ 3 files changed, 125 insertions(+), 11 deletions(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 21ba0f58f5..91a12c5049 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -2272,7 +2272,9 @@ def _form_field_value(control: object) -> tuple[bool, Optional[str]]: return False, None if not isinstance(value, str): return False, None - return True, value[:_MAX_READ_TEXT] + # This is approval evidence, not a display preview: truncating a value + # before its rectangle is hidden would lose edits beyond the prefix. + return True, value def _form_field_state(control: object, control_type: str) -> Optional[str]: @@ -2331,7 +2333,17 @@ def _window_form_fields( return None, False title = " ".join(str(_control_value(window, "Name", "") or "").split()) fields: list[dict[str, Any]] = [] - stack: list[tuple[Any, int]] = [(c, 1) for c in reversed(_children(window))] + + def children_of(control: Any) -> list[Any]: + # The general preview helper treats a provider error as no children. + # Here that could make a container look like a leaf and hide text we + # never read, so an incomplete walk must refuse the projection. + return list(control.GetChildren()) + + try: + stack: list[tuple[Any, int]] = [(c, 1) for c in reversed(children_of(window))] + except Exception: # noqa: BLE001 - incomplete UIA is no projection + return None, False visited = 0 while stack: control, depth = stack.pop() @@ -2341,18 +2353,22 @@ def _window_form_fields( control_type = str(_control_value(control, "ControlTypeName", "")) bounds = _bounds(control) on_screen = _control_value(control, "IsOffscreen", True) is False + try: + children = children_of(control) + except Exception: # noqa: BLE001 - an unknown subtree is not a leaf + return None, False if control_type == "TitleBarControl": if bounds is not None: fields.append( { "kind": "title_bar", "rect": _rect(bounds), - "text": title[:_MAX_READ_TEXT], + "text": title, "state": None, } ) continue - if control_type in _FORM_VALUE_TYPES: + if control_type in _FORM_VALUE_TYPES and not children: readable, value = _form_field_value(control) if bounds is not None and on_screen and readable: fields.append( @@ -2364,14 +2380,18 @@ def _window_form_fields( } ) continue - children = _children(control) state = _form_field_state(control, control_type) + if control_type in {"CheckBoxControl", "RadioButtonControl", "TabItemControl"}: + if state is None: + # The label alone does not account for the control's state. + # Keep these pixels in the OCR read when UIA cannot name it. + continue if not children and control_type in _FORM_NAMED_TYPES | _FORM_ITEM_TYPES: readable, value = _form_field_value(control) text = value if readable and value else None if text is None and control_type in _FORM_NAMED_TYPES: name = " ".join(str(_control_value(control, "Name", "") or "").split()) - text = name[:_MAX_READ_TEXT] or None + text = name or None if bounds is not None and on_screen and text: fields.append( { @@ -2386,7 +2406,9 @@ def _window_form_fields( fields.append( {"kind": "state", "rect": _rect(bounds), "text": "", "state": state} ) - if depth < _MAX_UIA_DEPTH: + if children: + if depth >= _MAX_UIA_DEPTH: + return fields, True stack.extend((c, depth + 1) for c in reversed(children)) return fields, False diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index ddc6d7489b..1d4a296609 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -13127,11 +13127,9 @@ def _approval_form_state( from openadapt_flow.approval_mode import form_state as fs try: - results = getattr(self._approval_report, "results", ()) + prior = getattr(self._approval_report, "results", ()) step, backend = self._approval_form_step_id, self.backend - return fs.approval_form_state( - backend, self.vision, frame_png, step, results - ) + return fs.approval_form_state(backend, self.vision, frame_png, step, prior) except Exception: # noqa: BLE001 - unreadable is never "unchanged" return None diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 81625808e6..3643f99025 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -603,3 +603,97 @@ def test_the_agent_refuses_a_window_uia_cannot_open(monkeypatch): perform = _agent(monkeypatch, None) assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["window"] is None assert perform("window-form-fields", {"hwnd": 7, "pid": 11})["window"] is None + + +@pytest.mark.parametrize( + "control_type,source", + [ + ("EditControl", "value"), + ("DocumentControl", "value"), + ("DataItemControl", "value"), + ("TextControl", "name"), + ("ButtonControl", "name"), + ("TitleBarControl", "title"), + ], +) +def test_every_masked_text_source_retains_an_edit_beyond_preview_length( + monkeypatch, control_type, source +): + # Same visible prefix, different stored suffix: the projection must not + # turn these distinct forms into the same approval digest. + import openadapt_flow.backends.win_agent.server as agent_server + + prefix = "x" * agent_server._MAX_READ_TEXT + control = _Control(control_type, bounds=(20, 44, 500, 70)) + window = _window(control) + perform = _agent(monkeypatch, window) + frame = io.BytesIO() + Image.new("RGB", SIZE, "white").save(frame, format="PNG") + no_words = SimpleNamespace(ocr=lambda _png: []) + + def read(suffix): + value = prefix + suffix + if source == "title": + window.Name = value + elif source == "name": + control.Name = value + else: + control._value = value + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert answer["fields"][0]["text"] == value + return window_fields_state( + no_words, + frame.getvalue(), + {"bounds": WINDOW, "fields": answer["fields"]}, + ) + + before, after = read("a"), read("b") + assert before is not None and after is not None and before != after + + +@pytest.mark.parametrize( + "control_type", ["CheckBoxControl", "RadioButtonControl", "TabItemControl"] +) +def test_a_stateful_control_with_unreadable_state_keeps_its_pixels( + monkeypatch, control_type +): + control = _Control(control_type, name="Choice", bounds=(20, 44, 500, 70)) + perform = _agent(monkeypatch, _window(control)) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert answer["window"] is not None + assert answer["fields"] == [] + + +@pytest.mark.parametrize("failed_at", ["window", "control"]) +def test_a_failed_child_read_never_turns_an_unknown_subtree_into_a_mask( + monkeypatch, failed_at +): + control = _Control("TextControl", name="Summary", bounds=(20, 44, 500, 70)) + window = _window(control) + + def failed(): + raise RuntimeError("provider cannot enumerate this subtree") + + (window if failed_at == "window" else control).GetChildren = failed + perform = _agent(monkeypatch, window) + assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["window"] is None + + +def test_a_value_container_does_not_hide_its_descendant_fields(monkeypatch): + child = _Control("EditControl", value="actual field", bounds=(20, 44, 500, 70)) + document = _Control( + "DocumentControl", value="summary", bounds=(0, 30, 1024, 720), children=[child] + ) + perform = _agent(monkeypatch, _window(document)) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert [field["text"] for field in answer["fields"]] == ["actual field"] + + +def test_a_depth_limited_form_walk_is_incomplete(monkeypatch): + import openadapt_flow.backends.win_agent.server as agent_server + + monkeypatch.setattr(agent_server, "_MAX_UIA_DEPTH", 1) + child = _Control("EditControl", value="unseen field") + pane = _Control("PaneControl", children=[child]) + perform = _agent(monkeypatch, _window(pane)) + assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["window"] is None From ed175d9518b823f69ab5e8509e2a522f9ceb0260 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 19:30:28 -0500 Subject: [PATCH 08/34] fix(approval): leave empty and password controls visible --- llms-full.txt | 3 +++ packages/flow/CHANGELOG.md | 6 +++++ packages/flow/docs/LIMITS.md | 3 +++ .../backends/win_agent/server.py | 14 ++++++++-- .../flow/tests/test_approval_form_fields.py | 27 +++++++++++++++++++ 5 files changed, 51 insertions(+), 2 deletions(-) diff --git a/llms-full.txt b/llms-full.txt index fb3c601d5c..e5a262299d 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -2225,6 +2225,9 @@ What is not: rectangle would hide a change there. Custom-drawn text that UI Automation does not expose stays in the OCR read, and any other window of the app sends the whole window back to OCR alone. + Values used to mask a control retain the complete text, rather than the + preview prefix. Password, empty and state-unreadable controls stay in OCR; + unknown subtrees are not treated as fully read controls. - No live model has been run against these fixtures yet; the live-model test is off by default because it costs money. diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 9ac3d8461f..bcdafae92b 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -19,6 +19,12 @@ ### Fixes +- Approval form projections retain complete control values, including edits + beyond the preview length. Empty, redacted or state-unreadable controls + stay in the OCR read. A failed or depth-limited UI Automation walk does + not certify a complete control read, and a container cannot hide its + unread descendants ([#2291](https://github.com/OpenAdaptAI/OpenAdapt/pull/2291)). + - A desktop approval no longer halts on a form that did not change ([#2189](https://github.com/OpenAdaptAI/OpenAdapt/issues/2189)). On the hosted Windows governed run, two reads of the same Patient Notes window diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index 3c053141dd..4556557147 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -953,6 +953,9 @@ What is not: rectangle would hide a change there. Custom-drawn text that UI Automation does not expose stays in the OCR read, and any other window of the app sends the whole window back to OCR alone. + Values used to mask a control retain the complete text, rather than the + preview prefix. Password, empty and state-unreadable controls stay in OCR; + unknown subtrees are not treated as fully read controls. - No live model has been run against these fixtures yet; the live-model test is off by default because it costs money. diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 91a12c5049..af8969409e 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -2358,7 +2358,7 @@ def children_of(control: Any) -> list[Any]: except Exception: # noqa: BLE001 - an unknown subtree is not a leaf return None, False if control_type == "TitleBarControl": - if bounds is not None: + if bounds is not None and on_screen and title: fields.append( { "kind": "title_bar", @@ -2369,8 +2369,18 @@ def children_of(control: Any) -> list[Any]: ) continue if control_type in _FORM_VALUE_TYPES and not children: + # A password provider may return an empty or redacted Value. + # Empty values and unknown password status also account for no + # visible text, so all of those pixels must stay in the OCR. + password = _control_value(control, "IsPassword", None) readable, value = _form_field_value(control) - if bounds is not None and on_screen and readable: + if ( + bounds is not None + and on_screen + and password is False + and readable + and value + ): fields.append( { "kind": "edit", diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 3643f99025..ea3a284ca9 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -386,7 +386,9 @@ def __init__( children=(), selected=None, toggle=None, + password=False, ): + self.IsPassword = password self._selected = selected self._toggle = toggle self.ControlTypeName = control_type @@ -697,3 +699,28 @@ def test_a_depth_limited_form_walk_is_incomplete(monkeypatch): pane = _Control("PaneControl", children=[child]) perform = _agent(monkeypatch, _window(pane)) assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["window"] is None + + +@pytest.mark.parametrize("control_type", ["EditControl", "DocumentControl"]) +@pytest.mark.parametrize( + "value,password", + [("", False), ("", True), ("redacted", True), ("value", None)], + ids=["empty", "empty-password", "redacted-password", "password-status-unknown"], +) +def test_an_empty_or_redacted_value_never_hides_the_visible_field( + monkeypatch, control_type, value, password +): + control = _Control( + control_type, value=value, password=password, bounds=(20, 44, 500, 70) + ) + perform = _agent(monkeypatch, _window(control)) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert answer["window"] is not None + assert answer["fields"] == [] + + +def test_an_unreadable_title_never_hides_the_title_bar(monkeypatch): + window = _window(_Control("TitleBarControl", bounds=(0, 0, 1024, 30))) + window.Name = "" + perform = _agent(monkeypatch, window) + assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["fields"] == [] From 2ddc51d36fbd086dd278fd8d8f739f748007cdfd Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 23:10:15 -0500 Subject: [PATCH 09/34] Require independent native extent and UIA agreement for complete values --- .../backends/win_agent/native_value.py | 299 +++++++++++++++ .../tests/test_native_value_completeness.py | 348 ++++++++++++++++++ 2 files changed, 647 insertions(+) create mode 100644 packages/flow/openadapt_flow/backends/win_agent/native_value.py create mode 100644 packages/flow/tests/test_native_value_completeness.py diff --git a/packages/flow/openadapt_flow/backends/win_agent/native_value.py b/packages/flow/openadapt_flow/backends/win_agent/native_value.py new file mode 100644 index 0000000000..8d75201a2a --- /dev/null +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -0,0 +1,299 @@ +"""One conservative completeness contract for native UIA value consumers. + +A provider value is complete only when two identity-bound Unicode native +extent/full reads agree with two exact UIA reads. A disagreement is unavailable, +never an instruction to prefer one source. No names, normalization or truncation +are used. The caller also supplies its current focus/window identity guard. +""" + +from __future__ import annotations + +import ctypes +import hashlib +import time +from dataclasses import asdict, dataclass +from typing import Any, Callable, Protocol + +MAX_UTF16_UNITS = 65536 +PROOF_SCHEMA = "openadapt.native-value-completeness/v1" + + +def utf16_bytes(value: str) -> bytes: + return value.encode("utf-16-le", errors="surrogatepass") + + +class ValueUnavailable(Exception): + """A specific absence of completeness evidence; never carries field text.""" + + +@dataclass(frozen=True) +class NativeOwner: + hwnd: int + pid: int + thread: int + + +@dataclass(frozen=True) +class NativeRead: + owner: NativeOwner + extent: int + copied: int + value: str + + +@dataclass(frozen=True) +class ValueProof: + schema: str + method: str + hwnd: int + pid: int + thread: int + utf16_units: int + sha256_utf16le: str + native_reads: int = 2 + uia_reads: int = 2 + + def payload(self) -> dict[str, Any]: + return asdict(self) + + +@dataclass(frozen=True) +class CompleteValue: + complete: bool + value: str | None + reason: str | None + proof: ValueProof | None + + +class NativeTextReader(Protocol): + def owner(self, hwnd: int) -> NativeOwner: ... + def read(self, owner: NativeOwner) -> NativeRead: ... + + +class Win32TextReader: + """Bounded Unicode WM_GETTEXTLENGTH/WM_GETTEXT, without sending input. + + Only a real Unicode HWND owned by the bound UIA PID is accepted. The length + may overestimate for some controls; exact copied count and UTF-16 length + must agree or the observation is refused. Every message has a timeout. + """ + + def __init__(self) -> None: + from ctypes import wintypes + + load = getattr(ctypes, "WinDLL", None) + if load is None: + raise ValueUnavailable("native_api_unavailable") + self._user = load("user32", use_last_error=True) + self._user.IsWindow.argtypes = [wintypes.HWND] + self._user.IsWindow.restype = wintypes.BOOL + self._user.IsWindowUnicode.argtypes = [wintypes.HWND] + self._user.IsWindowUnicode.restype = wintypes.BOOL + self._user.GetWindowThreadProcessId.argtypes = [ + wintypes.HWND, + ctypes.POINTER(wintypes.DWORD), + ] + self._user.GetWindowThreadProcessId.restype = wintypes.DWORD + self._user.SendMessageTimeoutW.argtypes = [ + wintypes.HWND, + wintypes.UINT, + ctypes.c_size_t, + ctypes.c_ssize_t, + wintypes.UINT, + wintypes.UINT, + ctypes.POINTER(ctypes.c_size_t), + ] + self._user.SendMessageTimeoutW.restype = ctypes.c_ssize_t + + def owner(self, hwnd: int) -> NativeOwner: + from ctypes import wintypes + + if not self._user.IsWindow(hwnd) or not self._user.IsWindowUnicode(hwnd): + raise ValueUnavailable("native_window_unavailable_or_not_unicode") + pid = wintypes.DWORD() + thread = self._user.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) + if not thread or not pid.value: + raise ValueUnavailable("native_owner_unavailable") + return NativeOwner(hwnd, int(pid.value), int(thread)) + + def _message( + self, hwnd: int, message: int, count: int = 0, pointer: int = 0 + ) -> int: + result = ctypes.c_size_t() + # BLOCK | ABORTIFHUNG | ERRORONEXIT. No input, focus or value mutation. + accepted = self._user.SendMessageTimeoutW( + hwnd, message, count, pointer, 0x23, 1000, ctypes.byref(result) + ) + if not accepted: + raise ValueUnavailable("native_text_timeout_or_failure") + return int(result.value) + + def read(self, owner: NativeOwner) -> NativeRead: + def unchanged() -> None: + if self.owner(owner.hwnd) != owner: + raise ValueUnavailable("native_owner_changed") + + unchanged() + extent = self._message(owner.hwnd, 0x000E) + unchanged() + if not 0 <= extent <= MAX_UTF16_UNITS: + raise ValueUnavailable("value_exceeds_limit") + # Win32 WCHAR is always two bytes, including when protocol-tested on a + # host where ctypes.c_wchar is four bytes. Decode exact copied units. + buffer = (ctypes.c_uint16 * (extent + 1))() + copied = self._message(owner.hwnd, 0x000D, extent + 1, ctypes.addressof(buffer)) + unchanged() + if copied != extent or buffer[extent] != 0: + raise ValueUnavailable("native_extent_or_copy_incomplete") + value = ctypes.string_at(ctypes.addressof(buffer), copied * 2).decode( + "utf-16-le", errors="surrogatepass" + ) + if len(utf16_bytes(value)) // 2 != extent or "\x00" in value: + raise ValueUnavailable("native_extent_or_copy_incomplete") + return NativeRead(owner, extent, copied, value) + + +def _positive_int(value: object) -> bool: + return type(value) is int and value > 0 + + +def _identity(control: Any) -> tuple[int, int, tuple[int, ...]]: + hwnd, pid = control.NativeWindowHandle, control.ProcessId + runtime = control.GetRuntimeId() + if ( + not _positive_int(hwnd) + 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("native_identity_unavailable") + return hwnd, pid, tuple(runtime) + + +def observe_complete_value( + control: Any, + *, + identity: Callable[[], str | None], + require_editable: bool = False, + native_reader: NativeTextReader | None = None, + clock: Callable[[], float] = time.monotonic, +) -> CompleteValue: + """Observe exactly one stable value or return an explicit incomplete result. + + ``identity`` must re-read the caller's bound target scope (including actual + focus for editable input). Returning None or a changed identity refuses. + The helper separately re-reads UIA HWND/PID/RuntimeId and native ownership + around every source read. It never upgrades either disagreeing source. + """ + try: + deadline = clock() + 5.0 + binding = identity() + if not isinstance(binding, str) or not 1 <= len(binding) <= 256: + raise ValueUnavailable("bound_identity_unavailable") + bound = _identity(control) + reader = native_reader if native_reader is not None else Win32TextReader() + owner = reader.owner(bound[0]) + if ( + owner.hwnd != bound[0] + or owner.pid != bound[1] + or not _positive_int(owner.thread) + ): + raise ValueUnavailable("native_owner_disagreement") + + def guard() -> None: + if clock() >= deadline: + raise ValueUnavailable("value_observation_deadline") + if ( + identity() != binding + or _identity(control) != bound + or reader.owner(bound[0]) != owner + ): + raise ValueUnavailable("value_identity_changed") + if getattr(control, "IsPassword", None) is not False: + raise ValueUnavailable("password_or_password_status_unavailable") + if ( + require_editable + and getattr(control, "ControlTypeName", None) != "EditControl" + ): + raise ValueUnavailable("not_editable_value_control") + + def uia() -> str: + guard() + pattern = control.GetValuePattern() + read_only = getattr(pattern, "IsReadOnly", None) + if type(read_only) is not bool or (require_editable and read_only): + raise ValueUnavailable("read_only_or_read_only_status_unavailable") + value = getattr(pattern, "Value", None) + 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 read_only: + raise ValueUnavailable("value_readability_changed") + guard() + return value + + def native() -> NativeRead: + guard() + result = reader.read(owner) + guard() + units = len(utf16_bytes(result.value)) // 2 + if not 0 <= result.extent <= MAX_UTF16_UNITS: + raise ValueUnavailable("value_exceeds_limit") + if ( + result.owner != owner + or result.extent != result.copied + or units != result.extent + ): + raise ValueUnavailable("native_extent_or_copy_incomplete") + return result + + # Native extent is read first so oversized storage cannot be hidden by + # a short provider prefix. Sources bracket one another twice. + before = native() + first = uia() + after = native() + second = uia() + guard() + if before != after or first != second: + raise ValueUnavailable("value_observation_changed") + if utf16_bytes(first) != utf16_bytes(before.value): + raise ValueUnavailable("provider_native_value_disagreement") + proof = ValueProof( + PROOF_SCHEMA, + "uia-value+wm-gettext", + owner.hwnd, + owner.pid, + owner.thread, + before.extent, + hashlib.sha256(utf16_bytes(first)).hexdigest(), + ) + return CompleteValue(True, first, None, proof) + except ValueUnavailable as exc: + return CompleteValue(False, None, str(exc), None) + except Exception: + # COM/ctypes/provider errors never expose a partial value or a Name. + return CompleteValue(False, None, "value_observation_unavailable", None) + + +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( + ValueProof.__dataclass_fields__ + ): + return False + raw = utf16_bytes(value) + return ( + proof["schema"] == PROOF_SCHEMA + and proof["method"] == "uia-value+wm-gettext" + and all(_positive_int(proof[key]) for key in ("hwnd", "pid", "thread")) + and type(proof["utf16_units"]) is int + and 0 <= proof["utf16_units"] <= MAX_UTF16_UNITS + and proof["utf16_units"] == len(raw) // 2 + and proof["sha256_utf16le"] == hashlib.sha256(raw).hexdigest() + and type(proof["native_reads"]) is int + and proof["native_reads"] == 2 + and type(proof["uia_reads"]) is int + and proof["uia_reads"] == 2 + ) diff --git a/packages/flow/tests/test_native_value_completeness.py b/packages/flow/tests/test_native_value_completeness.py new file mode 100644 index 0000000000..9a53ef4ea6 --- /dev/null +++ b/packages/flow/tests/test_native_value_completeness.py @@ -0,0 +1,348 @@ +"""Independent extent/full reads must qualify every complete native value.""" + +from __future__ import annotations + +import ctypes +from dataclasses import replace +from types import SimpleNamespace + +import pytest +from hypothesis import given +from hypothesis import strategies as st + +from openadapt_flow.backends.win_agent.native_value import ( + NativeOwner, + NativeRead, + ValueUnavailable, + Win32TextReader, + observe_complete_value, + utf16_bytes, + valid_value_proof, +) + +OWNER = NativeOwner(123, 456, 789) + + +def control(value=""): + pattern = SimpleNamespace(Value=value, IsReadOnly=False) + target = SimpleNamespace( + NativeWindowHandle=OWNER.hwnd, + ProcessId=OWNER.pid, + GetRuntimeId=lambda: [1, 2], + IsPassword=False, + ControlTypeName="EditControl", + GetValuePattern=lambda: pattern, + Name="never use Name", + ) + return target, pattern + + +class Reader: + def __init__(self, value=""): + self.value = value + self.reads = 0 + self.owner_value = OWNER + + def owner(self, hwnd): + assert hwnd == OWNER.hwnd + return self.owner_value + + def read(self, owner): + self.reads += 1 + units = len(utf16_bytes(self.value)) // 2 + return NativeRead(owner, units, units, self.value) + + +def observe(target, reader, **kwargs): + return observe_complete_value( + target, identity=lambda: "bound:1", native_reader=reader, **kwargs + ) + + +@given(st.text(max_size=9000)) +def test_exact_complete_values_require_both_sources_and_utf16_proof(value): + target, _ = control(value) + reader = Reader(value) + result = observe(target, reader) + assert result.complete and result.value == value and result.reason is None + assert reader.reads == 2 + assert result.proof is not None + proof = result.proof.payload() + assert valid_value_proof(value, proof) + assert proof["utf16_units"] == len(utf16_bytes(value)) // 2 + assert proof["hwnd"] == OWNER.hwnd and proof["pid"] == OWNER.pid + + +@pytest.mark.parametrize( + "stored,provider", + [ + ("x" * 8192 + "-END", "x" * 4096), + ("x" * 4096 + "D", "x" * 4096), + ("hidden suffix", ""), + ("", "Name"), + ], +) +def test_truncated_or_disagreeing_provider_never_becomes_a_complete_baseline_or_mask( + stored, provider +): + target, _ = control(provider) + result = observe(target, Reader(stored)) + assert not result.complete and result.value is None and result.proof is None + assert result.reason == "provider_native_value_disagreement" + + +@pytest.mark.parametrize( + "fault", + [ + "password", + "password_unknown", + "readonly_unknown", + "pattern", + "nonstring", + "missing_hwnd", + "missing_pid", + "missing_runtime", + "wrong_owner", + "timeout", + "oversize", + "unstable_native", + "unstable_provider", + "replaced_identity", + "scope_changed", + "deadline", + "bad_copy", + "owner_changed", + ], +) +def test_missing_or_unstable_completeness_evidence_is_explicitly_unavailable(fault): + target, pattern = control("exact") + reader = Reader("exact") + kwargs = {} + if fault == "password": + target.IsPassword = True + elif fault == "password_unknown": + target.IsPassword = None + elif fault == "readonly_unknown": + pattern.IsReadOnly = None + elif fault == "pattern": + target.GetValuePattern = lambda: None + elif fault == "nonstring": + pattern.Value = None + elif fault == "missing_hwnd": + target.NativeWindowHandle = 0 + elif fault == "missing_pid": + target.ProcessId = 0 + elif fault == "missing_runtime": + target.GetRuntimeId = lambda: [] + elif fault == "wrong_owner": + reader.owner_value = replace(OWNER, pid=999) + elif fault == "timeout": + + def timeout(owner): + raise ValueUnavailable("native_text_timeout_or_failure") + + reader.read = timeout + elif fault == "oversize": + reader.value = "x" * 65537 + elif fault == "unstable_native": + original = reader.read + + def changing(owner): + reader.value += "x" + return original(owner) + + reader.read = changing + elif fault == "unstable_provider": + + class Pattern: + IsReadOnly = False + reads = 0 + + @property + def Value(self): + self.reads += 1 + return "exact" if self.reads == 1 else "changed" + + target.GetValuePattern = Pattern + # Reuse one actual provider, not one object per read. + instance = Pattern() + target.GetValuePattern = lambda: instance + elif fault == "replaced_identity": + original = reader.read + + def replacing(owner): + target.GetRuntimeId = lambda: [9, 9] + return original(owner) + + reader.read = replacing + elif fault == "scope_changed": + bindings = iter(["first", None]) + kwargs["identity"] = lambda: next(bindings, None) + elif fault == "deadline": + times = iter([0.0, 6.0]) + kwargs["clock"] = lambda: next(times, 6.0) + elif fault == "bad_copy": + reader.read = lambda owner: NativeRead(owner, 5, 4, "exact") + elif fault == "owner_changed": + original = reader.read + + def replace_owner(owner): + reader.owner_value = replace(OWNER, thread=999) + return original(owner) + + reader.read = replace_owner + result = observe_complete_value( + target, + native_reader=reader, + identity=kwargs.pop("identity", lambda: "bound"), + **kwargs, + ) + assert not result.complete and result.value is None and result.proof is None + assert result.reason + if fault.startswith("password"): + assert reader.reads == 0 + + +def test_readonly_is_allowed_for_approval_observation_but_not_edit_baseline(): + target, pattern = control("") + pattern.IsReadOnly = True + assert observe(target, Reader()).complete + result = observe(target, Reader(), require_editable=True) + assert not result.complete and result.value is None + + +@pytest.mark.parametrize( + "key,value", + [ + ("native_reads", True), + ("uia_reads", 1), + ("utf16_units", True), + ("sha256_utf16le", "0" * 64), + ("hwnd", 0), + ("method", "uia-only"), + ("schema", "legacy"), + ("extra", "x"), + ], +) +def test_client_proof_rejects_missing_fake_or_legacy_completeness(key, value): + target, _ = control("é𝄞 ") + result = observe(target, Reader("é𝄞 ")) + proof = result.proof.payload() + proof[key] = value + assert not valid_value_proof("é𝄞 ", proof) + + +class User32: + def __init__(self, value): + self.raw = utf16_bytes(value) + self.calls = [] + self.pid = OWNER.pid + self.timeout = False + self.unicode = True + self.extent_delta = 0 + self.copy_delta = 0 + self.replace_after_extent = False + + def IsWindow(self, hwnd): + return hwnd == OWNER.hwnd + + def IsWindowUnicode(self, hwnd): + return self.unicode + + def GetWindowThreadProcessId(self, hwnd, pointer): + from ctypes import wintypes + + ctypes.cast(pointer, ctypes.POINTER(wintypes.DWORD))[0] = self.pid + return OWNER.thread + + def SendMessageTimeoutW( + self, hwnd, message, count, pointer, flags, timeout, result + ): + self.calls.append((message, count, flags, timeout)) + assert hwnd == OWNER.hwnd and flags == 0x23 and timeout == 1000 + if self.timeout: + return 0 + if message == 0xE: + assert count == pointer == 0 + returned = len(self.raw) // 2 + self.extent_delta + if self.replace_after_extent: + self.pid += 1 + elif message == 0xD: + assert count == len(self.raw) // 2 + self.extent_delta + 1 + ctypes.memmove(pointer, self.raw + b"\0\0", len(self.raw) + 2) + returned = len(self.raw) // 2 + self.copy_delta + else: + raise AssertionError("unexpected native message") + ctypes.cast(result, ctypes.POINTER(ctypes.c_size_t))[0] = returned + return 1 + + +def protocol_reader(value): + reader = Win32TextReader.__new__(Win32TextReader) + user = User32(value) + reader._user = user + return reader, user + + +@pytest.mark.parametrize("value", ["", "é𝄞 \n", "x" * 8192 + "-END"]) +def test_actual_native_message_protocol_uses_exact_utf16_buffer_and_counts(value): + reader, user = protocol_reader(value) + result = reader.read(OWNER) + assert result.value == value and result.extent == len(utf16_bytes(value)) // 2 + assert [entry[0] for entry in user.calls] == [0xE, 0xD] + + +@pytest.mark.parametrize( + "fault,reason", + [ + ("timeout", "native_text_timeout_or_failure"), + ("extent", "native_extent_or_copy_incomplete"), + ("copied", "native_extent_or_copy_incomplete"), + ("oversize", "value_exceeds_limit"), + ("replace", "native_owner_changed"), + ("ansi", "native_window_unavailable_or_not_unicode"), + ("null", "native_extent_or_copy_incomplete"), + ], +) +def test_native_protocol_never_promotes_timeout_owner_change_or_incomplete_copy( + fault, reason +): + reader, user = protocol_reader("a\x00b" if fault == "null" else "exact") + if fault == "timeout": + user.timeout = True + elif fault == "extent": + user.extent_delta = 1 + elif fault == "copied": + user.copy_delta = -1 + elif fault == "oversize": + user.extent_delta = 65537 + elif fault == "replace": + user.replace_after_extent = True + elif fault == "ansi": + user.unicode = False + with pytest.raises(ValueUnavailable, match=reason): + reader.read(OWNER) + if fault in {"timeout", "oversize", "replace", "ansi"}: + assert 0xD not in [entry[0] for entry in user.calls] + + +def test_uia_only_without_native_api_never_claims_complete(monkeypatch): + monkeypatch.delattr(ctypes, "WinDLL", raising=False) + target, _ = control("a complete-looking provider value") + result = observe_complete_value(target, identity=lambda: "bound") + assert not result.complete and result.value is None and result.proof is None + assert result.reason == "native_api_unavailable" + + +def test_provider_without_a_native_extent_or_with_a_mutable_scope_is_incomplete(): + target, _ = control("exact") + for scope in (None, {}, [], ""): + result = observe_complete_value( + target, identity=lambda: scope, native_reader=Reader("exact") + ) + assert not result.complete and result.value is None + assert not valid_value_proof("exact", None) + result = observe(target, Reader("exact")) + proof = result.proof.payload() + del proof["native_reads"] + assert not valid_value_proof("exact", proof) From 8bd2e9d8aabe5e0b2aae5dbe5407718f6fbbeeda Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 23:33:22 -0500 Subject: [PATCH 10/34] Refuse incomplete native values at approval boundaries --- .../approval_mode/form_state.py | 46 ++- .../approval_mode/window_fields.py | 55 +++ .../openadapt_flow/backends/parallels_vm.py | 6 + .../backends/win_agent/server.py | 214 ++++++++--- .../backends/windows_backend.py | 30 +- .../openadapt_flow/rl_env/windows_guest.py | 7 +- packages/flow/scripts/desktop/winrm_lab.py | 7 +- .../flow/tests/test_approval_form_fields.py | 177 +++++++-- .../tests/test_approval_value_completeness.py | 336 ++++++++++++++++++ .../tests/test_native_value_deployment.py | 150 ++++++++ packages/flow/tests/test_parallels_vm.py | 1 + 11 files changed, 911 insertions(+), 118 deletions(-) create mode 100644 packages/flow/openadapt_flow/approval_mode/window_fields.py create mode 100644 packages/flow/tests/test_approval_value_completeness.py create mode 100644 packages/flow/tests/test_native_value_deployment.py diff --git a/packages/flow/openadapt_flow/approval_mode/form_state.py b/packages/flow/openadapt_flow/approval_mode/form_state.py index 7c51a138b8..d512b63d0e 100644 --- a/packages/flow/openadapt_flow/approval_mode/form_state.py +++ b/packages/flow/openadapt_flow/approval_mode/form_state.py @@ -37,6 +37,8 @@ import re from typing import Any, Optional, Sequence +from openadapt_flow.approval_mode.window_fields import valid_form_field + #: (kind, "sha256:") FormState = tuple[str, str] #: x, y, width, height in frame pixels. @@ -199,14 +201,20 @@ def window_fields_state( draw = ImageDraw.Draw(crop) rows: list[Any] = [] for field in fields: - kind, text = str(field["kind"]), str(field["text"]) - fx, fy, fw, fh = (int(v) for v in field["rect"]) - state = field.get("state") - rows.append([kind, [fx, fy, fw, fh], text, state]) - # A ``state`` entry (a selected grid row) carries no text: its - # pixels stay in the OCR read. + if not valid_form_field(field): + return None + kind, text = field["kind"], field["text"] + fx, fy, fw, fh = field["rect"] + state, proof = field["state"], field["value_proof"] + 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. inside = ( - None if kind == "state" else _clamp((fx - x0, fy - y0, fw, fh), w, h) + None + if kind in {"state", "value"} or not text + else _clamp((fx - x0, fy - y0, fw, fh), w, h) ) if inside is not None: ix, iy, iw, ih = inside @@ -307,11 +315,11 @@ def approval_window_fields( backend: Any, save_step: Optional[str], results: Sequence[Any] = () ) -> Optional[dict[str, Any]]: """The backend's ``approval_form_fields`` answer for the approval's - window, or ``None`` (and the caller reads the window by OCR alone). + window, or ``None`` (the approval refuses when this channel is required). The same window :func:`approval_window_regions` names; the save step is left out and the earlier steps' points name the window on a resumed run. - Never raises. + An unreadable native value never falls back to OCR. Never raises. """ fields_of = getattr(backend, "approval_form_fields", None) @@ -340,16 +348,22 @@ def approval_form_state( ) -> Optional[FormState]: """The approval's form state for ``save_step``, or ``None``. - The app window's fields by value where the backend can read them, - otherwise the window (or the whole screen) by OCR. A request and its - recheck that read through different channels get different kinds, so - the save halts. + A backend offering native field reads must return complete evidence; + unavailable values refuse without an OCR downgrade. Backends without + that channel retain their existing DOM or screen read. Different read + channels have different kinds, so a changed channel halts the save. """ - if frame_png is not None: + if callable(getattr(backend, "approval_form_fields", None)): + # Once a native field channel is required, no answer (including a + # legacy/malformed response or a missing complete value) is a refusal. + # OCR cannot establish equality of a hidden or omitted suffix. + if frame_png is None: + return None fields = approval_window_fields(backend, save_step, results) - if fields is not None: - return capture_form_state(backend, vision, frame_png, window_fields=fields) + if fields is None: + return None + return window_fields_state(vision, frame_png, fields) regions = approval_window_regions(backend, frame_png, save_step, results) return capture_form_state(backend, vision, frame_png, regions) diff --git a/packages/flow/openadapt_flow/approval_mode/window_fields.py b/packages/flow/openadapt_flow/approval_mode/window_fields.py new file mode 100644 index 0000000000..895a05ec97 --- /dev/null +++ b/packages/flow/openadapt_flow/approval_mode/window_fields.py @@ -0,0 +1,55 @@ +"""Closed native form-field wire contract shared by client and approval gate.""" + +from __future__ import annotations + +import re +from typing import Any + +from openadapt_flow.backends.win_agent.native_value import valid_value_proof + +FIELD_KEYS = frozenset( + {"kind", "rect", "text", "state", "value_proof", "value_identity"} +) +FIELD_KINDS = frozenset({"title_bar", "edit", "value", "text", "state"}) +FIELD_STATES = frozenset({None, "on", "off", "indeterminate", "selected", "unselected"}) + + +def valid_form_field(field: Any, *, pid: int | None = None) -> bool: + """No incomplete native value may authorize either a digest or a mask. + + ``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, + not a signature or caller-provided authorization. + """ + try: + if not isinstance(field, dict) or set(field) != FIELD_KEYS: + return False + kind, rect, text, state, proof = ( + field[key] for key in ("kind", "rect", "text", "state", "value_proof") + ) + if ( + kind not in FIELD_KINDS + or state not in FIELD_STATES + or not isinstance(text, str) + or not isinstance(rect, (tuple, list)) + or len(rect) != 4 + or any(type(value) is not int for value in rect) + 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 == "state" and (text != "" or state is None)) + ): + return False + identity = field["value_identity"] + if proof is None: + return identity is None + return ( + isinstance(identity, str) + and re.fullmatch(r"[0-9a-f]{64}", identity) is not None + and valid_value_proof(text, proof) + and (pid is None or proof["pid"] == pid) + ) + except (KeyError, TypeError, ValueError): + return False diff --git a/packages/flow/openadapt_flow/backends/parallels_vm.py b/packages/flow/openadapt_flow/backends/parallels_vm.py index b338313f64..b5ecb1599b 100644 --- a/packages/flow/openadapt_flow/backends/parallels_vm.py +++ b/packages/flow/openadapt_flow/backends/parallels_vm.py @@ -736,9 +736,15 @@ def launch_agent( host_ip = host_ip or self.host_ip() guest_ip = self.guest_ip() server = self._agent_server_path() + native_value = os.path.join(os.path.dirname(server), "native_value.py") + if not os.path.isfile(native_value): + raise FileNotFoundError("agent native-value helper is missing") launcher = os.path.abspath(os.path.join(_SCRIPT_DIR, "session1_launch.py")) self.exec_cmd(f"if not exist {GUEST_DIR} mkdir {GUEST_DIR}") self.push_file(server, f"{GUEST_DIR}/win_agent_server.py", host_ip=host_ip) + self.push_file( + native_value, f"{GUEST_DIR}/win_agent_native_value.py", host_ip=host_ip + ) self.push_file(launcher, f"{GUEST_DIR}/session1_launch.py", host_ip=host_ip) self.exec( [ diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index af8969409e..538eb387ce 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -2260,21 +2260,90 @@ def _window_operation( _TOGGLE_STATES = {0: "off", 1: "on", 2: "indeterminate"} -def _form_field_value(control: object) -> tuple[bool, Optional[str]]: - """``(readable, value)`` of a control through its Value pattern.""" +def _form_exposes_value(control: object) -> bool: + """A visible label may also expose a value; never downgrade that value.""" method = _control_value(control, "GetValuePattern", None) if not callable(method): - return False, None + return False try: - pattern = method() - value = getattr(pattern, "Value", None) if pattern is not None else None - except Exception: # noqa: BLE001 - pattern not supported - return False, None - if not isinstance(value, str): - return False, None - # This is approval evidence, not a display preview: truncating a value - # before its rectangle is hidden would lose edits beyond the prefix. - return True, value + return isinstance(getattr(method(), "Value", None), str) + except Exception: # noqa: BLE001 - the visible-label channel has no Value pattern + return False + + +def _form_field_value(control: object, identity: Callable[[], Optional[str]]) -> Any: + """A complete identity-bound value; partial/unsupported sources refuse.""" + if __package__: + from openadapt_flow.backends.win_agent.native_value import ( + observe_complete_value, + ) + else: # standalone deployment must use its exact sibling, not an installed copy + from win_agent_native_value import observe_complete_value # type: ignore[import-not-found,no-redef] + + return observe_complete_value(control, identity=identity) + + +def _form_value_identity( + control: object, window: object, hwnd: int, scope: Callable[[], bool], auto: Any +) -> Optional[str]: + """Fresh immutable field/window scope, including ancestry and geometry.""" + try: + if not scope() or _control_value(window, "NativeWindowHandle", None) != hwnd: + 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) + ): + return None + if _control_value(control, "ProcessId", None) != pid: + return None + live_window = auto.ControlFromHandle(hwnd) + live_control = auto.ControlFromHandle( + _control_value(control, "NativeWindowHandle", 0) + ) + if ( + live_window is None + or live_control is None + or _runtime_id(live_window) != root_id + or _runtime_id(live_control) != field_id + or _bounds(live_control) != _bounds(control) + or _control_value(live_control, "ControlTypeName", None) + != _control_value(control, "ControlTypeName", None) + ): + return None + chain = [] + node = live_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( + [ + 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 def _form_field_state(control: object, control_type: str) -> Optional[str]: @@ -2304,7 +2373,7 @@ def _rect(bounds: list[int]) -> list[int]: def _window_form_fields( - auto: Any, hwnd: int + auto: Any, hwnd: int, scope: Callable[[], bool] ) -> tuple[Optional[list[dict[str, Any]]], bool]: """The window's controls whose text UIA reads, in tree order. @@ -2315,12 +2384,15 @@ def _window_form_fields( - ``text``, a leaf label or button with its value or name, or a leaf list or grid cell with its value, and ``state`` its toggle or selection state; + - ``value``, a complete container value whose pixels stay visible; - ``state``, a container (a grid row) whose selection state UIA reads: it carries no text and its pixels stay in the caller's OCR read. - A control that is off screen, or whose text cannot be read or is empty, - is left out, so its pixels stay in the OCR read. ``(None, False)`` when - UIA cannot open the window; ``truncated`` when the walk hit its bounds. + Value-backed entries include independent complete-value proof, including + empty values. Missing proof refuses the entire projection; OCR is not an + alternative for a hidden suffix. Off-screen controls are left out. + ``(None, False)`` when any required observation is unavailable; + ``truncated`` when the walk hit its bounds. """ from_handle = getattr(auto, "ControlFromHandle", None) if not callable(from_handle): @@ -2365,31 +2437,40 @@ def children_of(control: Any) -> list[Any]: "rect": _rect(bounds), "text": title, "state": None, + "value_proof": None, + "value_identity": None, } ) continue - if control_type in _FORM_VALUE_TYPES and not children: - # A password provider may return an empty or redacted Value. - # Empty values and unknown password status also account for no - # visible text, so all of those pixels must stay in the OCR. - password = _control_value(control, "IsPassword", None) - readable, value = _form_field_value(control) - if ( - bounds is not None - and on_screen - and password is False - and readable - and value - ): + + def identity(c: object = control) -> Optional[str]: + return _form_value_identity(c, window, hwnd, scope, auto) + + if control_type in _FORM_VALUE_TYPES: + if bounds is not None and on_screen: + value_identity = identity() + observed = _form_field_value(control, identity) + if ( + not observed.complete + or observed.proof is None + or value_identity is None + or identity() != value_identity + ): + return None, False fields.append( { - "kind": "edit", + # Container values are evidence too, but must never + # hide descendants that have their own obligations. + "kind": "value" if children else "edit", "rect": _rect(bounds), - "text": value, + "text": observed.value, "state": None, + "value_proof": observed.proof.payload(), + "value_identity": value_identity, } ) - continue + if not children: + continue state = _form_field_state(control, control_type) if control_type in {"CheckBoxControl", "RadioButtonControl", "TabItemControl"}: if state is None: @@ -2397,24 +2478,46 @@ def children_of(control: Any) -> list[Any]: # Keep these pixels in the OCR read when UIA cannot name it. continue if not children and control_type in _FORM_NAMED_TYPES | _FORM_ITEM_TYPES: - readable, value = _form_field_value(control) - text = value if readable and value else None - if text is None and control_type in _FORM_NAMED_TYPES: - name = " ".join(str(_control_value(control, "Name", "") or "").split()) - text = name or None - if bounds is not None and on_screen and text: - fields.append( - { - "kind": "text", - "rect": _rect(bounds), - "text": text, - "state": state, - } - ) + text, proof, value_identity = None, None, None + if bounds is not None and on_screen: + if control_type in _FORM_ITEM_TYPES or _form_exposes_value(control): + value_identity = identity() + observed = _form_field_value(control, identity) + if ( + not observed.complete + or observed.proof is None + or value_identity is None + or identity() != value_identity + ): + return None, False + text, proof = observed.value, observed.proof.payload() + else: + name = " ".join( + str(_control_value(control, "Name", "") or "").split() + ) + text = name or None + if text is not None: + fields.append( + { + "kind": "text", + "rect": _rect(bounds), + "text": text, + "state": state, + "value_proof": proof, + "value_identity": value_identity, + } + ) continue if state is not None and bounds is not None and on_screen: fields.append( - {"kind": "state", "rect": _rect(bounds), "text": "", "state": state} + { + "kind": "state", + "rect": _rect(bounds), + "text": "", + "state": state, + "value_proof": None, + "value_identity": None, + } ) if children: if depth >= _MAX_UIA_DEPTH: @@ -2447,10 +2550,23 @@ def _window_form_fields_operation( cloaked = user32.is_cloaked(candidate) if cloaked is None or not cloaked: return {"status": "ok", "window": None, "fields": []} + + def unchanged() -> bool: + fresh = _window_operation("window-bounds", payload, user32).get("window") + if fresh != window: + return False + return all( + candidate == hwnd + or user32.pid_of(candidate) != pid + or not user32.is_visible(candidate) + or user32.is_cloaked(candidate) is True + for candidate in user32.top_level_windows() + ) + auto = auto_loader() with auto.UIAutomationInitializerInThread(): - fields, truncated = _window_form_fields(auto, hwnd) - if fields is None or truncated: + fields, truncated = _window_form_fields(auto, hwnd, unchanged) + if fields is None or truncated or not unchanged(): return {"status": "ok", "window": None, "fields": []} return {"status": "ok", "window": window, "fields": fields} diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index a09bbc3629..13ea085ac6 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -45,6 +45,7 @@ import requests +from openadapt_flow.approval_mode.window_fields import valid_form_field from openadapt_flow.backend import ActionDeliveryUncertain, StructuralResolutionRefused from openadapt_flow.ir import ( ActionDeliveryReceipt, @@ -232,14 +233,6 @@ def _pixel_box(value: object) -> Optional[dict[str, int]]: return {k: int(value[k]) for k in ("x", "y", "w", "h")} -#: The approval form-field read's contract (win_agent ``window-form-fields``). -_FIELD_KEYS = frozenset({"kind", "rect", "text", "state"}) -_FIELD_KINDS = frozenset({"title_bar", "edit", "text", "state"}) -_FIELD_STATES = frozenset( - {None, "on", "off", "indeterminate", "selected", "unselected"} -) - - def _window_frame( window: Any, hwnd: int, pid: int ) -> Optional[tuple[int, int, int, int]]: @@ -1080,8 +1073,9 @@ def approval_form_fields( labels, buttons and cells whose text UIA reads (with toggle and selection state), in tree order. The caller reads those fields by value and the rest of the window by OCR, so a blinking caret or a hovered title-bar button - no longer changes the digest. None when the agent cannot say, when - the app shows another window, or on any doubt. Never raises. + no longer changes the digest. Value-backed entries require independent + complete-value proof. None on any doubt; approval must then refuse, + including when an older agent does not provide the proof. Never raises. """ try: found = self._approval_window(exclude_step, points) @@ -1100,26 +1094,18 @@ def approval_form_fields( return None checked: list[dict[str, Any]] = [] for field in fields: - if not isinstance(field, dict) or set(field) != _FIELD_KEYS: + if not valid_form_field(field, pid=pid): return None rect, text = field["rect"], field["text"] - if ( - field["kind"] not in _FIELD_KINDS - or field["state"] not in _FIELD_STATES - or not isinstance(text, str) - or not isinstance(rect, list) - or len(rect) != 4 - or any(isinstance(v, bool) or not isinstance(v, int) for v in rect) - or rect[2] <= 0 - or rect[3] <= 0 - ): - return None + proof = field["value_proof"] checked.append( { "kind": field["kind"], "rect": tuple(rect), "text": text, "state": field["state"], + "value_proof": proof, + "value_identity": field["value_identity"], } ) return {"bounds": bounds, "fields": checked} diff --git a/packages/flow/openadapt_flow/rl_env/windows_guest.py b/packages/flow/openadapt_flow/rl_env/windows_guest.py index 033862e1b5..5f7d2b2f9d 100644 --- a/packages/flow/openadapt_flow/rl_env/windows_guest.py +++ b/packages/flow/openadapt_flow/rl_env/windows_guest.py @@ -673,6 +673,10 @@ def launch_agent( generate_self_signed_cert, ) + source = Path(agent_server.__file__) + native_value = source.with_name("native_value.py") + if not native_value.is_file(): + raise FileNotFoundError("agent native-value helper is missing") self.attach_console() self.run_ps( f"Stop-ScheduledTask -TaskName '{AGENT_TASK}' -ErrorAction SilentlyContinue; " @@ -681,7 +685,8 @@ def launch_agent( "$_.ProcessId -Force }", check=False, ) - self.push_file(Path(agent_server.__file__), rf"{GUEST_DIR}\win_agent_server.py") + self.push_file(source, rf"{GUEST_DIR}\win_agent_server.py") + self.push_file(native_value, rf"{GUEST_DIR}\win_agent_native_value.py") bundle = generate_self_signed_cert([self.host]) try: self.push_file(Path(bundle.certfile), rf"{GUEST_DIR}\agent-cert.pem") diff --git a/packages/flow/scripts/desktop/winrm_lab.py b/packages/flow/scripts/desktop/winrm_lab.py index 0e337c874e..46235395a3 100644 --- a/packages/flow/scripts/desktop/winrm_lab.py +++ b/packages/flow/scripts/desktop/winrm_lab.py @@ -536,6 +536,10 @@ def launch_agent( python = python or self.resolve_python() guest_dir = guest_dir or self.profile.guest_dir + source = Path(server_path or agent_server.__file__) + native_value = source.with_name("native_value.py") + if not native_value.is_file(): + raise FileNotFoundError("agent native-value helper is missing") self.attach_console() self.stop_interactive("OAFlowAgent") # A previous agent stuck inside a UI Automation call keeps its port. @@ -546,9 +550,10 @@ def launch_agent( check=False, ) self.push_file( - Path(server_path or agent_server.__file__), + source, rf"{guest_dir}\win_agent_server.py", ) + self.push_file(native_value, rf"{guest_dir}\win_agent_native_value.py") bundle = generate_self_signed_cert([self.host]) try: self.push_file(Path(bundle.certfile), rf"{guest_dir}\agent-cert.pem") diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index ea3a284ca9..f17a8b3578 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -12,6 +12,7 @@ from __future__ import annotations +import hashlib import io import sys import types @@ -27,8 +28,51 @@ screen_text_state, window_fields_state, ) +from openadapt_flow.backends.win_agent.native_value import ( + NativeOwner, + NativeRead, + valid_value_proof, +) from openadapt_flow.backends.windows_backend import WindowsBackend + +def _proof(text, hwnd=100, pid=10): + raw = text.encode("utf-16-le", errors="surrogatepass") + return { + "schema": "openadapt.native-value-completeness/v1", + "method": "uia-value+wm-gettext", + "hwnd": hwnd, + "pid": pid, + "thread": 5, + "utf16_units": len(raw) // 2, + "sha256_utf16le": hashlib.sha256(raw).hexdigest(), + "native_reads": 2, + "uia_reads": 2, + } + + +def _proved_fields(answer): + for field in answer["fields"]: + field["value_identity"] = ( + "a" * 64 if field["kind"] in {"edit", "value"} else None + ) + field["value_proof"] = ( + _proof(field["text"]) if field["kind"] in {"edit", "value"} else None + ) + return answer + + +def _without_proofs(fields): + return [ + { + key: value + for key, value in field.items() + if key not in {"value_proof", "value_identity"} + } + for field in fields + ] + + SIZE = (1024, 768) WINDOW = (0, 0, 1024, 720) TITLE_BAR = (0, 0, 1024, 30) @@ -106,21 +150,23 @@ def _fields( {"kind": "text", "rect": rect, "text": text, "state": None} for rect, text in zip(CELLS, ("Neil", "Sorenson", "1984-03-12")) ] - return { - "bounds": WINDOW, - "fields": [ - { - "kind": "title_bar", - "rect": TITLE_BAR, - "text": "Patient Notes - Benchmark Harness", - "state": None, - }, - {"kind": "edit", "rect": SEARCH, "text": search, "state": None}, - {"kind": "state", "rect": ROW, "text": "", "state": selected}, - *cells, - {"kind": "edit", "rect": NOTE, "text": note, "state": None}, - ], - } + return _proved_fields( + { + "bounds": WINDOW, + "fields": [ + { + "kind": "title_bar", + "rect": TITLE_BAR, + "text": "Patient Notes - Benchmark Harness", + "state": None, + }, + {"kind": "edit", "rect": SEARCH, "text": search, "state": None}, + {"kind": "state", "rect": ROW, "text": "", "state": selected}, + *cells, + {"kind": "edit", "rect": NOTE, "text": note, "state": None}, + ], + } + ) def _state(fields=None, **frame): @@ -186,7 +232,14 @@ def test_a_field_covers_only_its_own_pixels(): # other channel: a different field set is a different digest. covering = _fields() covering["fields"].append( - {"kind": "edit", "rect": (20, 296, 500, 30), "text": "", "state": None} + { + "kind": "edit", + "rect": (20, 296, 500, 30), + "text": "", + "state": None, + "value_proof": _proof(""), + "value_identity": "a" * 64, + } ) assert _state(covering) != _state() @@ -228,16 +281,15 @@ def fields(exclude_step, points): [None, "fields", {"bounds": WINDOW}, {"bounds": WINDOW, "fields": [], "x": 1}], ids=["none", "not-a-dict", "missing", "extra"], ) -def test_without_fields_the_window_is_read_by_ocr(answer): +def test_an_advertised_but_unavailable_field_channel_never_downgrades_to_ocr(answer): backend = SimpleNamespace( approval_form_fields=lambda *_a: answer, approval_form_region=lambda *_a: WINDOW, ) frame = _frame() assert approval_window_fields(backend, "save", _RESULTS) is None - assert approval_form_state(backend, vision, frame, "save", _RESULTS) == ( - screen_text_state(vision, frame, [WINDOW]) - ) + assert screen_text_state(vision, frame, [WINDOW]) is not None + assert approval_form_state(backend, vision, frame, "save", _RESULTS) is None def test_a_request_and_recheck_through_different_channels_never_match(): @@ -289,13 +341,19 @@ def post(path, payload): {"kind": "state", "rect": [20, 100, 600, 40], "text": "", "state": "selected"}, ], } +_proved_fields(_GOOD) def test_the_windows_backend_reads_the_fields_of_its_one_window(): backend, sent = _windows_backend({"s1": (7, 10), "save": (99, 10)}, _GOOD) answer = backend.approval_form_fields("save") assert sent == [("/window/form-fields", {"hwnd": 7, "pid": 10})] - assert answer == { + assert answer is not None + assert answer["bounds"] == (0, 0, 1024, 720) + assert valid_value_proof( + answer["fields"][1]["text"], answer["fields"][1]["value_proof"] + ) + assert {**answer, "fields": _without_proofs(answer["fields"])} == { "bounds": (0, 0, 1024, 720), "fields": [ { @@ -375,6 +433,8 @@ def __init__(self, left, top, right, bottom): class _Control: + next_hwnd = 100 + def __init__( self, control_type, @@ -388,6 +448,11 @@ def __init__( toggle=None, password=False, ): + self.NativeWindowHandle = _Control.next_hwnd + _Control.next_hwnd += 1 + self.ProcessId = 10 + self.parent = None + self.native_override = None self.IsPassword = password self._selected = selected self._toggle = toggle @@ -398,13 +463,19 @@ def __init__( self._value = value self._children = list(children) + def GetRuntimeId(self): + return [42, self.NativeWindowHandle] + + def GetParentControl(self): + return self.parent + def GetChildren(self): return self._children def GetValuePattern(self): if self._value is None: raise RuntimeError("no value pattern") - return SimpleNamespace(Value=self._value) + return SimpleNamespace(Value=self._value, IsReadOnly=False) def GetSelectionItemPattern(self): if self._selected is None: @@ -475,8 +546,37 @@ def _agent(monkeypatch, window, desktop=None): agent_server, "os", types.SimpleNamespace(**{**vars(os), "name": "nt"}) ) monkeypatch.setattr(agent_server, "_user32_factory", lambda: desktop or _Desktop()) + import openadapt_flow.backends.win_agent.native_value as native + + controls = {} + + def attach(control, parent=None): + control.parent = parent + controls[control.NativeWindowHandle] = control + for child in control._children: + attach(child, control) + + if window is not None: + window.NativeWindowHandle = 7 + attach(window) + + class Reader: + def owner(self, hwnd): + return NativeOwner(hwnd, controls[hwnd].ProcessId, 5) + + def read(self, owner): + control = controls[owner.hwnd] + value = ( + control._value + if control.native_override is None + else control.native_override + ) + units = len(value.encode("utf-16-le", errors="surrogatepass")) // 2 + return NativeRead(owner, units, units, value) + + monkeypatch.setattr(native, "Win32TextReader", Reader) auto = types.SimpleNamespace( - ControlFromHandle=lambda hwnd: window if hwnd == 7 else None, + ControlFromHandle=lambda hwnd: controls.get(hwnd), UIAutomationInitializerInThread=_Init, ) monkeypatch.setitem(sys.modules, "uiautomation", auto) @@ -496,7 +596,12 @@ def test_the_agent_reads_the_title_bar_and_every_readable_text_field(monkeypatch _Control("DataItemControl", bounds=(220, 140, 420, 180), value=""), # A cell whose only text is its position name: not read, so its # pixels stay in the OCR. - _Control("DataItemControl", bounds=(420, 140, 620, 180), name="dob Row 0"), + _Control( + "DataItemControl", + bounds=(420, 140, 620, 180), + value="", + name="dob Row 0", + ), ], ) window = _window( @@ -517,7 +622,7 @@ def test_the_agent_reads_the_title_bar_and_every_readable_text_field(monkeypatch offscreen=True, ), # A password box: no value, so its pixels stay in the OCR. - _Control("EditControl", bounds=(20, 110, 500, 130)), + _Control("EditControl", bounds=(20, 110, 500, 130), value=""), row, _Control( "DocumentControl", bounds=(20, 340, 620, 460), value="BP 128/82" @@ -539,7 +644,12 @@ def test_the_agent_reads_the_title_bar_and_every_readable_text_field(monkeypatch perform = _agent(monkeypatch, window) answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) assert answer["window"] == {"hwnd": 7, "pid": 10, "bounds": [0, 0, 1024, 720]} - assert answer["fields"] == [ + assert all( + valid_value_proof(f["text"], f["value_proof"]) + for f in answer["fields"] + if f["value_proof"] is not None + ) + assert _without_proofs(answer["fields"]) == [ { "kind": "title_bar", "rect": [0, 0, 1024, 30], @@ -547,8 +657,11 @@ def test_the_agent_reads_the_title_bar_and_every_readable_text_field(monkeypatch "state": None, }, {"kind": "edit", "rect": [20, 44, 480, 26], "text": "Neil", "state": None}, + {"kind": "edit", "rect": [20, 110, 480, 20], "text": "", "state": None}, {"kind": "state", "rect": [20, 140, 600, 40], "text": "", "state": "selected"}, {"kind": "text", "rect": [20, 140, 200, 40], "text": "Neil", "state": None}, + {"kind": "text", "rect": [220, 140, 200, 40], "text": "", "state": None}, + {"kind": "text", "rect": [420, 140, 200, 40], "text": "", "state": None}, { "kind": "edit", "rect": [20, 340, 600, 120], @@ -688,7 +801,8 @@ def test_a_value_container_does_not_hide_its_descendant_fields(monkeypatch): ) perform = _agent(monkeypatch, _window(document)) answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) - assert [field["text"] for field in answer["fields"]] == ["actual field"] + assert [field["text"] for field in answer["fields"]] == ["summary", "actual field"] + assert [field["kind"] for field in answer["fields"]] == ["value", "edit"] def test_a_depth_limited_form_walk_is_incomplete(monkeypatch): @@ -715,8 +829,13 @@ def test_an_empty_or_redacted_value_never_hides_the_visible_field( ) perform = _agent(monkeypatch, _window(control)) answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) - assert answer["window"] is not None - assert answer["fields"] == [] + if password is False: + assert answer["window"] is not None + assert answer["fields"][0]["text"] == "" + assert valid_value_proof("", answer["fields"][0]["value_proof"]) + else: + assert answer["window"] is None + assert answer["fields"] == [] def test_an_unreadable_title_never_hides_the_title_bar(monkeypatch): diff --git a/packages/flow/tests/test_approval_value_completeness.py b/packages/flow/tests/test_approval_value_completeness.py new file mode 100644 index 0000000000..cb1d1f16f3 --- /dev/null +++ b/packages/flow/tests/test_approval_value_completeness.py @@ -0,0 +1,336 @@ +"""Incomplete native sources cannot authorize an approval through any entry.""" + +from __future__ import annotations + +from copy import deepcopy +from types import SimpleNamespace + +import pytest +from hypothesis import given +from hypothesis import strategies as st + +from openadapt_flow.approval_mode.form_state import ( + approval_form_state, + window_fields_state, +) +from openadapt_flow.approval_mode.window_fields import valid_form_field +from tests.test_approval_form_fields import ( + _agent, + _Control, + _fields, + _frame, + _proof, + _window, + _windows_backend, +) + +NO_OCR = SimpleNamespace(ocr=lambda _: []) +SAME_VISIBLE_OCR = SimpleNamespace(ocr=lambda _: [{"text": "same visible prefix"}]) + + +def _through_wire(answer): + return _windows_backend({"type": (7, 10)}, answer)[0] + + +@pytest.mark.parametrize( + "kind,stored,provider", + [ + (kind, stored, provider) + for kind in ( + "EditControl", + "DocumentControl", + "DataItemControl", + "TextControl", + "ButtonControl", + ) + for stored, provider in ( + ("x" * 4096 + "-different suffix", "x" * 4096), + ("hidden stored text", ""), + ("stored", None), + ) + if provider is not None + or kind in {"EditControl", "DocumentControl", "DataItemControl"} + ], +) +def test_omitted_storage_refuses_the_actual_server_client_and_approval_path( + monkeypatch, + kind, + stored, + provider, +): + control = _Control(kind, value=provider) + control.native_override = stored + perform = _agent(monkeypatch, _window(control)) + wire = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert wire["window"] is None and wire["fields"] == [] + backend = _through_wire(wire) + assert backend.approval_form_fields("save") is None + assert approval_form_state(backend, SAME_VISIBLE_OCR, _frame(), "save") is None + + +@pytest.mark.parametrize( + "fault", + [ + "missing_hwnd", + "missing_runtime", + "foreign_pid", + "password", + "password_unknown", + "no_ancestry", + ], +) +def test_unsupported_or_unbound_full_value_source_cannot_downgrade(monkeypatch, fault): + control = _Control("EditControl", value="same visible prefix") + perform = _agent(monkeypatch, _window(control)) + if fault == "missing_hwnd": + control.NativeWindowHandle = 0 + elif fault == "missing_runtime": + control.GetRuntimeId = lambda: [] + elif fault == "foreign_pid": + control.ProcessId = 99 + elif fault == "password": + control.IsPassword = True + elif fault == "password_unknown": + control.IsPassword = None + else: + control.parent = None + wire = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert wire["window"] is None + assert ( + approval_form_state(_through_wire(wire), SAME_VISIBLE_OCR, _frame(), "save") + is None + ) + + +@pytest.mark.parametrize("kind", ["edit", "value", "text"]) +@pytest.mark.parametrize( + "fault", + [ + "absent", + "null", + "legacy_flag", + "wrong_hash", + "wrong_extent", + "wrong_pid", + "missing_read", + "bool_count", + "extra", + ], +) +def test_bad_value_proof_refuses_before_digest_or_mask_at_both_consumers(kind, fault): + fields = _fields() + field = fields["fields"][1] + field["kind"] = kind + proof = field["value_proof"] + if fault == "absent": + del field["value_proof"] + elif fault == "null": + field["value_proof"] = None + field["value_identity"] = None + elif fault == "legacy_flag": + field["value_proof"] = {"complete": True} + elif fault == "wrong_hash": + proof["sha256_utf16le"] = "0" * 64 + elif fault == "wrong_extent": + proof["utf16_units"] += 1 + elif fault == "wrong_pid": + proof["pid"] = 99 + elif fault == "missing_read": + proof["native_reads"] = 1 + elif fault == "bool_count": + proof["uia_reads"] = True + else: + proof["extra"] = True + # Unproved visible labels have a separate existing convention. They are + # not value-backed claims; a null proof is allowed only for that channel. + if kind == "text" and fault == "null": + assert valid_form_field(field) + return + wire = { + "status": "ok", + "window": {"hwnd": 7, "pid": 10, "bounds": list(fields["bounds"])}, + "fields": fields["fields"], + } + backend = _through_wire(wire) + assert backend.approval_form_fields("save") is None + assert approval_form_state(backend, SAME_VISIBLE_OCR, _frame(), "save") is None + if fault != "wrong_pid": + assert window_fields_state(NO_OCR, _frame(), fields) is None + + +@given(st.text(max_size=10000)) +def test_the_shared_wire_model_preserves_exact_unicode_value_and_proof(value): + field = { + "kind": "edit", + "rect": [1, 2, 30, 40], + "text": value, + "state": None, + "value_proof": _proof(value), + "value_identity": "a" * 64, + } + assert valid_form_field(field, pid=10) + mutated = deepcopy(field) + mutated["text"] += "hidden suffix" + assert not valid_form_field(mutated, pid=10) + + +def test_empty_and_container_values_are_retained_without_hiding_pixels(): + fields = _fields(search="", note="") + fields["fields"][1]["kind"] = "value" + seen = [] + + def ocr(png): + import io + + from PIL import Image + + with Image.open(io.BytesIO(png)) as image: + seen.append(image.crop((20, 340, 620, 460)).tobytes()) + return [{"text": "visible"}] + + assert window_fields_state(SimpleNamespace(ocr=ocr), _frame(), fields) is not None + # Compare the actual region, not an assumed ink pixel in the font. + import io + + from PIL import Image + + with Image.open(io.BytesIO(_frame())) as original: + expected = original.crop((20, 340, 620, 460)).tobytes() + assert seen == [expected] + + +def test_native_channel_failure_or_missing_frame_refuses_even_with_stable_ocr(): + def unavailable(*_): + raise RuntimeError("no independent full value") + + backend = SimpleNamespace(approval_form_fields=unavailable) + assert approval_form_state(backend, SAME_VISIBLE_OCR, _frame(), "save") is None + assert approval_form_state(backend, SAME_VISIBLE_OCR, None, "save") is None + + +@pytest.mark.usefixtures("approver") +@pytest.mark.parametrize("phase", ["before_request", "after_person_approval"]) +def test_actual_gate_refuses_incomplete_native_value_before_the_save(tmp_path, phase): + from openadapt_flow.approval_mode.gate import ApprovalGate, SaveContext, StepContext + from openadapt_flow.approval_mode.item_approval import ItemApprovalStore + from openadapt_flow.ir import ActionKind, Step, StepResult, Workflow + from tests.test_approval_mode_each_item import APPROVE, Person + + fields = _fields() + wire = { + "status": "ok", + "window": {"hwnd": 7, "pid": 10, "bounds": list(fields["bounds"])}, + "fields": fields["fields"], + } + backend = _through_wire(wire) + store = ItemApprovalStore(tmp_path / "run") + person = Person([APPROVE]) + person.store = store + gate = ApprovalGate( + "each_item", + approval_store=store, + approval_wait_s=5, + approval_poll_s=1, + sleep=person.sleep, + monotonic=person.monotonic, + ) + gate.begin_item(run_id="run-1", bundle_content_digest="a" * 64, profile="standard") + step = Step( + id="save", + intent="Save the approved item", + action=ActionKind.KEY, + key="Enter", + risk="irreversible", + ) + workflow = Workflow(name="native-completeness", steps=[step]) + result = StepResult(step_id=step.id, intent=step.intent, ok=False) + frame = _frame() + + def read(png): + return approval_form_state(backend, NO_OCR, png, step.id) + + if phase == "before_request": + fields["fields"][1]["value_proof"] = None + first = gate.before_step( + StepContext( + step=step, + workflow=workflow, + result=result, + step_index=0, + run_id="run-1", + frame=lambda: frame, + form_state=read, + ) + ) + if phase == "before_request": + assert not first.proceed + assert [check.detail for check in first.checks] == ["form_state_unreadable"] + assert store.requests() == [] + else: + assert first.proceed and len(store.requests()) == 1 + # A formerly complete channel becomes incomplete after actual signed + # approval. Unchanged pixels and valid historical approval cannot help. + fields["fields"][1]["value_proof"] = None + edge = gate.before_save( + SaveContext( + step=step, + workflow=workflow, + result=result, + prior_results=[], + effect_verifier=None, + governed_authorization=None, + model_calls=0, + frame=lambda: frame, + form_state=read, + ) + ) + assert not edge.proceed + assert [check.detail for check in edge.checks] == ["form_state_unreadable"] + + +@pytest.mark.parametrize("replacement", ["field", "window"]) +def test_fresh_handle_lookup_rejects_a_replaced_uia_runtime(monkeypatch, replacement): + import sys + + control = _Control("EditControl", value="unchanged") + window = _window(control) + perform = _agent(monkeypatch, window) + auto = sys.modules["uiautomation"] + original = auto.ControlFromHandle + lookup_count = 0 + changed = ( + _Control("EditControl", value="unchanged") + if replacement == "field" + else _window() + ) + changed.NativeWindowHandle = ( + control.NativeWindowHandle if replacement == "field" else 7 + ) + changed.GetRuntimeId = lambda: [42, changed.NativeWindowHandle, 999] + + def fresh(hwnd): + nonlocal lookup_count + if hwnd == 7: + lookup_count += 1 + if (replacement == "field" and hwnd == control.NativeWindowHandle) or ( + replacement == "window" and hwnd == 7 and lookup_count > 1 + ): + return changed + return original(hwnd) + + monkeypatch.setattr(auto, "ControlFromHandle", fresh) + wire = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert wire["window"] is None and wire["fields"] == [] + + +def test_field_identity_is_required_and_replacement_changes_the_approval_digest(): + before = _fields() + expected = window_fields_state(NO_OCR, _frame(), before) + assert expected is not None + changed = deepcopy(before) + changed["fields"][1]["value_identity"] = "b" * 64 + actual = window_fields_state(NO_OCR, _frame(), changed) + assert actual is not None and actual != expected + for missing in (None, True, "prefix", "A" * 64): + changed["fields"][1]["value_identity"] = missing + assert window_fields_state(NO_OCR, _frame(), changed) is None diff --git a/packages/flow/tests/test_native_value_deployment.py b/packages/flow/tests/test_native_value_deployment.py new file mode 100644 index 0000000000..9e56663399 --- /dev/null +++ b/packages/flow/tests/test_native_value_deployment.py @@ -0,0 +1,150 @@ +"""Every standalone agent launch ships the same complete-value implementation.""" + +from __future__ import annotations + +import hashlib +import os +import shutil +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from openadapt_flow.backends import parallels_vm as pv +from openadapt_flow.backends.win_agent import server, tls +from openadapt_flow.rl_env.windows_guest import WindowsGuest +from tests.test_winrm_lab import lab_mod + + +@pytest.mark.parametrize("route", ["parallels", "winrm", "guest"]) +@pytest.mark.parametrize("missing", [False, True]) +def test_actual_launch_paths_preflight_and_copy_exact_sibling( + monkeypatch, tmp_path, route, missing +): + source = tmp_path / "source" + source.mkdir() + shutil.copyfile(server.__file__, source / "server.py") + helper = Path(server.__file__).with_name("native_value.py") + if not missing: + shutil.copyfile(helper, source / "native_value.py") + # These are path placeholders, not generated or copied signing material. + bundle = SimpleNamespace( + certfile=str(tmp_path / "owned" / "cert"), + keyfile=str(tmp_path / "owned" / "key"), + fingerprint="a" * 64, + ) + monkeypatch.setattr(tls, "generate_self_signed_cert", lambda _: bundle) + monkeypatch.setattr( + pv.AgentEndpoint, "backend", lambda _: SimpleNamespace(probe=lambda: True) + ) + calls, pushed = [], [] + if route == "parallels": + instance = pv.ParallelsVM("synthetic-vm") + monkeypatch.setattr(instance, "host_ip", lambda *a: "127.0.0.1") + monkeypatch.setattr(instance, "guest_ip", lambda: "127.0.0.1") + monkeypatch.setattr( + instance, "_agent_server_path", lambda: str(source / "server.py") + ) + monkeypatch.setattr(instance, "_agent_alive", lambda *a, **k: True) + for name in ("exec", "exec_cmd", "kill_shim"): + monkeypatch.setattr( + instance, name, lambda *a, **k: calls.append("guest mutation") + ) + + def invoke(): + return instance.launch_agent(token="synthetic-token") + elif route == "winrm": + instance = object.__new__(lab_mod.WinRMLab) + instance.host = "127.0.0.1" + instance.profile = SimpleNamespace(guest_dir=r"C:\synthetic") + for name in ( + "attach_console", + "stop_interactive", + "run_ps", + "launch_interactive", + ): + monkeypatch.setattr( + instance, name, lambda *a, **k: calls.append("guest mutation") + ) + + def invoke(): + return instance.launch_agent( + token="synthetic-token", + python=r"C:\pythonw.exe", + server_path=source / "server.py", + ) + else: + instance = object.__new__(WindowsGuest) + instance.host, instance.python = "127.0.0.1", r"C:\python.exe" + monkeypatch.setattr(server, "__file__", str(source / "server.py")) + monkeypatch.setattr(instance, "_via", lambda *a: ("127.0.0.1", 5000)) + for name in ("attach_console", "run_ps", "_interactive_script"): + monkeypatch.setattr( + instance, name, lambda *a, **k: calls.append("guest mutation") + ) + + def invoke(): + return instance.launch_agent(token="synthetic-token") + + monkeypatch.setattr( + instance, + "push_file", + lambda local, guest, **k: pushed.append((Path(local), guest)), + ) + if missing: + with pytest.raises(FileNotFoundError, match="native-value helper"): + invoke() + assert calls == [] and pushed == [] + else: + invoke() + copied = [ + (local, target) + for local, target in pushed + if "win_agent_native_value.py" in target + ] + assert len(copied) == 1 + assert ( + hashlib.sha256(copied[0][0].read_bytes()).digest() + == hashlib.sha256(helper.read_bytes()).digest() + ) + + +@pytest.mark.parametrize("missing", [False, True]) +def test_standalone_server_requires_exact_local_helper_without_package_fallback( + tmp_path, missing +): + shutil.copyfile(server.__file__, tmp_path / "win_agent_server.py") + if not missing: + shutil.copyfile( + Path(server.__file__).with_name("native_value.py"), + tmp_path / "win_agent_native_value.py", + ) + script = """import sys +sys.path.insert(0, sys.argv[1]) +import win_agent_server as server +value = server._form_field_value(None, lambda: 'scope') +assert not value.complete and value.value is None +import win_agent_native_value as helper +from pathlib import Path +assert Path(helper.__file__).resolve().parent == Path(sys.argv[1]).resolve() +print('exact standalone helper imported; incomplete observation refused') +""" + env = { + key: value + for key, value in os.environ.items() + if key not in {"PYTHONPATH", "PYTHONHOME"} + } + result = subprocess.run( + [sys.executable, "-S", "-c", script, str(tmp_path)], + cwd=tmp_path, + env=env, + text=True, + capture_output=True, + ) + if missing: + assert result.returncode != 0 and "win_agent_native_value" in result.stderr + else: + assert result.returncode == 0, result.stderr + assert "incomplete observation refused" in result.stdout diff --git a/packages/flow/tests/test_parallels_vm.py b/packages/flow/tests/test_parallels_vm.py index c702e1e845..4b5815a952 100644 --- a/packages/flow/tests/test_parallels_vm.py +++ b/packages/flow/tests/test_parallels_vm.py @@ -397,6 +397,7 @@ def test_launch_agent_autoprovisions_tls_and_returns_pinned_endpoint(monkeypatch assert ep.require_tls is True assert ep.token == "tok-xyz" assert ep.pin_fingerprint and len(ep.pin_fingerprint) == 64 # SHA-256 hex + assert f"{pv.GUEST_DIR}/win_agent_native_value.py" in pushed # The per-run cert + key were provisioned into the guest. assert f"{pv.GUEST_DIR}/agent-cert.pem" in pushed assert f"{pv.GUEST_DIR}/agent-key.pem" in pushed From b18f73396f8ad8096a996adef2a619bbe69b06d2 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 23:40:56 -0500 Subject: [PATCH 11/34] Exercise native approval completeness and physical evidence on Windows --- .github/workflows/desktop-replay.yml | 19 +- .../e2e/test_windows_approval_completeness.py | 306 ++++++++++++++++++ 2 files changed, 323 insertions(+), 2 deletions(-) create mode 100644 packages/flow/tests/e2e/test_windows_approval_completeness.py diff --git a/.github/workflows/desktop-replay.yml b/.github/workflows/desktop-replay.yml index 716518eb64..fb692166dd 100644 --- a/.github/workflows/desktop-replay.yml +++ b/.github/workflows/desktop-replay.yml @@ -27,6 +27,7 @@ on: - packages/flow/scripts/desktop/patient_notes.ps1 - packages/flow/tests/e2e/test_windows_hosted_replay.py - packages/flow/tests/e2e/test_windows_hosted_governed.py + - packages/flow/tests/e2e/test_windows_approval_completeness.py - packages/flow/tests/_approver_keys.py - packages/flow/tests/conftest.py - packages/flow/tests/e2e/conftest.py @@ -36,6 +37,9 @@ on: - packages/flow/tests/native_apps/check_it_gtk.py - packages/flow/tests/test_approval_form_window.py - packages/flow/tests/test_approval_form_fields.py + - packages/flow/tests/test_approval_value_completeness.py + - packages/flow/tests/test_native_value_completeness.py + - packages/flow/tests/test_native_value_deployment.py - packages/flow/tests/test_binary_file_descriptors.py - packages/flow/tests/_binary_descriptor_contract.py - packages/flow/benchmark/rdp_pool/** @@ -92,7 +96,16 @@ jobs: mkdir -p runs pytest -v -rs -p no:cacheprovider tests/test_windows_attempt_ledger.py \ tests/test_approval_form_window.py tests/test_approval_form_fields.py \ - tests/test_binary_file_descriptors.py --junitxml=runs/windows-guards-junit.xml + tests/test_binary_file_descriptors.py tests/test_native_value_completeness.py \ + tests/test_approval_value_completeness.py tests/test_native_value_deployment.py \ + --junitxml=runs/windows-guards-junit.xml + - name: Native approval complete values and no-write refusal + env: + OAFLOW_WINDOWS_HOSTED_E2E: "1" + OAFLOW_NATIVE_APPROVAL_EVIDENCE: ${{ runner.temp }}/native-approval-evidence.json + run: | + pytest -v -rs -p no:cacheprovider --basetemp="$RUNNER_TEMP/ac" \ + tests/e2e/test_windows_approval_completeness.py --junitxml=runs/native-approval-junit.xml - name: Record, compile and replay, judged from the record env: OAFLOW_WINDOWS_HOSTED_E2E: "1" @@ -108,7 +121,7 @@ jobs: import xml.etree.ElementTree as ET cases = [ case - for name in ("windows-guards", "windows-replay") + for name in ("windows-guards", "native-approval", "windows-replay") for case in ET.parse(f"runs/{name}-junit.xml").getroot().iter("testcase") ] skipped = [c for c in cases if c.find("skipped") is not None] @@ -146,6 +159,8 @@ jobs: with: name: windows-replay-evidence path: | + ${{ runner.temp }}/native-approval-evidence.json + ${{ runner.temp }}/native-approval-evidence.frames/*.png ${{ runner.temp }}/windows-replay-evidence.json ${{ runner.temp }}/windows-governed-evidence.json ${{ runner.temp }}/wg/**/report.json diff --git a/packages/flow/tests/e2e/test_windows_approval_completeness.py b/packages/flow/tests/e2e/test_windows_approval_completeness.py new file mode 100644 index 0000000000..a25942707c --- /dev/null +++ b/packages/flow/tests/e2e/test_windows_approval_completeness.py @@ -0,0 +1,306 @@ +"""Native approval values, independent managed storage, and no-write refusal. + +This synthetic observation variant removes the grid from the visible form so +virtual cells with no independent native value source do not obscure the +specific field contract under test. The original SQLite data and save handler +remain. It qualifies neither those virtual cells nor a complete Flow save. +""" + +from __future__ import annotations + +import hashlib +import io +import json +import os +import time +from pathlib import Path + +import pytest +from PIL import Image + +from openadapt_flow import vision +from openadapt_flow.approval_mode.form_state import approval_form_state +from openadapt_flow.approval_mode.gate import ApprovalGate, StepContext +from openadapt_flow.approval_mode.item_approval import ItemApprovalStore +from openadapt_flow.backends.win_agent import server +from openadapt_flow.backends.win_agent.native_value import valid_value_proof +from openadapt_flow.ir import ActionKind, Step, StepResult, Workflow +from tests.e2e.test_windows_hosted_replay import RUN_E2E, _Host + +pytestmark = [ + pytest.mark.skipif( + not RUN_E2E, reason="opt-in hosted Windows native approval proof" + ), + pytest.mark.timeout(300), +] +EVIDENCE_ENV = "OAFLOW_NATIVE_APPROVAL_EVIDENCE" +SHORT = "Synthetic Ω café 42" +HOOK = r""" +# This is a synthetic observation variant, not qualification of virtual cells. +$form.Controls.Remove($grid) +$grid.Hide() +$approvalProbe = New-Object System.Windows.Forms.TextBox +$approvalProbe.Name = 'approvalProbe' +$approvalProbe.AccessibleName = 'approvalProbe' +$approvalProbe.Location = New-Object System.Drawing.Point(20, 120) +$approvalProbe.Size = New-Object System.Drawing.Size(590, 28) +$approvalProbe.MaxLength = 131072 +$form.Controls.Add($approvalProbe) +function Get-ApprovalStored { + $values = @{} + $controls = @{ probe=$script:approvalProbe; search=$script:searchBox; note=$script:noteBox } + foreach ($id in $controls.Keys) { + $control = $controls[$id] + $text = [string]$control.Text + $bytes = [Text.Encoding]::Unicode.GetBytes($text) + $hasher = [Security.Cryptography.SHA256]::Create() + try { $hash = ([BitConverter]::ToString($hasher.ComputeHash($bytes))).Replace('-', '').ToLowerInvariant() } + finally { $hasher.Dispose() } + $values[$id] = @{ utf16_units=$text.Length; sha256_utf16le=$hash; + suffix=$text.Substring([Math]::Max(0, $text.Length - 16)); + hwnd=$control.Handle.ToInt64(); pid=$PID } + } + return @{ fields=$values; form_hwnd=$form.Handle.ToInt64(); pid=$PID } +} +$approvalTimer = New-Object System.Windows.Forms.Timer +$approvalTimer.Interval = 40 +$approvalTimer.Add_Tick({ + $commandPath = Join-Path $PSScriptRoot 'approval-command' + if (-not (Test-Path $commandPath)) { return } + $command = [IO.File]::ReadAllText($commandPath) + Remove-Item $commandPath + switch ($command) { + 'empty' { $script:approvalProbe.Text = '' } + 'short' { $script:approvalProbe.Text = 'Synthetic Ω café 42' } + 'long' { $script:approvalProbe.Text = ('x' * 8192) + '-END' } + 'snapshot' { } + default { throw 'Unknown synthetic approval fixture command' } + } + [void]$script:approvalProbe.Focus() + $snapshot = Get-ApprovalStored + $snapshot['command'] = $command + $temporary = Join-Path $PSScriptRoot 'approval-ack.tmp' + [IO.File]::WriteAllText($temporary, ($snapshot | ConvertTo-Json -Depth 6)) + [IO.File]::Move($temporary, (Join-Path $PSScriptRoot 'approval-ack.json')) +}) +$approvalTimer.Start() +""" + + +def _command(root: Path, command: str) -> dict: + ack = root / "approval-ack.json" + ack.unlink(missing_ok=True) + temporary = root / "approval-command.tmp" + temporary.write_text(command) + temporary.replace(root / "approval-command") + deadline = time.monotonic() + 15 + while not ack.is_file(): + assert time.monotonic() < deadline, "synthetic approval fixture timed out" + time.sleep(0.05) + result = json.loads(ack.read_text(encoding="utf-8-sig")) + assert result["command"] == command + return result + + +def _check_stored(snapshot: dict, expected: str) -> None: + actual = snapshot["fields"]["probe"] + raw = expected.encode("utf-16-le") + assert actual["utf16_units"] == len(raw) // 2 + assert actual["sha256_utf16le"] == hashlib.sha256(raw).hexdigest() + assert actual["suffix"] == expected[-16:] + + +def test_native_approval_completeness_refuses_a_provider_prefix(tmp_path, monkeypatch): + import uiautomation as auto + + destination = Path(os.environ[EVIDENCE_ENV]) + destination.parent.mkdir(parents=True, exist_ok=True) + frames = destination.with_suffix(".frames") + frames.mkdir(exist_ok=True) + evidence = { + "schema": "openadapt.native-approval-completeness-proof/v1", + "scope": "synthetic observation variant, not full Flow/save qualification", + "phases": [], + "transport": [], + } + host = _Host(tmp_path) + fixture = tmp_path / "patient_notes.ps1" + fixture.write_text( + fixture.read_text().replace( + "[void]$form.ShowDialog()", HOOK + "\n[void]$form.ShowDialog()" + ), + encoding="utf-8-sig", + ) + try: + backend = host.start_agent() + original_post = backend._session.post + writes = [] + + def post(url, **kwargs): + path = url.removeprefix(backend.server_url) + if path in {"/input", "/input/guarded", "/uia/act", "/execute_windows"}: + writes.append(path) + response = original_post(url, **kwargs) + if path == "/window/form-fields": + evidence["transport"].append( + { + "path": path, + "request": kwargs["json"], + "status": response.status_code, + "response": response.json(), + } + ) + return response + + monkeypatch.setattr(backend._session, "post", post) + host.launch_app() + before = host.rows() + evidence["before_rows"] = before + for name, expected in ( + ("empty", ""), + ("short", SHORT), + ("long", "x" * 8192 + "-END"), + ): + managed = _command(tmp_path, name) + _check_stored(managed, expected) + payload = {"hwnd": managed["form_hwnd"], "pid": managed["pid"]} + # Reacquire actual UIA/runtime/native scope, using the exact engine + # reader independently in this process as well as over HTTP. + with auto.UIAutomationInitializerInThread(): + window = auto.ControlFromHandle(payload["hwnd"]) + control = auto.ControlFromHandle(managed["fields"]["probe"]["hwnd"]) + user32 = server._user32_factory() + initial = server._window_operation("window-bounds", payload, user32)[ + "window" + ] + assert initial is not None + + def identity(): + return server._form_value_identity( + control, + window, + payload["hwnd"], + lambda: ( + server._window_operation("window-bounds", payload, user32)[ + "window" + ] + == initial + ), + auto, + ) + + observed = server._form_field_value(control, identity) + uia_value = control.GetValuePattern().Value + rect = control.BoundingRectangle + point = ( + int((rect.left + rect.right) / 2), + int((rect.top + rect.bottom) / 2), + ) + assert backend.record_verified_window("probe", *point) + fields = backend.approval_form_fields("save") + phase = { + "name": name, + "managed_before": managed, + "uia_utf16_units": len(uia_value.encode("utf-16-le")) // 2, + "uia_sha256_utf16le": hashlib.sha256( + uia_value.encode("utf-16-le") + ).hexdigest(), + "direct_complete": observed.complete, + "direct_reason": observed.reason, + "fields": fields, + } + evidence["phases"].append(phase) + if name == "long": + assert ( + not observed.complete + and observed.reason == "provider_native_value_disagreement" + ) + assert phase["uia_utf16_units"] == 4096 and fields is None + else: + assert observed.complete and observed.value == expected + assert observed.proof is not None and valid_value_proof( + expected, observed.proof.payload() + ) + assert fields is not None + by_hwnd = { + f["value_proof"]["hwnd"]: f + for f in fields["fields"] + if f["value_proof"] is not None + } + for stored in managed["fields"].values(): + field = by_hwnd[stored["hwnd"]] + assert ( + field["value_proof"]["sha256_utf16le"] + == stored["sha256_utf16le"] + ) + assert field["value_proof"]["utf16_units"] == stored["utf16_units"] + assert field["value_proof"]["pid"] == stored["pid"] + frame = backend.screenshot() + store = ItemApprovalStore(tmp_path / ("run-" + name)) + gate = ApprovalGate("each_item", approval_store=store, approval_wait_s=0) + gate.begin_item( + run_id="run-" + name, bundle_content_digest="a" * 64, profile="standard" + ) + step = Step( + id="save", + intent="Save synthetic fixture", + action=ActionKind.KEY, + key="Enter", + risk="irreversible", + ) + result = StepResult(step_id=step.id, intent=step.intent, ok=False) + verdict = gate.before_step( + StepContext( + step=step, + workflow=Workflow(name="native approval", steps=[step]), + result=result, + step_index=0, + run_id="run-" + name, + frame=lambda: frame, + form_state=lambda png: approval_form_state( + backend, vision, png, "save" + ), + ) + ) + assert not verdict.proceed # nobody approved; no input may occur + phase["gate_checks"] = [ + check.model_dump(mode="json") for check in verdict.checks + ] + requests = store.requests() + phase["request_count"] = len(requests) + if name == "long": + assert not requests and any( + c.detail == "form_state_unreadable" for c in verdict.checks + ) + else: + assert ( + len(requests) == 1 + and requests[0].form_state_kind == "window_fields" + ) + request = requests[0] + raw = (store.run_dir / request.screenshot).read_bytes() + assert hashlib.sha256(raw).hexdigest() == request.screenshot_sha256 + with Image.open(io.BytesIO(raw)) as image: + size = image.size + image.verify() + (frames / (name + ".png")).write_bytes(raw) + phase["frame"] = { + "file": name + ".png", + "sha256": request.screenshot_sha256, + "size": size, + "bytes": len(raw), + } + after = _command(tmp_path, "snapshot") + _check_stored(after, expected) + assert after["fields"] == managed["fields"] + phase["managed_after"] = after + phase["after_rows"] = host.rows() + assert phase["after_rows"] == before + assert not writes + evidence["input_requests"] = writes + finally: + host.close() + evidence["fixture_and_agent_stopped"] = host.app is None and ( + host.agent is None or host.agent.poll() is not None + ) + destination.write_text(json.dumps(evidence, indent=2), encoding="utf-8") From 4de570121d662bddca9e9096b6b50053e9544ca7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 00:42:03 -0500 Subject: [PATCH 12/34] Require complete structural values and preserve marker uncertainty --- .github/workflows/desktop-replay.yml | 4 + .../approval_mode/window_fields.py | 10 +- .../backends/win_agent/server.py | 139 +++++- .../backends/win_agent/value_protocol.py | 120 +++++ .../backends/windows_backend.py | 54 +- .../runtime/effects/desktop_readback.py | 141 ++++-- .../effects/desktop_readback_sessions.py | 59 ++- .../e2e/test_windows_approval_completeness.py | 55 ++- .../flow/tests/test_approval_form_fields.py | 2 + packages/flow/tests/test_desktop_readback.py | 121 +++-- .../test_structural_value_completeness.py | 462 ++++++++++++++++++ 11 files changed, 1004 insertions(+), 163 deletions(-) create mode 100644 packages/flow/openadapt_flow/backends/win_agent/value_protocol.py create mode 100644 packages/flow/tests/test_structural_value_completeness.py diff --git a/.github/workflows/desktop-replay.yml b/.github/workflows/desktop-replay.yml index fb692166dd..ce54dde889 100644 --- a/.github/workflows/desktop-replay.yml +++ b/.github/workflows/desktop-replay.yml @@ -40,6 +40,8 @@ on: - packages/flow/tests/test_approval_value_completeness.py - packages/flow/tests/test_native_value_completeness.py - packages/flow/tests/test_native_value_deployment.py + - packages/flow/tests/test_structural_value_completeness.py + - packages/flow/tests/test_desktop_readback.py - packages/flow/tests/test_binary_file_descriptors.py - packages/flow/tests/_binary_descriptor_contract.py - packages/flow/benchmark/rdp_pool/** @@ -98,11 +100,13 @@ jobs: tests/test_approval_form_window.py tests/test_approval_form_fields.py \ tests/test_binary_file_descriptors.py tests/test_native_value_completeness.py \ tests/test_approval_value_completeness.py tests/test_native_value_deployment.py \ + tests/test_structural_value_completeness.py tests/test_desktop_readback.py \ --junitxml=runs/windows-guards-junit.xml - name: Native approval complete values and no-write refusal env: OAFLOW_WINDOWS_HOSTED_E2E: "1" OAFLOW_NATIVE_APPROVAL_EVIDENCE: ${{ runner.temp }}/native-approval-evidence.json + OAFLOW_NATIVE_APPROVAL_SOURCE_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} run: | pytest -v -rs -p no:cacheprovider --basetemp="$RUNNER_TEMP/ac" \ tests/e2e/test_windows_approval_completeness.py --junitxml=runs/native-approval-junit.xml diff --git a/packages/flow/openadapt_flow/approval_mode/window_fields.py b/packages/flow/openadapt_flow/approval_mode/window_fields.py index 895a05ec97..873fc3cfbf 100644 --- a/packages/flow/openadapt_flow/approval_mode/window_fields.py +++ b/packages/flow/openadapt_flow/approval_mode/window_fields.py @@ -2,10 +2,9 @@ from __future__ import annotations -import re from typing import Any -from openadapt_flow.backends.win_agent.native_value import valid_value_proof +from openadapt_flow.backends.win_agent.value_protocol import valid_value_observation FIELD_KEYS = frozenset( {"kind", "rect", "text", "state", "value_proof", "value_identity"} @@ -45,11 +44,6 @@ def valid_form_field(field: Any, *, pid: int | None = None) -> bool: identity = field["value_identity"] if proof is None: return identity is None - return ( - isinstance(identity, str) - and re.fullmatch(r"[0-9a-f]{64}", identity) is not None - and valid_value_proof(text, proof) - and (pid is None or proof["pid"] == pid) - ) + return valid_value_observation(text, proof, identity, pid=pid) except (KeyError, TypeError, ValueError): return False diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 538eb387ce..082dd0f06c 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -19,8 +19,8 @@ POST /uia/identity-candidates-at -> rows that read the same as that row POST /uia/find -> zero / unique / ambiguous exact candidates POST /uia/act -> unique native UIA action + delivery receipt - POST /uia/read -> read-only text of one unique control (value or - name) and, on request, the text of its rows + POST /uia/read -> complete native value of one unique control, + with non-authorizing text/row previews separate POST /execute_windows -> legacy WAA-shaped input commands, DISABLED by default (``--allow-legacy-commands``). Commands are parsed into an allow-listed set of @@ -973,7 +973,7 @@ def _candidate(control: object) -> Optional[dict[str, Any]]: def _find_candidates( - locator: dict[str, Any], auto: Any + locator: dict[str, Any], auto: Any, *, strict_walk: bool = False ) -> tuple[list[tuple[Any, dict[str, Any]]], bool]: try: root = auto.GetRootControl() @@ -991,7 +991,47 @@ def _find_candidates( if visited > _MAX_UIA_NODES: truncated = True break + possible = False + if strict_walk: + # A failed selector/bounds read cannot hide a second match and + # turn a partial query into unique value authority. + try: + facts = { + key: getattr(control, key) + for key in ("AutomationId", "Name", "ControlTypeName") + } + if any(not isinstance(value, str) for value in facts.values()): + return found, True + possible = all( + expected is None or actual == expected + for expected, actual in ( + (locator.get("automation_id"), facts["AutomationId"] or None), + (locator.get("name"), " ".join(facts["Name"].split()) or None), + ( + locator.get("role"), + "button" + if facts["ControlTypeName"] == "SplitButtonControl" + else _CONTROL_TO_ROLE.get(facts["ControlTypeName"]), + ), + ) + ) + if possible: + node = control + for _ in range(_MAX_UIA_DEPTH + 1): + if node is None: + break + if node.ControlTypeName == "WindowControl": + if not isinstance(node.Name, str): + return found, True + break + node = node.GetParentControl() + else: + return found, True + except Exception: # noqa: BLE001 - unknown query scope is incomplete + return found, True candidate = _candidate(control) + if strict_walk and possible and candidate is None: + return found, True if candidate is not None: matches = True for key in ("automation_id", "role", "name", "window_name"): @@ -1004,13 +1044,21 @@ def _find_candidates( if len(found) >= _MAX_UIA_CANDIDATES: truncated = True break - if depth >= _MAX_UIA_DEPTH: + if depth >= _MAX_UIA_DEPTH and not strict_walk: continue children = _control_value(control, "GetChildren", None) try: + if strict_walk and not callable(children): + return found, True values = list(children()) if callable(children) else [] except Exception: # noqa: BLE001 + if strict_walk: + return found, True values = [] + if depth >= _MAX_UIA_DEPTH: + if values: + return found, True + continue stack.extend((child, depth + 1) for child in reversed(values)) return found, truncated @@ -1563,27 +1611,76 @@ def _perform_uia_initialized( ) if not isinstance(data.get("rows", False), bool): raise AgentRequestError(400, "invalid_schema", "rows must be a boolean") - locator = _locator_payload(data["locator"]) - found, truncated = _find_candidates(locator, auto) - if len(found) != 1 or truncated: - return { - "status": "ok", - "match": "ambiguous" if found or truncated else "not_found", - "candidate_count": len(found), - "text": None, - } - control, candidate = found[0] + read_locator = _locator_payload(data["locator"]) + found, truncated = _find_candidates(read_locator, auto, strict_walk=True) + unique = len(found) == 1 and not truncated result: dict[str, Any] = { "status": "ok", - "match": "unique", - "candidate_count": 1, - "text": _value_text(control), - "point": candidate["point"], + "match": "unique" + if unique + else "ambiguous" + if found or truncated + else "not_found", + "candidate_count": len(found), + "text": None, + "point": None, + "complete": False, + "value_proof": None, + "value_identity": None, + "read_scope": read_locator, + "preview_text": None, + "reason": "not_unique", } + if unique: + control, candidate = found[0] + result["point"] = candidate["point"] + # Existing display previews remain explicit non-authorizing data. + # A legacy client sees text=None for every unavailable value. + result["preview_text"] = _value_text(control) + + def identity() -> Optional[str]: + fresh, cut = _find_candidates(read_locator, auto, strict_walk=True) + if ( + cut + or len(fresh) != 1 + or fresh[0][1]["fingerprint"] != candidate["fingerprint"] + ): + return None + return hashlib.sha256( + json.dumps( + [read_locator, fresh[0][1]["fingerprint"]], + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + ).encode("utf-8") + ).hexdigest() + + binding = identity() + observed = _form_field_value(control, identity) + result["reason"] = observed.reason or "value_identity_changed" + if ( + observed.complete + and observed.proof is not None + and binding is not None + and identity() == binding + ): + result.update( + text=observed.value, + complete=True, + reason=None, + value_proof=observed.proof.payload(), + value_identity=binding, + ) if data.get("rows"): - rows, rows_truncated = _read_rows(control) - result["rows"] = rows - result["rows_truncated"] = rows_truncated + # Row/cell concatenation and a bounded preview walk do not prove + # full text or inventory. No composite row source is qualified. + preview_rows, _ = _read_rows(found[0][0]) if unique else ([], True) + result.update( + rows=None, + rows_truncated=True, + rows_complete=False, + preview_rows=preview_rows, + ) return result data = _exact_object( diff --git a/packages/flow/openadapt_flow/backends/win_agent/value_protocol.py b/packages/flow/openadapt_flow/backends/win_agent/value_protocol.py new file mode 100644 index 0000000000..6e706a8539 --- /dev/null +++ b/packages/flow/openadapt_flow/backends/win_agent/value_protocol.py @@ -0,0 +1,120 @@ +"""Strict native value observations; previews are never effect evidence.""" + +from __future__ import annotations + +import re +from typing import Any, Mapping + +from .native_value import valid_value_proof + +SCOPE_KEYS = ("automation_id", "role", "name", "window_name") +READ_KEYS = frozenset( + { + "status", + "match", + "candidate_count", + "point", + "text", + "complete", + "value_proof", + "value_identity", + "read_scope", + "preview_text", + "reason", + } +) +ROW_KEYS = frozenset({"rows", "rows_truncated", "rows_complete", "preview_rows"}) + + +def locator_scope(locator: Mapping[str, Any]) -> dict[str, Any]: + return {key: locator.get(key) for key in SCOPE_KEYS} + + +def valid_value_observation( + value: object, proof: object, identity: object, *, pid: int | None = None +) -> bool: + return ( + isinstance(value, str) + and isinstance(identity, str) + and re.fullmatch(r"[0-9a-f]{64}", identity) is not None + and isinstance(proof, dict) + and valid_value_proof(value, proof) + and (pid is None or proof["pid"] == pid) + ) + + +def valid_structural_response( + payload: object, scope: Mapping[str, Any], *, rows: bool = False +) -> bool: + try: + if not isinstance(payload, dict) or set(payload) != READ_KEYS | ( + ROW_KEYS if rows else set() + ): + return False + if payload["status"] != "ok" or payload["read_scope"] != locator_scope(scope): + return False + match, count, point = ( + payload["match"], + payload["candidate_count"], + payload["point"], + ) + if ( + match not in {"unique", "ambiguous", "not_found"} + or type(count) is not int + or count < 0 + ): + return False + if match == "unique": + if ( + count != 1 + or not isinstance(point, list) + or len(point) != 2 + or any(type(v) is not int for v in point) + ): + return False + elif point is not None or (match == "not_found" and count != 0): + return False + preview = payload["preview_text"] + if preview is not None and ( + not isinstance(preview, str) or len(preview) > 4096 + ): + return False + if type(payload["complete"]) is not bool: + return False + if payload["complete"]: + if ( + match != "unique" + or payload["reason"] is not None + or not valid_value_observation( + payload["text"], payload["value_proof"], payload["value_identity"] + ) + ): + return False + elif ( + payload["text"] is not None + or payload["value_proof"] is not None + or payload["value_identity"] is not None + or not isinstance(payload["reason"], str) + or not 1 <= len(payload["reason"]) <= 128 + ): + return False + if rows and ( + payload["rows"] is not None + or payload["rows_truncated"] is not True + or payload["rows_complete"] is not False + or not isinstance(payload["preview_rows"], list) + ): + # No native row-inventory/composite completeness contract is + # qualified yet. In particular, empty previews never prove zero. + return False + return True + except (KeyError, TypeError, ValueError): + return False + + +def valid_structural_value(payload: object, scope: Mapping[str, Any]) -> bool: + return ( + isinstance(payload, dict) + and valid_structural_response(payload, scope) + and payload["complete"] is True + ) diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index 13ea085ac6..ba06c230bd 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -47,6 +47,10 @@ from openadapt_flow.approval_mode.window_fields import valid_form_field from openadapt_flow.backend import ActionDeliveryUncertain, StructuralResolutionRefused +from openadapt_flow.backends.win_agent.value_protocol import ( + locator_scope, + valid_structural_response, +) from openadapt_flow.ir import ( ActionDeliveryReceipt, StructuralHandle, @@ -1543,51 +1547,25 @@ def read_structural( ) -> Optional[dict]: """Read one control's text (and, with ``rows``, its rows) via UIA. - Read-only: the agent returns the control's value or name and never - acts on it. Returns the agent's payload (``match`` is ``unique``, - ``ambiguous`` or ``not_found``), or None when the read is unavailable - (older agent, transport error, malformed answer). + Read-only. Normal text requires an exact complete native-value proof; + visible labels/MSAA/clipped strings are preview_text only. Missing or + malformed proof never becomes a field value. Unsupported values return + text=None; legacy responses or unqualified row inventories return None. """ + scope = locator_scope(locator.model_dump(mode="json", exclude_none=True)) typed = self._post_typed_read( "/uia/read", - { - "locator": locator.model_dump(mode="json", exclude_none=True), - **({"rows": True} if rows else {}), - }, + {"locator": scope, **({"rows": True} if rows else {})}, ) payload = typed.payload - if not typed.available or payload is None: - return None - if payload.get("match") not in ("unique", "ambiguous", "not_found"): + if not typed.available or not valid_structural_response( + payload, scope, rows=rows + ): return None - text = payload.get("text") - if text is not None and not isinstance(text, str): + if rows: + # Explicit preview rows cannot authorize semantic record counts, + # field values or absence. A qualified inventory is still required. return None - if rows and payload.get("match") == "unique": - items = payload.get("rows") - if not isinstance(items, list) or not all( - isinstance(item, dict) - and isinstance(item.get("text"), str) - and isinstance(item.get("point"), list) - and len(item["point"]) == 2 - and all( - isinstance(v, int) and not isinstance(v, bool) - for v in item["point"] - ) - and all( - isinstance(cell, dict) - and isinstance(cell.get("text"), str) - and isinstance(cell.get("point"), list) - and len(cell["point"]) == 2 - and all( - isinstance(v, int) and not isinstance(v, bool) - for v in cell["point"] - ) - for cell in item.get("cells") or [] - ) - for item in items - ): - return None return payload def window_tree( diff --git a/packages/flow/openadapt_flow/runtime/effects/desktop_readback.py b/packages/flow/openadapt_flow/runtime/effects/desktop_readback.py index f2296615f1..cdca0da67c 100644 --- a/packages/flow/openadapt_flow/runtime/effects/desktop_readback.py +++ b/packages/flow/openadapt_flow/runtime/effects/desktop_readback.py @@ -62,6 +62,7 @@ import time from contextlib import AbstractContextManager from dataclasses import dataclass, field +from datetime import datetime from typing import Any, Callable, Literal, Mapping, Optional, Protocol from pydantic import BaseModel, ConfigDict, Field, model_validator @@ -797,23 +798,25 @@ def _identity_piece(row: Seen, identity: str) -> Seen: return row -def _present(surface: DesktopReadSurface, ref: ControlRef) -> bool: - """Whether a marker is on screen, shows some text, and (when set) shows - ``ref.shows``.""" +def _present(surface: DesktopReadSurface, ref: ControlRef) -> Optional[bool]: + """Three-valued marker predicate, never an inference of element absence. + Missing/unavailable observations have no qualified absence inventory. + Complete empty values without an explicit text predicate are unknown, + too. Only a complete native value can disprove an explicit value marker; + an OCR mismatch may simply have missed its text. + """ seen = surface.read(ref) - if ref.structured and ref.shows is None and seen.status == "unavailable": - # A UI Automation control that exposes no text at all (a panel): - # present when it is there. A control that reads as empty is absent. - return surface.locate(ref).status == "ok" - if seen.status != "ok" or seen.item is None or not seen.item.text.strip(): - return False + if seen.status != "ok" or seen.item is None: + return None + text = seen.item.text.strip() if ref.shows is None: - return True + return True if text else None from openadapt_flow.runtime.effects.readback_values import token_occurrences - # Whole tokens: a marker "Saved" is not shown by "Unsaved". - return token_occurrences(_norm(seen.item.text), _norm(ref.shows)) >= 1 + if token_occurrences(_norm(text), _norm(ref.shows)) >= 1: + return True + return None if seen.item.ocr else False def _view(surface: DesktopReadSurface, spec: DesktopReadbackSpec) -> tuple[Any, ...]: @@ -861,7 +864,12 @@ def fail(reason: str) -> RawRecordView: # -- sign in (the application's own form) -------------------------------- if spec.sign_in is not None: sign_in = spec.sign_in - if _present(surface, sign_in.signed_in): + initial_signed_in = _present(surface, sign_in.signed_in) + if initial_signed_in is None: + return fail( + "the signed-in marker state is unknown; not inferring signed out" + ) + if initial_signed_in is True: # Someone is already signed in here. The check must sign in with # its own account, or it is not a separately signed-in session. return fail( @@ -885,7 +893,7 @@ def fail(reason: str) -> RawRecordView: signed = _wait_for( surface, guard, - lambda: True if _present(surface, sign_in.signed_in) else None, + lambda: True if _present(surface, sign_in.signed_in) is True else None, timeout, ) guard.phase = "look_up" @@ -917,12 +925,18 @@ def fail(reason: str) -> RawRecordView: # What a session that persists between look-ups may still show from an # earlier one. A view (or a not-found message) that was up before the # search counts only once it changes or goes away and comes back. - stale_view = _view(surface, spec) if _present(surface, spec.ready) else None - stale_not_found = spec.not_found is not None and _present(surface, spec.not_found) - # A marker counts as gone only after two polls in a row without it, so - # one OCR miss or a brief overlay can't pass a stale screen. - seen_gone = {"view": stale_view is None, "not_found": not stale_not_found} - absent = {"view": 0, "not_found": 0} + initial_ready = _present(surface, spec.ready) + stale_view = _view(surface, spec) if initial_ready is True else None + stale_not_found = ( + _present(surface, spec.not_found) if spec.not_found is not None else None + ) + # Only a qualified negative value-predicate observation contributes to + # freshness. Missing/unknown is not element absence or a negative poll. + observed_negative = { + "view": initial_ready is False, + "not_found": stale_not_found is False, + } + negative_streak = {"view": 0, "not_found": 0} if spec.search.submit is None: guard.press_enter(surface, box_ref) else: @@ -932,22 +946,38 @@ def fail(reason: str) -> RawRecordView: guard.click(surface, spec.search.submit, button.item) surface.settle() - def gone(name: str, shown: bool) -> None: - absent[name] = 0 if shown else absent[name] + 1 - if absent[name] >= 2: - seen_gone[name] = True + def gone(name: str, shown: Optional[bool]) -> None: + # Unknown is neither a negative observation nor a gap we can bridge + # in the required consecutive negative sequence. + negative_streak[name] = negative_streak[name] + 1 if shown is False else 0 + if negative_streak[name] >= 2: + observed_negative[name] = True def not_found_shown() -> bool: - shown = spec.not_found is not None and _present(surface, spec.not_found) + if spec.not_found is None: + return False # no negative predicate exists in this contract + shown = _present(surface, spec.not_found) gone("not_found", shown) - return shown and seen_gone["not_found"] + return shown is True and observed_negative["not_found"] def fresh_view() -> bool: shown = _present(surface, spec.ready) gone("view", shown) - if not shown: + if shown is not True: return False - return seen_gone["view"] or _view(surface, spec) != stale_view + if observed_negative["view"]: + return True + current = _view(surface, spec) + complete_before = stale_view is not None and all( + status == "ok" for status, _ in stale_view + ) + complete_after = all(status == "ok" for status, _ in current) + return ( + initial_ready is True + and complete_before + and complete_after + and current != stale_view + ) # -- open the one matching result ------------------------------------------- if spec.open is not None: @@ -993,7 +1023,7 @@ def ready_or_absent() -> Optional[str]: if state == "not_found": return RawRecordView(ok=True, not_found=True, inputs=list(guard.inputs)) if state is None: - if stale_view is not None and _present(surface, spec.ready): + if stale_view is not None and _present(surface, spec.ready) is True: return fail( "the record view still shows what it showed before the search; " "it may not have refreshed, so it can't be read as this save" @@ -1066,6 +1096,49 @@ def collapse(name: str, expr: Optional[ValueExpr]) -> Optional[ValueExpr]: return effect.model_copy(update={"match": match, "value": value}, deep=True) +def _exact_value( + text: str, reader: DesktopFieldReader, *, expected: bool = False +) -> tuple[str, bool]: + """Preserve structural values; only explicit field transforms may alter them.""" + if reader.date_format: + formats = ( + ("%Y-%m-%d", reader.date_format) if expected else (reader.date_format,) + ) + for layout in formats: + try: + text = datetime.strptime(text, layout).date().isoformat() + break + except ValueError: + continue + else: + return text, False + return (text.casefold() if reader.casefold else text), True + + +def _desktop_effect( + effect: Effect, readers: Mapping[str, DesktopFieldReader], ocr_fields: set[str] +) -> Effect: + """Apply the same explicit transforms to expected and observed native values.""" + display = normalized_effect( + effect, {name: reader for name, reader in readers.items() if name in ocr_fields} + ) + + def norm(name: str, expr: Optional[ValueExpr]) -> Optional[ValueExpr]: + if ( + expr is None + or expr.literal is None + or name not in readers + or name in ocr_fields + ): + return expr + text, _ = _exact_value(expr.literal, readers[name], expected=True) + return ValueExpr(literal=text) + + match = {name: norm(name, expr) or expr for name, expr in display.match.items()} + value = norm(display.field, display.value) if display.field else display.value + return display.model_copy(update={"match": match, "value": value}, deep=True) + + class DesktopReadbackVerifier(VerifierAdapterBase): """Check a saved record by looking it up in a separate desktop, RDP, or Citrix session, as a person would. @@ -1257,7 +1330,10 @@ def _normalize(self, raw: RawRecordView) -> _ReadRecord: m and stripped.endswith(m) for m in spec.truncation_markers ): uncertain.add((0, name)) - normalized, parsed = normalize_value(text, reader) # type: ignore[arg-type] + if seen.ocr: + normalized, parsed = normalize_value(text, reader) # type: ignore[arg-type] + else: + normalized, parsed = _exact_value(text, reader) spaced[name] = ( " ".join(normalized.split()) if seen.ocr and isinstance(normalized, str) @@ -1347,7 +1423,7 @@ def _judge( return problem spec = self._target.spec normalized = _without_spaces_for( - normalized_effect(effect, spec.fields), read.ocr_fields + _desktop_effect(effect, spec.fields, read.ocr_fields), read.ocr_fields ) blocking = blocking_uncertain_fields(normalized, read.records, read.uncertain) if blocking: @@ -1382,7 +1458,8 @@ def _judge( # once its spaces are removed is not proof. spaced = judge_records( _collapse_spaces_for( - normalized_effect(effect, spec.fields), read.ocr_fields + _desktop_effect(effect, spec.fields, read.ocr_fields), + read.ocr_fields, ), before, read.spaced, diff --git a/packages/flow/openadapt_flow/runtime/effects/desktop_readback_sessions.py b/packages/flow/openadapt_flow/runtime/effects/desktop_readback_sessions.py index 6dd3386cde..abd07e2e0b 100644 --- a/packages/flow/openadapt_flow/runtime/effects/desktop_readback_sessions.py +++ b/packages/flow/openadapt_flow/runtime/effects/desktop_readback_sessions.py @@ -4,8 +4,9 @@ Two ways to read, chosen per control: - :class:`UiaReadSurface` reads Windows UI Automation through the in-guest - agent's read-only ``/uia/read`` route: a control's value (edit boxes, grid - cells) or name (labels, buttons), and the rows of a list or grid. + agent's read-only ``/uia/read`` route. Semantic values require independent + native extent/full-read agreement. Names, MSAA and clipped strings remain + explicit previews; row inventories are unavailable until qualified. - :class:`PixelReadSurface` reads the screen pixels with OCR. It is the path for RDP, Citrix, and any application without an accessibility tree. A value is the text on the same line right of its label, or on the next line below @@ -27,6 +28,10 @@ from contextlib import AbstractContextManager from typing import Any, Callable, Mapping, Optional +from openadapt_flow.backends.win_agent.value_protocol import ( + locator_scope, + valid_structural_value, +) from openadapt_flow.runtime.effects.desktop_readback import ( ControlRef, DesktopReadbackDriver, @@ -383,7 +388,9 @@ def _read_structural( return self._backend.read_structural(locator, rows=rows) @staticmethod - def _located(payload: Optional[dict], *, need_text: bool) -> Located: + def _located( + payload: Optional[dict], *, need_text: bool, scope: Mapping[str, Any] + ) -> Located: if payload is None: return Located("unavailable") match = payload.get("match") @@ -392,45 +399,49 @@ def _located(payload: Optional[dict], *, need_text: bool) -> Located: if match != "unique": return Located("ambiguous") text = payload.get("text") - if text is None and need_text: + if need_text and not valid_structural_value(payload, scope): # The control is there but exposes no value or name: unreadable, # never an empty value. return Located("unavailable") - point = payload.get("point") or [0, 0] + point = payload.get("point") + if ( + not isinstance(point, list) + or len(point) != 2 + or any(type(v) is not int for v in point) + ): + return Located("unavailable") return Located( "ok", - Seen(text=_collapse(text or ""), point=(int(point[0]), int(point[1]))), + Seen( + text=text if isinstance(text, str) else "", + point=(int(point[0]), int(point[1])), + ), ) def locate(self, ref: ControlRef) -> Located: if not ref.structured: return super().locate(ref) - return self._located(self._read_structural(ref), need_text=False) + return self._located( + self._read_structural(ref), + need_text=False, + scope=locator_scope(ref.model_dump()), + ) def read(self, ref: ControlRef) -> Located: if not ref.structured: return super().read(ref) - return self._located(self._read_structural(ref), need_text=True) + return self._located( + self._read_structural(ref), + need_text=True, + scope=locator_scope(ref.model_dump()), + ) def rows(self, ref: ControlRef) -> Optional[list[Seen]]: if not ref.structured: return super().rows(ref) - payload = self._read_structural(ref, rows=True) - if payload is None or payload.get("match") != "unique": - return None - if payload.get("rows_truncated"): - return None - return [ - Seen( - text=_collapse(item["text"]), - point=(item["point"][0], item["point"][1]), - parts=tuple( - (_collapse(cell["text"]), (cell["point"][0], cell["point"][1])) - for cell in item.get("cells") or [] - ), - ) - for item in payload.get("rows") or [] - ] + # Declared structural rows have no qualified native leaf/composite + # inventory source yet. Never downgrade them to preview strings/OCR. + return None class BackendSessionDriver: diff --git a/packages/flow/tests/e2e/test_windows_approval_completeness.py b/packages/flow/tests/e2e/test_windows_approval_completeness.py index a25942707c..3a922b8001 100644 --- a/packages/flow/tests/e2e/test_windows_approval_completeness.py +++ b/packages/flow/tests/e2e/test_windows_approval_completeness.py @@ -12,6 +12,7 @@ import io import json import os +import subprocess import time from pathlib import Path @@ -24,7 +25,12 @@ from openadapt_flow.approval_mode.item_approval import ItemApprovalStore from openadapt_flow.backends.win_agent import server from openadapt_flow.backends.win_agent.native_value import valid_value_proof -from openadapt_flow.ir import ActionKind, Step, StepResult, Workflow +from openadapt_flow.ir import ActionKind, Step, StepResult, StructuralLocator, Workflow +from openadapt_flow.runtime.effects.desktop_readback import ( + ControlRef, + DesktopSessionFacts, +) +from openadapt_flow.runtime.effects.desktop_readback_sessions import UiaReadSurface from tests.e2e.test_windows_hosted_replay import RUN_E2E, _Host pytestmark = [ @@ -123,6 +129,31 @@ def test_native_approval_completeness_refuses_a_provider_prefix(tmp_path, monkey "phases": [], "transport": [], } + repository = Path(__file__).resolve().parents[4] + evidence["actual_checkout_commit"] = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=repository, text=True + ).strip() + evidence["actual_checkout_tree"] = subprocess.check_output( + ["git", "rev-parse", "HEAD^{tree}"], cwd=repository, text=True + ).strip() + evidence["declared_pr_or_dispatch_head"] = os.environ.get( + "OAFLOW_NATIVE_APPROVAL_SOURCE_HEAD" + ) + critical = ( + "packages/flow/openadapt_flow/backends/win_agent/native_value.py", + "packages/flow/openadapt_flow/backends/win_agent/value_protocol.py", + "packages/flow/openadapt_flow/backends/win_agent/server.py", + "packages/flow/openadapt_flow/backends/windows_backend.py", + "packages/flow/openadapt_flow/approval_mode/form_state.py", + "packages/flow/openadapt_flow/approval_mode/window_fields.py", + "packages/flow/openadapt_flow/runtime/effects/desktop_readback_sessions.py", + "packages/flow/openadapt_flow/runtime/effects/desktop_readback.py", + ".github/workflows/desktop-replay.yml", + ) + evidence["source_sha256"] = { + name: hashlib.sha256((repository / name).read_bytes()).hexdigest() + for name in critical + } host = _Host(tmp_path) fixture = tmp_path / "patient_notes.ps1" fixture.write_text( @@ -141,7 +172,7 @@ def post(url, **kwargs): if path in {"/input", "/input/guarded", "/uia/act", "/execute_windows"}: writes.append(path) response = original_post(url, **kwargs) - if path == "/window/form-fields": + if path in {"/window/form-fields", "/uia/read"}: evidence["transport"].append( { "path": path, @@ -235,6 +266,26 @@ def identity(): ) assert field["value_proof"]["utf16_units"] == stored["utf16_units"] assert field["value_proof"]["pid"] == stored["pid"] + semantic = backend.read_structural( + StructuralLocator(automation_id="approvalProbe") + ) + phase["structural"] = semantic + surface = UiaReadSurface( + backend, + facts=DesktopSessionFacts(True, False, False, "uia"), + settle_s=0, + ) + located = surface.read(ControlRef(automation_id="approvalProbe")) + phase["structural_located"] = located.status + assert semantic is not None + if name == "long": + assert semantic["complete"] is False and semantic["text"] is None + assert semantic["reason"] == "provider_native_value_disagreement" + assert located.status == "unavailable" and located.item is None + else: + assert semantic["complete"] is True and semantic["text"] == expected + assert located.status == "ok" and located.item is not None + assert located.item.text == expected frame = backend.screenshot() store = ItemApprovalStore(tmp_path / ("run-" + name)) gate = ApprovalGate("each_item", approval_store=store, approval_wait_s=0) diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index f17a8b3578..0895d40071 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -451,6 +451,8 @@ def __init__( self.NativeWindowHandle = _Control.next_hwnd _Control.next_hwnd += 1 self.ProcessId = 10 + self.AutomationId = "" + self.ClassName = "SyntheticNativeControl" self.parent = None self.native_override = None self.IsPassword = password diff --git a/packages/flow/tests/test_desktop_readback.py b/packages/flow/tests/test_desktop_readback.py index 52e137f28e..fef004d1ed 100644 --- a/packages/flow/tests/test_desktop_readback.py +++ b/packages/flow/tests/test_desktop_readback.py @@ -250,7 +250,9 @@ def _note_equals(value: str) -> Effect: ) -def test_winforms_save_is_confirmed_by_looking_the_patient_up(winforms: Any) -> None: +def test_winforms_without_native_completeness_cannot_confirm_saved_state( + winforms: Any, +) -> None: verifier = _winforms_verifier(winforms, NEIL) # Without its own sign-in, a separate window re-reads saved state. assert ( @@ -259,41 +261,47 @@ def test_winforms_save_is_confirmed_by_looking_the_patient_up(winforms: Any) -> assert verifier.independent_system_of_record is False before = verifier.capture_pre_state() - assert before.reachable - assert before.records == [{"note": "", "patient": "Neil Sorenson"}] + # This faithful legacy stand-in has HWND0 and Name-only labels/virtual + # rows, so it cannot invent independent native completeness evidence. + assert not before.reachable and before.records == [] - winforms.save_note(1, "Follow up in two weeks") # the run's save + winforms.save_note(1, "Follow up in two weeks") # fixture setup, not verifier input + stored = winforms.all_patients() verdict = verifier.verify(_note_equals("Follow up in two weeks"), before) - assert verdict.verdict is Verdict.CONFIRMED, verdict.reason - assert verdict.assurance == "screen_readback" - # The read-back typed the surname, pressed Search, opened Neil Sorenson. - # It never pressed Save Note and never touched the note. + assert verdict.verdict is Verdict.INDETERMINATE, verdict.reason + assert verdict.unavailable and verdict.assurance == "unchecked" + assert winforms.all_patients() == stored + # Declared complete-source effect semantics have separate positive tests. + # An unqualified preview cannot certify either a match or a mismatch. assert winforms.saves == 0 assert set(winforms.clicked) <= {"searchBox", "searchButton", "Row 0", "Row 1"} assert "saveButton" not in winforms.clicked assert winforms.all_patients()[0]["note"] == "Follow up in two weeks" -def test_winforms_wrong_note_is_refuted_through_ui_automation(winforms: Any) -> None: +def test_winforms_without_complete_values_does_not_refute_from_previews( + winforms: Any, +) -> None: verifier = _winforms_verifier(winforms, NEIL) before = verifier.capture_pre_state() winforms.save_note(1, "Follow up in three weeks") verdict = verifier.verify(_note_equals("Follow up in two weeks"), before) - assert verdict.verdict is Verdict.REFUTED - assert "record view" in verdict.reason - assert "system of record" not in verdict.reason + assert verdict.verdict is Verdict.INDETERMINATE and verdict.unavailable + assert "cannot certify" in verdict.reason + assert winforms.saves == 0 -def test_winforms_decoy_with_the_same_first_name_is_not_opened(winforms: Any) -> None: - # Searching "Neil" lists Neil Anderson above Neil Sorenson. Only the row - # showing the full identity is opened. +def test_unqualified_value_source_does_not_choose_a_row(winforms: Any) -> None: + # No row may be chosen before the field and inventory sources qualify. + # The complete-source ambiguity branch has a separate unit control. verifier = _winforms_verifier( winforms, {"patient_last": "Neil", "patient": "Neil Sorenson"} ) before = verifier.capture_pre_state() winforms.save_note(1, "Seen today") verdict = verifier.verify(_note_equals("Seen today"), before) - assert verdict.verdict is Verdict.CONFIRMED, verdict.reason + assert verdict.verdict is Verdict.INDETERMINATE and verdict.unavailable + assert winforms.saves == 0 and "saveButton" not in winforms.clicked def test_winforms_two_matching_rows_is_indeterminate(winforms: Any) -> None: @@ -309,11 +317,11 @@ def test_winforms_two_matching_rows_is_indeterminate(winforms: Any) -> None: verifier.capture_pre_state(), ) assert verdict.verdict is Verdict.INDETERMINATE - assert "2 search results" in verdict.reason + assert verdict.unavailable and "cannot certify" in verdict.reason assert winforms.saves == 0 -def test_winforms_search_button_declared_as_save_is_refused(winforms: Any) -> None: +def test_unqualified_lookup_never_reaches_a_declared_save_target(winforms: Any) -> None: verifier = _winforms_verifier( winforms, NEIL, @@ -325,7 +333,7 @@ def test_winforms_search_button_declared_as_save_is_refused(winforms: Any) -> No ) verdict = verifier.verify(_note_equals("x"), verifier.capture_pre_state()) assert verdict.verdict is Verdict.INDETERMINATE - assert "save-like" in verdict.reason + assert verdict.unavailable and "cannot certify" in verdict.reason assert winforms.saves == 0 @@ -406,7 +414,7 @@ def _booked(field: str = "visit_type", value: str = "follow-up") -> Effect: ) -def test_kiosk_booking_is_confirmed_from_its_own_rdp_session( +def test_kiosk_without_complete_marker_transition_remains_indeterminate( kiosk: KioskLookupTransport, ) -> None: verifier = _kiosk_verifier(kiosk, "REQ-4815") @@ -414,27 +422,32 @@ def test_kiosk_booking_is_confirmed_from_its_own_rdp_session( assert verifier_effect_tier(verifier) is VerificationTier.INDEPENDENT_SESSION before = verifier.capture_pre_state() - assert before.reachable - assert before.records == [] # the kiosk says "No appointment found" + assert not before.reachable + assert before.records == [] # unreachable, not proof of record absence kiosk.book("REQ-4815", "MRN A1001", "Ada Lovelace", "2026-11-02 09:30", "Follow-up") + stored = kiosk.db_path.read_bytes() verdict = verifier.verify(_booked(), before) - assert verdict.verdict is Verdict.CONFIRMED, verdict.reason - assert verifier.verify(_booked("patient_mrn", "MRN A1001"), before).confirmed - assert verdict.assurance == "screen_readback" + assert verdict.verdict is Verdict.INDETERMINATE and verdict.unavailable + assert not verifier.verify(_booked("patient_mrn", "MRN A1001"), before).confirmed + assert verdict.assurance == "unchecked" + assert kiosk.db_path.read_bytes() == stored # Only the look-up box and Find were touched. assert kiosk.sessions assert all(screen.save_clicks == 0 for screen in kiosk.sessions) assert all(screen.booking_typed == "" for screen in kiosk.sessions) -def test_kiosk_ocr_mismatch_is_never_refuted(kiosk: KioskLookupTransport) -> None: +def test_unqualified_marker_prevents_classifying_an_ocr_mismatch( + kiosk: KioskLookupTransport, +) -> None: verifier = _kiosk_verifier(kiosk, "REQ-4815") before = verifier.capture_pre_state() kiosk.book("REQ-4815", "MRN A1001", "Ada Lovelace", "2026-11-02 09:30", "Intake") verdict = verifier.verify(_booked(), before) assert verdict.verdict is Verdict.INDETERMINATE - assert "OCR can misread" in verdict.reason + assert verdict.unavailable and "cannot certify" in verdict.reason + # The complete-marker + OCR-mismatch policy is covered separately. def test_kiosk_count_check_without_a_results_list_halts( @@ -745,7 +758,7 @@ def test_app_sign_in_needs_a_network_rdp_session() -> None: ) -def test_a_ui_automation_marker_without_text_counts_when_present() -> None: +def test_an_unavailable_ui_automation_marker_cannot_become_presence() -> None: from openadapt_flow.runtime.effects.desktop_readback import _present class Panel(_ScriptedSurface): @@ -755,10 +768,10 @@ def read(self, ref: ControlRef) -> Located: return super().read(ref) surface = Panel({"recordPanel": "", "statusLabel": ""}) - assert _present(surface, ControlRef(automation_id="recordPanel")) - assert not _present(surface, ControlRef(automation_id="otherPanel")) - # A control that reads as empty (a label still filling in) is absent. - assert not _present(surface, ControlRef(automation_id="statusLabel")) + assert _present(surface, ControlRef(automation_id="recordPanel")) is None + assert _present(surface, ControlRef(automation_id="otherPanel")) is None + # A complete empty value does not prove that an element is absent. + assert _present(surface, ControlRef(automation_id="statusLabel")) is None def test_result_rows_are_data_and_sign_in_ok_is_allowed() -> None: @@ -884,11 +897,11 @@ def test_the_row_click_aims_at_the_identifier() -> None: assert _identity_piece(cells, "Neil Sorenson").point == (200, 200) -def test_a_later_unreadable_look_up_never_replaces_a_readable_verdict( +def test_unqualified_source_cannot_supply_a_first_readable_verdict( winforms: Any, ) -> None: - # Persistent seat: poll 1 reads a wrong note (REFUTED); poll 2 sees the - # same view and can't read it as fresh. The REFUTED stands. + # No first readable verdict exists when the native source is incomplete. + # The complete-then-unavailable polling contract is tested separately. verifier = _winforms_verifier(winforms, NEIL) before = verifier.capture_pre_state() winforms.save_note(1, "Follow up in three weeks") @@ -896,7 +909,8 @@ def test_a_later_unreadable_look_up_never_replaces_a_readable_verdict( update={"timeout_s": 2.0} ) verdict = verifier.verify(effect, before) - assert verdict.verdict is Verdict.REFUTED + assert verdict.verdict is Verdict.INDETERMINATE and verdict.unavailable + assert winforms.saves == 0 # -- the same look-up through a Citrix window and a macOS window ----------------------- @@ -1009,8 +1023,10 @@ def open_backend(_u: str, _p: str) -> tuple[Any, DesktopSessionFacts]: assert ( verifier_effect_tier(verifier) is VerificationTier.PERSISTED_STATE_REACQUISITION ) + stored = kiosk.db_path.read_bytes() verdict = verifier.verify(_booked(), verifier.capture_pre_state()) - assert verdict.verdict is Verdict.CONFIRMED, verdict.reason + assert verdict.verdict is Verdict.INDETERMINATE and verdict.unavailable + assert kiosk.db_path.read_bytes() == stored assert all(s.save_clicks == 0 and s.booking_typed == "" for s in kiosk.sessions) @@ -1053,6 +1069,35 @@ def open_backend(_u: str, _p: str) -> tuple[Any, DesktopSessionFacts]: return backend, DesktopSessionFacts(True, False, False, "ocr") verifier = _window_verifier(open_backend, "macos") + stored = kiosk.db_path.read_bytes() verdict = verifier.verify(_booked(), verifier.capture_pre_state()) - assert verdict.verdict is Verdict.CONFIRMED, verdict.reason + assert verdict.verdict is Verdict.INDETERMINATE and verdict.unavailable + assert kiosk.db_path.read_bytes() == stored assert all(s.save_clicks == 0 and s.booking_typed == "" for s in kiosk.sessions) + + +def test_declared_row_ambiguity_and_save_guard_still_refuse_without_preview_authority(): + class Rows(_ScriptedSurface): + def rows(self, _ref): + return [Seen("Neil Sorenson", (1, 1)), Seen("Neil Sorenson", (2, 2))] + + target = resolve_desktop_spec(_winforms_spec(), NEIL) + rows = Rows({"searchBox": "Sorenson", "searchButton": "Search"}, under="Search") + raw = look_up(rows, target, ReadOnlyLookupGuard(target.spec)) + assert not raw.ok and "2 search results" in raw.reason + assert rows.actions == ["click Search"] + + spec = _winforms_spec( + search={ + "box": {"automation_id": "searchBox"}, + "query": "Sorenson", + "submit": {"automation_id": "saveButton"}, + } + ) + target = resolve_desktop_spec(spec, NEIL) + dangerous = _ScriptedSurface( + {"searchBox": "Sorenson", "saveButton": "Save Note"}, under="Save Note" + ) + with pytest.raises(ReadOnlyViolation, match="save-like"): + look_up(dangerous, target, ReadOnlyLookupGuard(spec)) + assert dangerous.actions == [] diff --git a/packages/flow/tests/test_structural_value_completeness.py b/packages/flow/tests/test_structural_value_completeness.py new file mode 100644 index 0000000000..c83247ce8c --- /dev/null +++ b/packages/flow/tests/test_structural_value_completeness.py @@ -0,0 +1,462 @@ +"""Native structural previews cannot become semantic values or effects.""" + +from __future__ import annotations + +from contextlib import contextmanager +from types import SimpleNamespace + +import pytest +from hypothesis import given +from hypothesis import strategies as st + +from openadapt_flow.backends.win_agent.value_protocol import ( + locator_scope, + valid_structural_value, +) +from openadapt_flow.backends.windows_backend import WindowsBackend +from openadapt_flow.ir import StructuralLocator +from openadapt_flow.runtime.effects import Effect, EffectKind, ValueExpr, Verdict +from openadapt_flow.runtime.effects.desktop_readback import ( + ControlRef, + DesktopReadbackSpec, + DesktopReadbackVerifier, + DesktopSessionFacts, + Located, + Seen, + resolve_desktop_spec, +) +from openadapt_flow.runtime.effects.desktop_readback_sessions import UiaReadSurface +from tests.test_approval_form_fields import _agent, _Control, _proof, _window + +SCOPE = locator_scope({"automation_id": "field"}) + + +def complete(value): + return { + "status": "ok", + "match": "unique", + "candidate_count": 1, + "point": [1, 2], + "text": value, + "complete": True, + "value_proof": _proof(value), + "value_identity": "a" * 64, + "read_scope": SCOPE, + "preview_text": value[:4096], + "reason": None, + } + + +def unavailable(preview="prefix"): + return { + **complete(""), + "text": None, + "complete": False, + "value_proof": None, + "value_identity": None, + "preview_text": preview, + "reason": "value_unavailable", + } + + +def client(payload): + backend = object.__new__(WindowsBackend) + backend._post_typed_read = lambda *_a, **_k: SimpleNamespace( + available=True, payload=payload + ) + return backend + + +def surface(payload): + return UiaReadSurface( + client(payload), facts=DesktopSessionFacts(True, True, False, "uia"), settle_s=0 + ) + + +@given(st.text(max_size=10000)) +def test_complete_wire_and_surface_retain_full_value_without_preview_clipping(value): + payload = complete(value) + backend = client(payload) + assert ( + backend.read_structural(StructuralLocator(automation_id="field"))["text"] + == value + ) + seen = surface(payload).read(ControlRef(automation_id="field")) + assert seen.status == "ok" and seen.item.text == value + + +@pytest.mark.parametrize( + "fault", + [ + "legacy", + "missing_proof", + "bad_hash", + "bad_extent", + "bad_identity", + "wrong_scope", + "bool_count", + "missing_point", + "extra", + "incomplete_text", + ], +) +def test_missing_mismatched_or_legacy_value_proof_cannot_create_seen(fault): + payload = complete("full value") + if fault == "legacy": + payload = { + key: payload[key] + for key in ("status", "match", "candidate_count", "point", "text") + } + elif fault == "missing_proof": + payload["value_proof"] = None + elif fault == "bad_hash": + payload["value_proof"]["sha256_utf16le"] = "0" * 64 + elif fault == "bad_extent": + payload["value_proof"]["utf16_units"] += 1 + elif fault == "bad_identity": + payload["value_identity"] = None + elif fault == "wrong_scope": + payload["read_scope"] = locator_scope({"automation_id": "other"}) + elif fault == "bool_count": + payload["candidate_count"] = True + elif fault == "missing_point": + payload["point"] = None + elif fault == "extra": + payload["unchecked"] = True + else: + payload = {**unavailable(), "text": "prefix"} + assert ( + client(payload).read_structural(StructuralLocator(automation_id="field")) + is None + ) + # Also enforce proof on a direct backend implementation bypassing the + # Windows wire client, rather than trusting a complete=True caller flag. + direct = SimpleNamespace(read_structural=lambda *_a, **_k: payload) + observed = UiaReadSurface( + direct, facts=DesktopSessionFacts(True, True, False, "uia"), settle_s=0 + ).read(ControlRef(automation_id="field")) + assert observed.status != "ok" and observed.item is None + + +@pytest.mark.parametrize("kind", ["EditControl", "DocumentControl", "TextControl"]) +def test_server_uses_full_shared_observation_and_separates_preview(monkeypatch, kind): + import sys + + control = _Control(kind, value="z" * 8196) + control.AutomationId = "field" + perform = _agent(monkeypatch, _window(control)) + sys.modules["uiautomation"].GetRootControl = lambda: control.parent + answer = perform("read", {"locator": {"automation_id": "field"}}) + assert valid_structural_value(answer, SCOPE) and answer["text"] == "z" * 8196 + assert len(answer["preview_text"]) == 4096 + control.native_override = "z" * 8196 + "different storage" + refused = perform("read", {"locator": {"automation_id": "field"}}) + assert refused["text"] is None and not refused["complete"] + assert ( + refused["value_proof"] is None + and refused["reason"] == "provider_native_value_disagreement" + ) + assert refused["preview_text"] == "z" * 4096 + + +@pytest.mark.parametrize( + "fault", + ["child_error", "depth_limit", "ambiguous", "name_only", "hidden_matching_bounds"], +) +def test_unqualified_scope_and_name_only_sources_never_become_values( + monkeypatch, fault +): + import sys + + import openadapt_flow.backends.win_agent.server as server + + control = _Control("EditControl", value="exact") + control.AutomationId = "field" + window = _window(control) + perform = _agent(monkeypatch, window) + sys.modules["uiautomation"].GetRootControl = lambda: window + if fault == "child_error": + control.GetChildren = lambda: (_ for _ in ()).throw(RuntimeError("unreadable")) + elif fault == "depth_limit": + monkeypatch.setattr(server, "_MAX_UIA_DEPTH", 0) + elif fault == "ambiguous": + other = _Control("EditControl", value="exact") + other.AutomationId = "field" + window._children.append(other) + elif fault == "name_only": + control._value = None + control.Name = "exact" + else: + other = _Control("EditControl", value="same locator but unreadable bounds") + other.AutomationId = "field" + other.BoundingRectangle = None + window._children.append(other) + answer = perform("read", {"locator": {"automation_id": "field"}}) + assert answer["text"] is None and answer["complete"] is False + + +def test_row_previews_cannot_authorize_inventory_even_when_empty(): + payload = { + **complete("value"), + "rows": None, + "rows_truncated": True, + "rows_complete": False, + "preview_rows": [], + } + assert ( + client(payload).read_structural( + StructuralLocator(automation_id="field"), rows=True + ) + is None + ) + direct = SimpleNamespace( + read_structural=lambda *_a, **_k: { + **payload, + "rows": [], + "rows_truncated": False, + } + ) + observed = UiaReadSurface( + direct, facts=DesktopSessionFacts(True, True, False, "uia"), settle_s=0 + ) + assert observed.rows(ControlRef(automation_id="field")) is None + + +@pytest.mark.parametrize( + "actual,expected,outcome,later_unavailable,ocr", + [ + ("short", "short", Verdict.CONFIRMED, False, False), + ("short", "other", Verdict.REFUTED, False, False), + ("p" * 8196, "p" * 8196, Verdict.CONFIRMED, False, False), + ("p" * 8196, "p" * 4096, Verdict.REFUTED, False, False), + ("value" + " " * 4100, "value", Verdict.REFUTED, False, False), + (" value\r\n", " value\r\n", Verdict.CONFIRMED, False, False), + (None, "p" * 4096, Verdict.INDETERMINATE, False, False), + ("short", "other", Verdict.REFUTED, True, False), + ("short", "other", Verdict.INDETERMINATE, False, True), + ], +) +def test_normal_effect_contract_requires_complete_value( + actual, expected, outcome, later_unavailable, ocr +): + # An ordinary declared-source unit fixture, with no server/SQL baseline + # replay and no native execution or system-of-record qualification claim. + field_surface = surface( + complete(actual) if actual is not None else unavailable("p" * 4096) + ) + spec = DesktopReadbackSpec.model_validate( + { + "session": {"kind": "windows"}, + "search": {"box": {"automation_id": "search"}, "query": "record"}, + "ready": {"automation_id": "ready", "shows": "Ready"}, + "identity": { + "reader": {"automation_id": "identity"}, + "value": "record", + "field": "id", + }, + "fields": { + "field": { + "control": {"text": "Field", "at": "right"} + if ocr + else {"automation_id": "field"} + } + }, + "navigation_timeout_s": 0.1, + "settle_s": 0, + } + ) + + class DeclaredSurface: + facts = DesktopSessionFacts(True, True, False, "uia") + entered = False + + def __init__(self, source): + self.source = source + + def read(self, ref): + if ref.automation_id == "field" or ref.text == "Field": + if ocr: + return Located( + "ok", Seen(actual, (1, 2), ocr=True, confidence=0.95) + ) + return self.source.read(ref) + if ref.automation_id == "ready": + return Located( + "ok", Seen("Ready" if self.entered else "Loading", (1, 2)) + ) + return Located("ok", Seen("record", (1, 2))) + + locate = read + + def press_enter(self): + self.entered = True + + def settle(self): + pass + + def text_at(self, _): + return "record" + + class Driver: + opens = 0 + + @contextmanager + def open(self, *_): + self.opens += 1 + source = ( + surface(unavailable()) + if later_unavailable and self.opens > 2 + else field_surface + ) + yield DeclaredSurface(source) + + driver = Driver() + verifier = DesktopReadbackVerifier( + resolve_desktop_spec(spec), driver=driver, poll_interval_s=0.01 + ) + before = verifier.capture_pre_state() + effect = Effect( + kind=EffectKind.FIELD_EQUALS, + match={"id": ValueExpr(literal="record")}, + field="field", + value=ValueExpr(literal=expected), + timeout_s=0.2 if later_unavailable else 0, + ) + verdict = verifier.verify(effect, before) + assert verdict.verdict is outcome + if ocr: + assert "OCR can misread" in verdict.reason + if later_unavailable: + assert driver.opens > 2 + + +def test_incomplete_native_marker_cannot_prove_ready_or_record_absence(): + from openadapt_flow.runtime.effects.desktop_readback import _present + + source = surface(unavailable("Visible marker preview")) + marker = ControlRef(automation_id="field") + assert source.locate(marker).status == "ok" + assert source.read(marker).status == "unavailable" + assert _present(source, marker) is None + assert _present(surface(complete("Ready")), marker) is True + assert _present(surface(complete("")), marker) is None + explicit = ControlRef(automation_id="field", shows="Ready") + assert _present(surface(complete("Loading")), explicit) is False + assert _present(surface(unavailable("Loading")), explicit) is None + + +@pytest.mark.parametrize( + "marker,before,after,expected_ok,expected_not_found", + [ + ("ready", None, "Ready", False, False), + ("ready", "Loading", "Ready", True, False), + ("not_found", None, "No record", False, False), + ("not_found", "Waiting", "No record", True, True), + ], +) +def test_unknown_positive_and_negative_markers_do_not_supply_absence( + marker, + before, + after, + expected_ok, + expected_not_found, +): + from openadapt_flow.runtime.effects.desktop_readback import ( + ReadOnlyLookupGuard, + look_up, + ) + + spec = DesktopReadbackSpec.model_validate( + { + "session": {"kind": "windows"}, + "search": {"box": {"automation_id": "search"}, "query": "record"}, + "ready": {"automation_id": "ready", "shows": "Ready"}, + "not_found": {"automation_id": "not_found", "shows": "No record"} + if marker == "not_found" + else None, + "identity": { + "reader": {"automation_id": "identity"}, + "value": "record", + "field": "id", + }, + "fields": {"field": {"control": {"automation_id": "field"}}}, + "navigation_timeout_s": 0.01, + "settle_s": 0, + } + ) + + class Markers: + entered = False + + def read(self, ref): + if ref.automation_id == marker: + value = after if self.entered else before + payload = complete(value) if value is not None else unavailable() + payload["read_scope"] = locator_scope({"automation_id": marker}) + return surface(payload).read(ref) + if ref.automation_id in {"ready", "not_found"}: + return Located("unavailable") + return Located( + "ok", + Seen("record" if ref.automation_id != "field" else "value", (1, 2)), + ) + + locate = read + + def press_enter(self): + self.entered = True + + def settle(self): + pass + + def text_at(self, _): + return "record" + + target = resolve_desktop_spec(spec) + raw = look_up(Markers(), target, ReadOnlyLookupGuard(spec)) + assert raw.ok is expected_ok and raw.not_found is expected_not_found + + +def test_ocr_mismatch_and_missing_native_marker_remain_unknown(): + from openadapt_flow.runtime.effects.desktop_readback import _present + + marker = ControlRef(automation_id="field", shows="Ready") + + class Source: + def read(self, _): + return Located("ok", Seen("Loading", (1, 2), ocr=True)) + + assert _present(Source(), marker) is None + missing = { + **unavailable(), + "match": "not_found", + "candidate_count": 0, + "point": None, + } + assert _present(surface(missing), marker) is None + + +def test_explicit_native_transforms_do_not_imply_whitespace_loss(): + from openadapt_flow.runtime.effects.desktop_readback import ( + DesktopFieldReader, + _desktop_effect, + _exact_value, + ) + + reference = ControlRef(automation_id="field") + exact = DesktopFieldReader(control=reference) + assert _exact_value(" Value\r\n", exact) == (" Value\r\n", True) + folded = DesktopFieldReader(control=reference, casefold=True) + assert _exact_value(" A B ", folded) == (" a b ", True) + dated = DesktopFieldReader(control=reference, date_format="%d/%m/%Y") + observed, parsed = _exact_value("20/11/2026", dated) + effect = Effect( + kind=EffectKind.FIELD_EQUALS, + match={"id": ValueExpr(literal="record")}, + field="field", + value=ValueExpr(literal="2026-11-20"), + ) + transformed = _desktop_effect(effect, {"field": dated}, set()) + assert parsed and observed == transformed.value.literal == "2026-11-20" + assert effect.value.literal == "2026-11-20" + assert _exact_value("invalid", dated)[1] is False From f9cac7f470a7333ddb62088ec6e9fba30229c6ad Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 01:08:23 -0500 Subject: [PATCH 13/34] Guard every native value read with current sensitive status --- .../backends/win_agent/native_value.py | 38 +++++- .../tests/test_native_value_completeness.py | 124 ++++++++++++++++-- 2 files changed, 144 insertions(+), 18 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 8d75201a2a..a3c20c40d2 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -15,7 +15,7 @@ from typing import Any, Callable, Protocol MAX_UTF16_UNITS = 65536 -PROOF_SCHEMA = "openadapt.native-value-completeness/v1" +PROOF_SCHEMA = "openadapt.native-value-completeness/v2" def utf16_bytes(value: str) -> bytes: @@ -67,7 +67,7 @@ class CompleteValue: class NativeTextReader(Protocol): def owner(self, hwnd: int) -> NativeOwner: ... - def read(self, owner: NativeOwner) -> NativeRead: ... + def read(self, owner: NativeOwner, *, guard: Callable[[], None]) -> NativeRead: ... class Win32TextReader: @@ -128,10 +128,13 @@ def _message( raise ValueUnavailable("native_text_timeout_or_failure") return int(result.value) - def read(self, owner: NativeOwner) -> NativeRead: + def read(self, owner: NativeOwner, *, guard: Callable[[], None]) -> NativeRead: def unchanged() -> None: if self.owner(owner.hwnd) != owner: raise ValueUnavailable("native_owner_changed") + # Extent and full-text messages are separate provider calls. + # Recheck sensitivity after ownership and before each message. + guard() unchanged() extent = self._message(owner.hwnd, 0x000E) @@ -171,6 +174,22 @@ def _identity(control: Any) -> tuple[int, int, tuple[int, ...]]: return hwnd, pid, tuple(runtime) +def require_non_sensitive_value(control: Any) -> None: + """Refuse text access unless the current password status is exactly False. + + Missing, exceptional and non-boolean states do not authorize a getter. + All value, capability and preview consumers share this rule. Call again + after any provider call and immediately before each text getter; a prior + result or negotiated protocol version is never authority for a later read. + """ + try: + allowed = control.IsPassword is False + except Exception: + allowed = False + if not allowed: + raise ValueUnavailable("password_or_password_status_unavailable") + + def observe_complete_value( control: Any, *, @@ -187,6 +206,7 @@ def observe_complete_value( around every source read. It never upgrades either disagreeing source. """ try: + require_non_sensitive_value(control) deadline = clock() + 5.0 binding = identity() if not isinstance(binding, str) or not 1 <= len(binding) <= 256: @@ -210,8 +230,7 @@ def guard() -> None: or reader.owner(bound[0]) != owner ): raise ValueUnavailable("value_identity_changed") - if getattr(control, "IsPassword", None) is not False: - raise ValueUnavailable("password_or_password_status_unavailable") + require_non_sensitive_value(control) if ( require_editable and getattr(control, "ControlTypeName", None) != "EditControl" @@ -220,11 +239,16 @@ def guard() -> None: def uia() -> str: guard() - pattern = control.GetValuePattern() + method = control.GetValuePattern + guard() + pattern = method() + guard() read_only = getattr(pattern, "IsReadOnly", None) + guard() if type(read_only) is not bool or (require_editable and read_only): raise ValueUnavailable("read_only_or_read_only_status_unavailable") 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: @@ -236,7 +260,7 @@ def uia() -> str: def native() -> NativeRead: guard() - result = reader.read(owner) + result = reader.read(owner, guard=guard) guard() units = len(utf16_bytes(result.value)) // 2 if not 0 <= result.extent <= MAX_UTF16_UNITS: diff --git a/packages/flow/tests/test_native_value_completeness.py b/packages/flow/tests/test_native_value_completeness.py index 9a53ef4ea6..e907308767 100644 --- a/packages/flow/tests/test_native_value_completeness.py +++ b/packages/flow/tests/test_native_value_completeness.py @@ -11,11 +11,13 @@ from hypothesis import strategies as st from openadapt_flow.backends.win_agent.native_value import ( + PROOF_SCHEMA, NativeOwner, NativeRead, ValueUnavailable, Win32TextReader, observe_complete_value, + require_non_sensitive_value, utf16_bytes, valid_value_proof, ) @@ -47,7 +49,8 @@ def owner(self, hwnd): assert hwnd == OWNER.hwnd return self.owner_value - def read(self, owner): + def read(self, owner, *, guard): + guard() self.reads += 1 units = len(utf16_bytes(self.value)) // 2 return NativeRead(owner, units, units, self.value) @@ -138,7 +141,7 @@ def test_missing_or_unstable_completeness_evidence_is_explicitly_unavailable(fau reader.owner_value = replace(OWNER, pid=999) elif fault == "timeout": - def timeout(owner): + def timeout(owner, *, guard): raise ValueUnavailable("native_text_timeout_or_failure") reader.read = timeout @@ -147,9 +150,9 @@ def timeout(owner): elif fault == "unstable_native": original = reader.read - def changing(owner): + def changing(owner, *, guard): reader.value += "x" - return original(owner) + return original(owner, guard=guard) reader.read = changing elif fault == "unstable_provider": @@ -170,9 +173,9 @@ def Value(self): elif fault == "replaced_identity": original = reader.read - def replacing(owner): + def replacing(owner, *, guard): target.GetRuntimeId = lambda: [9, 9] - return original(owner) + return original(owner, guard=guard) reader.read = replacing elif fault == "scope_changed": @@ -182,13 +185,13 @@ def replacing(owner): times = iter([0.0, 6.0]) kwargs["clock"] = lambda: next(times, 6.0) elif fault == "bad_copy": - reader.read = lambda owner: NativeRead(owner, 5, 4, "exact") + reader.read = lambda owner, *, guard: NativeRead(owner, 5, 4, "exact") elif fault == "owner_changed": original = reader.read - def replace_owner(owner): + def replace_owner(owner, *, guard): reader.owner_value = replace(OWNER, thread=999) - return original(owner) + return original(owner, guard=guard) reader.read = replace_owner result = observe_complete_value( @@ -287,7 +290,7 @@ def protocol_reader(value): @pytest.mark.parametrize("value", ["", "é𝄞 \n", "x" * 8192 + "-END"]) def test_actual_native_message_protocol_uses_exact_utf16_buffer_and_counts(value): reader, user = protocol_reader(value) - result = reader.read(OWNER) + result = reader.read(OWNER, guard=lambda: None) assert result.value == value and result.extent == len(utf16_bytes(value)) // 2 assert [entry[0] for entry in user.calls] == [0xE, 0xD] @@ -321,7 +324,7 @@ def test_native_protocol_never_promotes_timeout_owner_change_or_incomplete_copy( elif fault == "ansi": user.unicode = False with pytest.raises(ValueUnavailable, match=reason): - reader.read(OWNER) + reader.read(OWNER, guard=lambda: None) if fault in {"timeout", "oversize", "replace", "ansi"}: assert 0xD not in [entry[0] for entry in user.calls] @@ -346,3 +349,102 @@ def test_provider_without_a_native_extent_or_with_a_mutable_scope_is_incomplete( proof = result.proof.payload() del proof["native_reads"] assert not valid_value_proof("exact", proof) + + +@pytest.mark.parametrize("status", [True, None, 0, 1, "false", "error"]) +def test_shared_sensitive_guard_refuses_before_any_source_or_capability_getter(status): + class Target: + calls = [] + + @property + def IsPassword(self): + if status == "error": + raise RuntimeError("status unavailable") + return status + + def __getattr__(self, name): + self.calls.append(name) + raise AssertionError("no source or capability access is allowed") + + target = Target() + with pytest.raises( + ValueUnavailable, match="password_or_password_status_unavailable" + ): + require_non_sensitive_value(target) + result = observe_complete_value( + target, identity=lambda: "bound", native_reader=Reader() + ) + assert ( + not result.complete + and result.reason == "password_or_password_status_unavailable" + ) + assert target.calls == [] + + +@pytest.mark.parametrize("stage", ["pattern_lookup", "pattern_call", "readability"]) +@pytest.mark.parametrize("status", [True, None]) +def test_status_changes_during_capability_calls_never_reach_value_getter(stage, status): + target, _ = control("exact") + calls = [] + + class Pattern: + @property + def IsReadOnly(self): + calls.append("readability") + if stage == "readability": + target.IsPassword = status + return False + + @property + def Value(self): + calls.append("value") + raise AssertionError("sensitive getter must not be called") + + def factory(): + calls.append("pattern_call") + if stage == "pattern_call": + target.IsPassword = status + return Pattern() + + class Target(type(target)): + @property + def GetValuePattern(self): + calls.append("pattern_lookup") + if stage == "pattern_lookup": + self.IsPassword = status + return factory + + target = Target(**{k: v for k, v in vars(target).items() if k != "GetValuePattern"}) + result = observe(target, Reader("exact")) + assert not result.complete and result.value is None + assert result.reason == "password_or_password_status_unavailable" + assert "value" not in calls + if stage == "pattern_lookup": + assert "pattern_call" not in calls + + +def test_native_extent_status_change_refuses_before_full_text_message(): + target, _ = control("exact") + reader, user = protocol_reader("exact") + original = user.SendMessageTimeoutW + + def message(*args): + result = original(*args) + if args[1] == 0xE: + target.IsPassword = True + return result + + user.SendMessageTimeoutW = message + result = observe(target, reader) + assert not result.complete and result.value is None + assert result.reason == "password_or_password_status_unavailable" + assert [call[0] for call in user.calls] == [0xE] + + +def test_previous_proof_version_is_not_compatible_with_pre_read_sensitive_guard(): + target, _ = control("exact") + result = observe(target, Reader("exact")) + assert result.complete and result.proof.schema == PROOF_SCHEMA + proof = result.proof.payload() + proof["schema"] = "openadapt.native-value-completeness/v1" + assert not valid_value_proof("exact", proof) From 7f65509068feb035236dd1d8a78db4daa5038e69 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 01:13:27 -0500 Subject: [PATCH 14/34] Check sensitivity after all provider metadata in value guards --- .../backends/win_agent/native_value.py | 4 +- .../tests/test_native_value_completeness.py | 44 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) 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 a3c20c40d2..db0b8f5a9a 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -230,12 +230,14 @@ def guard() -> None: or reader.owner(bound[0]) != owner ): raise ValueUnavailable("value_identity_changed") - require_non_sensitive_value(control) if ( require_editable and getattr(control, "ControlTypeName", None) != "EditControl" ): raise ValueUnavailable("not_editable_value_control") + # This MUST be last: any preceding provider metadata/identity + # getter can change the sensitive status before the next access. + require_non_sensitive_value(control) def uia() -> str: guard() diff --git a/packages/flow/tests/test_native_value_completeness.py b/packages/flow/tests/test_native_value_completeness.py index e907308767..4f242b6333 100644 --- a/packages/flow/tests/test_native_value_completeness.py +++ b/packages/flow/tests/test_native_value_completeness.py @@ -448,3 +448,47 @@ def test_previous_proof_version_is_not_compatible_with_pre_read_sensitive_guard( proof = result.proof.payload() proof["schema"] = "openadapt.native-value-completeness/v1" assert not valid_value_proof("exact", proof) + + +@pytest.mark.parametrize("stage", ["extent", "full", "value"]) +@pytest.mark.parametrize("status", [True, None]) +def test_editability_metadata_cannot_invalidate_final_sensitive_guard(stage, status): + class Target(SimpleNamespace): + armed = False + + @property + def ControlTypeName(self): + if self.armed: + self.IsPassword = status + return "EditControl" + + base, _ = control("") + target = Target(**{k: v for k, v in vars(base).items() if k != "ControlTypeName"}) + accesses = [] + + class StagedReader(Reader): + def read(self, owner, *, guard): + target.armed = stage == "extent" + guard() + accesses.append("extent") + target.armed = stage == "full" + guard() + accesses.append("full") + return NativeRead(owner, 0, 0, "") + + class Pattern: + @property + def IsReadOnly(self): + target.armed = stage == "value" + return False + + @property + def Value(self): + accesses.append("value") + return "" + + target.GetValuePattern = Pattern + result = observe(target, StagedReader(), require_editable=True) + assert not result.complete and result.value is None + assert result.reason == "password_or_password_status_unavailable" + assert stage not in accesses From 87d29b31b81131d591a8033ceac84e533f68264b Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 01:20:36 -0500 Subject: [PATCH 15/34] Negotiate native value reads before guarded previews and probes --- .github/workflows/desktop-replay.yml | 2 + .../backends/win_agent/server.py | 323 ++++++++++++------ .../backends/windows_backend.py | 10 +- .../flow/tests/test_approval_form_fields.py | 18 +- .../flow/tests/test_native_sensitive_reads.py | 254 ++++++++++++++ .../test_structural_value_completeness.py | 57 ++++ 6 files changed, 551 insertions(+), 113 deletions(-) create mode 100644 packages/flow/tests/test_native_sensitive_reads.py diff --git a/.github/workflows/desktop-replay.yml b/.github/workflows/desktop-replay.yml index ce54dde889..2c2fa0f812 100644 --- a/.github/workflows/desktop-replay.yml +++ b/.github/workflows/desktop-replay.yml @@ -39,6 +39,7 @@ on: - packages/flow/tests/test_approval_form_fields.py - packages/flow/tests/test_approval_value_completeness.py - packages/flow/tests/test_native_value_completeness.py + - packages/flow/tests/test_native_sensitive_reads.py - packages/flow/tests/test_native_value_deployment.py - packages/flow/tests/test_structural_value_completeness.py - packages/flow/tests/test_desktop_readback.py @@ -99,6 +100,7 @@ jobs: pytest -v -rs -p no:cacheprovider tests/test_windows_attempt_ledger.py \ tests/test_approval_form_window.py tests/test_approval_form_fields.py \ tests/test_binary_file_descriptors.py tests/test_native_value_completeness.py \ + tests/test_native_sensitive_reads.py \ tests/test_approval_value_completeness.py tests/test_native_value_deployment.py \ tests/test_structural_value_completeness.py tests/test_desktop_readback.py \ --junitxml=runs/windows-guards-junit.xml diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 082dd0f06c..d0ef7ad1e0 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -537,35 +537,43 @@ def _control_value(control: object, attr: str, default: object = "") -> object: return default -def _parent(control: object) -> Optional[object]: - method = _control_value(control, "GetParentControl", None) +def _parent( + control: object, *, get: Callable[..., Any] = _control_value +) -> Optional[object]: + method = get(control, "GetParentControl", None) try: return method() if callable(method) else None except Exception: # noqa: BLE001 return None -def _window_name(control: object) -> Optional[str]: +def _window_name( + control: object, *, get: Callable[..., Any] = _control_value +) -> Optional[str]: node: Optional[object] = control for _ in range(_MAX_UIA_DEPTH): - if str(_control_value(node, "ControlTypeName", "")) == "WindowControl": - value = " ".join(str(_control_value(node, "Name", "") or "").split()) + if str(get(node, "ControlTypeName", "")) == "WindowControl": + value = " ".join(str(get(node, "Name", "") or "").split()) return value or None - node = _parent(node) + node = _parent(node, get=get) if node is None: break return None -def _role(control: object) -> Optional[str]: - control_type = str(_control_value(control, "ControlTypeName", "")) +def _role( + control: object, *, get: Callable[..., Any] = _control_value +) -> Optional[str]: + control_type = str(get(control, "ControlTypeName", "")) if control_type == "SplitButtonControl": return "button" return _CONTROL_TO_ROLE.get(control_type) -def _bounds(control: object) -> Optional[list[int]]: - rect: Any = _control_value(control, "BoundingRectangle", None) +def _bounds( + control: object, *, get: Callable[..., Any] = _control_value +) -> Optional[list[int]]: + rect: Any = get(control, "BoundingRectangle", None) try: if rect is None or rect.right <= rect.left or rect.bottom <= rect.top: return None @@ -597,17 +605,19 @@ def _centered_on(control: object, x: int, y: int) -> bool: ) -def _locator_from_control(control: object) -> Optional[dict[str, Any]]: - automation_id = str(_control_value(control, "AutomationId", "") or "") or None - name = " ".join(str(_control_value(control, "Name", "") or "").split()) or None - role = _role(control) +def _locator_from_control( + control: object, *, get: Callable[..., Any] = _control_value +) -> Optional[dict[str, Any]]: + automation_id = str(get(control, "AutomationId", "") or "") or None + name = " ".join(str(get(control, "Name", "") or "").split()) or None + role = _role(control, get=get) if not automation_id and not (role and name): return None return { "automation_id": automation_id, "role": role, "name": name, - "window_name": _window_name(control), + "window_name": _window_name(control, get=get), } @@ -876,9 +886,11 @@ def _locator_payload(value: object) -> dict[str, Any]: return out -def _runtime_id(control: object) -> list[int]: +def _runtime_id( + control: object, *, get: Callable[..., Any] = _control_value +) -> list[int]: """Return UIA's per-element runtime id as a bounded JSON value.""" - method = _control_value(control, "GetRuntimeId", None) + method = get(control, "GetRuntimeId", None) try: value = list(method()) if callable(method) else [] except Exception: # noqa: BLE001 - some providers omit RuntimeId @@ -890,7 +902,12 @@ def _runtime_id(control: object) -> list[int]: return value -def _target_fingerprint(control: object, candidate: dict[str, Any]) -> str: +def _target_fingerprint( + control: object, + candidate: dict[str, Any], + *, + get: Callable[..., Any] = _control_value, +) -> str: """Bind resolution to this exact live UIA element and geometry. The locator alone is intentionally insufficient: a closed/reopened window @@ -904,10 +921,10 @@ def _target_fingerprint(control: object, candidate: dict[str, Any]) -> str: for key in ("automation_id", "role", "name", "window_name") }, "bounds": candidate.get("bounds"), - "runtime_id": _runtime_id(control), - "process_id": _control_value(control, "ProcessId", 0), - "native_window_handle": _control_value(control, "NativeWindowHandle", 0), - "class_name": str(_control_value(control, "ClassName", "") or ""), + "runtime_id": _runtime_id(control, get=get), + "process_id": get(control, "ProcessId", 0), + "native_window_handle": get(control, "NativeWindowHandle", 0), + "class_name": str(get(control, "ClassName", "") or ""), } canonical = json.dumps(identity, sort_keys=True, separators=(",", ":")) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() @@ -946,9 +963,11 @@ def _focused_field_label(auto: Any) -> Optional[str]: return _uia_field_label(focused) -def _candidate(control: object) -> Optional[dict[str, Any]]: - locator = _locator_from_control(control) - bounds = _bounds(control) +def _candidate( + control: object, *, get: Callable[..., Any] = _control_value +) -> Optional[dict[str, Any]]: + locator = _locator_from_control(control, get=get) + bounds = _bounds(control, get=get) if locator is None or bounds is None: return None role = locator["role"] @@ -968,7 +987,7 @@ def _candidate(control: object) -> Optional[dict[str, Any]]: "point": [int((bounds[0] + bounds[2]) / 2), int((bounds[1] + bounds[3]) / 2)], "supported_operations": operations, } - candidate["fingerprint"] = _target_fingerprint(control, candidate) + candidate["fingerprint"] = _target_fingerprint(control, candidate, get=get) return candidate @@ -996,10 +1015,12 @@ def _find_candidates( # A failed selector/bounds read cannot hide a second match and # turn a partial query into unique value authority. try: + _native_value_api().require_non_sensitive_value(control) facts = { - key: getattr(control, key) + key: _read_control_value(control, key, None) for key in ("AutomationId", "Name", "ControlTypeName") } + _native_value_api().require_non_sensitive_value(control) if any(not isinstance(value, str) for value in facts.values()): return found, True possible = all( @@ -1020,16 +1041,28 @@ def _find_candidates( for _ in range(_MAX_UIA_DEPTH + 1): if node is None: break - if node.ControlTypeName == "WindowControl": - if not isinstance(node.Name, str): + if ( + _read_control_value(node, "ControlTypeName", None) + == "WindowControl" + ): + if not isinstance( + _read_control_value(node, "Name", None), str + ): return found, True break - node = node.GetParentControl() + node = _parent(node, get=_read_control_value) else: return found, True except Exception: # noqa: BLE001 - unknown query scope is incomplete return found, True - candidate = _candidate(control) + try: + candidate = _candidate( + control, get=_read_control_value if strict_walk else _control_value + ) + except Exception: # noqa: BLE001 - changing sensitive metadata is no complete census + if strict_walk: + return found, True + raise if strict_walk and possible and candidate is None: return found, True if candidate is not None: @@ -1330,34 +1363,63 @@ def same(a: object, b: object) -> bool: _MAX_ROW_DEPTH = 4 +def _native_value_api() -> Any: + """Use the canonical package helper or its exact standalone sibling.""" + if __package__: + from openadapt_flow.backends.win_agent import native_value + else: + import win_agent_native_value as native_value # type: ignore[import-not-found,no-redef] + + return native_value + + +def _read_control_value(control: object, name: str, default: Any) -> Any: + """Metadata for a semantic value read, without a sensitivity-order gap.""" + guard = _native_value_api().require_non_sensitive_value + guard(control) + value = _control_value(control, name, default) + guard(control) + return value + + +def _require_value_contract(value: object) -> None: + if value != _native_value_api().PROOF_SCHEMA or not isinstance(value, str): + raise AgentRequestError( + 400, "invalid_schema", "incompatible native value contract" + ) + + def _value_text(control: object) -> Optional[str]: - """The text a person sees in ``control``: its value, else its name. + """Bounded non-authorizing preview, only for known non-sensitive controls. - Read-only. Edit boxes and grid cells expose their content through the - Value pattern (an empty box reads as empty, never as its name); other - controls through the legacy MSAA value or their Name. + A protocol declaration never authorizes a getter. Recheck the shared + sensitive-status guard before/after every capability, value or fallback + call; changes during a provider call discard the preview and stop fallback. """ - method = _control_value(control, "GetValuePattern", None) - if callable(method): - try: - pattern = method() - value = getattr(pattern, "Value", None) if pattern is not None else None - except Exception: # noqa: BLE001 - pattern not supported - value = None - if isinstance(value, str): - return value[:_MAX_READ_TEXT] - method = _control_value(control, "GetLegacyIAccessiblePattern", None) - if callable(method): - try: - value = getattr(method(), "Value", None) - except Exception: # noqa: BLE001 - pattern not supported - value = None - if isinstance(value, str) and value: - return value[:_MAX_READ_TEXT] - name = _control_value(control, "Name", "") - if isinstance(name, str) and name: - return name[:_MAX_READ_TEXT] - return None + guard = _native_value_api().require_non_sensitive_value + try: + guard(control) + for capability in ("GetValuePattern", "GetLegacyIAccessiblePattern"): + guard(control) + method = _control_value(control, capability, None) + guard(control) + if not callable(method): + continue + try: + pattern = method() + guard(control) + value = getattr(pattern, "Value", None) + except Exception: # noqa: BLE001 - unsupported capability is no value + value = None + guard(control) + if isinstance(value, str) and (value or capability == "GetValuePattern"): + return value[:_MAX_READ_TEXT] + guard(control) + name = _control_value(control, "Name", "") + guard(control) + return name[:_MAX_READ_TEXT] if isinstance(name, str) and name else None + except Exception: # noqa: BLE001 - sensitivity and provider failures refuse + return None def _children(control: object) -> list[object]: @@ -1605,13 +1667,15 @@ def _perform_uia_initialized( if operation == "read": data = _exact_object( payload, - required=frozenset({"locator"}), + required=frozenset({"locator", "value_contract"}), optional=frozenset({"rows"}), label="uia read", ) + _require_value_contract(data["value_contract"]) if not isinstance(data.get("rows", False), bool): raise AgentRequestError(400, "invalid_schema", "rows must be a boolean") read_locator = _locator_payload(data["locator"]) + read_deadline = time.monotonic() + 5.0 found, truncated = _find_candidates(read_locator, auto, strict_walk=True) unique = len(found) == 1 and not truncated result: dict[str, Any] = { @@ -1638,39 +1702,60 @@ def _perform_uia_initialized( # A legacy client sees text=None for every unavailable value. result["preview_text"] = _value_text(control) + hwnd = _control_value(control, "NativeWindowHandle", 0) + def identity() -> Optional[str]: - fresh, cut = _find_candidates(read_locator, auto, strict_walk=True) - if ( - cut - or len(fresh) != 1 - or fresh[0][1]["fingerprint"] != candidate["fingerprint"] - ): + # A strict complete census is required at both observation + # endpoints. Between them, guard the fixed element through a + # fresh handle lookup, RuntimeId/PID/geometry/locator binding. + # This is neither continuous global uniqueness nor permission + # for a future write. Rewalking the whole desktop for every + # native guard exhausted the unchanged five-second bound. + try: + if ( + time.monotonic() >= read_deadline + or type(hwnd) is not int + or hwnd <= 0 + ): + return None + live = auto.ControlFromHandle(hwnd) + _native_value_api().require_non_sensitive_value(live) + current = _candidate(live, get=_read_control_value) + _native_value_api().require_non_sensitive_value(live) + if ( + current is None + or current["fingerprint"] != candidate["fingerprint"] + ): + return None + return hashlib.sha256( + json.dumps( + [read_locator, current["fingerprint"]], + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + ).encode("utf-8") + ).hexdigest() + except Exception: # noqa: BLE001 - unknown fixed identity refuses return None - return hashlib.sha256( - json.dumps( - [read_locator, fresh[0][1]["fingerprint"]], - sort_keys=True, - separators=(",", ":"), - ensure_ascii=False, - ).encode("utf-8") - ).hexdigest() binding = identity() observed = _form_field_value(control, identity) result["reason"] = observed.reason or "value_identity_changed" - if ( - observed.complete - and observed.proof is not None - and binding is not None - and identity() == binding - ): - result.update( - text=observed.value, - complete=True, - reason=None, - value_proof=observed.proof.payload(), - value_identity=binding, - ) + if observed.complete and observed.proof is not None and binding is not None: + fresh, cut = _find_candidates(read_locator, auto, strict_walk=True) + if ( + not cut + and len(fresh) == 1 + and fresh[0][1]["fingerprint"] == candidate["fingerprint"] + and identity() == binding + ): + result.update( + text=observed.value, + complete=True, + reason=None, + value_proof=observed.proof.payload(), + value_identity=binding, + ) if data.get("rows"): # Row/cell concatenation and a bounded preview walk do not prove # full text or inventory. No composite row source is qualified. @@ -2357,27 +2442,30 @@ def _window_operation( _TOGGLE_STATES = {0: "off", 1: "on", 2: "indeterminate"} -def _form_exposes_value(control: object) -> bool: - """A visible label may also expose a value; never downgrade that value.""" - method = _control_value(control, "GetValuePattern", None) - if not callable(method): - return False +def _form_exposes_value(control: object) -> Optional[bool]: + """Value capability, or unknown; an unknown must not fall back to Name.""" + guard = _native_value_api().require_non_sensitive_value try: - return isinstance(getattr(method(), "Value", None), str) - except Exception: # noqa: BLE001 - the visible-label channel has no Value pattern - return False + guard(control) + method = _control_value(control, "GetValuePattern", None) + guard(control) + if not callable(method): + return False + try: + pattern = method() + guard(control) + value = getattr(pattern, "Value", None) + except Exception: # noqa: BLE001 - unsupported value capability + value = None + guard(control) + return isinstance(value, str) + except Exception: # noqa: BLE001 - a sensitive/unknown capability is not absence + return None def _form_field_value(control: object, identity: Callable[[], Optional[str]]) -> Any: """A complete identity-bound value; partial/unsupported sources refuse.""" - if __package__: - from openadapt_flow.backends.win_agent.native_value import ( - observe_complete_value, - ) - else: # standalone deployment must use its exact sibling, not an installed copy - from win_agent_native_value import observe_complete_value # type: ignore[import-not-found,no-redef] - - return observe_complete_value(control, identity=identity) + return _native_value_api().observe_complete_value(control, identity=identity) def _form_value_identity( @@ -2500,7 +2588,13 @@ def _window_form_fields( return None, False if window is None: return None, False - title = " ".join(str(_control_value(window, "Name", "") or "").split()) + guard = _native_value_api().require_non_sensitive_value + try: + guard(window) + title = " ".join(str(_control_value(window, "Name", "") or "").split()) + guard(window) + except Exception: # noqa: BLE001 - no sensitive/unknown name preview + return None, False fields: list[dict[str, Any]] = [] def children_of(control: Any) -> list[Any]: @@ -2577,7 +2671,10 @@ def identity(c: object = control) -> Optional[str]: if not children and control_type in _FORM_NAMED_TYPES | _FORM_ITEM_TYPES: text, proof, value_identity = None, None, None if bounds is not None and on_screen: - if control_type in _FORM_ITEM_TYPES or _form_exposes_value(control): + exposes = _form_exposes_value(control) + if exposes is None: + return None, False + if control_type in _FORM_ITEM_TYPES or exposes: value_identity = identity() observed = _form_field_value(control, identity) if ( @@ -2589,9 +2686,14 @@ def identity(c: object = control) -> Optional[str]: return None, False text, proof = observed.value, observed.proof.payload() else: - name = " ".join( - str(_control_value(control, "Name", "") or "").split() - ) + try: + guard(control) + name = " ".join( + str(_control_value(control, "Name", "") or "").split() + ) + guard(control) + except Exception: # noqa: BLE001 - no sensitive/unknown fallback + return None, False text = name or None if text is not None: fields.append( @@ -2634,7 +2736,14 @@ def _window_form_fields_operation( other window (it could sit over a field whose pixels the caller leaves out), or UIA cannot read the window completely. """ - framed = _window_operation("window-bounds", payload, user32) + data = _exact_object( + payload, + required=frozenset({"hwnd", "pid", "value_contract"}), + label="window form fields", + ) + _require_value_contract(data["value_contract"]) + frame_payload = {key: data[key] for key in ("hwnd", "pid")} + framed = _window_operation("window-bounds", frame_payload, user32) window = framed.get("window") if window is None: return {"status": "ok", "window": None, "fields": []} @@ -2649,7 +2758,7 @@ def _window_form_fields_operation( return {"status": "ok", "window": None, "fields": []} def unchanged() -> bool: - fresh = _window_operation("window-bounds", payload, user32).get("window") + fresh = _window_operation("window-bounds", frame_payload, user32).get("window") if fresh != window: return False return all( diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index ba06c230bd..df50d98831 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -47,6 +47,7 @@ from openadapt_flow.approval_mode.window_fields import valid_form_field from openadapt_flow.backend import ActionDeliveryUncertain, StructuralResolutionRefused +from openadapt_flow.backends.win_agent.native_value import PROOF_SCHEMA from openadapt_flow.backends.win_agent.value_protocol import ( locator_scope, valid_structural_response, @@ -1087,7 +1088,8 @@ def approval_form_fields( return None hwnd, pid = found typed = self._post_typed_read( - "/window/form-fields", {"hwnd": hwnd, "pid": pid} + "/window/form-fields", + {"hwnd": hwnd, "pid": pid, "value_contract": PROOF_SCHEMA}, ) payload = typed.payload if payload is None or set(payload) != {"status", "window", "fields"}: @@ -1555,7 +1557,11 @@ def read_structural( scope = locator_scope(locator.model_dump(mode="json", exclude_none=True)) typed = self._post_typed_read( "/uia/read", - {"locator": scope, **({"rows": True} if rows else {})}, + { + "locator": scope, + "value_contract": PROOF_SCHEMA, + **({"rows": True} if rows else {}), + }, ) payload = typed.payload if not typed.available or not valid_structural_response( diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 0895d40071..882ebf0dd5 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -29,6 +29,7 @@ window_fields_state, ) from openadapt_flow.backends.win_agent.native_value import ( + PROOF_SCHEMA, NativeOwner, NativeRead, valid_value_proof, @@ -39,7 +40,7 @@ def _proof(text, hwnd=100, pid=10): raw = text.encode("utf-16-le", errors="surrogatepass") return { - "schema": "openadapt.native-value-completeness/v1", + "schema": PROOF_SCHEMA, "method": "uia-value+wm-gettext", "hwnd": hwnd, "pid": pid, @@ -347,7 +348,9 @@ def post(path, payload): def test_the_windows_backend_reads_the_fields_of_its_one_window(): backend, sent = _windows_backend({"s1": (7, 10), "save": (99, 10)}, _GOOD) answer = backend.approval_form_fields("save") - assert sent == [("/window/form-fields", {"hwnd": 7, "pid": 10})] + assert sent == [ + ("/window/form-fields", {"hwnd": 7, "pid": 10, "value_contract": PROOF_SCHEMA}) + ] assert answer is not None assert answer["bounds"] == (0, 0, 1024, 720) assert valid_value_proof( @@ -566,7 +569,8 @@ class Reader: def owner(self, hwnd): return NativeOwner(hwnd, controls[hwnd].ProcessId, 5) - def read(self, owner): + def read(self, owner, *, guard): + guard() control = controls[owner.hwnd] value = ( control._value @@ -585,7 +589,13 @@ def read(self, owner): client = types.SimpleNamespace(gen_dir="unset") monkeypatch.setitem(sys.modules, "comtypes", types.SimpleNamespace(client=client)) monkeypatch.setitem(sys.modules, "comtypes.client", client) - return agent_server._perform_uia + + def perform(operation, payload): + if operation in {"read", "window-form-fields"}: + payload = {"value_contract": PROOF_SCHEMA, **payload} + return agent_server._perform_uia(operation, payload) + + return perform def test_the_agent_reads_the_title_bar_and_every_readable_text_field(monkeypatch): diff --git a/packages/flow/tests/test_native_sensitive_reads.py b/packages/flow/tests/test_native_sensitive_reads.py new file mode 100644 index 0000000000..2cb829432d --- /dev/null +++ b/packages/flow/tests/test_native_sensitive_reads.py @@ -0,0 +1,254 @@ +"""All native previews, probes and reads share one current sensitivity guard.""" + +from types import SimpleNamespace + +import pytest + +from openadapt_flow.backends.win_agent import server +from openadapt_flow.backends.win_agent.native_value import PROOF_SCHEMA +from openadapt_flow.backends.windows_backend import WindowsBackend +from openadapt_flow.ir import StructuralLocator +from tests.test_approval_form_fields import _agent, _Control, _window + + +class CountedControl(_Control): + def __init__(self, status=False, change=None): + self.calls = [] + self._status = status + self.change = change + super().__init__("TextControl", value="fixture value", name="fixture label") + self._status = status + self.AutomationId = "field" + + @property + def IsPassword(self): + if self._status == "error": + raise RuntimeError("status unavailable") + return self._status + + @IsPassword.setter + def IsPassword(self, value): + self._status = value + + @property + def Name(self): + self.calls.append("Name") + if self.change == "name": + self._status = True + return self._name + + @Name.setter + def Name(self, value): + self._name = value + + @property + def GetValuePattern(self): + self.calls.append("pattern_lookup") + if self.change == "pattern_lookup": + self._status = True + + def factory(): + self.calls.append("pattern_call") + if self.change == "pattern_call": + self._status = True + outer = self + + class Pattern: + IsReadOnly = False + + @property + def Value(self): + outer.calls.append("Value") + if outer.change == "value": + outer._status = True + return outer._value + + if self.change in {"legacy", "name"}: + raise RuntimeError("no value pattern") + return Pattern() + + return factory + + def GetLegacyIAccessiblePattern(self): + self.calls.append("legacy_call") + if self.change == "legacy": + self._status = True + outer = self + + class Pattern: + @property + def Value(self): + outer.calls.append("LegacyValue") + return None + + return Pattern() + + +def invoke(monkeypatch, target, entry): + if entry == "preview": + return server._value_text(target) + if entry == "probe": + return server._form_exposes_value(target) + window = _window(target) + perform = _agent(monkeypatch, window) + if entry == "form": + return perform("window-form-fields", {"hwnd": 7, "pid": 10}) + import sys + + sys.modules["uiautomation"].GetRootControl = lambda: window + return perform( + "read", {"locator": {"automation_id": "field"}, "rows": entry == "rows"} + ) + + +@pytest.mark.parametrize("entry", ["preview", "probe", "form", "read", "rows"]) +@pytest.mark.parametrize("status", [True, None, 0, 1, "false", "error"]) +def test_sensitive_unknown_or_nonboolean_status_never_calls_a_text_getter( + monkeypatch, entry, status +): + target = CountedControl(status) + result = invoke(monkeypatch, target, entry) + assert target.calls == [] + if entry in {"preview", "probe"}: + assert result is None + elif entry == "form": + assert result["window"] is None and result["fields"] == [] + else: + assert result["text"] is None and result["preview_text"] is None + assert result["complete"] is False + if entry == "rows": + assert result["rows"] is None and result["preview_rows"] == [] + + +@pytest.mark.parametrize("entry", ["preview", "probe"]) +@pytest.mark.parametrize( + "change", ["pattern_lookup", "pattern_call", "value", "legacy", "name"] +) +def test_preview_and_capability_changes_stop_later_getters_and_discard_data( + monkeypatch, entry, change +): + target = CountedControl(change=change) + result = invoke(monkeypatch, target, entry) + if entry == "probe" and change in {"legacy", "name"}: + # A non-value capability result need not inspect preview fallbacks. + assert result is False + assert "legacy_call" not in target.calls and "Name" not in target.calls + else: + assert result is None + if change == "pattern_lookup": + assert "pattern_call" not in target.calls + if change in {"pattern_lookup", "pattern_call"}: + assert "Value" not in target.calls + if change == "legacy": + assert "LegacyValue" not in target.calls and "Name" not in target.calls + if change != "name": + assert "Name" not in target.calls + + +@pytest.mark.parametrize("entry", ["preview", "probe", "form", "read", "rows"]) +def test_known_nonsensitive_controls_keep_qualified_values_and_explicit_previews( + monkeypatch, entry +): + target = CountedControl() + result = invoke(monkeypatch, target, entry) + if entry == "preview": + assert result == "fixture value" + elif entry == "probe": + assert result is True + elif entry == "form": + assert result["window"] is not None + assert result["fields"][0]["text"] == "fixture value" + assert result["fields"][0]["value_proof"]["schema"] == PROOF_SCHEMA + else: + assert result["complete"] is True and result["text"] == "fixture value" + assert result["preview_text"] == "fixture value" + if entry == "rows": + assert result["rows"] is None and result["rows_complete"] is False + + +@pytest.mark.parametrize("operation", ["read", "window-form-fields"]) +@pytest.mark.parametrize( + "version", [None, "openadapt.native-value-completeness/v1", True] +) +def test_old_client_new_server_refuses_protocol_before_any_provider_access( + operation, version +): + calls = [] + + class NoProvider: + def __getattr__(self, name): + calls.append(name) + raise AssertionError("protocol mismatch must precede provider access") + + payload = ( + {"locator": {"automation_id": "field"}} + if operation == "read" + else {"hwnd": 7, "pid": 10} + ) + if version is not None: + payload["value_contract"] = version + with pytest.raises(server.AgentRequestError) as error: + if operation == "read": + server._perform_uia_initialized(NoProvider(), operation, payload) + else: + server._window_form_fields_operation(payload, NoProvider(), NoProvider()) + assert error.value.code == "invalid_schema" and calls == [] + + +@pytest.mark.parametrize("operation", ["read", "window-form-fields"]) +def test_new_client_old_closed_server_refuses_before_any_getter(operation): + backend = object.__new__(WindowsBackend) + backend._approval_window = lambda *_a: (7, 10) + calls = [] + + def legacy_route(path, payload): + assert payload["value_contract"] == PROOF_SCHEMA + required = {"locator"} if operation == "read" else {"hwnd", "pid"} + try: + server._exact_object( + payload, required=frozenset(required), label="legacy exact request" + ) + except server.AgentRequestError as error: + assert error.code == "invalid_schema" + return SimpleNamespace(available=False, payload=None) + calls.append("unsafe_legacy_getter") + raise AssertionError("new request must be refused before legacy preview") + + backend._post_typed_read = legacy_route + result = ( + backend.read_structural(StructuralLocator(automation_id="field")) + if operation == "read" + else backend.approval_form_fields() + ) + assert result is None and calls == [] + + +@pytest.mark.parametrize( + "metadata", + ["AutomationId", "ControlTypeName", "ClassName", "ProcessId", "BoundingRectangle"], +) +@pytest.mark.parametrize("status", [True, None]) +def test_semantic_candidate_metadata_cannot_open_a_later_name_getter( + monkeypatch, metadata, status +): + class MetadataControl(CountedControl): + armed = False + changed = False + + def __getattribute__(self, key): + value = super().__getattribute__(key) + if key == metadata and super().__getattribute__("armed"): + self._status = status + self.changed = True + if key == "Name" and super().__getattribute__("changed"): + raise AssertionError("no Name getter after sensitive metadata change") + return value + + target = MetadataControl() + target.armed = True + # Each metadata property has the same last-check model, independently of + # which structural census field happens to be queried first. + with pytest.raises(Exception) as error: + server._candidate(target, get=server._read_control_value) + assert type(error.value).__name__ == "ValueUnavailable" + assert "Value" not in target.calls and "legacy_call" not in target.calls diff --git a/packages/flow/tests/test_structural_value_completeness.py b/packages/flow/tests/test_structural_value_completeness.py index c83247ce8c..cc8ba1a60a 100644 --- a/packages/flow/tests/test_structural_value_completeness.py +++ b/packages/flow/tests/test_structural_value_completeness.py @@ -460,3 +460,60 @@ def test_explicit_native_transforms_do_not_imply_whitespace_loss(): assert parsed and observed == transformed.value.literal == "2026-11-20" assert effect.value.literal == "2026-11-20" assert _exact_value("invalid", dated)[1] is False + + +@pytest.mark.parametrize( + "fault", ["none", "replacement", "aba", "final_duplicate", "final_incomplete"] +) +def test_structural_scope_checks_complete_census_endpoints_and_fresh_fixed_identity( + monkeypatch, fault +): + import sys + + from openadapt_flow.backends.win_agent import server + + target = _Control("EditControl", value="exact") + target.AutomationId = "field" + window = _window(target) + perform = _agent(monkeypatch, window) + auto = sys.modules["uiautomation"] + auto.GetRootControl = lambda: window + original_lookup = auto.ControlFromHandle + replaced = _Control("EditControl", value="exact") + replaced.NativeWindowHandle = target.NativeWindowHandle + replaced.AutomationId = "field" + replaced.parent = window + replaced.GetRuntimeId = lambda: [99, target.NativeWindowHandle] + lookups = [] + + def lookup(hwnd): + lookups.append(hwnd) + if fault == "replacement" or (fault == "aba" and len(lookups) == 2): + return replaced + return original_lookup(hwnd) + + monkeypatch.setattr(auto, "ControlFromHandle", lookup) + original_census = server._find_candidates + censuses = [] + + def census(*args, **kwargs): + censuses.append(True) + found, truncated = original_census(*args, **kwargs) + if len(censuses) == 2 and fault == "final_duplicate": + return found + found, truncated + if len(censuses) == 2 and fault == "final_incomplete": + return found, True + return found, truncated + + monkeypatch.setattr(server, "_find_candidates", census) + result = perform("read", {"locator": {"automation_id": "field"}}) + if fault == "none": + assert result["complete"] is True and result["text"] == "exact" + assert len(censuses) == 2 and len(lookups) > 2 + else: + assert result["complete"] is False and result["text"] is None + assert result["value_proof"] is None + if fault.startswith("final"): + assert len(censuses) == 2 + # Observing a replacement once permanently refuses this observation; + # restoring the old handle/runtime later cannot upgrade the result. From b476bbfcea4dec17d16a6d526b2590fc74ad62cb Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 01:34:36 -0500 Subject: [PATCH 16/34] Require supported raw password status before native text reads --- .../backends/win_agent/native_value.py | 10 ++- .../tests/test_native_value_completeness.py | 69 ++++++++++++++++++- 2 files changed, 75 insertions(+), 4 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 db0b8f5a9a..ffb18801dd 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -15,7 +15,8 @@ from typing import Any, Callable, Protocol MAX_UTF16_UNITS = 65536 -PROOF_SCHEMA = "openadapt.native-value-completeness/v2" +PROOF_SCHEMA = "openadapt.native-value-completeness/v3" +IS_PASSWORD_PROPERTY = 30019 def utf16_bytes(value: str) -> bytes: @@ -183,7 +184,12 @@ def require_non_sensitive_value(control: Any) -> None: result or negotiated protocol version is never authority for a later read. """ try: - allowed = control.IsPassword is False + # CurrentIsPassword/Control.IsPassword can return a default FALSE for + # unsupported status. Request the raw property with defaults ignored; + # a reserved unsupported object is unknown, not non-sensitive. + method = getattr(control, "GetPropertyValueEx", None) + raw = method(IS_PASSWORD_PROPERTY, 1) if callable(method) else None + allowed = type(raw) is bool and raw is False except Exception: allowed = False if not allowed: diff --git a/packages/flow/tests/test_native_value_completeness.py b/packages/flow/tests/test_native_value_completeness.py index 4f242b6333..983947ec9e 100644 --- a/packages/flow/tests/test_native_value_completeness.py +++ b/packages/flow/tests/test_native_value_completeness.py @@ -36,6 +36,12 @@ def control(value=""): GetValuePattern=lambda: pattern, Name="never use Name", ) + + def property_ex(property_id, ignore_default): + assert property_id == 30019 and ignore_default == 1 + return target.IsPassword + + target.GetPropertyValueEx = property_ex return target, pattern @@ -362,6 +368,10 @@ def IsPassword(self): raise RuntimeError("status unavailable") return status + def GetPropertyValueEx(self, property_id, ignore_default): + assert property_id == 30019 and ignore_default == 1 + return self.IsPassword + def __getattr__(self, name): self.calls.append(name) raise AssertionError("no source or capability access is allowed") @@ -415,6 +425,7 @@ def GetValuePattern(self): return factory target = Target(**{k: v for k, v in vars(target).items() if k != "GetValuePattern"}) + target.GetPropertyValueEx = lambda property_id, ignore_default: target.IsPassword result = observe(target, Reader("exact")) assert not result.complete and result.value is None assert result.reason == "password_or_password_status_unavailable" @@ -446,8 +457,9 @@ def test_previous_proof_version_is_not_compatible_with_pre_read_sensitive_guard( result = observe(target, Reader("exact")) assert result.complete and result.proof.schema == PROOF_SCHEMA proof = result.proof.payload() - proof["schema"] = "openadapt.native-value-completeness/v1" - assert not valid_value_proof("exact", proof) + for previous in ("v1", "v2"): + proof["schema"] = "openadapt.native-value-completeness/" + previous + assert not valid_value_proof("exact", proof) @pytest.mark.parametrize("stage", ["extent", "full", "value"]) @@ -464,6 +476,7 @@ def ControlTypeName(self): base, _ = control("") target = Target(**{k: v for k, v in vars(base).items() if k != "ControlTypeName"}) + target.GetPropertyValueEx = lambda property_id, ignore_default: target.IsPassword accesses = [] class StagedReader(Reader): @@ -492,3 +505,55 @@ def Value(self): assert not result.complete and result.value is None assert result.reason == "password_or_password_status_unavailable" assert stage not in accesses + + +@pytest.mark.parametrize("raw", [None, object(), 0, 1, "false", True]) +def test_defaulted_false_password_wrapper_is_not_known_nonsensitive_status(raw): + target, _ = control("") + # The friendly wrapper says False even when the raw ignored-default + # property is unavailable or unsupported. Only the raw result qualifies. + target.IsPassword = False + queries = [] + + def property_ex(property_id, ignore_default): + queries.append((property_id, ignore_default)) + return raw + + target.GetPropertyValueEx = property_ex + target.GetValuePattern = lambda: pytest.fail( + "unknown raw status must not read value" + ) + reader = Reader() + result = observe(target, reader) + assert ( + not result.complete + and result.reason == "password_or_password_status_unavailable" + ) + assert queries == [(30019, 1)] and reader.reads == 0 + + +@pytest.mark.parametrize("fault", ["missing", "lookup", "call"]) +def test_unavailable_raw_password_status_refuses_without_wrapper_or_text_access(fault): + class Target: + @property + def GetPropertyValueEx(self): + if fault == "missing": + return None + if fault == "lookup": + raise RuntimeError("raw status lookup failed") + return lambda *_: (_ for _ in ()).throw(RuntimeError("raw query failed")) + + @property + def IsPassword(self): + pytest.fail("coerced/defaulted wrapper is not an authority source") + + def GetValuePattern(self): + pytest.fail("missing raw status must not read value") + + result = observe_complete_value( + Target(), identity=lambda: "bound", native_reader=Reader() + ) + assert ( + not result.complete + and result.reason == "password_or_password_status_unavailable" + ) From f05aabdb86ef1ba8d6327ee753bef85aa585b56d Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 01:39:36 -0500 Subject: [PATCH 17/34] Refuse unknown native capabilities and bind complete read deployment --- CAPABILITIES.md | 2 +- llms-full.txt | 32 ++- packages/flow/CHANGELOG.md | 41 ++-- packages/flow/docs/LIMITS.md | 30 ++- .../backends/win_agent/README.md | 7 +- .../backends/win_agent/server.py | 92 ++++++-- .../backends/windows_backend.py | 6 +- .../e2e/test_windows_approval_completeness.py | 28 ++- .../flow/tests/test_approval_form_fields.py | 15 +- .../flow/tests/test_native_sensitive_reads.py | 196 +++++++++++++++++- .../tests/test_native_value_deployment.py | 68 ++++-- 11 files changed, 420 insertions(+), 97 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index f5a99fd06e..a69c618d2e 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -233,7 +233,7 @@ improvising or retrying when something is off. | Surface | Status | Evidence | Where | | --- | --- | --- | --- | | Web (Playwright, Chromium) | Released | Real apps on local test copies (OpenEMR, Odoo, Frappe Lending, openIMIS) and Medplum; CI runs in-tree apps on every build | [SURFACES.md](packages/flow/docs/SURFACES.md) | -| Native Windows (UI Automation) | Released | Synthetic (a WinForms test app in a Windows 11 VM, 3 of 3 trials); CI on a GitHub-hosted Windows runner on every change to the Windows path and nightly: record, compile and replay of the WinForms Patient Notes app through the real win_agent, judged from its SQLite record, with a near-identical sibling roster that must not be written, and a non-gating governed run of the same workflow under the Standard profile with a person's signed approval, a hold and a resume, whose resume completes the save (`VERIFIED`, the note on the target row only) now that the approval reads the window's text fields, labels and grid cells by value through UI Automation and only the rest by OCR ([#2189](https://github.com/OpenAdaptAI/OpenAdapt/issues/2189), [#2291](https://github.com/OpenAdaptAI/OpenAdapt/pull/2291)), followed by a gating check that fails the job on any sibling, held or unverified write ([desktop-replay.yml](.github/workflows/desktop-replay.yml)); on a real Windows 11 ARM machine, record, compile and replay of the same kind of WinForms test form with an owned confirm dialog, 3 of 3 trials, each also refusing a target covered by another app's window and one blocked by a modal dialog before any input | [SURFACES.md](packages/flow/docs/SURFACES.md) | +| Native Windows (UI Automation) | Released | Earlier synthetic evidence: a WinForms test app in a Windows 11 VM, 3 of 3 trials; GitHub-hosted CI records, compiles and replays Patient Notes through the real agent with SQLite and sibling-write checks. A historical short-note approval/hold/resume composition completed verified target-only saves ([run44665211915](https://github.com/OpenAdaptAI/OpenAdapt/actions/runs/44665211915)); it does not qualify the new complete-value contract. Current approval/structural work ([#2291](https://github.com/OpenAdaptAI/OpenAdapt/pull/2291)) remains held on current-head native evidence and independently qualified record identity. Its synthetic native observation variant excludes a full Flow save and unsupported virtual cells. Existing safety/no-skip gates remain enabled ([desktop-replay.yml](.github/workflows/desktop-replay.yml)). Earlier Windows 11 ARM evidence: record, compile and replay of a WinForms form with an owned confirm dialog, 3 of 3 trials, plus covered-target/modal refusal before input. | [SURFACES.md](packages/flow/docs/SURFACES.md) | | Native macOS (Accessibility) | Released | Synthetic (TextEdit, 3 of 3 file effects, driving the backend directly); a real third-party app, calibre (Qt, SQLite library): record, compile (certified under `clinical-write`) and a `standard` run checked against the library's database, `VERIFIED` with only the target book changed; a same-title book by another author stopped at the identity check and two identical books were refused as ambiguous, each with nothing written ([benchmark/macos_native](packages/flow/benchmark/macos_native/README.md)) | [SURFACES.md](packages/flow/docs/SURFACES.md) | | Native Linux (AT-SPI, X11) | Released | Real AT-SPI in CI (`flow-linux-atspi`, Xvfb with a window manager): a GTK3 fixture (3 verified effects, 3 ambiguous and 3 stale targets refused) and a GTK3 chart app with SQLite: record, compile (certified under `clinical-write`), a `standard` run `VERIFIED` against the database, another patient's chart and a look-alike chart stopped before the save, and a repaired notice admitted on its AT-SPI element identity ([benchmark/repair_every_backend](packages/flow/benchmark/repair_every_backend/README.md)) | [LINUX_NATIVE.md](packages/flow/docs/desktop/LINUX_NATIVE.md) | | RDP (pixels; Aardwolf or headless FreeRDP with a session pool) | Released | A Windows 11 VM over Aardwolf RDP, 3 of 3 (transport and input), plus a FreeRDP batch; through the stock Remote Desktop client on a real H.264/AVC444 session, 105 scripted runs on two apps (OpenEMR in Edge and a WinForms test app): 55 saves confirmed in the database, 0 wrong-record saves, 40 false stops ranked by cause | [SURFACES.md](packages/flow/docs/SURFACES.md), `backends/xfreerdp.py`, [benchmark/rdp_avc_real](packages/flow/benchmark/rdp_avc_real/README.md) | diff --git a/llms-full.txt b/llms-full.txt index 93b2a7096c..e23ade4ed6 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -667,7 +667,7 @@ improvising or retrying when something is off. | Surface | Status | Evidence | Where | | --- | --- | --- | --- | | Web (Playwright, Chromium) | Released | Real apps on local test copies (OpenEMR, Odoo, Frappe Lending, openIMIS) and Medplum; CI runs in-tree apps on every build | [SURFACES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SURFACES.md) | -| Native Windows (UI Automation) | Released | Synthetic (a WinForms test app in a Windows 11 VM, 3 of 3 trials); CI on a GitHub-hosted Windows runner on every change to the Windows path and nightly: record, compile and replay of the WinForms Patient Notes app through the real win_agent, judged from its SQLite record, with a near-identical sibling roster that must not be written, and a non-gating governed run of the same workflow under the Standard profile with a person's signed approval, a hold and a resume, whose resume completes the save (`VERIFIED`, the note on the target row only) now that the approval reads the window's text fields, labels and grid cells by value through UI Automation and only the rest by OCR ([#2189](https://github.com/OpenAdaptAI/OpenAdapt/issues/2189), [#2291](https://github.com/OpenAdaptAI/OpenAdapt/pull/2291)), followed by a gating check that fails the job on any sibling, held or unverified write ([desktop-replay.yml](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/.github/workflows/desktop-replay.yml)); on a real Windows 11 ARM machine, record, compile and replay of the same kind of WinForms test form with an owned confirm dialog, 3 of 3 trials, each also refusing a target covered by another app's window and one blocked by a modal dialog before any input | [SURFACES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SURFACES.md) | +| Native Windows (UI Automation) | Released | Earlier synthetic evidence: a WinForms test app in a Windows 11 VM, 3 of 3 trials; GitHub-hosted CI records, compiles and replays Patient Notes through the real agent with SQLite and sibling-write checks. A historical short-note approval/hold/resume composition completed verified target-only saves ([run44665211915](https://github.com/OpenAdaptAI/OpenAdapt/actions/runs/44665211915)); it does not qualify the new complete-value contract. Current approval/structural work ([#2291](https://github.com/OpenAdaptAI/OpenAdapt/pull/2291)) remains held on current-head native evidence and independently qualified record identity. Its synthetic native observation variant excludes a full Flow save and unsupported virtual cells. Existing safety/no-skip gates remain enabled ([desktop-replay.yml](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/.github/workflows/desktop-replay.yml)). Earlier Windows 11 ARM evidence: record, compile and replay of a WinForms form with an owned confirm dialog, 3 of 3 trials, plus covered-target/modal refusal before input. | [SURFACES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SURFACES.md) | | Native macOS (Accessibility) | Released | Synthetic (TextEdit, 3 of 3 file effects, driving the backend directly); a real third-party app, calibre (Qt, SQLite library): record, compile (certified under `clinical-write`) and a `standard` run checked against the library's database, `VERIFIED` with only the target book changed; a same-title book by another author stopped at the identity check and two identical books were refused as ambiguous, each with nothing written ([benchmark/macos_native](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/macos_native/README.md)) | [SURFACES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SURFACES.md) | | Native Linux (AT-SPI, X11) | Released | Real AT-SPI in CI (`flow-linux-atspi`, Xvfb with a window manager): a GTK3 fixture (3 verified effects, 3 ambiguous and 3 stale targets refused) and a GTK3 chart app with SQLite: record, compile (certified under `clinical-write`), a `standard` run `VERIFIED` against the database, another patient's chart and a look-alike chart stopped before the save, and a repaired notice admitted on its AT-SPI element identity ([benchmark/repair_every_backend](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/repair_every_backend/README.md)) | [LINUX_NATIVE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/desktop/LINUX_NATIVE.md) | | RDP (pixels; Aardwolf or headless FreeRDP with a session pool) | Released | A Windows 11 VM over Aardwolf RDP, 3 of 3 (transport and input), plus a FreeRDP batch; through the stock Remote Desktop client on a real H.264/AVC444 session, 105 scripted runs on two apps (OpenEMR in Edge and a WinForms test app): 55 saves confirmed in the database, 0 wrong-record saves, 40 false stops ranked by cause | [SURFACES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SURFACES.md), `backends/xfreerdp.py`, [benchmark/rdp_avc_real](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/rdp_avc_real/README.md) | @@ -2221,16 +2221,26 @@ What is not: - Values chosen by clicking (not typing), drag and drop, and WebSocket traffic are checked only by the write adapter or the read-back, if at all. - The instruction detector on approval forms is a heuristic display aid. -- On Windows, a desktop approval reads the app window's text fields, labels, - buttons and grid cells by their UI Automation value or name and paints them - out of the OCR read. It trusts that a standard control draws the text UI - Automation reports; a control that paints other text under the same - rectangle would hide a change there. Custom-drawn text that UI Automation - does not expose stays in the OCR read, and any other window of the app - sends the whole window back to OCR alone. - Values used to mask a control retain the complete text, rather than the - preview prefix. Password, empty and state-unreadable controls stay in OCR; - unknown subtrees are not treated as fully read controls. +- On Windows, value-backed approval controls require identity-bound agreement + between exact UI Automation values and independent native extent/full reads. + Missing, sensitive, incomplete or disagreeing values, unknown subtrees and + another visible owned window refuse the advertised native projection; the + whole window is not downgraded to OCR. Empty complete values remain covered. + Password status and value-pattern availability use raw UIA properties with + default values ignored; an unsupported default False is unknown. A named + control is a separate caption channel only when its value-pattern + absence is known; a failed/unknown value probe cannot hide required data in + a caption mask. This does not prove a caption is a record identity. + The remaining unmasked pixels are read by OCR. The projection still trusts + that standard controls render the qualified text inside their rectangles; + custom painting that violates that relationship is not qualified. + Structural field values require the same complete-value contract. Name/MSAA + and clipped previews do not authorize business-value or absence predicates; + unknown markers remain indeterminate. No complete native row-inventory + source is qualified. Structural uniqueness is checked at both observation + endpoints, with fresh fixed-control identity during reads, not continuously + or as authority for a later write. Current complete-value Flow/save and + held-out application qualification remain pending. - No live model has been run against these fixtures yet; the live-model test is off by default because it costs money. diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index bcdafae92b..6e82d7f8e9 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -19,30 +19,23 @@ ### Fixes -- Approval form projections retain complete control values, including edits - beyond the preview length. Empty, redacted or state-unreadable controls - stay in the OCR read. A failed or depth-limited UI Automation walk does - not certify a complete control read, and a container cannot hide its - unread descendants ([#2291](https://github.com/OpenAdaptAI/OpenAdapt/pull/2291)). - -- A desktop approval no longer halts on a form that did not change - ([#2189](https://github.com/OpenAdaptAI/OpenAdapt/issues/2189)). On the - hosted Windows governed run, two reads of the same Patient Notes window - gave different OCR words (the caret in the search box, the title bar's - close button, a selected grid row), so every resumed approval stopped - with `form_changed_after_approval`. The win_agent has a new typed read, - `window-form-fields` (capability `window_form_fields_v1`): the approval - window's frame, its title bar, and every on-screen text field, label, - button and list or grid cell whose text UI Automation reads, with toggle - and selection state. The approval's form state (kind `window_fields`) - reads those controls by value, paints them out of the window crop, and - reads the rest of the window by OCR. A changed value still changes the - digest through either channel. Cells count only by value, never by a - positional name. The agent answers no window when the app shows any other - window or the walk is incomplete, and the window is then read by OCR as - before; a request and a recheck read through different channels never - match. The governed run now resumes to `VERIFIED` with the note on the - target row only. +- Native approval and structural field reads require exact UIA values to agree + with independent native extent/full reads under the same control identity. + Missing, sensitive, incomplete or disagreeing values refuse the observation; + an advertised native approval channel does not fall back to OCR. Empty + complete values remain values. A container cannot hide unread descendants + ([#2291](https://github.com/OpenAdaptAI/OpenAdapt/pull/2291)). +- Value reads negotiate a server-owned read contract and require helper proof v3 + before any preview or value getter. One + current sensitivity guard protects values, previews and capability probes. + Failed/unknown capability probes cannot become caption masks. Structural + previews and unqualified row inventories do not authorize effect checks. +- Approval form state reads proven values separately from the remaining OCR + pixels, so caret/title-bar display noise need not alter an unchanged field's + value digest ([#2189](https://github.com/OpenAdaptAI/OpenAdapt/issues/2189)). + Current complete-value approval/structural qualification is pending. The + native observation fixture excludes a full Flow save; earlier short-note + governed evidence does not qualify this new source or unbounded values. ## v3.3.0 (2026-11-19) diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index 4556557147..85ddccab2b 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -946,16 +946,26 @@ What is not: - Values chosen by clicking (not typing), drag and drop, and WebSocket traffic are checked only by the write adapter or the read-back, if at all. - The instruction detector on approval forms is a heuristic display aid. -- On Windows, a desktop approval reads the app window's text fields, labels, - buttons and grid cells by their UI Automation value or name and paints them - out of the OCR read. It trusts that a standard control draws the text UI - Automation reports; a control that paints other text under the same - rectangle would hide a change there. Custom-drawn text that UI Automation - does not expose stays in the OCR read, and any other window of the app - sends the whole window back to OCR alone. - Values used to mask a control retain the complete text, rather than the - preview prefix. Password, empty and state-unreadable controls stay in OCR; - unknown subtrees are not treated as fully read controls. +- On Windows, value-backed approval controls require identity-bound agreement + between exact UI Automation values and independent native extent/full reads. + Missing, sensitive, incomplete or disagreeing values, unknown subtrees and + another visible owned window refuse the advertised native projection; the + whole window is not downgraded to OCR. Empty complete values remain covered. + Password status and value-pattern availability use raw UIA properties with + default values ignored; an unsupported default False is unknown. A named + control is a separate caption channel only when its value-pattern + absence is known; a failed/unknown value probe cannot hide required data in + a caption mask. This does not prove a caption is a record identity. + The remaining unmasked pixels are read by OCR. The projection still trusts + that standard controls render the qualified text inside their rectangles; + custom painting that violates that relationship is not qualified. + Structural field values require the same complete-value contract. Name/MSAA + and clipped previews do not authorize business-value or absence predicates; + unknown markers remain indeterminate. No complete native row-inventory + source is qualified. Structural uniqueness is checked at both observation + endpoints, with fresh fixed-control identity during reads, not continuously + or as authority for a later write. Current complete-value Flow/save and + held-out application qualification remain pending. - No live model has been run against these fixtures yet; the live-model test is off by default because it costs money. diff --git a/packages/flow/openadapt_flow/backends/win_agent/README.md b/packages/flow/openadapt_flow/backends/win_agent/README.md index d311445afd..1b8907b47f 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/README.md +++ b/packages/flow/openadapt_flow/backends/win_agent/README.md @@ -71,7 +71,12 @@ a token.** The client refuses plaintext to a non-loopback host by default then polls `/health`. This is what the opt-in e2e harness uses. ### B. At user logon — unattended VM -1. Copy this folder into the guest, e.g. `C:\oa\win_agent\`. +1. Copy this entire folder into the guest, e.g. `C:\oa\win_agent\`, + including `server.py` and its `native_value.py` sibling. The programmatic + single-file deployments name that same helper `win_agent_native_value.py`. + The standalone server loads only these exact local sibling files and refuses + missing or conflicting copies; it never falls back to an installed package. + Client and agent must agree on the server-owned read contract (openadapt.native-value-read/v1) and helper proof v3 before value/preview reads. 2. Register a logon scheduled task **running as the interactive user** (not SYSTEM), highest privileges: diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index d0ef7ad1e0..b31c6e324c 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -1363,14 +1363,58 @@ def same(a: object, b: object) -> bool: _MAX_ROW_DEPTH = 4 +_STANDALONE_NATIVE_VALUE_API: Any = None + + def _native_value_api() -> Any: - """Use the canonical package helper or its exact standalone sibling.""" + """Use the package helper or load only the exact local deployment sibling. + + The three programmatic launchers use win_agent_native_value.py; the + documented copied-folder/run_agent.bat route keeps native_value.py. Never + search installed modules, and refuse conflicting local copies. A process + binds the selected source once, as it does its own loaded server source. + """ if __package__: from openadapt_flow.backends.win_agent import native_value - else: - import win_agent_native_value as native_value # type: ignore[import-not-found,no-redef] - return native_value + return native_value + global _STANDALONE_NATIVE_VALUE_API + if _STANDALONE_NATIVE_VALUE_API is not None: + return _STANDALONE_NATIVE_VALUE_API + import importlib.util + from pathlib import Path + + directory = Path(__file__).resolve().parent + sources = [] + for name in ("win_agent_native_value.py", "native_value.py"): + path = directory / name + if path.is_symlink(): + raise ImportError("native-value helper must be an exact local file") + if path.is_file(): + sources.append((path, path.read_bytes())) + if not sources: + raise ModuleNotFoundError("exact local native-value helper is missing") + if any(raw != sources[0][1] for _, raw in sources[1:]): + raise ImportError("conflicting local native-value helpers") + path, raw = sources[0] + key = ( + "_win_agent_native_value_" + + hashlib.sha256(str(path).encode() + raw).hexdigest() + ) + spec = importlib.util.spec_from_file_location(key, path) + if spec is None or spec.loader is None: + raise ImportError("exact local native-value helper cannot be loaded") + module = importlib.util.module_from_spec(spec) + sys.modules[key] = module + try: + # Execute the exact bytes selected above, not a same-name installed + # module or a second path read after validating the selected source. + exec(compile(raw, str(path), "exec"), module.__dict__) + except Exception: + sys.modules.pop(key, None) + raise + _STANDALONE_NATIVE_VALUE_API = module + return module def _read_control_value(control: object, name: str, default: Any) -> Any: @@ -1382,8 +1426,18 @@ def _read_control_value(control: object, name: str, default: Any) -> Any: return value +# This contract belongs to the SERVER consumer semantics, not to the helper. +# Updating a helper beside an older server cannot advertise a new read policy. +VALUE_READ_CONTRACT = "openadapt.native-value-read/v1" +_EXPECTED_VALUE_PROOF_SCHEMA = "openadapt.native-value-completeness/v3" + + def _require_value_contract(value: object) -> None: - if value != _native_value_api().PROOF_SCHEMA or not isinstance(value, str): + if ( + not isinstance(value, str) + or value != VALUE_READ_CONTRACT + or _native_value_api().PROOF_SCHEMA != _EXPECTED_VALUE_PROOF_SCHEMA + ): raise AgentRequestError( 400, "invalid_schema", "incompatible native value contract" ) @@ -2442,24 +2496,28 @@ def _window_operation( _TOGGLE_STATES = {0: "off", 1: "on", 2: "indeterminate"} +_UIA_IS_VALUE_PATTERN_AVAILABLE = 30043 + + def _form_exposes_value(control: object) -> Optional[bool]: - """Value capability, or unknown; an unknown must not fall back to Name.""" + """Known value capability, known absence, or unknown; never guess by text. + + UIA's availability property is VT_BOOL. Ignore default values so a missing + property yields the reserved unsupported object, not a default False that + could authorize Name fallback. Provider failures remain unknown. The probe + itself never touches a Value/Legacy/Name getter. + """ guard = _native_value_api().require_non_sensitive_value try: guard(control) - method = _control_value(control, "GetValuePattern", None) + method = _control_value(control, "GetPropertyValueEx", None) guard(control) if not callable(method): - return False - try: - pattern = method() - guard(control) - value = getattr(pattern, "Value", None) - except Exception: # noqa: BLE001 - unsupported value capability - value = None + return None + available = method(_UIA_IS_VALUE_PATTERN_AVAILABLE, 1) guard(control) - return isinstance(value, str) - except Exception: # noqa: BLE001 - a sensitive/unknown capability is not absence + return available if type(available) is bool else None + except Exception: # noqa: BLE001 - unknown capability is not absence return None @@ -2692,6 +2750,8 @@ def identity(c: object = control) -> Optional[str]: str(_control_value(control, "Name", "") or "").split() ) guard(control) + if _form_exposes_value(control) is not False: + return None, False except Exception: # noqa: BLE001 - no sensitive/unknown fallback return None, False text = name or None diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index df50d98831..bc7cb80654 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -47,7 +47,7 @@ from openadapt_flow.approval_mode.window_fields import valid_form_field from openadapt_flow.backend import ActionDeliveryUncertain, StructuralResolutionRefused -from openadapt_flow.backends.win_agent.native_value import PROOF_SCHEMA +from openadapt_flow.backends.win_agent.server import VALUE_READ_CONTRACT from openadapt_flow.backends.win_agent.value_protocol import ( locator_scope, valid_structural_response, @@ -1089,7 +1089,7 @@ def approval_form_fields( hwnd, pid = found typed = self._post_typed_read( "/window/form-fields", - {"hwnd": hwnd, "pid": pid, "value_contract": PROOF_SCHEMA}, + {"hwnd": hwnd, "pid": pid, "value_contract": VALUE_READ_CONTRACT}, ) payload = typed.payload if payload is None or set(payload) != {"status", "window", "fields"}: @@ -1559,7 +1559,7 @@ def read_structural( "/uia/read", { "locator": scope, - "value_contract": PROOF_SCHEMA, + "value_contract": VALUE_READ_CONTRACT, **({"rows": True} if rows else {}), }, ) diff --git a/packages/flow/tests/e2e/test_windows_approval_completeness.py b/packages/flow/tests/e2e/test_windows_approval_completeness.py index 3a922b8001..77de98284d 100644 --- a/packages/flow/tests/e2e/test_windows_approval_completeness.py +++ b/packages/flow/tests/e2e/test_windows_approval_completeness.py @@ -221,7 +221,24 @@ def identity(): ) observed = server._form_field_value(control, identity) - uia_value = control.GetValuePattern().Value + api = server._native_value_api() + raw_status = control.GetPropertyValueEx(30019, 1) + status_measurement = { + "source": "GetPropertyValueEx(30019,1)", + "kind": type(raw_status).__name__, + "value": raw_status if type(raw_status) is bool else None, + } + uia_value = None + if type(raw_status) is bool and raw_status is False: + # This separate provider-prefix measurement is diagnostic + # only and obeys the same shared pre/post getter guard. + api.require_non_sensitive_value(control) + method = control.GetValuePattern + api.require_non_sensitive_value(control) + pattern = method() + api.require_non_sensitive_value(control) + uia_value = pattern.Value + api.require_non_sensitive_value(control) rect = control.BoundingRectangle point = ( int((rect.left + rect.right) / 2), @@ -232,10 +249,15 @@ def identity(): phase = { "name": name, "managed_before": managed, - "uia_utf16_units": len(uia_value.encode("utf-16-le")) // 2, + "raw_password_status": status_measurement, + "uia_utf16_units": len(uia_value.encode("utf-16-le")) // 2 + if uia_value is not None + else None, "uia_sha256_utf16le": hashlib.sha256( uia_value.encode("utf-16-le") - ).hexdigest(), + ).hexdigest() + if uia_value is not None + else None, "direct_complete": observed.complete, "direct_reason": observed.reason, "fields": fields, diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 882ebf0dd5..2e2ee22315 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -34,6 +34,7 @@ NativeRead, valid_value_proof, ) +from openadapt_flow.backends.win_agent.server import VALUE_READ_CONTRACT from openadapt_flow.backends.windows_backend import WindowsBackend @@ -349,7 +350,10 @@ def test_the_windows_backend_reads_the_fields_of_its_one_window(): backend, sent = _windows_backend({"s1": (7, 10), "save": (99, 10)}, _GOOD) answer = backend.approval_form_fields("save") assert sent == [ - ("/window/form-fields", {"hwnd": 7, "pid": 10, "value_contract": PROOF_SCHEMA}) + ( + "/window/form-fields", + {"hwnd": 7, "pid": 10, "value_contract": VALUE_READ_CONTRACT}, + ) ] assert answer is not None assert answer["bounds"] == (0, 0, 1024, 720) @@ -477,6 +481,13 @@ def GetParentControl(self): def GetChildren(self): return self._children + def GetPropertyValueEx(self, property_id, ignore_default): + assert ignore_default == 1 + if property_id == 30019: + return self.IsPassword + assert property_id == 30043 + return self._value is not None + def GetValuePattern(self): if self._value is None: raise RuntimeError("no value pattern") @@ -592,7 +603,7 @@ def read(self, owner, *, guard): def perform(operation, payload): if operation in {"read", "window-form-fields"}: - payload = {"value_contract": PROOF_SCHEMA, **payload} + payload = {"value_contract": VALUE_READ_CONTRACT, **payload} return agent_server._perform_uia(operation, payload) return perform diff --git a/packages/flow/tests/test_native_sensitive_reads.py b/packages/flow/tests/test_native_sensitive_reads.py index 2cb829432d..b898f3405a 100644 --- a/packages/flow/tests/test_native_sensitive_reads.py +++ b/packages/flow/tests/test_native_sensitive_reads.py @@ -129,12 +129,11 @@ def test_preview_and_capability_changes_stop_later_getters_and_discard_data( ): target = CountedControl(change=change) result = invoke(monkeypatch, target, entry) - if entry == "probe" and change in {"legacy", "name"}: - # A non-value capability result need not inspect preview fallbacks. - assert result is False - assert "legacy_call" not in target.calls and "Name" not in target.calls - else: - assert result is None + if entry == "probe": + # The availability probe no longer touches any text/pattern getter. + assert result is True and target.calls == [] + return + assert result is None if change == "pattern_lookup": assert "pattern_call" not in target.calls if change in {"pattern_lookup", "pattern_call"}: @@ -168,7 +167,14 @@ def test_known_nonsensitive_controls_keep_qualified_values_and_explicit_previews @pytest.mark.parametrize("operation", ["read", "window-form-fields"]) @pytest.mark.parametrize( - "version", [None, "openadapt.native-value-completeness/v1", True] + "version", + [ + None, + "openadapt.native-value-completeness/v1", + "openadapt.native-value-completeness/v2", + "openadapt.native-value-completeness/v3", + True, + ], ) def test_old_client_new_server_refuses_protocol_before_any_provider_access( operation, version @@ -202,7 +208,7 @@ def test_new_client_old_closed_server_refuses_before_any_getter(operation): calls = [] def legacy_route(path, payload): - assert payload["value_contract"] == PROOF_SCHEMA + assert payload["value_contract"] == server.VALUE_READ_CONTRACT required = {"locator"} if operation == "read" else {"hwnd", "pid"} try: server._exact_object( @@ -252,3 +258,177 @@ def __getattribute__(self, key): server._candidate(target, get=server._read_control_value) assert type(error.value).__name__ == "ValueUnavailable" assert "Value" not in target.calls and "legacy_call" not in target.calls + + +@pytest.mark.parametrize( + "fault", ["missing", "lookup", "call", "none", "object", "integer"] +) +def test_unknown_value_capability_never_becomes_a_caption_or_mask(monkeypatch, fault): + class Target(CountedControl): + @property + def GetPropertyValueEx(self): + if fault == "missing": + return None + if fault == "lookup": + raise RuntimeError("availability lookup failed") + + def query(property_id, ignore_default): + assert ignore_default == 1 + if property_id == 30019: + return self.IsPassword + assert property_id == 30043 + if fault == "call": + raise RuntimeError("availability query failed") + return {"none": None, "object": object(), "integer": 0}[fault] + + return query + + target = Target() + result = invoke(monkeypatch, target, "form") + assert result["window"] is None and result["fields"] == [] + assert target.calls == [] + + +@pytest.mark.parametrize("fault", ["lookup", "call", "readability", "value"]) +def test_known_value_capability_failure_never_downgrades_to_name_mask( + monkeypatch, fault +): + class Target(CountedControl): + @property + def GetValuePattern(self): + self.calls.append("pattern_lookup") + if fault == "lookup": + raise RuntimeError("pattern lookup failed") + outer = self + + def factory(): + outer.calls.append("pattern_call") + if fault == "call": + raise RuntimeError("pattern query failed") + + class Pattern: + @property + def IsReadOnly(self): + if fault == "readability": + raise RuntimeError("readability failed") + return False + + @property + def Value(self): + outer.calls.append("Value") + raise RuntimeError("value failed") + + return Pattern() + + return factory + + target = Target() + result = invoke(monkeypatch, target, "form") + assert result["window"] is None and result["fields"] == [] + assert "Name" not in target.calls and "legacy_call" not in target.calls + + +@pytest.mark.parametrize("status", [True, None]) +@pytest.mark.parametrize("stage", ["lookup", "call"]) +def test_availability_metadata_change_obeys_shared_sensitive_guard( + monkeypatch, stage, status +): + class Target(CountedControl): + @property + def GetPropertyValueEx(self): + if stage == "lookup": + self._status = status + + def query(property_id, ignore_default): + assert ignore_default == 1 + if property_id == 30019: + return self._status + assert property_id == 30043 + self.calls.append("availability_call") + self._status = status + return False + + return query + + target = Target() + assert server._form_exposes_value(target) is None + assert target.calls == ([] if stage == "lookup" else ["availability_call"]) + + +def test_known_absent_value_pattern_keeps_caption_separate_and_rechecks_after_name( + monkeypatch, +): + target = CountedControl() + target._value = None + result = invoke(monkeypatch, target, "form") + assert result["window"] is not None + field = result["fields"][0] + assert field["kind"] == "text" and field["text"] == "fixture label" + assert field["value_proof"] is None and field["value_identity"] is None + assert "pattern_lookup" not in target.calls and "Value" not in target.calls + + class ChangingCaption(CountedControl): + @property + def Name(self): + self._value = "new required value" + return self._name + + @Name.setter + def Name(self, value): + self._name = value + + target = ChangingCaption() + target._value = None + changed = invoke(monkeypatch, target, "form") + assert changed["window"] is None and changed["fields"] == [] + + +@pytest.mark.parametrize("operation", ["read", "window-form-fields"]) +@pytest.mark.parametrize( + "helper_version", + [ + "openadapt.native-value-completeness/v1", + "openadapt.native-value-completeness/v2", + ], +) +def test_new_server_old_helper_refuses_before_provider_access( + monkeypatch, operation, helper_version +): + calls = [] + monkeypatch.setattr( + server, + "_native_value_api", + lambda: SimpleNamespace(PROOF_SCHEMA=helper_version), + ) + + class NoProvider: + def __getattr__(self, name): + calls.append(name) + raise AssertionError("old helper must refuse before content reads") + + payload = ( + {"locator": {"automation_id": "field"}} + if operation == "read" + else {"hwnd": 7, "pid": 10} + ) + payload["value_contract"] = server.VALUE_READ_CONTRACT + with pytest.raises( + server.AgentRequestError, match="incompatible native value contract" + ): + if operation == "read": + server._perform_uia_initialized(NoProvider(), operation, payload) + else: + server._window_form_fields_operation(payload, NoProvider(), NoProvider()) + assert calls == [] + + +def test_changing_only_helper_cannot_make_old_server_advertise_new_consumer_policy(): + # Historical87d negotiated against helper.PROOF_SCHEMA. The new client + # sends a server-consumer namespace, deliberately different from ANY + # supported helper proof version, so helper-only replacement cannot turn + # the old read/probe/preview semantics into the new protocol. + assert server.VALUE_READ_CONTRACT.startswith("openadapt.native-value-read/") + assert server.VALUE_READ_CONTRACT != PROOF_SCHEMA + for version in ("v1", "v2", "v3"): + old_server_helper_contract = "openadapt.native-value-completeness/" + version + assert server.VALUE_READ_CONTRACT != old_server_helper_contract diff --git a/packages/flow/tests/test_native_value_deployment.py b/packages/flow/tests/test_native_value_deployment.py index 9e56663399..07258da07d 100644 --- a/packages/flow/tests/test_native_value_deployment.py +++ b/packages/flow/tests/test_native_value_deployment.py @@ -111,25 +111,44 @@ def invoke(): ) -@pytest.mark.parametrize("missing", [False, True]) -def test_standalone_server_requires_exact_local_helper_without_package_fallback( - tmp_path, missing +@pytest.mark.parametrize( + "layout", ["renamed", "copied_folder", "both_identical", "conflicting", "missing"] +) +def test_standalone_server_requires_exact_local_helper_for_every_documented_layout( + tmp_path, layout ): - shutil.copyfile(server.__file__, tmp_path / "win_agent_server.py") - if not missing: - shutil.copyfile( - Path(server.__file__).with_name("native_value.py"), - tmp_path / "win_agent_native_value.py", + source = Path(server.__file__).with_name("native_value.py") + destination = tmp_path / ( + "server.py" if layout == "copied_folder" else "win_agent_server.py" + ) + shutil.copyfile(server.__file__, destination) + if layout in {"renamed", "both_identical", "conflicting"}: + shutil.copyfile(source, tmp_path / "win_agent_native_value.py") + if layout in {"copied_folder", "both_identical"}: + shutil.copyfile(source, tmp_path / "native_value.py") + elif layout == "conflicting": + (tmp_path / "native_value.py").write_text( + "raise AssertionError('conflicting file must never execute')\n" ) - script = """import sys -sys.path.insert(0, sys.argv[1]) -import win_agent_server as server + script = """import importlib.util,sys,hashlib +from pathlib import Path +from types import SimpleNamespace +# A same-name installed/preloaded module cannot satisfy the local-source rule. +sys.modules['win_agent_native_value'] = SimpleNamespace(PROOF_SCHEMA='poison') +sys.modules['native_value'] = SimpleNamespace(PROOF_SCHEMA='poison') +spec = importlib.util.spec_from_file_location('isolated_agent', sys.argv[1]) +server = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = server +spec.loader.exec_module(server) +helper = server._native_value_api() +assert Path(helper.__file__).resolve().parent == Path(sys.argv[1]).resolve().parent +assert Path(helper.__spec__.origin).resolve() == Path(helper.__file__).resolve() +assert hashlib.sha256(Path(helper.__file__).read_bytes()).hexdigest() == sys.argv[2] +assert helper.PROOF_SCHEMA == 'openadapt.native-value-completeness/v3' value = server._form_field_value(None, lambda: 'scope') assert not value.complete and value.value is None -import win_agent_native_value as helper -from pathlib import Path -assert Path(helper.__file__).resolve().parent == Path(sys.argv[1]).resolve() -print('exact standalone helper imported; incomplete observation refused') +assert server._native_value_api() is helper +print('exact local helper imported; incomplete observation refused') """ env = { key: value @@ -137,14 +156,27 @@ def test_standalone_server_requires_exact_local_helper_without_package_fallback( if key not in {"PYTHONPATH", "PYTHONHOME"} } result = subprocess.run( - [sys.executable, "-S", "-c", script, str(tmp_path)], + [ + sys.executable, + "-I", + "-S", + "-c", + script, + str(destination), + hashlib.sha256(source.read_bytes()).hexdigest(), + ], cwd=tmp_path, env=env, text=True, capture_output=True, ) - if missing: - assert result.returncode != 0 and "win_agent_native_value" in result.stderr + if layout in {"missing", "conflicting"}: + assert result.returncode != 0 + assert ( + "exact local native-value helper" + if layout == "missing" + else "conflicting local native-value helpers" + ) in result.stderr else: assert result.returncode == 0, result.stderr assert "incomplete observation refused" in result.stdout From 93347ab10e9d433ecf994cb63554696f502df9e3 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 02:01:55 -0500 Subject: [PATCH 18/34] Refuse incomplete native visibility, value and state projections --- llms-full.txt | 8 +- packages/flow/docs/LIMITS.md | 8 +- .../backends/win_agent/server.py | 269 +++++++++++------- .../flow/tests/test_approval_form_fields.py | 16 +- .../flow/tests/test_native_sensitive_reads.py | 208 +++++++++++++- 5 files changed, 402 insertions(+), 107 deletions(-) diff --git a/llms-full.txt b/llms-full.txt index 996eb4c8bc..4c9bcecea3 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -2226,7 +2226,13 @@ What is not: between exact UI Automation values and independent native extent/full reads. Missing, sensitive, incomplete or disagreeing values, unknown subtrees and another visible owned window refuse the advertised native projection; the - whole window is not downgraded to OCR. Empty complete values remain covered. + whole window is not downgraded to OCR. Visibility is an exact supported raw + property; unknown visibility or required visible bounds/type refuses the + projection. Relevant toggle/selection state has a separate complete/state + observation: unknown, failed or unrepresented composite state refuses before + masking. Known absent state patterns do not establish absent business state. + Empty complete values remain covered. A value-capable control carries its + full-value obligation regardless of type; generic containers stay unmasked. Password status and value-pattern availability use raw UIA properties with default values ignored; an unsupported default False is unknown. A named control is a separate caption channel only when its value-pattern diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index 85ddccab2b..d08519fd63 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -950,7 +950,13 @@ What is not: between exact UI Automation values and independent native extent/full reads. Missing, sensitive, incomplete or disagreeing values, unknown subtrees and another visible owned window refuse the advertised native projection; the - whole window is not downgraded to OCR. Empty complete values remain covered. + whole window is not downgraded to OCR. Visibility is an exact supported raw + property; unknown visibility or required visible bounds/type refuses the + projection. Relevant toggle/selection state has a separate complete/state + observation: unknown, failed or unrepresented composite state refuses before + masking. Known absent state patterns do not establish absent business state. + Empty complete values remain covered. A value-capable control carries its + full-value obligation regardless of type; generic containers stay unmasked. Password status and value-pattern availability use raw UIA properties with default values ignored; an unsupported default False is unknown. A named control is a separate caption channel only when its value-pattern diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index b31c6e324c..8ceba89ee8 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -2499,8 +2499,8 @@ def _window_operation( _UIA_IS_VALUE_PATTERN_AVAILABLE = 30043 -def _form_exposes_value(control: object) -> Optional[bool]: - """Known value capability, known absence, or unknown; never guess by text. +def _form_boolean_property(control: object, property_id: int) -> Optional[bool]: + """An exact supported UIA boolean property, or unknown; never default. UIA's availability property is VT_BOOL. Ignore default values so a missing property yields the reserved unsupported object, not a default False that @@ -2514,13 +2514,17 @@ def _form_exposes_value(control: object) -> Optional[bool]: guard(control) if not callable(method): return None - available = method(_UIA_IS_VALUE_PATTERN_AVAILABLE, 1) + available = method(property_id, 1) guard(control) return available if type(available) is bool else None except Exception: # noqa: BLE001 - unknown capability is not absence return None +def _form_exposes_value(control: object) -> Optional[bool]: + return _form_boolean_property(control, _UIA_IS_VALUE_PATTERN_AVAILABLE) + + def _form_field_value(control: object, identity: Callable[[], Optional[str]]) -> Any: """A complete identity-bound value; partial/unsupported sources refuse.""" return _native_value_api().observe_complete_value(control, identity=identity) @@ -2589,26 +2593,68 @@ def _form_value_identity( return None -def _form_field_state(control: object, control_type: str) -> Optional[str]: - """A check box's toggle state, or whether an item is selected; else None.""" - if control_type in ("CheckBoxControl", "RadioButtonControl"): - method = _control_value(control, "GetTogglePattern", None) - if callable(method): - try: - state = getattr(method(), "ToggleState", None) - except Exception: # noqa: BLE001 - pattern not supported - state = None - if state in _TOGGLE_STATES: - return _TOGGLE_STATES[state] - method = _control_value(control, "GetSelectionItemPattern", None) - if callable(method): - try: - selected = getattr(method(), "IsSelected", None) - except Exception: # noqa: BLE001 - pattern not supported - selected = None - if isinstance(selected, bool): - return "selected" if selected else "unselected" - return None +@dataclass(frozen=True) +class _FormStateObservation: + complete: bool + state: Optional[str] + reason: Optional[str] = None + + +def _form_field_state(control: object) -> _FormStateObservation: + """Distinguish known absent state patterns from unknown observations. + + This describes the two state patterns in the declared form projection; + it does not establish element absence, record identity or a business value. + Composite toggle+selection state has no wire representation and refuses. + """ + guard = _native_value_api().require_non_sensitive_value + + def read(capability: str, attribute: str) -> Any: + guard(control) + method = _control_value(control, capability, None) + guard(control) + if not callable(method): + raise ValueError("state pattern unavailable") + pattern = method() + guard(control) + value = getattr(pattern, attribute, None) + guard(control) + return value + + try: + toggle = _form_boolean_property(control, 30041) + selection = _form_boolean_property(control, 30036) + if toggle is None or selection is None: + return _FormStateObservation(False, None, "state_capability_unknown") + if toggle and selection: + return _FormStateObservation(False, None, "composite_state_unrepresented") + + def unchanged() -> bool: + return ( + _form_boolean_property(control, 30041), + _form_boolean_property(control, 30036), + ) == (toggle, selection) + + if toggle: + value = read("GetTogglePattern", "ToggleState") + if type(value) is not int or value not in _TOGGLE_STATES: + return _FormStateObservation(False, None, "toggle_state_unavailable") + if not unchanged(): + return _FormStateObservation(False, None, "state_capability_changed") + return _FormStateObservation(True, _TOGGLE_STATES[value]) + if selection: + value = read("GetSelectionItemPattern", "IsSelected") + if type(value) is not bool: + return _FormStateObservation(False, None, "selection_state_unavailable") + if not unchanged(): + return _FormStateObservation(False, None, "state_capability_changed") + return _FormStateObservation(True, "selected" if value else "unselected") + complete = unchanged() + return _FormStateObservation( + complete, None, None if complete else "state_capability_changed" + ) + except Exception: # noqa: BLE001 - no sensitive/unknown state fallback + return _FormStateObservation(False, None, "state_observation_unavailable") def _rect(bounds: list[int]) -> list[int]: @@ -2671,118 +2717,137 @@ def children_of(control: Any) -> list[Any]: visited += 1 if visited > _MAX_UIA_NODES or len(fields) > _MAX_FORM_FIELDS: return fields, True - control_type = str(_control_value(control, "ControlTypeName", "")) + control_type = _control_value(control, "ControlTypeName", None) bounds = _bounds(control) - on_screen = _control_value(control, "IsOffscreen", True) is False + offscreen = _form_boolean_property(control, 30022) + if offscreen is None: + return None, False + on_screen = not offscreen + if on_screen and ( + bounds is None or not isinstance(control_type, str) or not control_type + ): + return None, False try: children = children_of(control) except Exception: # noqa: BLE001 - an unknown subtree is not a leaf return None, False - if control_type == "TitleBarControl": - if bounds is not None and on_screen and title: + state = None + exposes = False + if on_screen: + observed_state = _form_field_state(control) + if not observed_state.complete: + return None, False + state = observed_state.state + capability = _form_exposes_value(control) + if capability is None: + return None, False + exposes = capability + + def identity(c: object = control) -> Optional[str]: + return _form_value_identity(c, window, hwnd, scope, auto) + + def append_state() -> None: + if state is not None and bounds is not None and on_screen: fields.append( { - "kind": "title_bar", + "kind": "state", "rect": _rect(bounds), - "text": title, - "state": None, + "text": "", + "state": state, "value_proof": None, "value_identity": None, } ) - continue - - def identity(c: object = control) -> Optional[str]: - return _form_value_identity(c, window, hwnd, scope, auto) - if control_type in _FORM_VALUE_TYPES: - if bounds is not None and on_screen: - value_identity = identity() - observed = _form_field_value(control, identity) - if ( - not observed.complete - or observed.proof is None - or value_identity is None - or identity() != value_identity - ): - return None, False + if 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. + value_identity = identity() + observed = _form_field_value(control, identity) + if ( + not observed.complete + or observed.proof is None + or value_identity is None + or identity() != value_identity + ): + return None, False + if ( + children + or control_type + not in _FORM_VALUE_TYPES | _FORM_NAMED_TYPES | _FORM_ITEM_TYPES + ): + kind = "value" + else: + kind = "edit" if control_type in _FORM_VALUE_TYPES else "text" + fields.append( + { + "kind": kind, + "rect": _rect(bounds), + "text": observed.value, + "state": state if kind == "text" else None, + "value_proof": observed.proof.payload(), + "value_identity": value_identity, + } + ) + if kind != "text": + append_state() + if not children: + continue + elif on_screen and ( + control_type in _FORM_VALUE_TYPES + or (not children and control_type in _FORM_ITEM_TYPES) + ): + # A required field with no supported value source is unavailable; + # pattern absence does not establish absence of business data. + return None, False + elif control_type == "TitleBarControl": + if bounds is not None and on_screen and title: fields.append( { - # Container values are evidence too, but must never - # hide descendants that have their own obligations. - "kind": "value" if children else "edit", + "kind": "title_bar", "rect": _rect(bounds), - "text": observed.value, + "text": title, "state": None, - "value_proof": observed.proof.payload(), - "value_identity": value_identity, + "value_proof": None, + "value_identity": None, } ) - if not children: - continue - state = _form_field_state(control, control_type) - if control_type in {"CheckBoxControl", "RadioButtonControl", "TabItemControl"}: - if state is None: - # The label alone does not account for the control's state. - # Keep these pixels in the OCR read when UIA cannot name it. - continue - if not children and control_type in _FORM_NAMED_TYPES | _FORM_ITEM_TYPES: - text, proof, value_identity = None, None, None + append_state() + continue + elif not children and control_type in _FORM_NAMED_TYPES: if bounds is not None and on_screen: - exposes = _form_exposes_value(control) - if exposes is None: - return None, False - if control_type in _FORM_ITEM_TYPES or exposes: - value_identity = identity() - observed = _form_field_value(control, identity) - if ( - not observed.complete - or observed.proof is None - or value_identity is None - or identity() != value_identity - ): - return None, False - text, proof = observed.value, observed.proof.payload() - else: - try: - guard(control) - name = " ".join( - str(_control_value(control, "Name", "") or "").split() - ) - guard(control) - if _form_exposes_value(control) is not False: - return None, False - except Exception: # noqa: BLE001 - no sensitive/unknown fallback + try: + guard(control) + name = " ".join( + str(_control_value(control, "Name", "") or "").split() + ) + guard(control) + if _form_exposes_value(control) is not False: return None, False - text = name or None - if text is not None: + except Exception: # noqa: BLE001 - no sensitive/unknown fallback + return None, False + if name: fields.append( { "kind": "text", "rect": _rect(bounds), - "text": text, + "text": name, "state": state, - "value_proof": proof, - "value_identity": value_identity, + "value_proof": None, + "value_identity": None, } ) + elif state is not None: + append_state() continue - if state is not None and bounds is not None and on_screen: - fields.append( - { - "kind": "state", - "rect": _rect(bounds), - "text": "", - "state": state, - "value_proof": None, - "value_identity": None, - } - ) + else: + append_state() if children: if depth >= _MAX_UIA_DEPTH: return fields, True stack.extend((c, depth + 1) for c in reversed(children)) - return fields, False + return fields, len(fields) > _MAX_FORM_FIELDS def _window_form_fields_operation( diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 2e2ee22315..d4777e8f98 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -485,6 +485,12 @@ def GetPropertyValueEx(self, property_id, ignore_default): assert ignore_default == 1 if property_id == 30019: return self.IsPassword + if property_id == 30022: + return self.IsOffscreen + if property_id == 30041: + return self._toggle is not None + if property_id == 30036: + return self._selected is not None assert property_id == 30043 return self._value is not None @@ -792,13 +798,19 @@ def read(suffix): @pytest.mark.parametrize( "control_type", ["CheckBoxControl", "RadioButtonControl", "TabItemControl"] ) -def test_a_stateful_control_with_unreadable_state_keeps_its_pixels( +def test_a_stateful_control_with_unreadable_state_refuses_projection( monkeypatch, control_type ): control = _Control(control_type, name="Choice", bounds=(20, 44, 500, 70)) + original_property = control.GetPropertyValueEx + control.GetPropertyValueEx = lambda property_id, ignore_default: ( + None + if property_id in {30036, 30041} + else original_property(property_id, ignore_default) + ) perform = _agent(monkeypatch, _window(control)) answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) - assert answer["window"] is not None + assert answer["window"] is None assert answer["fields"] == [] diff --git a/packages/flow/tests/test_native_sensitive_reads.py b/packages/flow/tests/test_native_sensitive_reads.py index b898f3405a..1e5db263e2 100644 --- a/packages/flow/tests/test_native_sensitive_reads.py +++ b/packages/flow/tests/test_native_sensitive_reads.py @@ -276,7 +276,10 @@ def query(property_id, ignore_default): assert ignore_default == 1 if property_id == 30019: return self.IsPassword - assert property_id == 30043 + if property_id != 30043: + return _Control.GetPropertyValueEx( + self, property_id, ignore_default + ) if fault == "call": raise RuntimeError("availability query failed") return {"none": None, "object": object(), "integer": 0}[fault] @@ -432,3 +435,206 @@ def test_changing_only_helper_cannot_make_old_server_advertise_new_consumer_poli for version in ("v1", "v2", "v3"): old_server_helper_contract = "openadapt.native-value-completeness/" + version assert server.VALUE_READ_CONTRACT != old_server_helper_contract + + +@pytest.mark.parametrize("state_kind", ["toggle", "selection"]) +@pytest.mark.parametrize("status", [True, None, "error", 0]) +def test_state_sources_share_the_raw_sensitive_no_getter_guard(state_kind, status): + target = CountedControl(status=status) + target.GetTogglePattern = lambda: pytest.fail("sensitive toggle capability called") + target.GetSelectionItemPattern = lambda: pytest.fail( + "sensitive selection capability called" + ) + observed = server._form_field_state(target) + assert not observed.complete and observed.state is None + assert target.calls == [] + + +@pytest.mark.parametrize("state_kind", ["toggle", "selection"]) +@pytest.mark.parametrize("stage", ["factory", "state"]) +@pytest.mark.parametrize("status", [True, None]) +def test_state_source_metadata_changes_do_not_expose_or_retain_state( + state_kind, stage, status +): + target = CountedControl() + accesses = [] + target._toggle = 0 if state_kind == "toggle" else None + target._selected = False if state_kind == "selection" else None + + def factory(): + if stage == "factory": + target._status = status + + class Pattern: + def __getattribute__(self, attribute): + if attribute in {"ToggleState", "IsSelected"}: + accesses.append(attribute) + target._status = status + return 0 if attribute == "ToggleState" else False + return super().__getattribute__(attribute) + + return Pattern() + + if state_kind == "toggle": + target.GetTogglePattern = factory + else: + target.GetSelectionItemPattern = factory + observed = server._form_field_state(target) + assert not observed.complete and observed.state is None + if stage == "factory": + assert accesses == [] + + +@pytest.mark.parametrize( + "raw_state,expected", + [(0, "off"), (1, "on"), (2, "indeterminate"), (True, None), (None, None)], +) +def test_qualified_toggle_states_preserve_exact_typed_results(raw_state, expected): + target = _Control("CheckBoxControl", toggle=raw_state) + observed = server._form_field_state(target) + assert observed.state == expected + assert observed.complete is (raw_state is None or type(raw_state) is int) + + +@pytest.mark.parametrize( + "raw_state,expected", + [(False, "unselected"), (True, "selected"), (0, None), (None, None)], +) +def test_qualified_selection_states_do_not_coerce_unknown_to_false(raw_state, expected): + target = _Control("TabItemControl", selected=raw_state) + observed = server._form_field_state(target) + assert observed.state == expected + assert observed.complete is (raw_state is None or type(raw_state) is bool) + + +@pytest.mark.parametrize( + "role", + [ + "EditControl", + "DocumentControl", + "TextControl", + "ButtonControl", + "ListItemControl", + "CustomControl", + "PaneControl", + "TitleBarControl", + ], +) +@pytest.mark.parametrize("fault", ["unknown", "nonbool", "error"]) +def test_unknown_state_scope_refuses_before_any_value_or_caption_mask( + monkeypatch, role, fault +): + target = CountedControl() + target.ControlTypeName = role + original = target.GetPropertyValueEx + + def query(property_id, ignore_default): + if property_id == 30036: + if fault == "error": + raise RuntimeError("selection availability unreadable") + return None if fault == "unknown" else 0 + return original(property_id, ignore_default) + + target.GetPropertyValueEx = query + result = invoke(monkeypatch, target, "form") + assert result["window"] is None and result["fields"] == [] + assert target.calls == [] + + +def test_supported_absent_state_and_unrepresentable_composite_stay_distinct(): + absent = server._form_field_state(_Control("CustomControl")) + assert absent.complete and absent.state is None and absent.reason is None + both = _Control("CustomControl", toggle=0, selected=False) + refused = server._form_field_state(both) + assert not refused.complete and refused.state is None + assert refused.reason == "composite_state_unrepresented" + + +def test_complete_leaf_value_retains_its_independent_state_without_hiding_it( + monkeypatch, +): + target = _Control("EditControl", value="value", selected=False) + result = invoke(monkeypatch, target, "form") + assert result["window"] is not None + assert [entry["kind"] for entry in result["fields"]] == ["edit", "state"] + assert result["fields"][1]["state"] == "unselected" + + +@pytest.mark.parametrize("pattern", ["toggle", "selection"]) +def test_state_capability_change_during_getter_is_not_known_absence_or_state(pattern): + target = _Control( + "CustomControl", + toggle=0 if pattern == "toggle" else None, + selected=False if pattern == "selection" else None, + ) + + class Pattern: + @property + def ToggleState(self): + target._toggle = None + return 0 + + @property + def IsSelected(self): + target._selected = None + return False + + if pattern == "toggle": + target.GetTogglePattern = Pattern + else: + target.GetSelectionItemPattern = Pattern + observed = server._form_field_state(target) + assert not observed.complete and observed.state is None + assert observed.reason == "state_capability_changed" + + +@pytest.mark.parametrize( + "fault", + [ + "visibility_unknown", + "visibility_nonbool", + "visibility_error", + "bounds_unknown", + "type_unknown", + "type_nonstring", + ], +) +def test_unreadable_visible_scope_never_omits_a_required_value(monkeypatch, fault): + target = _Control("EditControl", value="required value") + original = target.GetPropertyValueEx + if fault.startswith("visibility"): + + def query(property_id, ignore_default): + if property_id == 30022: + if fault == "visibility_error": + raise RuntimeError("visibility unavailable") + return None if fault == "visibility_unknown" else 0 + return original(property_id, ignore_default) + + target.GetPropertyValueEx = query + elif fault == "bounds_unknown": + target.BoundingRectangle = None + else: + target.ControlTypeName = None if fault == "type_unknown" else 42 + result = invoke(monkeypatch, target, "form") + assert result["window"] is None and result["fields"] == [] + + +@pytest.mark.parametrize("role", ["PaneControl", "GroupControl", "UnknownValueControl"]) +@pytest.mark.parametrize("children", [False, True]) +def test_any_capability_true_generic_value_retains_unmasked_complete_obligation( + monkeypatch, role, children +): + target = _Control( + role, + value="full generic value", + children=[_Control("EditControl", value="child")] if children else [], + ) + result = invoke(monkeypatch, target, "form") + assert result["window"] is not None + assert result["fields"][0]["kind"] == "value" + assert result["fields"][0]["text"] == "full generic value" + assert result["fields"][0]["value_proof"] is not None + target.native_override = "full generic value with omitted suffix" + refused = invoke(monkeypatch, target, "form") + assert refused["window"] is None and refused["fields"] == [] From b1b6cbdf0a16b543f798ee586bbdcc2918ed1127 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 02:42:27 -0500 Subject: [PATCH 19/34] Report request-local non-content native projection refusals --- .github/workflows/desktop-replay.yml | 3 +- llms-full.txt | 5 +- packages/flow/CHANGELOG.md | 4 + packages/flow/docs/LIMITS.md | 5 +- .../backends/win_agent/README.md | 12 +- .../backends/win_agent/server.py | 358 +++++++++++++++--- .../backends/windows_backend.py | 23 +- .../e2e/test_windows_approval_completeness.py | 8 + .../flow/tests/test_approval_form_fields.py | 2 + .../tests/test_approval_value_completeness.py | 2 + .../tests/test_form_projection_refusal.py | 336 ++++++++++++++++ .../flow/tests/test_native_sensitive_reads.py | 1 + 12 files changed, 695 insertions(+), 64 deletions(-) create mode 100644 packages/flow/tests/test_form_projection_refusal.py diff --git a/.github/workflows/desktop-replay.yml b/.github/workflows/desktop-replay.yml index e9c72aba8c..e03212405e 100644 --- a/.github/workflows/desktop-replay.yml +++ b/.github/workflows/desktop-replay.yml @@ -40,6 +40,7 @@ on: - packages/flow/tests/test_approval_value_completeness.py - packages/flow/tests/test_native_value_completeness.py - packages/flow/tests/test_native_sensitive_reads.py + - packages/flow/tests/test_form_projection_refusal.py - packages/flow/tests/test_native_value_deployment.py - packages/flow/tests/test_structural_value_completeness.py - packages/flow/tests/test_desktop_readback.py @@ -100,7 +101,7 @@ jobs: pytest -v -rs -p no:cacheprovider tests/test_windows_attempt_ledger.py \ tests/test_approval_form_window.py tests/test_approval_form_fields.py \ tests/test_binary_file_descriptors.py tests/test_native_value_completeness.py \ - tests/test_native_sensitive_reads.py \ + tests/test_native_sensitive_reads.py tests/test_form_projection_refusal.py \ tests/test_approval_value_completeness.py tests/test_native_value_deployment.py \ tests/test_structural_value_completeness.py tests/test_desktop_readback.py \ --junitxml=runs/windows-guards-junit.xml diff --git a/llms-full.txt b/llms-full.txt index 4c9bcecea3..243faff3eb 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -2247,7 +2247,10 @@ What is not: source is qualified. Structural uniqueness is checked at both observation endpoints, with fresh fixed-control identity during reads, not continuously or as authority for a later write. Current complete-value Flow/save and - held-out application qualification remain pending. + held-out application qualification remain pending. Unavailable form reads + carry a closed request-local refusal receipt with fixed non-content codes; + it does not establish a specific provider cause beyond the observed channel, + does not collect extra source data after refusal and never permits retry. - No live model has been run against these fixtures yet; the live-model test is off by default because it costs money. diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 6e82d7f8e9..9029c6aa5b 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -30,6 +30,10 @@ current sensitivity guard protects values, previews and capability probes. Failed/unknown capability probes cannot become caption masks. Structural previews and unqualified row inventories do not authorize effect checks. +- Unavailable native form projections return a closed request-local refusal + receipt with stage/channel/reason and already-known numeric metadata only. + Partial fields, names, values and provider exceptions are excluded. No + additional source read, global last-error state, fallback or retry is added. - Approval form state reads proven values separately from the remaining OCR pixels, so caret/title-bar display noise need not alter an unchanged field's value digest ([#2189](https://github.com/OpenAdaptAI/OpenAdapt/issues/2189)). diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index d08519fd63..3a5d9257e9 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -971,7 +971,10 @@ What is not: source is qualified. Structural uniqueness is checked at both observation endpoints, with fresh fixed-control identity during reads, not continuously or as authority for a later write. Current complete-value Flow/save and - held-out application qualification remain pending. + held-out application qualification remain pending. Unavailable form reads + carry a closed request-local refusal receipt with fixed non-content codes; + it does not establish a specific provider cause beyond the observed channel, + does not collect extra source data after refusal and never permits retry. - No live model has been run against these fixtures yet; the live-model test is off by default because it costs money. diff --git a/packages/flow/openadapt_flow/backends/win_agent/README.md b/packages/flow/openadapt_flow/backends/win_agent/README.md index 1b8907b47f..ec20afe446 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/README.md +++ b/packages/flow/openadapt_flow/backends/win_agent/README.md @@ -76,7 +76,7 @@ then polls `/health`. This is what the opt-in e2e harness uses. single-file deployments name that same helper `win_agent_native_value.py`. The standalone server loads only these exact local sibling files and refuses missing or conflicting copies; it never falls back to an installed package. - Client and agent must agree on the server-owned read contract (openadapt.native-value-read/v1) and helper proof v3 before value/preview reads. + Client and agent must agree on the server-owned read contract (openadapt.native-value-read/v2) and helper proof v3 before value/preview reads. 2. Register a logon scheduled task **running as the interactive user** (not SYSTEM), highest privileges: @@ -101,3 +101,13 @@ The original `waa_shim.py` (Flask) is kept only for the desktop benchmark's accepts an optional bearer token, and no longer has an exec route. This package is the **hardened, dependency-free, auth-capable** successor used by `launch_agent()` and the snapshot-safe e2e; both speak the identical `WindowsBackend` contract. + +### Unavailable form observations + +The `window/form-fields` response has a closed `refusal` field. On success it +is null. On refusal, `window` is null, `fields` is empty, and the receipt gives +fixed stage/channel/reason codes with only the already-verified window handle, +process ID and traversal ordinal when known. It contains no names, values, +provider exception text or control representation. No diagnostic source read +runs after refusal, and reasons never select a fallback or retry. This receipt +is request-local observation metadata, not write permission or qualification. diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 8ceba89ee8..e6be19899f 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -1428,7 +1428,7 @@ def _read_control_value(control: object, name: str, default: Any) -> Any: # This contract belongs to the SERVER consumer semantics, not to the helper. # Updating a helper beside an older server cannot advertise a new read policy. -VALUE_READ_CONTRACT = "openadapt.native-value-read/v1" +VALUE_READ_CONTRACT = "openadapt.native-value-read/v2" _EXPECTED_VALUE_PROOF_SCHEMA = "openadapt.native-value-completeness/v3" @@ -2661,9 +2661,175 @@ def _rect(bounds: list[int]) -> list[int]: return [bounds[0], bounds[1], bounds[2] - bounds[0], bounds[3] - bounds[1]] +FORM_REFUSAL_SCHEMA = "openadapt.native-form-projection-refusal/v1" +_FORM_VALUE_REFUSAL_REASONS = frozenset( + { + "value_unavailable", + "value_proof_unavailable", + "required_value_unavailable", + "native_api_unavailable", + "native_window_unavailable_or_not_unicode", + "native_owner_unavailable", + "native_text_timeout_or_failure", + "value_exceeds_limit", + "native_owner_changed", + "native_extent_or_copy_incomplete", + "bound_identity_unavailable", + "native_identity_unavailable", + "native_owner_disagreement", + "value_observation_deadline", + "password_or_password_status_unavailable", + "not_editable_value_control", + "read_only_or_read_only_status_unavailable", + "value_pattern_unavailable", + "value_readability_changed", + "value_observation_changed", + "provider_native_value_disagreement", + "value_observation_unavailable", + "value_identity_changed", + } +) +# One closed model binds reason to its stage/channel. No free-text diagnostic +# slot or provider exception can cross this boundary. +_FORM_REFUSAL_MODEL = { + ("frame", "window"): frozenset({"window_unavailable"}), + ("owned_windows", "window"): frozenset( + {"owned_window_present", "owned_window_inventory_unavailable"} + ), + ("uia_setup", "uia"): frozenset({"uia_unavailable", "root_unavailable"}), + ("traversal", "children"): frozenset({"children_unavailable"}), + ("traversal", "limits"): frozenset({"node_limit", "field_limit", "depth_limit"}), + ("observation", "visibility"): frozenset({"visibility_unknown"}), + ("observation", "geometry"): frozenset({"geometry_unavailable"}), + ("observation", "control_type"): frozenset({"control_type_unavailable"}), + ("observation", "state"): frozenset( + { + "state_capability_unknown", + "composite_state_unrepresented", + "toggle_state_unavailable", + "selection_state_unavailable", + "state_capability_changed", + "state_observation_unavailable", + } + ), + ("observation", "value_capability"): frozenset({"value_capability_unknown"}), + ("observation", "value"): _FORM_VALUE_REFUSAL_REASONS, + ("observation", "value_identity"): frozenset( + {"value_identity_unavailable", "value_identity_changed"} + ), + ("observation", "caption"): frozenset( + {"caption_unavailable", "caption_capability_changed"} + ), + ("final_scope", "window"): frozenset({"final_window_unavailable"}), +} +_FORM_REFUSAL_MODEL = { + key: reasons | {"projection_unavailable"} + for key, reasons in _FORM_REFUSAL_MODEL.items() +} +_FORM_REFUSAL_REASONS = frozenset().union(*_FORM_REFUSAL_MODEL.values()) + + +def valid_form_projection_refusal( + payload: object, *, window: Optional[tuple[int, int]] = None +) -> bool: + """Closed non-content receipt. It cannot authorize a projection or retry.""" + if type(payload) is not dict or set(payload) != { + "schema", + "stage", + "channel", + "reason", + "ordinal", + "window", + }: + return False + if type(payload["schema"]) is not str or payload["schema"] != FORM_REFUSAL_SCHEMA: + return False + if any(type(payload[key]) is not str for key in ("stage", "channel", "reason")): + return False + allowed = _FORM_REFUSAL_MODEL.get((payload["stage"], payload["channel"])) + if allowed is None or payload["reason"] not in allowed: + return False + ordinal = payload["ordinal"] + if ordinal is not None and ( + type(ordinal) is not int or not 0 <= ordinal <= _MAX_UIA_NODES + 1 + ): + return False + framed = payload["window"] + if framed is not None: + if ( + type(framed) is not dict + or set(framed) != {"hwnd", "pid"} + or any( + type(framed[key]) is not int or framed[key] <= 0 + for key in ("hwnd", "pid") + ) + ): + return False + if window is not None and (framed["hwnd"], framed["pid"]) != window: + return False + return True + + +@dataclass(frozen=True) +class _FormProjectionRefusal: + stage: str + channel: str + reason: str + ordinal: Optional[int] = None + + def payload(self, window: Optional[tuple[int, int]] = None) -> dict[str, Any]: + # Never serialize controls, provider errors, names or partial fields. + value = { + "schema": FORM_REFUSAL_SCHEMA, + "stage": self.stage, + "channel": self.channel, + "reason": self.reason, + "ordinal": self.ordinal, + "window": {"hwnd": window[0], "pid": window[1]} + if window is not None + else None, + } + if not valid_form_projection_refusal(value): + raise ValueError("invalid non-content projection refusal") + return value + + +@dataclass(frozen=True) +class _FormProjectionObservation: + fields: Optional[list[dict[str, Any]]] + refusal: Optional[_FormProjectionRefusal] = None + + +def _form_refused( + stage: str, channel: str, reason: object, ordinal: Optional[int] = None +) -> _FormProjectionObservation: + # Only enum values cross the wire. Do not str/repr an unknown reason, even + # if a provider injected its exception into an incomplete observation. + fixed = ( + reason + if type(reason) is str + and reason in _FORM_REFUSAL_MODEL.get((stage, channel), ()) + else "projection_unavailable" + ) + return _FormProjectionObservation( + None, _FormProjectionRefusal(stage, channel, fixed, ordinal) + ) + + +def _form_unavailable( + refusal: _FormProjectionRefusal, window: Optional[tuple[int, int]] = None +) -> dict[str, Any]: + return { + "status": "ok", + "window": None, + "fields": [], + "refusal": refusal.payload(window), + } + + def _window_form_fields( auto: Any, hwnd: int, scope: Callable[[], bool] -) -> tuple[Optional[list[dict[str, Any]]], bool]: +) -> _FormProjectionObservation: """The window's controls whose text UIA reads, in tree order. Each entry is ``{"kind", "rect": [x, y, w, h], "text", "state"}``: @@ -2680,25 +2846,25 @@ def _window_form_fields( Value-backed entries include independent complete-value proof, including empty values. Missing proof refuses the entire projection; OCR is not an alternative for a hidden suffix. Off-screen controls are left out. - ``(None, False)`` when any required observation is unavailable; - ``truncated`` when the walk hit its bounds. + An unavailable observation carries only a request-local closed refusal; + partial fields are discarded. No diagnostic getter runs after refusal. """ from_handle = getattr(auto, "ControlFromHandle", None) if not callable(from_handle): - return None, False + return _form_refused("uia_setup", "uia", "root_unavailable") try: window = from_handle(hwnd) except Exception: # noqa: BLE001 - provider failure is no answer - return None, False + return _form_refused("uia_setup", "uia", "root_unavailable") if window is None: - return None, False + return _form_refused("uia_setup", "uia", "root_unavailable") guard = _native_value_api().require_non_sensitive_value try: guard(window) title = " ".join(str(_control_value(window, "Name", "") or "").split()) guard(window) except Exception: # noqa: BLE001 - no sensitive/unknown name preview - return None, False + return _form_refused("observation", "caption", "caption_unavailable", 0) fields: list[dict[str, Any]] = [] def children_of(control: Any) -> list[Any]: @@ -2710,37 +2876,54 @@ def children_of(control: Any) -> list[Any]: try: stack: list[tuple[Any, int]] = [(c, 1) for c in reversed(children_of(window))] except Exception: # noqa: BLE001 - incomplete UIA is no projection - return None, False + return _form_refused("traversal", "children", "children_unavailable", 0) visited = 0 while stack: control, depth = stack.pop() visited += 1 - if visited > _MAX_UIA_NODES or len(fields) > _MAX_FORM_FIELDS: - return fields, True + if visited > _MAX_UIA_NODES: + return _form_refused("traversal", "limits", "node_limit", visited) + if len(fields) > _MAX_FORM_FIELDS: + return _form_refused("traversal", "limits", "field_limit", visited) control_type = _control_value(control, "ControlTypeName", None) bounds = _bounds(control) offscreen = _form_boolean_property(control, 30022) if offscreen is None: - return None, False + return _form_refused( + "observation", "visibility", "visibility_unknown", visited + ) on_screen = not offscreen - if on_screen and ( - bounds is None or not isinstance(control_type, str) or not control_type - ): - return None, False + if on_screen and bounds is None: + return _form_refused( + "observation", "geometry", "geometry_unavailable", visited + ) + if on_screen and (not isinstance(control_type, str) or not control_type): + return _form_refused( + "observation", "control_type", "control_type_unavailable", visited + ) try: children = children_of(control) except Exception: # noqa: BLE001 - an unknown subtree is not a leaf - return None, False + return _form_refused( + "traversal", "children", "children_unavailable", visited + ) state = None exposes = False if on_screen: observed_state = _form_field_state(control) if not observed_state.complete: - return None, False + return _form_refused( + "observation", "state", observed_state.reason, visited + ) state = observed_state.state capability = _form_exposes_value(control) if capability is None: - return None, False + return _form_refused( + "observation", + "value_capability", + "value_capability_unknown", + visited, + ) exposes = capability def identity(c: object = control) -> Optional[str]: @@ -2765,13 +2948,29 @@ def append_state() -> None: # no Edit/Document or nominal label type may hide an unread value. value_identity = identity() observed = _form_field_value(control, identity) - if ( - not observed.complete - or observed.proof is None - or value_identity is None - or identity() != value_identity - ): - return None, False + if not observed.complete: + reason = ( + observed.reason + if type(observed.reason) is str + and observed.reason in _FORM_REFUSAL_REASONS + else "value_unavailable" + ) + return _form_refused("observation", "value", reason, visited) + if observed.proof is None: + return _form_refused( + "observation", "value", "value_proof_unavailable", visited + ) + if value_identity is None: + return _form_refused( + "observation", + "value_identity", + "value_identity_unavailable", + visited, + ) + if identity() != value_identity: + return _form_refused( + "observation", "value_identity", "value_identity_changed", visited + ) if ( children or control_type @@ -2800,7 +2999,9 @@ def append_state() -> None: ): # A required field with no supported value source is unavailable; # pattern absence does not establish absence of business data. - return None, False + return _form_refused( + "observation", "value", "required_value_unavailable", visited + ) elif control_type == "TitleBarControl": if bounds is not None and on_screen and title: fields.append( @@ -2824,9 +3025,16 @@ def append_state() -> None: ) guard(control) if _form_exposes_value(control) is not False: - return None, False + return _form_refused( + "observation", + "caption", + "caption_capability_changed", + visited, + ) except Exception: # noqa: BLE001 - no sensitive/unknown fallback - return None, False + return _form_refused( + "observation", "caption", "caption_unavailable", visited + ) if name: fields.append( { @@ -2845,22 +3053,17 @@ def append_state() -> None: append_state() if children: if depth >= _MAX_UIA_DEPTH: - return fields, True + return _form_refused("traversal", "limits", "depth_limit", visited) stack.extend((c, depth + 1) for c in reversed(children)) - return fields, len(fields) > _MAX_FORM_FIELDS + if len(fields) > _MAX_FORM_FIELDS: + return _form_refused("traversal", "limits", "field_limit", visited) + return _FormProjectionObservation(fields) def _window_form_fields_operation( payload: dict[str, Any], user32: Any, auto_loader: Callable[[], Any] ) -> dict[str, Any]: - """``window-form-fields``: the window's frame (as ``window-bounds``) and - its text fields' values, for an approval's form state. - - Answers ``window: None`` whenever the read could hide something on the - screen: the window is not one ``window-bounds`` names, the app shows any - other window (it could sit over a field whose pixels the caller leaves - out), or UIA cannot read the window completely. - """ + """One complete projection or its request-local non-content refusal.""" data = _exact_object( payload, required=frozenset({"hwnd", "pid", "value_contract"}), @@ -2871,16 +3074,32 @@ def _window_form_fields_operation( framed = _window_operation("window-bounds", frame_payload, user32) window = framed.get("window") if window is None: - return {"status": "ok", "window": None, "fields": []} + return _form_unavailable( + _FormProjectionRefusal("frame", "window", "window_unavailable") + ) hwnd, pid = window["hwnd"], window["pid"] - for candidate in user32.top_level_windows(): - if candidate == hwnd or user32.pid_of(candidate) != pid: - continue - if not user32.is_visible(candidate): - continue - cloaked = user32.is_cloaked(candidate) - if cloaked is None or not cloaked: - return {"status": "ok", "window": None, "fields": []} + known_window = (hwnd, pid) + try: + for candidate in user32.top_level_windows(): + if candidate == hwnd or user32.pid_of(candidate) != pid: + continue + if not user32.is_visible(candidate): + continue + cloaked = user32.is_cloaked(candidate) + if cloaked is None or not cloaked: + return _form_unavailable( + _FormProjectionRefusal( + "owned_windows", "window", "owned_window_present" + ), + known_window, + ) + except Exception: # noqa: BLE001 - no provider error text in diagnostics + return _form_unavailable( + _FormProjectionRefusal( + "owned_windows", "window", "owned_window_inventory_unavailable" + ), + known_window, + ) def unchanged() -> bool: fresh = _window_operation("window-bounds", frame_payload, user32).get("window") @@ -2894,12 +3113,35 @@ def unchanged() -> bool: for candidate in user32.top_level_windows() ) - auto = auto_loader() - with auto.UIAutomationInitializerInThread(): - fields, truncated = _window_form_fields(auto, hwnd, unchanged) - if fields is None or truncated or not unchanged(): - return {"status": "ok", "window": None, "fields": []} - return {"status": "ok", "window": window, "fields": fields} + result: Optional[_FormProjectionObservation] = None + try: + auto = auto_loader() + with auto.UIAutomationInitializerInThread(): + result = _window_form_fields(auto, hwnd, unchanged) + except Exception: # noqa: BLE001 - a cleanup error never overwrites first refusal + if result is not None and result.refusal is not None: + return _form_unavailable(result.refusal, known_window) + return _form_unavailable( + _FormProjectionRefusal("uia_setup", "uia", "uia_unavailable"), known_window + ) + if result.refusal is not None: + # No unchanged(), tree query or extra getter after the first refusal. + return _form_unavailable(result.refusal, known_window) + if result.fields is None: + return _form_unavailable( + _FormProjectionRefusal("uia_setup", "uia", "projection_unavailable"), + known_window, + ) + try: + current = unchanged() + except Exception: # noqa: BLE001 - no extra source query to diagnose this + current = False + if not current: + return _form_unavailable( + _FormProjectionRefusal("final_scope", "window", "final_window_unavailable"), + known_window, + ) + return {"status": "ok", "window": window, "fields": result.fields, "refusal": None} def _load_uiautomation() -> Any: @@ -2927,10 +3169,10 @@ def _perform_uia(operation: str, payload: dict[str, Any]) -> dict[str, Any]: ) except AgentRequestError: raise - except Exception as exc: # noqa: BLE001 - bounded, never a crash - raise AgentRequestError( - 503, "uia_unavailable", "window state is unavailable" - ) from exc + except Exception: # noqa: BLE001 - no provider exception text in receipt + return _form_unavailable( + _FormProjectionRefusal("uia_setup", "uia", "uia_unavailable") + ) if operation in _WINDOW_OPERATIONS: if os.name != "nt": raise AgentRequestError(503, "uia_unavailable", "Win32 is unavailable") diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index bc7cb80654..b466aab7f8 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -47,7 +47,10 @@ from openadapt_flow.approval_mode.window_fields import valid_form_field from openadapt_flow.backend import ActionDeliveryUncertain, StructuralResolutionRefused -from openadapt_flow.backends.win_agent.server import VALUE_READ_CONTRACT +from openadapt_flow.backends.win_agent.server import ( + VALUE_READ_CONTRACT, + valid_form_projection_refusal, +) from openadapt_flow.backends.win_agent.value_protocol import ( locator_scope, valid_structural_response, @@ -1092,7 +1095,23 @@ def approval_form_fields( {"hwnd": hwnd, "pid": pid, "value_contract": VALUE_READ_CONTRACT}, ) payload = typed.payload - if payload is None or set(payload) != {"status", "window", "fields"}: + if ( + payload is None + or set(payload) != {"status", "window", "fields", "refusal"} + or payload["status"] != "ok" + ): + return None + if payload["refusal"] is not None: + # A closed reason is diagnosis only, never permission or retry. + # Do not retain it as mutable backend/last-error state. + if ( + payload["window"] is not None + or payload["fields"] != [] + or not valid_form_projection_refusal( + payload["refusal"], window=(hwnd, pid) + ) + ): + return None return None bounds = _window_frame(payload["window"], hwnd, pid) fields = payload["fields"] diff --git a/packages/flow/tests/e2e/test_windows_approval_completeness.py b/packages/flow/tests/e2e/test_windows_approval_completeness.py index 77de98284d..1402f37657 100644 --- a/packages/flow/tests/e2e/test_windows_approval_completeness.py +++ b/packages/flow/tests/e2e/test_windows_approval_completeness.py @@ -246,6 +246,13 @@ def identity(): ) assert backend.record_verified_window("probe", *point) fields = backend.approval_form_fields("save") + # Already retained response only: never run another source getter + # to identify a refused control/channel after this request. + projection_response = next( + entry["response"] + for entry in reversed(evidence["transport"]) + if entry["path"] == "/window/form-fields" + ) phase = { "name": name, "managed_before": managed, @@ -261,6 +268,7 @@ def identity(): "direct_complete": observed.complete, "direct_reason": observed.reason, "fields": fields, + "projection_refusal": projection_response.get("refusal"), } evidence["phases"].append(phase) if name == "long": diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index d4777e8f98..b2980a629c 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -54,6 +54,8 @@ def _proof(text, hwnd=100, pid=10): def _proved_fields(answer): + if "status" in answer: + answer.setdefault("refusal", None) for field in answer["fields"]: field["value_identity"] = ( "a" * 64 if field["kind"] in {"edit", "value"} else None diff --git a/packages/flow/tests/test_approval_value_completeness.py b/packages/flow/tests/test_approval_value_completeness.py index cb1d1f16f3..2a181612f3 100644 --- a/packages/flow/tests/test_approval_value_completeness.py +++ b/packages/flow/tests/test_approval_value_completeness.py @@ -150,6 +150,7 @@ def test_bad_value_proof_refuses_before_digest_or_mask_at_both_consumers(kind, f "status": "ok", "window": {"hwnd": 7, "pid": 10, "bounds": list(fields["bounds"])}, "fields": fields["fields"], + "refusal": None, } backend = _through_wire(wire) assert backend.approval_form_fields("save") is None @@ -221,6 +222,7 @@ def test_actual_gate_refuses_incomplete_native_value_before_the_save(tmp_path, p "status": "ok", "window": {"hwnd": 7, "pid": 10, "bounds": list(fields["bounds"])}, "fields": fields["fields"], + "refusal": None, } backend = _through_wire(wire) store = ItemApprovalStore(tmp_path / "run") diff --git a/packages/flow/tests/test_form_projection_refusal.py b/packages/flow/tests/test_form_projection_refusal.py new file mode 100644 index 0000000000..175b327224 --- /dev/null +++ b/packages/flow/tests/test_form_projection_refusal.py @@ -0,0 +1,336 @@ +"""A refused projection reports only closed request-local non-content facts.""" + +from __future__ import annotations + +import json +from concurrent.futures import ThreadPoolExecutor +from copy import deepcopy +from types import SimpleNamespace + +import pytest + +from openadapt_flow.backends.win_agent import server +from tests.test_approval_form_fields import ( + _Control, + _Desktop, + _Init, + _window, + _windows_backend, +) + +MARKER = "fixture-content-must-not-be-returned" + + +def context(*children, hwnd=7, pid=10, cleanup_error=False): + window = _window(*children) + window.NativeWindowHandle, window.ProcessId = hwnd, pid + window.Name = MARKER + desktop = _Desktop() + desktop.windows = {hwnd: (pid, (0, 0, 1024, 720), True, False)} + + class Initializer(_Init): + def __exit__(self, *args): + if cleanup_error: + raise RuntimeError(MARKER) + return None + + auto = SimpleNamespace( + ControlFromHandle=lambda h: window if h == hwnd else None, + UIAutomationInitializerInThread=Initializer, + ) + return window, desktop, auto + + +def operation(desktop, auto, hwnd=7, pid=10): + return server._window_form_fields_operation( + {"hwnd": hwnd, "pid": pid, "value_contract": server.VALUE_READ_CONTRACT}, + desktop, + lambda: auto, + ) + + +def check_refusal(answer, channel, reason, *, ordinal=1, window=(7, 10)): + assert set(answer) == {"status", "window", "fields", "refusal"} + assert ( + answer["status"] == "ok" and answer["window"] is None and answer["fields"] == [] + ) + receipt = answer["refusal"] + assert server.valid_form_projection_refusal(receipt, window=window) + assert receipt["channel"] == channel and receipt["reason"] == reason + assert receipt["ordinal"] == ordinal + assert receipt["window"] == ( + {"hwnd": window[0], "pid": window[1]} if window else None + ) + assert MARKER not in json.dumps(answer) + return receipt + + +@pytest.mark.parametrize( + "fault,channel,reason", + [ + ("visibility", "visibility", "visibility_unknown"), + ("geometry", "geometry", "geometry_unavailable"), + ("control_type", "control_type", "control_type_unavailable"), + ("children", "children", "children_unavailable"), + ("state", "state", "state_capability_unknown"), + ("value_capability", "value_capability", "value_capability_unknown"), + ("required_value", "value", "required_value_unavailable"), + ], +) +def test_closed_refusal_discards_partial_fields_and_provider_content( + fault, channel, reason +): + target = _Control( + "EditControl" if fault == "required_value" else "TextControl", name=MARKER + ) + original = target.GetPropertyValueEx + + def query(property_id, ignore_default): + if (fault, property_id) in { + ("visibility", 30022), + ("state", 30036), + ("value_capability", 30043), + }: + return None + return original(property_id, ignore_default) + + target.GetPropertyValueEx = query + if fault == "geometry": + target.BoundingRectangle = None + elif fault == "control_type": + target.ControlTypeName = None + elif fault == "children": + target.GetChildren = lambda: (_ for _ in ()).throw(RuntimeError(MARKER)) + _, desktop, auto = context(_Control("TitleBarControl"), target) + check_refusal(operation(desktop, auto), channel, reason, ordinal=2) + + +def test_no_source_getter_or_final_census_runs_after_refusal(monkeypatch): + forbidden = [] + stopped = False + + class Target(_Control): + def __getattribute__(self, key): + if stopped and not key.startswith("_"): + forbidden.append(key) + raise AssertionError("source getter after refusal") + return super().__getattribute__(key) + + target = Target("EditControl", value=MARKER) + original_property = target.GetPropertyValueEx + target.GetPropertyValueEx = lambda prop, ignore: ( + None if prop == 30022 else original_property(prop, ignore) + ) + _, desktop, auto = context(target) + original_refuse = server._form_refused + + def refuse(*args, **kwargs): + nonlocal stopped + result = original_refuse(*args, **kwargs) + stopped = True + return result + + monkeypatch.setattr(server, "_form_refused", refuse) + original_window = server._window_operation + frames = [] + + def frame(*args, **kwargs): + frames.append(True) + if stopped: + forbidden.append("window recheck") + raise AssertionError("final frame getter after refusal") + return original_window(*args, **kwargs) + + monkeypatch.setattr(server, "_window_operation", frame) + check_refusal(operation(desktop, auto), "visibility", "visibility_unknown") + assert forbidden == [] and len(frames) == 1 + + +def test_cleanup_exception_does_not_override_first_refusal_or_leak_text(): + target = _Control("TextControl") + original = target.GetPropertyValueEx + target.GetPropertyValueEx = lambda prop, ignore: ( + None if prop == 30022 else original(prop, ignore) + ) + _, desktop, auto = context(target, cleanup_error=True) + check_refusal(operation(desktop, auto), "visibility", "visibility_unknown") + + +def test_unknown_observer_reason_is_not_stringified_or_copied(monkeypatch): + class Opaque: + def __repr__(self): + pytest.fail("provider repr must never be used") + + def __str__(self): + pytest.fail("provider text must never be used") + + monkeypatch.setattr( + server, + "_form_field_state", + lambda _: server._FormStateObservation(False, None, Opaque()), + ) + _, desktop, auto = context(_Control("TextControl", name=MARKER)) + check_refusal(operation(desktop, auto), "state", "projection_unavailable") + + +def test_frame_unavailable_has_no_unverified_window_echo_or_uia_reads(): + _, desktop, _ = context() + desktop.windows = {} + answer = server._window_form_fields_operation( + {"hwnd": 7, "pid": 10, "value_contract": server.VALUE_READ_CONTRACT}, + desktop, + lambda: pytest.fail("UIA read after frame unavailable"), + ) + receipt = check_refusal( + answer, "window", "window_unavailable", ordinal=None, window=None + ) + assert receipt["stage"] == "frame" + + +def test_owned_window_refusal_does_not_load_uia(): + _, desktop, _ = context() + desktop.windows[8] = (10, (20, 20, 200, 100), True, False) + answer = server._window_form_fields_operation( + {"hwnd": 7, "pid": 10, "value_contract": server.VALUE_READ_CONTRACT}, + desktop, + lambda: pytest.fail("UIA read after owned-window refusal"), + ) + receipt = check_refusal(answer, "window", "owned_window_present", ordinal=None) + assert receipt["stage"] == "owned_windows" + + +def test_uia_setup_failure_is_closed_and_non_content(): + _, desktop, _ = context() + answer = server._window_form_fields_operation( + {"hwnd": 7, "pid": 10, "value_contract": server.VALUE_READ_CONTRACT}, + desktop, + lambda: (_ for _ in ()).throw(RuntimeError(MARKER)), + ) + check_refusal(answer, "uia", "uia_unavailable", ordinal=None) + + +def test_final_scope_failure_reports_original_verified_window_without_extra_recheck(): + _, desktop, auto = context() + calls = [] + original = desktop.rect + + def moved(hwnd): + calls.append(hwnd) + assert len(calls) <= 2 + return original(hwnd) if len(calls) == 1 else (1, 0, 1025, 720) + + desktop.rect = moved + receipt = check_refusal( + operation(desktop, auto), "window", "final_window_unavailable", ordinal=None + ) + assert receipt["stage"] == "final_scope" and len(calls) == 2 + + +@pytest.mark.parametrize("limit", ["nodes", "depth", "fields"]) +def test_limit_receipt_discards_partial_fields_without_a_recovery_walk( + monkeypatch, limit +): + if limit == "nodes": + monkeypatch.setattr(server, "_MAX_UIA_NODES", 0) + children = [_Control("TextControl")] + reason, ordinal = "node_limit", 1 + elif limit == "depth": + monkeypatch.setattr(server, "_MAX_UIA_DEPTH", 0) + children = [_Control("PaneControl", children=[_Control("TextControl")])] + reason, ordinal = "depth_limit", 1 + else: + monkeypatch.setattr(server, "_MAX_FORM_FIELDS", 0) + children = [_Control("TitleBarControl"), _Control("TextControl")] + reason, ordinal = "field_limit", 2 + _, desktop, auto = context(*children) + check_refusal(operation(desktop, auto), "limits", reason, ordinal=ordinal) + + +def test_interleaved_requests_cannot_share_or_overwrite_refusal_identity(): + def request(number): + target = _Control("TextControl") + original = target.GetPropertyValueEx + target.GetPropertyValueEx = lambda prop, ignore: ( + None if prop == 30022 else original(prop, ignore) + ) + hwnd, pid = 10 + number, 100 + number + count = number % 3 + _, desktop, auto = context( + *[_Control("TitleBarControl") for _ in range(count)], + target, + hwnd=hwnd, + pid=pid, + ) + answer = operation(desktop, auto, hwnd=hwnd, pid=pid) + check_refusal( + answer, + "visibility", + "visibility_unknown", + ordinal=count + 1, + window=(hwnd, pid), + ) + return answer + + with ThreadPoolExecutor(max_workers=4) as pool: + answers = list(pool.map(request, range(12))) + assert len({answer["refusal"]["window"]["hwnd"] for answer in answers}) == 12 + _, desktop, auto = context() + successful = operation(desktop, auto) + assert successful["refusal"] is None and successful["window"] is not None + + +@pytest.mark.parametrize( + "fault", + [ + "extra", + "free_reason", + "wrong_channel", + "bool_ordinal", + "wrong_window", + "extra_window_key", + "nonstring_schema", + ], +) +def test_client_rejects_malformed_refusal_without_retry_or_error_cache(fault): + receipt = server._FormProjectionRefusal( + "observation", "visibility", "visibility_unknown", 1 + ).payload((7, 10)) + if fault == "extra": + receipt["value"] = MARKER + elif fault == "free_reason": + receipt["reason"] = MARKER + elif fault == "wrong_channel": + receipt["channel"] = "geometry" + elif fault == "bool_ordinal": + receipt["ordinal"] = True + elif fault == "wrong_window": + receipt["window"]["pid"] = 99 + elif fault == "extra_window_key": + receipt["window"]["name"] = MARKER + else: + receipt["schema"] = 1 + assert not server.valid_form_projection_refusal(receipt, window=(7, 10)) + wire = {"status": "ok", "window": None, "fields": [], "refusal": receipt} + backend, requests = _windows_backend({"type": (7, 10)}, wire) + before = dict(vars(backend)) + assert backend.approval_form_fields("save") is None + assert len(requests) == 1 and vars(backend) == before + + +def test_every_closed_reason_is_diagnostic_only_and_roundtrips(): + for (stage, channel), reasons in server._FORM_REFUSAL_MODEL.items(): + for reason in reasons: + receipt = server._FormProjectionRefusal(stage, channel, reason, 1).payload( + (7, 10) + ) + assert server.valid_form_projection_refusal(receipt, window=(7, 10)) + backend, requests = _windows_backend( + {"type": (7, 10)}, + { + "status": "ok", + "window": None, + "fields": [], + "refusal": deepcopy(receipt), + }, + ) + assert backend.approval_form_fields("save") is None and len(requests) == 1 diff --git a/packages/flow/tests/test_native_sensitive_reads.py b/packages/flow/tests/test_native_sensitive_reads.py index 1e5db263e2..ed92a59dfc 100644 --- a/packages/flow/tests/test_native_sensitive_reads.py +++ b/packages/flow/tests/test_native_sensitive_reads.py @@ -173,6 +173,7 @@ def test_known_nonsensitive_controls_keep_qualified_values_and_explicit_previews "openadapt.native-value-completeness/v1", "openadapt.native-value-completeness/v2", "openadapt.native-value-completeness/v3", + "openadapt.native-value-read/v1", True, ], ) From 7527440e6f8afeae4bb183d3df938bfe3f567ef8 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 03:03:31 -0500 Subject: [PATCH 20/34] Bind native read negotiation to independently understood client code --- .../backends/win_agent/README.md | 6 ++ .../backends/win_agent/server.py | 7 +- .../backends/windows_backend.py | 12 +++- .../flow/tests/test_approval_form_fields.py | 10 +-- .../tests/test_form_projection_refusal.py | 8 +-- .../flow/tests/test_native_sensitive_reads.py | 70 +++++++++++++++++-- 6 files changed, 94 insertions(+), 19 deletions(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/README.md b/packages/flow/openadapt_flow/backends/win_agent/README.md index ec20afe446..b32c29ea4f 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/README.md +++ b/packages/flow/openadapt_flow/backends/win_agent/README.md @@ -111,3 +111,9 @@ process ID and traversal ordinal when known. It contains no names, values, provider exception text or control representation. No diagnostic source read runs after refusal, and reasons never select a fallback or retry. This receipt is request-local observation metadata, not write permission or qualification. + +The host client and guest server declare their understood read contract +independently. The historical server export `VALUE_READ_CONTRACT` is removed: +an older backend module mixed with a newer local server module fails import +before reading a control. Update the package coherently; server metadata never +upgrades the response parser of an older client. diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index e6be19899f..855dc42728 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -1427,15 +1427,18 @@ def _read_control_value(control: object, name: str, default: Any) -> Any: # This contract belongs to the SERVER consumer semantics, not to the helper. +# Deliberately do not export the historical VALUE_READ_CONTRACT name: old +# backend modules imported it and could falsely advertise a newer parser when +# only this local server module was replaced. Mixed old modules must fail import. # Updating a helper beside an older server cannot advertise a new read policy. -VALUE_READ_CONTRACT = "openadapt.native-value-read/v2" +SERVER_VALUE_READ_CONTRACT = "openadapt.native-value-read/v2" _EXPECTED_VALUE_PROOF_SCHEMA = "openadapt.native-value-completeness/v3" def _require_value_contract(value: object) -> None: if ( not isinstance(value, str) - or value != VALUE_READ_CONTRACT + or value != SERVER_VALUE_READ_CONTRACT or _native_value_api().PROOF_SCHEMA != _EXPECTED_VALUE_PROOF_SCHEMA ): raise AgentRequestError( diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index b466aab7f8..78c101f31c 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -48,7 +48,6 @@ from openadapt_flow.approval_mode.window_fields import valid_form_field from openadapt_flow.backend import ActionDeliveryUncertain, StructuralResolutionRefused from openadapt_flow.backends.win_agent.server import ( - VALUE_READ_CONTRACT, valid_form_projection_refusal, ) from openadapt_flow.backends.win_agent.value_protocol import ( @@ -63,6 +62,9 @@ from openadapt_flow.runtime.step_timing import timed_span DEFAULT_SERVER_URL = "http://localhost:5001" +# The client advertises only the wire semantics implemented by THIS module. +# Never import a version from a possibly newer local server/helper module. +CLIENT_VALUE_READ_CONTRACT = "openadapt.native-value-read/v2" # Hosts treated as loopback: plaintext HTTP to these never leaves the machine, # so it is permitted in dev (with a warning) even when TLS is not required. @@ -1092,7 +1094,11 @@ def approval_form_fields( hwnd, pid = found typed = self._post_typed_read( "/window/form-fields", - {"hwnd": hwnd, "pid": pid, "value_contract": VALUE_READ_CONTRACT}, + { + "hwnd": hwnd, + "pid": pid, + "value_contract": CLIENT_VALUE_READ_CONTRACT, + }, ) payload = typed.payload if ( @@ -1578,7 +1584,7 @@ def read_structural( "/uia/read", { "locator": scope, - "value_contract": VALUE_READ_CONTRACT, + "value_contract": CLIENT_VALUE_READ_CONTRACT, **({"rows": True} if rows else {}), }, ) diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index b2980a629c..a498d5e4bd 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -34,8 +34,10 @@ NativeRead, valid_value_proof, ) -from openadapt_flow.backends.win_agent.server import VALUE_READ_CONTRACT -from openadapt_flow.backends.windows_backend import WindowsBackend +from openadapt_flow.backends.windows_backend import ( + CLIENT_VALUE_READ_CONTRACT, + WindowsBackend, +) def _proof(text, hwnd=100, pid=10): @@ -354,7 +356,7 @@ def test_the_windows_backend_reads_the_fields_of_its_one_window(): assert sent == [ ( "/window/form-fields", - {"hwnd": 7, "pid": 10, "value_contract": VALUE_READ_CONTRACT}, + {"hwnd": 7, "pid": 10, "value_contract": CLIENT_VALUE_READ_CONTRACT}, ) ] assert answer is not None @@ -611,7 +613,7 @@ def read(self, owner, *, guard): def perform(operation, payload): if operation in {"read", "window-form-fields"}: - payload = {"value_contract": VALUE_READ_CONTRACT, **payload} + payload = {"value_contract": CLIENT_VALUE_READ_CONTRACT, **payload} return agent_server._perform_uia(operation, payload) return perform diff --git a/packages/flow/tests/test_form_projection_refusal.py b/packages/flow/tests/test_form_projection_refusal.py index 175b327224..b1fe17fb36 100644 --- a/packages/flow/tests/test_form_projection_refusal.py +++ b/packages/flow/tests/test_form_projection_refusal.py @@ -43,7 +43,7 @@ def __exit__(self, *args): def operation(desktop, auto, hwnd=7, pid=10): return server._window_form_fields_operation( - {"hwnd": hwnd, "pid": pid, "value_contract": server.VALUE_READ_CONTRACT}, + {"hwnd": hwnd, "pid": pid, "value_contract": server.SERVER_VALUE_READ_CONTRACT}, desktop, lambda: auto, ) @@ -177,7 +177,7 @@ def test_frame_unavailable_has_no_unverified_window_echo_or_uia_reads(): _, desktop, _ = context() desktop.windows = {} answer = server._window_form_fields_operation( - {"hwnd": 7, "pid": 10, "value_contract": server.VALUE_READ_CONTRACT}, + {"hwnd": 7, "pid": 10, "value_contract": server.SERVER_VALUE_READ_CONTRACT}, desktop, lambda: pytest.fail("UIA read after frame unavailable"), ) @@ -191,7 +191,7 @@ def test_owned_window_refusal_does_not_load_uia(): _, desktop, _ = context() desktop.windows[8] = (10, (20, 20, 200, 100), True, False) answer = server._window_form_fields_operation( - {"hwnd": 7, "pid": 10, "value_contract": server.VALUE_READ_CONTRACT}, + {"hwnd": 7, "pid": 10, "value_contract": server.SERVER_VALUE_READ_CONTRACT}, desktop, lambda: pytest.fail("UIA read after owned-window refusal"), ) @@ -202,7 +202,7 @@ def test_owned_window_refusal_does_not_load_uia(): def test_uia_setup_failure_is_closed_and_non_content(): _, desktop, _ = context() answer = server._window_form_fields_operation( - {"hwnd": 7, "pid": 10, "value_contract": server.VALUE_READ_CONTRACT}, + {"hwnd": 7, "pid": 10, "value_contract": server.SERVER_VALUE_READ_CONTRACT}, desktop, lambda: (_ for _ in ()).throw(RuntimeError(MARKER)), ) diff --git a/packages/flow/tests/test_native_sensitive_reads.py b/packages/flow/tests/test_native_sensitive_reads.py index ed92a59dfc..cf43c9ae4b 100644 --- a/packages/flow/tests/test_native_sensitive_reads.py +++ b/packages/flow/tests/test_native_sensitive_reads.py @@ -6,7 +6,10 @@ from openadapt_flow.backends.win_agent import server from openadapt_flow.backends.win_agent.native_value import PROOF_SCHEMA -from openadapt_flow.backends.windows_backend import WindowsBackend +from openadapt_flow.backends.windows_backend import ( + CLIENT_VALUE_READ_CONTRACT, + WindowsBackend, +) from openadapt_flow.ir import StructuralLocator from tests.test_approval_form_fields import _agent, _Control, _window @@ -209,7 +212,7 @@ def test_new_client_old_closed_server_refuses_before_any_getter(operation): calls = [] def legacy_route(path, payload): - assert payload["value_contract"] == server.VALUE_READ_CONTRACT + assert payload["value_contract"] == CLIENT_VALUE_READ_CONTRACT required = {"locator"} if operation == "read" else {"hwnd", "pid"} try: server._exact_object( @@ -415,7 +418,7 @@ def __getattr__(self, name): if operation == "read" else {"hwnd": 7, "pid": 10} ) - payload["value_contract"] = server.VALUE_READ_CONTRACT + payload["value_contract"] = server.SERVER_VALUE_READ_CONTRACT with pytest.raises( server.AgentRequestError, match="incompatible native value contract" ): @@ -431,11 +434,11 @@ def test_changing_only_helper_cannot_make_old_server_advertise_new_consumer_poli # sends a server-consumer namespace, deliberately different from ANY # supported helper proof version, so helper-only replacement cannot turn # the old read/probe/preview semantics into the new protocol. - assert server.VALUE_READ_CONTRACT.startswith("openadapt.native-value-read/") - assert server.VALUE_READ_CONTRACT != PROOF_SCHEMA + assert server.SERVER_VALUE_READ_CONTRACT.startswith("openadapt.native-value-read/") + assert server.SERVER_VALUE_READ_CONTRACT != PROOF_SCHEMA for version in ("v1", "v2", "v3"): old_server_helper_contract = "openadapt.native-value-completeness/" + version - assert server.VALUE_READ_CONTRACT != old_server_helper_contract + assert server.SERVER_VALUE_READ_CONTRACT != old_server_helper_contract @pytest.mark.parametrize("state_kind", ["toggle", "selection"]) @@ -639,3 +642,58 @@ def test_any_capability_true_generic_value_retains_unmasked_complete_obligation( target.native_override = "full generic value with omitted suffix" refused = invoke(monkeypatch, target, "form") assert refused["window"] is None and refused["fields"] == [] + + +@pytest.mark.parametrize("historical_head", ["93347ab1", "b1b6cbdf"]) +def test_historical_client_import_cannot_advertise_new_local_server_contract( + historical_head, +): + # This exact historical import precedes every backend read in both public + # modules. The independent reviewer also loads each full immutable module. + source = ( + "from openadapt_flow.backends.win_agent.server import VALUE_READ_CONTRACT\n" + "raise AssertionError('legacy backend must never reach its body')\n" + ) + assert "VALUE_READ_CONTRACT" not in vars(server) + with pytest.raises(ImportError, match="VALUE_READ_CONTRACT"): + exec( + compile( + source, f"historical-{historical_head}-windows_backend-import", "exec" + ), + {}, + ) + + +def test_client_contract_does_not_follow_local_server_metadata(monkeypatch): + monkeypatch.setattr( + server, "SERVER_VALUE_READ_CONTRACT", "openadapt.native-value-read/future" + ) + calls = [] + content_reads = [] + + class NoProvider: + def __getattr__(self, name): + content_reads.append(name) + raise AssertionError("incompatible client must refuse before source access") + + backend = object.__new__(WindowsBackend) + backend._approval_window = lambda *_args: (7, 10) + + def post(path, payload): + calls.append(payload["value_contract"]) + with pytest.raises( + server.AgentRequestError, match="incompatible native value contract" + ): + if path == "/uia/read": + server._perform_uia_initialized(NoProvider(), "read", payload) + else: + server._window_form_fields_operation( + payload, NoProvider(), NoProvider() + ) + return SimpleNamespace(available=False, payload=None) + + backend._post_typed_read = post + assert backend.read_structural(StructuralLocator(automation_id="field")) is None + assert backend.approval_form_fields() is None + assert calls == [CLIENT_VALUE_READ_CONTRACT, CLIENT_VALUE_READ_CONTRACT] + assert content_reads == [] From 4be4b543da10286105090950c57a89d5e7a9a497 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 03:47:30 -0500 Subject: [PATCH 21/34] fix(verification): isolate complete-value helper annotations --- .../backends/win_agent/native_value.py | 2 - .../tests/test_native_value_completeness.py | 51 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 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 ffb18801dd..78e47eb02e 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -6,8 +6,6 @@ are used. The caller also supplies its current focus/window identity guard. """ -from __future__ import annotations - import ctypes import hashlib import time diff --git a/packages/flow/tests/test_native_value_completeness.py b/packages/flow/tests/test_native_value_completeness.py index 983947ec9e..70b3ed503e 100644 --- a/packages/flow/tests/test_native_value_completeness.py +++ b/packages/flow/tests/test_native_value_completeness.py @@ -557,3 +557,54 @@ def GetValuePattern(self): not result.complete and result.reason == "password_or_password_status_unavailable" ) + + +def test_exact_helper_bytes_need_no_global_import_cache_registration() -> None: + import inspect + import sys + from pathlib import Path + from types import ModuleType + + from openadapt_flow.backends.win_agent import native_value + + source = Path(native_value.__file__).read_bytes() + name = "_unregistered_native_value_test" + assert name not in sys.modules + module = ModuleType(name) + # Compile inside this future-annotations test module: caller flags must + # not turn the helper's concrete annotations back into deferred strings. + exec( + compile(source, str(native_value.__file__), "exec", dont_inherit=True), + module.__dict__, + ) + assert name not in sys.modules + for value in vars(module).values(): + if (inspect.isfunction(value) or inspect.isclass(value)) and getattr( + value, "__module__", None + ) == name: + assert all( + type(annotation) is not str + for annotation in getattr(value, "__annotations__", {}).values() + ) + if inspect.isclass(value): + for member in vars(value).values(): + if inspect.isfunction(member): + assert all( + type(annotation) is not str + for annotation in member.__annotations__.values() + ) + owner = module.NativeOwner(1, 2, 3) + assert module.NativeRead(owner, 0, 0, "").value == "" + proof = module.ValueProof( + module.PROOF_SCHEMA, + "uia-value+wm-gettext", + 1, + 2, + 3, + 0, + module.hashlib.sha256(b"").hexdigest(), + ) + result = module.CompleteValue(True, "", None, proof) + assert result.complete and module.valid_value_proof( + result.value, result.proof.payload() + ) From a222b03a31be839cdf1c6d4ff261297334d11d6e Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 03:50:07 -0500 Subject: [PATCH 22/34] fix(windows): preserve loader isolation and lookup freshness --- .../backends/win_agent/server.py | 13 ++++----- packages/flow/tests/test_lookup_detect.py | 28 +++++++++++++++++-- .../tests/test_native_value_deployment.py | 5 ++++ 3 files changed, 36 insertions(+), 10 deletions(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 855dc42728..96530c5f24 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -1405,14 +1405,11 @@ def _native_value_api() -> Any: if spec is None or spec.loader is None: raise ImportError("exact local native-value helper cannot be loaded") module = importlib.util.module_from_spec(spec) - sys.modules[key] = module - try: - # Execute the exact bytes selected above, not a same-name installed - # module or a second path read after validating the selected source. - exec(compile(raw, str(path), "exec"), module.__dict__) - except Exception: - sys.modules.pop(key, None) - raise + # Execute the exact selected bytes without changing the interpreter's + # global import cache. The helper uses concrete annotations, so its + # dataclasses do not need a registered module to resolve forward strings. + # Do not inherit this server's future-annotations compiler flag. + exec(compile(raw, str(path), "exec", dont_inherit=True), module.__dict__) _STANDALONE_NATIVE_VALUE_API = module return module diff --git a/packages/flow/tests/test_lookup_detect.py b/packages/flow/tests/test_lookup_detect.py index 44be744635..399a5406a4 100644 --- a/packages/flow/tests/test_lookup_detect.py +++ b/packages/flow/tests/test_lookup_detect.py @@ -160,7 +160,12 @@ def test_no_look_up_means_no_proposal(tmp_path: Path) -> None: assert detect_lookup(recording) is None -def test_the_proposed_check_confirms_the_booking(tmp_path: Path) -> None: +@pytest.mark.parametrize( + "prior_loaded_view", [False, True], ids=["cold-view-unknown", "prior-view-changes"] +) +def test_the_proposed_check_confirms_the_booking( + tmp_path: Path, prior_loaded_view: bool +) -> None: recording, kiosk = _record(tmp_path) proposal = detect_lookup(recording) assert proposal is not None @@ -179,9 +184,22 @@ def test_the_proposed_check_confirms_the_booking(tmp_path: Path) -> None: spec = DesktopReadbackSpec.model_validate(section) readers: list[KioskLookupTransport] = [] + if prior_loaded_view: + # A separately stored prior record gives the positive fixture a real + # complete before-view and a changed after-view. A missing marker in + # the cold fixture is still unknown, never proof of absence/freshness. + kiosk.book( + "REQ-4814", "MRN B2002", "Prior Fixture", "2026-11-01 08:30", "Intake" + ) def open_backend(user: str, password: str) -> tuple[Any, DesktopSessionFacts]: reader = KioskLookupTransport(kiosk.db_path) # a fresh RDP logon + if prior_loaded_view: + reader.lookup = "REQ-4814" + reader._find() + # An empty query box with an already-loaded result avoids testing + # select-all input here; the old result remains until Find. + reader.lookup = "" readers.append(reader) return FreeRDPBackend(reader), DesktopSessionFacts(True, True, True, "ocr") @@ -198,7 +216,13 @@ def open_backend(user: str, password: str) -> tuple[Any, DesktopSessionFacts]: raw = {k: v for k, v in raw.items() if k != "needs_operator_confirmation"} effect = Effect.model_validate({**raw, "timeout_s": 0.0}).resolve(PARAMS) verdict = verifier.verify(effect, before) - assert verdict.verdict is Verdict.CONFIRMED, verdict.reason + if prior_loaded_view: + assert verdict.verdict is Verdict.CONFIRMED, verdict.reason + else: + assert verdict.verdict is Verdict.INDETERMINATE, verdict.reason + assert verdict.unavailable + assert "record view did not load" in verdict.reason + assert before.reachable is prior_loaded_view assert readers assert all(r.save_clicks == 0 and r.booking_typed == "" for r in readers) diff --git a/packages/flow/tests/test_native_value_deployment.py b/packages/flow/tests/test_native_value_deployment.py index 07258da07d..ef38ee89c2 100644 --- a/packages/flow/tests/test_native_value_deployment.py +++ b/packages/flow/tests/test_native_value_deployment.py @@ -140,7 +140,12 @@ def test_standalone_server_requires_exact_local_helper_for_every_documented_layo server = importlib.util.module_from_spec(spec) sys.modules[spec.name] = server spec.loader.exec_module(server) +cache_before = {name: sys.modules[name] for name in ('win_agent_native_value', 'native_value')} helper = server._native_value_api() +assert helper.__name__ not in sys.modules +assert all(sys.modules[name] is value for name, value in cache_before.items()) +assert not any(name.startswith('_win_agent_native_value_') for name in sys.modules) +assert helper.NativeOwner.__annotations__ == {'hwnd': int, 'pid': int, 'thread': int} assert Path(helper.__file__).resolve().parent == Path(sys.argv[1]).resolve().parent assert Path(helper.__spec__.origin).resolve() == Path(helper.__file__).resolve() assert hashlib.sha256(Path(helper.__file__).read_bytes()).hexdigest() == sys.argv[2] From 1a2503da4e240ba24620845cf85737d087c38e39 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 04:32:07 -0500 Subject: [PATCH 23/34] fix(verification): attribute unavailable raw property observations --- llms-full.txt | 9 +- packages/flow/CHANGELOG.md | 12 +- packages/flow/docs/LIMITS.md | 9 +- .../backends/win_agent/server.py | 229 ++++++++++--- .../backends/windows_backend.py | 6 +- .../tests/test_form_projection_refusal.py | 320 +++++++++++++++++- 6 files changed, 517 insertions(+), 68 deletions(-) diff --git a/llms-full.txt b/llms-full.txt index 243faff3eb..41376c3109 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -2248,9 +2248,12 @@ What is not: endpoints, with fresh fixed-control identity during reads, not continuously or as authority for a later write. Current complete-value Flow/save and held-out application qualification remain pending. Unavailable form reads - carry a closed request-local refusal receipt with fixed non-content codes; - it does not establish a specific provider cause beyond the observed channel, - does not collect extra source data after refusal and never permits retry. + carry a closed request-local refusal receipt with fixed non-content codes. + For the existing raw boolean probes it names only the property category, + guard/query phase and result category; this does not establish a provider + cause. It collects no extra source data after refusal and never permits + retry. Read-v3 client/server declarations are independent of helper proof-v3; + older incompatible consumers refuse before source getters. - No live model has been run against these fixtures yet; the live-model test is off by default because it costs money. diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 9029c6aa5b..6afc45c7f4 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -25,14 +25,18 @@ an advertised native approval channel does not fall back to OCR. Empty complete values remain values. A container cannot hide unread descendants ([#2291](https://github.com/OpenAdaptAI/OpenAdapt/pull/2291)). -- Value reads negotiate a server-owned read contract and require helper proof v3 - before any preview or value getter. One +- Value reads negotiate independent client/server read-v3 declarations and + require the separate helper proof-v3 contract before any preview or value + getter. Incompatible consumers refuse before provider access; versioned + refusal-parser imports reject mixed local modules. One current sensitivity guard protects values, previews and capability probes. Failed/unknown capability probes cannot become caption masks. Structural previews and unqualified row inventories do not authorize effect checks. - Unavailable native form projections return a closed request-local refusal - receipt with stage/channel/reason and already-known numeric metadata only. - Partial fields, names, values and provider exceptions are excluded. No + receipt with stage/channel/reason and already-known numeric metadata. A + closed property/guard-phase/result category locates raw-boolean failures; + the first unknown stops later probes. Partial fields, names, values, raw COM + objects and provider exceptions are excluded. No additional source read, global last-error state, fallback or retry is added. - Approval form state reads proven values separately from the remaining OCR pixels, so caret/title-bar display noise need not alter an unchanged field's diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index 3a5d9257e9..73c7626860 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -972,9 +972,12 @@ What is not: endpoints, with fresh fixed-control identity during reads, not continuously or as authority for a later write. Current complete-value Flow/save and held-out application qualification remain pending. Unavailable form reads - carry a closed request-local refusal receipt with fixed non-content codes; - it does not establish a specific provider cause beyond the observed channel, - does not collect extra source data after refusal and never permits retry. + carry a closed request-local refusal receipt with fixed non-content codes. + For the existing raw boolean probes it names only the property category, + guard/query phase and result category; this does not establish a provider + cause. It collects no extra source data after refusal and never permits + retry. Read-v3 client/server declarations are independent of helper proof-v3; + older incompatible consumers refuse before source getters. - No live model has been run against these fixtures yet; the live-model test is off by default because it costs money. diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 96530c5f24..15da975b5f 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -1428,7 +1428,7 @@ def _read_control_value(control: object, name: str, default: Any) -> Any: # backend modules imported it and could falsely advertise a newer parser when # only this local server module was replaced. Mixed old modules must fail import. # Updating a helper beside an older server cannot advertise a new read policy. -SERVER_VALUE_READ_CONTRACT = "openadapt.native-value-read/v2" +SERVER_VALUE_READ_CONTRACT = "openadapt.native-value-read/v3" _EXPECTED_VALUE_PROOF_SCHEMA = "openadapt.native-value-completeness/v3" @@ -2499,26 +2499,103 @@ def _window_operation( _UIA_IS_VALUE_PATTERN_AVAILABLE = 30043 -def _form_boolean_property(control: object, property_id: int) -> Optional[bool]: - """An exact supported UIA boolean property, or unknown; never default. +_FORM_PROPERTY_NAMES = { + 30041: "toggle", + 30036: "selection_item", + 30043: "value", + 30022: "offscreen", +} +_FORM_PROPERTY_PHASES = { + "guard_before_lookup": frozenset({"guard_refused"}), + "lookup": frozenset({"lookup_unavailable", "lookup_error"}), + "guard_before_query": frozenset({"guard_refused"}), + "query": frozenset({"query_error"}), + "guard_after_query": frozenset({"guard_refused"}), + "result_kind": frozenset({"none", "non_bool"}), +} + + +def _valid_form_property_detail(value: object) -> bool: + if type(value) is not dict or set(value) != {"property", "phase", "outcome"}: + return False + if any(type(item) is not str for item in value.values()): + return False + return value["property"] in _FORM_PROPERTY_NAMES.values() and value[ + "outcome" + ] in _FORM_PROPERTY_PHASES.get(value["phase"], ()) - UIA's availability property is VT_BOOL. Ignore default values so a missing - property yields the reserved unsupported object, not a default False that - could authorize Name fallback. Provider failures remain unknown. The probe - itself never touches a Value/Legacy/Name getter. + +@dataclass(frozen=True) +class _FormPropertyDetail: + property: str + phase: str + outcome: str + + def payload(self) -> dict[str, str]: + value = { + "property": self.property, + "phase": self.phase, + "outcome": self.outcome, + } + if not _valid_form_property_detail(value): + raise ValueError("invalid non-content property detail") + return value + + +@dataclass(frozen=True) +class _FormBooleanObservation: + value: Optional[bool] + detail: Optional[_FormPropertyDetail] = None + + +def _form_boolean_observation( + control: object, property_id: int +) -> _FormBooleanObservation: + """One existing raw-property probe, with closed failure attribution only. + + This never queries again to diagnose an unknown. Each guard/lookup/query + runs at most once; an already-unknown lookup/result stops immediately. + No provider text, type name, exception + value or representation enters the request-local result. """ - guard = _native_value_api().require_non_sensitive_value + name = _FORM_PROPERTY_NAMES.get(property_id) if type(property_id) is int else None + if name is None: + return _FormBooleanObservation(None) + + def refused(phase: str, outcome: str) -> _FormBooleanObservation: + return _FormBooleanObservation(None, _FormPropertyDetail(name, phase, outcome)) + try: + guard = _native_value_api().require_non_sensitive_value guard(control) - method = _control_value(control, "GetPropertyValueEx", None) + except Exception: # noqa: BLE001 - no provider exception data + return refused("guard_before_lookup", "guard_refused") + try: + method = getattr(control, "GetPropertyValueEx", None) + except Exception: # noqa: BLE001 - no diagnostic lookup after failure + return refused("lookup", "lookup_error") + if not callable(method): + return refused("lookup", "lookup_unavailable") + try: guard(control) - if not callable(method): - return None + except Exception: # noqa: BLE001 - no raw query after guard refusal + return refused("guard_before_query", "guard_refused") + try: available = method(property_id, 1) + except Exception: # noqa: BLE001 - do not stringify COM/provider errors + return refused("query", "query_error") + if type(available) is not bool: + return refused("result_kind", "none" if available is None else "non_bool") + try: guard(control) - return available if type(available) is bool else None - except Exception: # noqa: BLE001 - unknown capability is not absence - return None + except Exception: # noqa: BLE001 - no post-refusal diagnostic getter + return refused("guard_after_query", "guard_refused") + return _FormBooleanObservation(available) + + +def _form_boolean_property(control: object, property_id: int) -> Optional[bool]: + """An exact supported boolean, or unknown; never default or absence.""" + return _form_boolean_observation(control, property_id).value def _form_exposes_value(control: object) -> Optional[bool]: @@ -2598,15 +2675,11 @@ class _FormStateObservation: complete: bool state: Optional[str] reason: Optional[str] = None + detail: Optional[_FormPropertyDetail] = None def _form_field_state(control: object) -> _FormStateObservation: - """Distinguish known absent state patterns from unknown observations. - - This describes the two state patterns in the declared form projection; - it does not establish element absence, record identity or a business value. - Composite toggle+selection state has no wire representation and refuses. - """ + """Known absent patterns differ from unknown, with first-refusal detail.""" guard = _native_value_api().require_non_sensitive_value def read(capability: str, attribute: str) -> Any: @@ -2622,38 +2695,54 @@ def read(capability: str, attribute: str) -> Any: return value try: - toggle = _form_boolean_property(control, 30041) - selection = _form_boolean_property(control, 30036) - if toggle is None or selection is None: - return _FormStateObservation(False, None, "state_capability_unknown") + toggle_probe = _form_boolean_observation(control, 30041) + if toggle_probe.value is None: + return _FormStateObservation( + False, None, "state_capability_unknown", toggle_probe.detail + ) + selection_probe = _form_boolean_observation(control, 30036) + if selection_probe.value is None: + return _FormStateObservation( + False, None, "state_capability_unknown", selection_probe.detail + ) + toggle, selection = toggle_probe.value, selection_probe.value if toggle and selection: return _FormStateObservation(False, None, "composite_state_unrepresented") - def unchanged() -> bool: - return ( - _form_boolean_property(control, 30041), - _form_boolean_property(control, 30036), - ) == (toggle, selection) + def recheck() -> tuple[bool, Optional[_FormPropertyDetail]]: + for property_id, expected in ((30041, toggle), (30036, selection)): + current = _form_boolean_observation(control, property_id) + if current.value is None: + return False, current.detail + if current.value != expected: + return False, None + return True, None if toggle: value = read("GetTogglePattern", "ToggleState") if type(value) is not int or value not in _TOGGLE_STATES: return _FormStateObservation(False, None, "toggle_state_unavailable") - if not unchanged(): - return _FormStateObservation(False, None, "state_capability_changed") + complete, detail = recheck() + if not complete: + return _FormStateObservation( + False, None, "state_capability_changed", detail + ) return _FormStateObservation(True, _TOGGLE_STATES[value]) if selection: value = read("GetSelectionItemPattern", "IsSelected") if type(value) is not bool: return _FormStateObservation(False, None, "selection_state_unavailable") - if not unchanged(): - return _FormStateObservation(False, None, "state_capability_changed") + complete, detail = recheck() + if not complete: + return _FormStateObservation( + False, None, "state_capability_changed", detail + ) return _FormStateObservation(True, "selected" if value else "unselected") - complete = unchanged() + complete, detail = recheck() return _FormStateObservation( - complete, None, None if complete else "state_capability_changed" + complete, None, None if complete else "state_capability_changed", detail ) - except Exception: # noqa: BLE001 - no sensitive/unknown state fallback + except Exception: # noqa: BLE001 - non-boolean failures have no property detail return _FormStateObservation(False, None, "state_observation_unavailable") @@ -2661,7 +2750,7 @@ def _rect(bounds: list[int]) -> list[int]: return [bounds[0], bounds[1], bounds[2] - bounds[0], bounds[3] - bounds[1]] -FORM_REFUSAL_SCHEMA = "openadapt.native-form-projection-refusal/v1" +FORM_REFUSAL_SCHEMA = "openadapt.native-form-projection-refusal/v2" _FORM_VALUE_REFUSAL_REASONS = frozenset( { "value_unavailable", @@ -2727,9 +2816,25 @@ def _rect(bounds: list[int]) -> list[int]: for key, reasons in _FORM_REFUSAL_MODEL.items() } _FORM_REFUSAL_REASONS = frozenset().union(*_FORM_REFUSAL_MODEL.values()) +_FORM_PROPERTY_DETAIL_SCOPE = { + ("observation", "visibility", "visibility_unknown"): frozenset({"offscreen"}), + ("observation", "state", "state_capability_unknown"): frozenset( + {"toggle", "selection_item"} + ), + ("observation", "state", "state_capability_changed"): frozenset( + {"toggle", "selection_item"} + ), + ("observation", "value_capability", "value_capability_unknown"): frozenset( + {"value"} + ), + ("observation", "caption", "caption_capability_changed"): frozenset({"value"}), +} -def valid_form_projection_refusal( +# Do not export the legacy unversioned validator: a client must import the +# parser schema it actually implements, not silently borrow a newer/older one +# from a separately replaced local server module. +def valid_form_projection_refusal_v2( payload: object, *, window: Optional[tuple[int, int]] = None ) -> bool: """Closed non-content receipt. It cannot authorize a projection or retry.""" @@ -2740,6 +2845,7 @@ def valid_form_projection_refusal( "reason", "ordinal", "window", + "detail", }: return False if type(payload["schema"]) is not str or payload["schema"] != FORM_REFUSAL_SCHEMA: @@ -2749,6 +2855,14 @@ def valid_form_projection_refusal( allowed = _FORM_REFUSAL_MODEL.get((payload["stage"], payload["channel"])) if allowed is None or payload["reason"] not in allowed: return False + detail = payload["detail"] + if detail is not None: + if not _valid_form_property_detail(detail): + return False + if detail["property"] not in _FORM_PROPERTY_DETAIL_SCOPE.get( + (payload["stage"], payload["channel"], payload["reason"]), () + ): + return False ordinal = payload["ordinal"] if ordinal is not None and ( type(ordinal) is not int or not 0 <= ordinal <= _MAX_UIA_NODES + 1 @@ -2776,6 +2890,7 @@ class _FormProjectionRefusal: channel: str reason: str ordinal: Optional[int] = None + detail: Optional[_FormPropertyDetail] = None def payload(self, window: Optional[tuple[int, int]] = None) -> dict[str, Any]: # Never serialize controls, provider errors, names or partial fields. @@ -2785,11 +2900,12 @@ def payload(self, window: Optional[tuple[int, int]] = None) -> dict[str, Any]: "channel": self.channel, "reason": self.reason, "ordinal": self.ordinal, + "detail": self.detail.payload() if self.detail is not None else None, "window": {"hwnd": window[0], "pid": window[1]} if window is not None else None, } - if not valid_form_projection_refusal(value): + if not valid_form_projection_refusal_v2(value): raise ValueError("invalid non-content projection refusal") return value @@ -2801,7 +2917,11 @@ class _FormProjectionObservation: def _form_refused( - stage: str, channel: str, reason: object, ordinal: Optional[int] = None + stage: str, + channel: str, + reason: object, + ordinal: Optional[int] = None, + detail: Optional[_FormPropertyDetail] = None, ) -> _FormProjectionObservation: # Only enum values cross the wire. Do not str/repr an unknown reason, even # if a provider injected its exception into an incomplete observation. @@ -2812,7 +2932,7 @@ def _form_refused( else "projection_unavailable" ) return _FormProjectionObservation( - None, _FormProjectionRefusal(stage, channel, fixed, ordinal) + None, _FormProjectionRefusal(stage, channel, fixed, ordinal, detail) ) @@ -2887,10 +3007,15 @@ def children_of(control: Any) -> list[Any]: return _form_refused("traversal", "limits", "field_limit", visited) control_type = _control_value(control, "ControlTypeName", None) bounds = _bounds(control) - offscreen = _form_boolean_property(control, 30022) + visibility = _form_boolean_observation(control, 30022) + offscreen = visibility.value if offscreen is None: return _form_refused( - "observation", "visibility", "visibility_unknown", visited + "observation", + "visibility", + "visibility_unknown", + visited, + visibility.detail, ) on_screen = not offscreen if on_screen and bounds is None: @@ -2913,16 +3038,24 @@ def children_of(control: Any) -> list[Any]: observed_state = _form_field_state(control) if not observed_state.complete: return _form_refused( - "observation", "state", observed_state.reason, visited + "observation", + "state", + observed_state.reason, + visited, + observed_state.detail, ) state = observed_state.state - capability = _form_exposes_value(control) + value_probe = _form_boolean_observation( + control, _UIA_IS_VALUE_PATTERN_AVAILABLE + ) + capability = value_probe.value if capability is None: return _form_refused( "observation", "value_capability", "value_capability_unknown", visited, + value_probe.detail, ) exposes = capability @@ -3024,12 +3157,16 @@ def append_state() -> None: str(_control_value(control, "Name", "") or "").split() ) guard(control) - if _form_exposes_value(control) is not False: + caption_probe = _form_boolean_observation( + control, _UIA_IS_VALUE_PATTERN_AVAILABLE + ) + if caption_probe.value is not False: return _form_refused( "observation", "caption", "caption_capability_changed", visited, + caption_probe.detail, ) except Exception: # noqa: BLE001 - no sensitive/unknown fallback return _form_refused( diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index 78c101f31c..824897213b 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -48,7 +48,7 @@ from openadapt_flow.approval_mode.window_fields import valid_form_field from openadapt_flow.backend import ActionDeliveryUncertain, StructuralResolutionRefused from openadapt_flow.backends.win_agent.server import ( - valid_form_projection_refusal, + valid_form_projection_refusal_v2, ) from openadapt_flow.backends.win_agent.value_protocol import ( locator_scope, @@ -64,7 +64,7 @@ DEFAULT_SERVER_URL = "http://localhost:5001" # The client advertises only the wire semantics implemented by THIS module. # Never import a version from a possibly newer local server/helper module. -CLIENT_VALUE_READ_CONTRACT = "openadapt.native-value-read/v2" +CLIENT_VALUE_READ_CONTRACT = "openadapt.native-value-read/v3" # Hosts treated as loopback: plaintext HTTP to these never leaves the machine, # so it is permitted in dev (with a warning) even when TLS is not required. @@ -1113,7 +1113,7 @@ def approval_form_fields( if ( payload["window"] is not None or payload["fields"] != [] - or not valid_form_projection_refusal( + or not valid_form_projection_refusal_v2( payload["refusal"], window=(hwnd, pid) ) ): diff --git a/packages/flow/tests/test_form_projection_refusal.py b/packages/flow/tests/test_form_projection_refusal.py index b1fe17fb36..283f5fee3b 100644 --- a/packages/flow/tests/test_form_projection_refusal.py +++ b/packages/flow/tests/test_form_projection_refusal.py @@ -55,7 +55,7 @@ def check_refusal(answer, channel, reason, *, ordinal=1, window=(7, 10)): answer["status"] == "ok" and answer["window"] is None and answer["fields"] == [] ) receipt = answer["refusal"] - assert server.valid_form_projection_refusal(receipt, window=window) + assert server.valid_form_projection_refusal_v2(receipt, window=window) assert receipt["channel"] == channel and receipt["reason"] == reason assert receipt["ordinal"] == ordinal assert receipt["window"] == ( @@ -250,9 +250,22 @@ def test_interleaved_requests_cannot_share_or_overwrite_refusal_identity(): def request(number): target = _Control("TextControl") original = target.GetPropertyValueEx - target.GetPropertyValueEx = lambda prop, ignore: ( - None if prop == 30022 else original(prop, ignore) - ) + property_id = (30022, 30041, 30036, 30043)[number % 4] + category = { + 30022: ("visibility", "visibility_unknown"), + 30041: ("state", "state_capability_unknown"), + 30036: ("state", "state_capability_unknown"), + 30043: ("value_capability", "value_capability_unknown"), + }[property_id] + + def query(prop, ignore): + if prop != property_id: + return original(prop, ignore) + if number % 2: + raise RuntimeError(MARKER) + return None + + target.GetPropertyValueEx = query hwnd, pid = 10 + number, 100 + number count = number % 3 _, desktop, auto = context( @@ -262,13 +275,17 @@ def request(number): pid=pid, ) answer = operation(desktop, auto, hwnd=hwnd, pid=pid) - check_refusal( + receipt = check_refusal( answer, - "visibility", - "visibility_unknown", + *category, ordinal=count + 1, window=(hwnd, pid), ) + assert receipt["detail"] == { + "property": server._FORM_PROPERTY_NAMES[property_id], + "phase": "query" if number % 2 else "result_kind", + "outcome": "query_error" if number % 2 else "none", + } return answer with ThreadPoolExecutor(max_workers=4) as pool: @@ -309,7 +326,7 @@ def test_client_rejects_malformed_refusal_without_retry_or_error_cache(fault): receipt["window"]["name"] = MARKER else: receipt["schema"] = 1 - assert not server.valid_form_projection_refusal(receipt, window=(7, 10)) + assert not server.valid_form_projection_refusal_v2(receipt, window=(7, 10)) wire = {"status": "ok", "window": None, "fields": [], "refusal": receipt} backend, requests = _windows_backend({"type": (7, 10)}, wire) before = dict(vars(backend)) @@ -323,7 +340,7 @@ def test_every_closed_reason_is_diagnostic_only_and_roundtrips(): receipt = server._FormProjectionRefusal(stage, channel, reason, 1).payload( (7, 10) ) - assert server.valid_form_projection_refusal(receipt, window=(7, 10)) + assert server.valid_form_projection_refusal_v2(receipt, window=(7, 10)) backend, requests = _windows_backend( {"type": (7, 10)}, { @@ -334,3 +351,288 @@ def test_every_closed_reason_is_diagnostic_only_and_roundtrips(): }, ) assert backend.approval_form_fields("save") is None and len(requests) == 1 + + +class _OpaquePropertyError(Exception): + def __repr__(self): + pytest.fail("provider error repr is forbidden") + + def __str__(self): + pytest.fail("provider error text is forbidden") + + +class _OpaquePropertyValue: + def __repr__(self): + pytest.fail("raw property repr is forbidden") + + def __str__(self): + pytest.fail("raw property text is forbidden") + + +_PROPERTY_FAULTS = [ + ("guard_before_lookup", "guard_refused", 1, 0, 0), + ("lookup", "lookup_error", 1, 1, 0), + ("lookup", "lookup_unavailable", 1, 1, 0), + ("guard_before_query", "guard_refused", 2, 1, 0), + ("query", "query_error", 2, 1, 1), + ("guard_after_query", "guard_refused", 3, 1, 1), + ("result_kind", "none", 2, 1, 1), + ("result_kind", "non_bool", 2, 1, 1), +] + + +@pytest.mark.parametrize("property_id,name", list(server._FORM_PROPERTY_NAMES.items())) +@pytest.mark.parametrize("phase,outcome,guards,lookups,queries", _PROPERTY_FAULTS) +def test_raw_boolean_failure_detail_uses_only_original_reads( + monkeypatch, property_id, name, phase, outcome, guards, lookups, queries +): + calls = {"guard": 0, "lookup": 0, "query": 0} + + def guard(_control): + calls["guard"] += 1 + fail_at = { + "guard_before_lookup": 1, + "guard_before_query": 2, + "guard_after_query": 3, + } + if phase in fail_at and calls["guard"] == fail_at[phase]: + raise _OpaquePropertyError() + + class Target: + @property + def GetPropertyValueEx(self): + calls["lookup"] += 1 + if outcome == "lookup_error": + raise _OpaquePropertyError() + if outcome == "lookup_unavailable": + return None + return self.query + + def query(self, prop, ignore): + calls["query"] += 1 + assert (prop, ignore) == (property_id, 1) + if outcome == "query_error": + raise _OpaquePropertyError() + if outcome == "none": + return None + if outcome == "non_bool": + return _OpaquePropertyValue() + return False + + def __getattr__(self, key): + pytest.fail("no unrelated or content getter is permitted") + + monkeypatch.setattr( + server, + "_native_value_api", + lambda: SimpleNamespace(require_non_sensitive_value=guard), + ) + observation = server._form_boolean_observation(Target(), property_id) + assert observation.value is None + assert observation.detail.payload() == { + "property": name, + "phase": phase, + "outcome": outcome, + } + assert calls == {"guard": guards, "lookup": lookups, "query": queries} + assert MARKER not in json.dumps(observation.detail.payload()) + + +@pytest.mark.parametrize("property_id,name", list(server._FORM_PROPERTY_NAMES.items())) +@pytest.mark.parametrize("value", [False, True]) +def test_supported_boolean_values_have_no_failure_detail( + monkeypatch, property_id, name, value +): + calls = [] + + def guard(_): + calls.append("guard") + + target = SimpleNamespace( + GetPropertyValueEx=lambda prop, default: calls.append((prop, default)) or value + ) + monkeypatch.setattr( + server, + "_native_value_api", + lambda: SimpleNamespace(require_non_sensitive_value=guard), + ) + observed = server._form_boolean_observation(target, property_id) + assert observed.value is value and observed.detail is None + assert calls == ["guard", "guard", (property_id, 1), "guard"] + + +@pytest.mark.parametrize("failed_property", [30041, 30036]) +def test_state_first_unknown_prevents_later_probe_or_pattern_reads( + monkeypatch, failed_property +): + calls = [] + + def query(prop, ignore): + calls.append(prop) + return None if prop == failed_property else False + + target = SimpleNamespace(GetPropertyValueEx=query) + monkeypatch.setattr( + server, + "_native_value_api", + lambda: SimpleNamespace(require_non_sensitive_value=lambda _: None), + ) + observed = server._form_field_state(target) + assert not observed.complete and observed.state is None + assert observed.reason == "state_capability_unknown" + assert observed.detail.payload() == { + "property": server._FORM_PROPERTY_NAMES[failed_property], + "phase": "result_kind", + "outcome": "none", + } + assert calls == ([30041] if failed_property == 30041 else [30041, 30036]) + + +def test_state_recheck_unknown_stops_before_the_next_property(monkeypatch): + calls = [] + + def query(prop, ignore): + calls.append(prop) + return None if calls == [30041, 30036, 30041] else False + + target = SimpleNamespace(GetPropertyValueEx=query) + monkeypatch.setattr( + server, + "_native_value_api", + lambda: SimpleNamespace(require_non_sensitive_value=lambda _: None), + ) + observed = server._form_field_state(target) + assert not observed.complete and observed.reason == "state_capability_changed" + assert observed.detail.payload() == { + "property": "toggle", + "phase": "result_kind", + "outcome": "none", + } + assert calls == [30041, 30036, 30041] + + +@pytest.mark.parametrize( + "property_id,channel,reason", + [ + (30022, "visibility", "visibility_unknown"), + (30041, "state", "state_capability_unknown"), + (30036, "state", "state_capability_unknown"), + (30043, "value_capability", "value_capability_unknown"), + ], +) +def test_request_refusal_preserves_property_detail_with_ordinal_without_content( + property_id, channel, reason +): + target = _Control("TextControl", name=MARKER) + original = target.GetPropertyValueEx + target.GetPropertyValueEx = lambda prop, ignore: ( + None if prop == property_id else original(prop, ignore) + ) + _, desktop, auto = context(target, cleanup_error=True) + receipt = check_refusal(operation(desktop, auto), channel, reason) + assert receipt["detail"] == { + "property": server._FORM_PROPERTY_NAMES[property_id], + "phase": "result_kind", + "outcome": "none", + } + + +@pytest.mark.parametrize( + "fault", + ["extra", "property", "phase", "pair", "raw_type", "wrong_channel", "wrong_reason"], +) +def test_detail_closed_shape_and_phase_pairs_cannot_cross_client(fault): + detail = server._FormPropertyDetail("toggle", "result_kind", "none") + receipt = server._FormProjectionRefusal( + "observation", "state", "state_capability_unknown", 1, detail + ).payload((7, 10)) + if fault == "extra": + receipt["detail"]["value"] = MARKER + elif fault == "property": + receipt["detail"]["property"] = MARKER + elif fault == "phase": + receipt["detail"]["phase"] = MARKER + elif fault == "pair": + receipt["detail"]["phase"] = "query" + elif fault == "raw_type": + receipt["detail"]["outcome"] = 30041 + elif fault == "wrong_reason": + receipt["reason"] = "composite_state_unrepresented" + else: + receipt["channel"] = "value_capability" + receipt["reason"] = "value_capability_unknown" + assert not server.valid_form_projection_refusal_v2(receipt, window=(7, 10)) + backend, requests = _windows_backend( + {"type": (7, 10)}, + {"status": "ok", "window": None, "fields": [], "refusal": receipt}, + ) + before = dict(vars(backend)) + assert backend.approval_form_fields("save") is None + assert len(requests) == 1 and vars(backend) == before + + +@pytest.mark.parametrize("operation_name", ["read", "form"]) +def test_wire_v2_refuses_before_any_provider_or_helper_getter( + monkeypatch, operation_name +): + calls = [] + monkeypatch.setattr( + server, + "_native_value_api", + lambda: ( + calls.append("helper") + or pytest.fail("old client must refuse before helper lookup") + ), + ) + + class NoProvider: + def __getattr__(self, key): + calls.append(key) + pytest.fail("old client must refuse before provider lookup") + + payload = {"value_contract": "openadapt.native-value-read/v2"} + if operation_name == "read": + payload["locator"] = {"automation_id": "field"} + else: + payload.update(hwnd=7, pid=10) + with pytest.raises( + server.AgentRequestError, match="incompatible native value contract" + ): + if operation_name == "read": + server._perform_uia_initialized(NoProvider(), "read", payload) + else: + server._window_form_fields_operation(payload, NoProvider(), NoProvider()) + assert calls == [] + + +@pytest.mark.parametrize("historical_head", ["7527440e", "a222b03a"]) +def test_old_v2_client_import_requires_its_original_refusal_parser(historical_head): + assert "valid_form_projection_refusal" not in vars(server) + source = "from openadapt_flow.backends.win_agent.server import valid_form_projection_refusal\nraise AssertionError('old client body must not run')\n" + with pytest.raises(ImportError, match="valid_form_projection_refusal"): + exec( + compile( + source, "historical-" + historical_head + "-validator-import", "exec" + ), + {}, + ) + + +def test_new_client_refuses_old_local_validator_export_before_its_body(monkeypatch): + import sys + from pathlib import Path + from types import ModuleType + + import openadapt_flow.backends.windows_backend as client + + legacy = ModuleType("openadapt_flow.backends.win_agent.server") + legacy.valid_form_projection_refusal = lambda *_args, **_kwargs: pytest.fail( + "legacy validator must never run" + ) + monkeypatch.setitem(sys.modules, legacy.__name__, legacy) + source = Path(client.__file__).read_bytes() + with pytest.raises(ImportError, match="valid_form_projection_refusal_v2"): + exec( + compile(source, str(client.__file__), "exec"), + {"__name__": "mixed_client_source"}, + ) From e67aac28bf3e3ef1f9960a3f58948ff2fd5c63f8 Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Fri, 20 Nov 2026 21:04:50 -0500 Subject: [PATCH 24/34] Record one guarded UIA availability property in the Windows fixture --- .../e2e/test_windows_approval_completeness.py | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/packages/flow/tests/e2e/test_windows_approval_completeness.py b/packages/flow/tests/e2e/test_windows_approval_completeness.py index 7db3b7f1e0..69ec24a5e2 100644 --- a/packages/flow/tests/e2e/test_windows_approval_completeness.py +++ b/packages/flow/tests/e2e/test_windows_approval_completeness.py @@ -4,7 +4,7 @@ virtual cells with no independent native value source do not obscure the specific field contract under test. The original SQLite data and save handler remain. Empty and short values use the modern WinForms accessibility provider, -which supplies explicit pattern availability. The long-value negative uses +to test its reported pattern availability. The long-value negative uses the legacy provider that returns a 4,096-unit prefix. The two processes share the original SQLite seed. Neither the virtual cells nor a full save is covered. """ @@ -126,6 +126,39 @@ def _check_stored(snapshot: dict, expected: str) -> None: assert actual["suffix"] == expected[-16:] +def _first_toggle_property(window, pid: int) -> dict: + """Inspect one native VARIANT before Python unwraps it or approval reads it.""" + from ctypes import byref + + from comtypes.automation import VARIANT, VT_BOOL + from comtypes.client import CreateObject, GetModule + + result = {"ordinal": 1, "property_id": 30041, "complete": False} + guard = server._native_value_api().require_non_sensitive_value + try: + guard(window) + first = window.GetFirstChildControl() + if first is None or first.ProcessId != pid: + return result + uia = GetModule("UIAutomationCore.dll") + client = CreateObject(uia.CUIAutomation, interface=uia.IUIAutomation) + raw = VARIANT() + guard(first) + getter = first.Element._IUIAutomationElement__com_GetCurrentPropertyValueEx + guard(first) + if getter(30041, 1, byref(raw)) != 0: + return result + guard(first) + result["vartype"] = int(raw.vt) + result["is_not_supported"] = bool(client.CheckNotSupported(raw)) + if raw.vt == VT_BOOL: + result["boolean"] = raw.value + result["complete"] = True + except Exception: # A failed diagnostic supplies no substitute for approval. + pass + return result + + def test_native_approval_completeness_refuses_a_provider_prefix(tmp_path, monkeypatch): import uiautomation as auto @@ -215,6 +248,10 @@ def post(url, **kwargs): # reader independently in this process as well as over HTTP. with auto.UIAutomationInitializerInThread(): window = auto.ControlFromHandle(payload["hwnd"]) + if name == "empty": + evidence["first_toggle_property"] = _first_toggle_property( + window, managed["pid"] + ) control = auto.ControlFromHandle(managed["fields"]["probe"]["hwnd"]) user32 = server._user32_factory() initial = server._window_operation("window-bounds", payload, user32)[ From f084564d74e3ea11192e99e41a498384421b0506 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 03:01:28 -0500 Subject: [PATCH 25/34] Check the merged native proof contract in the Windows keyboard fixture --- .../tests/e2e/test_native_keyboard_lease.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/flow/tests/e2e/test_native_keyboard_lease.py b/packages/flow/tests/e2e/test_native_keyboard_lease.py index 4c61bff537..392229e2e3 100644 --- a/packages/flow/tests/e2e/test_native_keyboard_lease.py +++ b/packages/flow/tests/e2e/test_native_keyboard_lease.py @@ -167,8 +167,19 @@ def post(url, **kwargs): def _read(backend, automation_id: str) -> str: result = backend.read_structural(StructuralLocator(automation_id=automation_id)) - assert result is not None and result["match"] == "unique", result - assert result["candidate_count"] == 1 and isinstance(result["text"], str) + if result is None: + pytest.fail("UIA structural read unavailable", pytrace=False) + match, count = result["match"], result["candidate_count"] + if match != "unique" or count != 1: + # WindowsBackend validated the match and count. Keep provider text, + # previews and unrecognized reason strings out of the failure report. + reason = "not_unique" if result["reason"] == "not_unique" else "unclassified" + pytest.fail( + f"UIA census refused (match={match}, candidate_count={count}, reason={reason})", + pytrace=False, + ) + if result["complete"] is not True or not isinstance(result["text"], str): + pytest.fail("UIA value proof incomplete after a unique match", pytrace=False) return result["text"] @@ -783,7 +794,7 @@ def _editable_positive(backend, transport, root, aid, point, expected): ], "point": list(handle.point), "completeness_proof": { - "schema": "openadapt.native-value-completeness/v1", + "schema": "openadapt.native-value-completeness/v3", "method": "uia-value+wm-gettext", "hwnd": managed_before["hwnd"], "pid": managed_before["pid"], From fb25f6c5f5cca5947f77c7c76b06e1164505137e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 05:17:44 -0500 Subject: [PATCH 26/34] Fix agent formatting and record the strict census stop in the native fixture --- .../backends/win_agent/server.py | 55 +++++++++++++------ .../tests/e2e/test_native_keyboard_lease.py | 4 +- .../test_structural_value_completeness.py | 34 ++++++++++++ 3 files changed, 74 insertions(+), 19 deletions(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 6e76b0a224..cd2658c581 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -1118,6 +1118,7 @@ def unavailable(reason: str) -> dict[str, Any]: left <= point[0] < right and top <= point[1] < bottom ): return unavailable("point_outside_focused_target") + def current_binding() -> Optional[str]: current = _focused_target_control(auto, verify_locator_uniqueness=False) return current[1]["fingerprint"] if current is not None else None @@ -1193,26 +1194,45 @@ def _find_candidates( stack: list[tuple[Any, int]] = [(root, 0)] found: list[tuple[Any, dict[str, Any]]] = [] visited = 0 - truncated = False + native_api = None + + def incomplete(stage: str, error: Exception | None = None): + # Fixture diagnostics stay in the guest log. Never log control metadata + # or provider exceptions, including their messages. + if strict_walk and os.environ.get("OAFLOW_AGENT_TRACE_CENSUS") == "1": + if native_api is not None and isinstance( + error, native_api.ValueUnavailable + ): + stage = "sensitivity" + try: + print( + f"[win-agent] strict census stop: {stage}", + file=sys.stderr, + flush=True, + ) + except (OSError, ValueError): + pass + return found, True + while stack: control, depth = stack.pop() visited += 1 if visited > _MAX_UIA_NODES: - truncated = True - break + return incomplete("node_limit") possible = False if strict_walk: # A failed selector/bounds read cannot hide a second match and # turn a partial query into unique value authority. try: - _native_value_api().require_non_sensitive_value(control) + native_api = _native_value_api() + native_api.require_non_sensitive_value(control) facts = { key: _read_control_value(control, key, None) for key in ("AutomationId", "Name", "ControlTypeName") } _native_value_api().require_non_sensitive_value(control) if any(not isinstance(value, str) for value in facts.values()): - return found, True + return incomplete("selector_property") possible = all( expected is None or actual == expected for expected, actual in ( @@ -1238,23 +1258,23 @@ def _find_candidates( if not isinstance( _read_control_value(node, "Name", None), str ): - return found, True + return incomplete("ancestor_name") break node = _parent(node, get=_read_control_value) else: - return found, True - except Exception: # noqa: BLE001 - unknown query scope is incomplete - return found, True + return incomplete("ancestor_depth") + except Exception as exc: # noqa: BLE001 - unknown query scope is incomplete + return incomplete("selector", exc) try: candidate = _candidate( control, get=_read_control_value if strict_walk else _control_value ) - except Exception: # noqa: BLE001 - changing sensitive metadata is no complete census + except Exception as exc: # noqa: BLE001 - changing sensitive metadata is no complete census if strict_walk: - return found, True + return incomplete("candidate_properties", exc) raise if strict_walk and possible and candidate is None: - return found, True + return incomplete("candidate_unavailable") if candidate is not None: matches = True for key in ("automation_id", "role", "name", "window_name"): @@ -1265,25 +1285,24 @@ def _find_candidates( if matches: found.append((control, candidate)) if len(found) >= _MAX_UIA_CANDIDATES: - truncated = True - break + return incomplete("candidate_limit") if depth >= _MAX_UIA_DEPTH and not strict_walk: continue children = _control_value(control, "GetChildren", None) try: if strict_walk and not callable(children): - return found, True + return incomplete("children_unavailable") values = list(children()) if callable(children) else [] except Exception: # noqa: BLE001 if strict_walk: - return found, True + return incomplete("children_error") values = [] if depth >= _MAX_UIA_DEPTH: if values: - return found, True + return incomplete("depth_limit") continue stack.extend((child, depth + 1) for child in reversed(values)) - return found, truncated + return found, False def _structured_text_at(auto: Any, x: int, y: int) -> Optional[str]: diff --git a/packages/flow/tests/e2e/test_native_keyboard_lease.py b/packages/flow/tests/e2e/test_native_keyboard_lease.py index 392229e2e3..4b2d813e5d 100644 --- a/packages/flow/tests/e2e/test_native_keyboard_lease.py +++ b/packages/flow/tests/e2e/test_native_keyboard_lease.py @@ -346,7 +346,9 @@ def test_native_keyboard_lease_actual_delivery_and_refusal(tmp_path, monkeypatch ) evidence["fixture_sha256"] = _sha(app.read_bytes()) try: - backend = host.start_agent() + with monkeypatch.context() as agent_env: + agent_env.setenv("OAFLOW_AGENT_TRACE_CENSUS", "1") + backend = host.start_agent() capabilities = backend.agent_capabilities() evidence["capabilities"] = sorted(capabilities) assert { diff --git a/packages/flow/tests/test_structural_value_completeness.py b/packages/flow/tests/test_structural_value_completeness.py index cc8ba1a60a..07a05874d2 100644 --- a/packages/flow/tests/test_structural_value_completeness.py +++ b/packages/flow/tests/test_structural_value_completeness.py @@ -195,6 +195,40 @@ def test_unqualified_scope_and_name_only_sources_never_become_values( assert answer["text"] is None and answer["complete"] is False +@pytest.mark.parametrize("stage", ["sensitivity", "children_error", "depth_limit"]) +def test_census_trace_records_only_the_stopping_stage(monkeypatch, capsys, stage): + import sys + + import openadapt_flow.backends.win_agent.server as server + + control = _Control("EditControl", value="synthetic fixture content") + control.AutomationId = "field" + window = _window(control) + perform = _agent(monkeypatch, window) + sys.modules["uiautomation"].GetRootControl = lambda: window + if stage == "sensitivity": + control.GetPropertyValueEx = lambda *_: None + elif stage == "children_error": + + def fail(): + raise RuntimeError("private provider exception") + + control.GetChildren = fail + else: + monkeypatch.setattr(server, "_MAX_UIA_DEPTH", 0) + + request = {"locator": {"automation_id": "field"}} + monkeypatch.delenv("OAFLOW_AGENT_TRACE_CENSUS", raising=False) + refusal = perform("read", request) + assert refusal["reason"] == "not_unique" and not refusal["complete"] + assert capsys.readouterr().err == "" + monkeypatch.setenv("OAFLOW_AGENT_TRACE_CENSUS", "1") + assert perform("read", request) == refusal + assert capsys.readouterr().err.splitlines() == [ + f"[win-agent] strict census stop: {stage}" + ] + + def test_row_previews_cannot_authorize_inventory_even_when_empty(): payload = { **complete("value"), From 421390805c3deddc62d65f77158bf682d458b2bf Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:08:54 -0500 Subject: [PATCH 27/34] fix(flow): validate native observations in the host format layer --- .../approval_mode/window_fields.py | 52 +++++++++++++++++-- .../backends/win_agent/value_protocol.py | 18 ++----- .../tests/test_native_value_completeness.py | 13 +++++ 3 files changed, 65 insertions(+), 18 deletions(-) diff --git a/packages/flow/openadapt_flow/approval_mode/window_fields.py b/packages/flow/openadapt_flow/approval_mode/window_fields.py index 873fc3cfbf..70f1a4b22f 100644 --- a/packages/flow/openadapt_flow/approval_mode/window_fields.py +++ b/packages/flow/openadapt_flow/approval_mode/window_fields.py @@ -1,17 +1,63 @@ -"""Closed native form-field wire contract shared by client and approval gate.""" +"""Closed native value and form-field wire formats shared by host consumers.""" from __future__ import annotations +import hashlib +import re from typing import Any -from openadapt_flow.backends.win_agent.value_protocol import valid_value_observation - FIELD_KEYS = frozenset( {"kind", "rect", "text", "state", "value_proof", "value_identity"} ) FIELD_KINDS = frozenset({"title_bar", "edit", "value", "text", "state"}) FIELD_STATES = frozenset({None, "on", "off", "indeterminate", "selected", "unselected"}) +# The host checks the format it understands, independently of the deployed +# guest's proof class and version. The guest also runs as a standalone file. +_VALUE_PROOF_KEYS = frozenset( + { + "schema", + "method", + "hwnd", + "pid", + "thread", + "utf16_units", + "sha256_utf16le", + "native_reads", + "uia_reads", + } +) + + +def valid_value_observation( + value: object, proof: object, identity: object, *, pid: int | None = None +) -> bool: + if ( + not isinstance(value, str) + or not isinstance(identity, str) + or re.fullmatch(r"[0-9a-f]{64}", identity) is None + or not isinstance(proof, dict) + or set(proof) != _VALUE_PROOF_KEYS + ): + return False + raw = value.encode("utf-16-le", errors="surrogatepass") + return ( + proof["schema"] == "openadapt.native-value-completeness/v3" + and proof["method"] == "uia-value+wm-gettext" + and all( + type(proof[k]) is int and proof[k] > 0 for k in ("hwnd", "pid", "thread") + ) + and type(proof["utf16_units"]) is int + and 0 <= proof["utf16_units"] <= 65_536 + and proof["utf16_units"] == len(raw) // 2 + and proof["sha256_utf16le"] == hashlib.sha256(raw).hexdigest() + and type(proof["native_reads"]) is int + and proof["native_reads"] == 2 + and type(proof["uia_reads"]) is int + and proof["uia_reads"] == 2 + and (pid is None or proof["pid"] == pid) + ) + def valid_form_field(field: Any, *, pid: int | None = None) -> bool: """No incomplete native value may authorize either a digest or a mask. diff --git a/packages/flow/openadapt_flow/backends/win_agent/value_protocol.py b/packages/flow/openadapt_flow/backends/win_agent/value_protocol.py index 6e706a8539..e775833ad5 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/value_protocol.py +++ b/packages/flow/openadapt_flow/backends/win_agent/value_protocol.py @@ -2,10 +2,11 @@ from __future__ import annotations -import re from typing import Any, Mapping -from .native_value import valid_value_proof +from openadapt_flow.approval_mode.window_fields import valid_value_observation + +from .native_value import valid_value_proof as valid_value_proof SCOPE_KEYS = ("automation_id", "role", "name", "window_name") READ_KEYS = frozenset( @@ -30,19 +31,6 @@ def locator_scope(locator: Mapping[str, Any]) -> dict[str, Any]: return {key: locator.get(key) for key in SCOPE_KEYS} -def valid_value_observation( - value: object, proof: object, identity: object, *, pid: int | None = None -) -> bool: - return ( - isinstance(value, str) - and isinstance(identity, str) - and re.fullmatch(r"[0-9a-f]{64}", identity) is not None - and isinstance(proof, dict) - and valid_value_proof(value, proof) - and (pid is None or proof["pid"] == pid) - ) - - def valid_structural_response( payload: object, scope: Mapping[str, Any], *, rows: bool = False ) -> bool: diff --git a/packages/flow/tests/test_native_value_completeness.py b/packages/flow/tests/test_native_value_completeness.py index 70b3ed503e..f61311e88a 100644 --- a/packages/flow/tests/test_native_value_completeness.py +++ b/packages/flow/tests/test_native_value_completeness.py @@ -10,6 +10,7 @@ from hypothesis import given from hypothesis import strategies as st +from openadapt_flow.approval_mode.window_fields import valid_value_observation from openadapt_flow.backends.win_agent.native_value import ( PROOF_SCHEMA, NativeOwner, @@ -78,6 +79,7 @@ def test_exact_complete_values_require_both_sources_and_utf16_proof(value): assert result.proof is not None proof = result.proof.payload() assert valid_value_proof(value, proof) + assert valid_value_observation(value, proof, "a" * 64, pid=OWNER.pid) assert proof["utf16_units"] == len(utf16_bytes(value)) // 2 assert proof["hwnd"] == OWNER.hwnd and proof["pid"] == OWNER.pid @@ -239,6 +241,17 @@ def test_client_proof_rejects_missing_fake_or_legacy_completeness(key, value): proof = result.proof.payload() proof[key] = value assert not valid_value_proof("é𝄞 ", proof) + assert not valid_value_observation("é𝄞 ", proof, "a" * 64, pid=OWNER.pid) + + +def test_host_rejects_a_proof_version_understood_only_by_the_guest(monkeypatch): + from openadapt_flow.backends.win_agent import native_value + + monkeypatch.setattr(native_value, "PROOF_SCHEMA", "future-proof-format") + target, _ = control("exact") + proof = observe(target, Reader("exact")).proof.payload() + assert valid_value_proof("exact", proof) + assert not valid_value_observation("exact", proof, "a" * 64, pid=OWNER.pid) class User32: From 4bba2ceb70790427b150f9793196639530ce8124 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:43:16 -0500 Subject: [PATCH 28/34] fix(win-agent): accept Win32 EDIT evidence when a provider does not support IsPassword or pattern availability The hosted WinForms TextBox providers answer IsPassword and IsTogglePatternAvailable with the reserved not-supported value when defaults are ignored, so the strict guard refused every native keyboard lease and approval projection on Windows. A supported boolean is still the provider's answer. Only an unsupported status consults Win32: the control's own EDIT/RichEdit window with no ES_PASSWORD style and EM_GETPASSWORDCHAR 0. An unsupported pattern-availability property asks the raw element's GetCurrentPattern once; a COM error stays unknown. Query errors, missing getters and every other case still refuse. --- .../backends/win_agent/native_value.py | 66 +++++++- .../backends/win_agent/server.py | 40 ++++- .../tests/test_form_projection_refusal.py | 7 + .../flow/tests/test_native_sensitive_reads.py | 155 ++++++++++++++++++ .../tests/test_native_value_completeness.py | 7 +- 5 files changed, 269 insertions(+), 6 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 78e47eb02e..d710840e30 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -15,6 +15,10 @@ MAX_UTF16_UNITS = 65536 PROOF_SCHEMA = "openadapt.native-value-completeness/v3" IS_PASSWORD_PROPERTY = 30019 +# Win32 EDIT password evidence: the ES_PASSWORD style and EM_GETPASSWORDCHAR. +ES_PASSWORD = 0x0020 +EM_GETPASSWORDCHAR = 0x00D2 +_EDIT_CLASSES = frozenset({"edit", "richedit20w", "richedit50w", "richedit60w"}) def utf16_bytes(value: str) -> bytes: @@ -103,6 +107,14 @@ def __init__(self) -> None: ctypes.POINTER(ctypes.c_size_t), ] self._user.SendMessageTimeoutW.restype = ctypes.c_ssize_t + self._user.GetClassNameW.argtypes = [ + wintypes.HWND, + wintypes.LPWSTR, + ctypes.c_int, + ] + self._user.GetClassNameW.restype = ctypes.c_int + self._user.GetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int] + self._user.GetWindowLongW.restype = wintypes.LONG def owner(self, hwnd: int) -> NativeOwner: from ctypes import wintypes @@ -127,6 +139,23 @@ def _message( raise ValueUnavailable("native_text_timeout_or_failure") return int(result.value) + def plain_edit(self, hwnd: int) -> bool: + """True only for a Unicode EDIT window that shows its text. + + Its class is a Win32 or WinForms EDIT/RichEdit class, its style has no + ES_PASSWORD, and EM_GETPASSWORDCHAR answers 0 within the timeout. Any + other class, a failed call or a password character is False. + """ + self.owner(hwnd) + name = ctypes.create_unicode_buffer(257) + if not 0 < self._user.GetClassNameW(hwnd, name, 257) < 257: + return False + if not _edit_class(name.value): + return False + if self._user.GetWindowLongW(hwnd, -16) & ES_PASSWORD: # GWL_STYLE + return False + return self._message(hwnd, EM_GETPASSWORDCHAR) == 0 + def read(self, owner: NativeOwner, *, guard: Callable[[], None]) -> NativeRead: def unchanged() -> None: if self.owner(owner.hwnd) != owner: @@ -155,6 +184,29 @@ def unchanged() -> None: return NativeRead(owner, extent, copied, value) +def _edit_class(name: str) -> bool: + """A Win32 EDIT/RichEdit class, or WinForms' ``WindowsForms10.EDIT.app...``.""" + parts = name.casefold().split(".") + if len(parts) > 2 and parts[0].startswith("windowsforms") and parts[2] == "app": + return parts[1] in _EDIT_CLASSES + return len(parts) == 1 and parts[0] in _EDIT_CLASSES + + +_PASSWORD_EVIDENCE: list[Any] = [] + + +def _native_plain_edit(control: Any) -> bool: + """Win32 evidence for a provider that does not support IsPassword.""" + hwnd = control.NativeWindowHandle + if not _positive_int(hwnd): + return False + if not _PASSWORD_EVIDENCE: + _PASSWORD_EVIDENCE.append(Win32TextReader()) + reader = _PASSWORD_EVIDENCE[0] + plain = getattr(reader, "plain_edit", None) + return callable(plain) and plain(hwnd) is True + + def _positive_int(value: object) -> bool: return type(value) is int and value > 0 @@ -184,10 +236,18 @@ def require_non_sensitive_value(control: Any) -> None: try: # CurrentIsPassword/Control.IsPassword can return a default FALSE for # unsupported status. Request the raw property with defaults ignored; - # a reserved unsupported object is unknown, not non-sensitive. + # a reserved unsupported object is unknown, not non-sensitive. Some + # providers (the WinForms TextBox proxies) do not support IsPassword + # at all; then only Win32 evidence from the control's own EDIT window + # (no ES_PASSWORD style, no password character) allows the read. method = getattr(control, "GetPropertyValueEx", None) - raw = method(IS_PASSWORD_PROPERTY, 1) if callable(method) else None - allowed = type(raw) is bool and raw is False + if not callable(method): + raise ValueUnavailable("password_status_unavailable") + raw = method(IS_PASSWORD_PROPERTY, 1) + if type(raw) is bool: + allowed = raw is False + else: + allowed = _native_plain_edit(control) except Exception: allowed = False if not allowed: diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index cd2658c581..6d4f4b5ec6 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -2774,7 +2774,9 @@ def _form_boolean_observation( """One existing raw-property probe, with closed failure attribution only. This never queries again to diagnose an unknown. Each guard/lookup/query - runs at most once; an already-unknown lookup/result stops immediately. + runs at most once; an already-unknown lookup/result stops immediately, + except that an unsupported pattern-availability answer asks the raw + element for that pattern once (``_form_pattern_support``). No provider text, type name, exception value or representation enters the request-local result. """ @@ -2805,7 +2807,14 @@ def refused(phase: str, outcome: str) -> _FormBooleanObservation: except Exception: # noqa: BLE001 - do not stringify COM/provider errors return refused("query", "query_error") if type(available) is not bool: - return refused("result_kind", "none" if available is None else "non_bool") + # A provider that does not support a pattern-availability property + # (the WinForms proxies answer VT_UNKNOWN) still answers the pattern + # itself: UIA's GetCurrentPattern returns the pattern exactly when it + # is supported. Only that exact answer counts; anything else refuses. + outcome = "none" if available is None else "non_bool" + available = _form_pattern_support(control, property_id, guard) + if available is None: + return refused("result_kind", outcome) try: guard(control) except Exception: # noqa: BLE001 - no post-refusal diagnostic getter @@ -2813,6 +2822,33 @@ def refused(phase: str, outcome: str) -> _FormBooleanObservation: return _FormBooleanObservation(available) +# UIA pattern ids for the availability properties in _FORM_PROPERTY_NAMES. +_FORM_PATTERN_IDS = {30041: 10015, 30036: 10010, 30043: 10002} + + +def _form_pattern_support( + control: object, property_id: int, guard: Callable[[object], None] +) -> Optional[bool]: + """Whether the control supports the pattern, or None when not answerable.""" + pattern_id = _FORM_PATTERN_IDS.get(property_id) + if pattern_id is None: + return None + try: + # The raw IUIAutomationElement, not uiautomation's GetPattern, which + # turns a COM error into the same None as an unsupported pattern. + guard(control) + method = getattr(getattr(control, "Element", None), "GetCurrentPattern", None) + if not callable(method): + return None + guard(control) + pattern = method(pattern_id) + guard(control) + # comtypes answers a NULL interface pointer for an unsupported pattern. + return bool(pattern) + except Exception: # noqa: BLE001 - no provider exception data + return None + + def _form_boolean_property(control: object, property_id: int) -> Optional[bool]: """An exact supported boolean, or unknown; never default or absence.""" return _form_boolean_observation(control, property_id).value diff --git a/packages/flow/tests/test_form_projection_refusal.py b/packages/flow/tests/test_form_projection_refusal.py index 283f5fee3b..0d5fbcd462 100644 --- a/packages/flow/tests/test_form_projection_refusal.py +++ b/packages/flow/tests/test_form_projection_refusal.py @@ -399,6 +399,11 @@ def guard(_control): raise _OpaquePropertyError() class Target: + # An unsupported availability answer consults the raw pattern once + # (server._form_pattern_support); this element exposes no pattern + # getter, so the original refusal detail is kept. + Element = None + @property def GetPropertyValueEx(self): calls["lookup"] += 1 @@ -434,6 +439,8 @@ def __getattr__(self, key): "phase": phase, "outcome": outcome, } + if phase == "result_kind" and property_id in server._FORM_PATTERN_IDS: + guards += 1 # the guard before the pattern-support lookup assert calls == {"guard": guards, "lookup": lookups, "query": queries} assert MARKER not in json.dumps(observation.detail.payload()) diff --git a/packages/flow/tests/test_native_sensitive_reads.py b/packages/flow/tests/test_native_sensitive_reads.py index cf43c9ae4b..8dceaef8dd 100644 --- a/packages/flow/tests/test_native_sensitive_reads.py +++ b/packages/flow/tests/test_native_sensitive_reads.py @@ -697,3 +697,158 @@ def post(path, payload): assert backend.approval_form_fields() is None assert calls == [CLIENT_VALUE_READ_CONTRACT, CLIENT_VALUE_READ_CONTRACT] assert content_reads == [] + + +# Providers that do not support IsPassword or a pattern-availability property +# (the WinForms TextBox proxies on the hosted runner answer VT_UNKNOWN). +from openadapt_flow.backends.win_agent import native_value # noqa: E402 + +_UNSUPPORTED = object() + + +class _Evidence: + def __init__(self, plain): + self.plain = plain + self.hwnds = [] + + def plain_edit(self, hwnd): + self.hwnds.append(hwnd) + if isinstance(self.plain, Exception): + raise self.plain + return self.plain + + +def _unsupported_status_control(raw=_UNSUPPORTED, hwnd=4242): + return SimpleNamespace( + GetPropertyValueEx=lambda prop, ignore: raw, NativeWindowHandle=hwnd + ) + + +@pytest.mark.parametrize( + "raw,hwnd,plain,allowed", + [ + (_UNSUPPORTED, 4242, True, True), + (None, 4242, True, True), + (_UNSUPPORTED, 4242, False, False), + (_UNSUPPORTED, 4242, RuntimeError("timeout"), False), + (_UNSUPPORTED, 0, True, False), + (_UNSUPPORTED, None, True, False), + (True, 4242, True, False), + (False, 4242, False, True), + ("False", 4242, False, False), + ], +) +def test_unsupported_password_status_needs_win32_edit_evidence( + monkeypatch, raw, hwnd, plain, allowed +): + evidence = _Evidence(plain) + monkeypatch.setattr(native_value, "_PASSWORD_EVIDENCE", [evidence]) + control = _unsupported_status_control(raw, hwnd) + if allowed: + native_value.require_non_sensitive_value(control) + else: + with pytest.raises(native_value.ValueUnavailable): + native_value.require_non_sensitive_value(control) + # A supported boolean is the provider's answer; no Win32 fallback for it. + fallback = type(raw) is not bool and isinstance(hwnd, int) and hwnd > 0 + assert evidence.hwnds == ([hwnd] if fallback else []) + + +def test_password_status_query_error_never_falls_back(monkeypatch): + evidence = _Evidence(True) + monkeypatch.setattr(native_value, "_PASSWORD_EVIDENCE", [evidence]) + + def query(prop, ignore): + raise RuntimeError("provider error") + + control = SimpleNamespace(GetPropertyValueEx=query, NativeWindowHandle=4242) + with pytest.raises(native_value.ValueUnavailable): + native_value.require_non_sensitive_value(control) + missing = SimpleNamespace(NativeWindowHandle=4242) + with pytest.raises(native_value.ValueUnavailable): + native_value.require_non_sensitive_value(missing) + assert evidence.hwnds == [] + + +@pytest.mark.parametrize( + "name,edit", + [ + ("Edit", True), + ("RichEdit50W", True), + ("WindowsForms10.EDIT.app.0.141b42a_r6_ad1", True), + ("WindowsForms10.RichEdit20W.app.0.2bf8098_r6_ad1", True), + ("WindowsForms10.BUTTON.app.0.141b42a_r6_ad1", False), + ("Button", False), + ("NotEdit", False), + ("Edit.app", False), + ("", False), + ], +) +def test_edit_class_names(name, edit): + assert native_value._edit_class(name) is edit + + +@pytest.mark.parametrize( + "pattern,expected", [(object(), True), (None, False), (0, False)] +) +def test_unsupported_availability_uses_the_exact_pattern_answer( + monkeypatch, pattern, expected +): + calls = [] + element = SimpleNamespace( + GetCurrentPattern=lambda pattern_id: calls.append(pattern_id) or pattern + ) + target = SimpleNamespace( + GetPropertyValueEx=lambda prop, ignore: _UNSUPPORTED, Element=element + ) + monkeypatch.setattr( + server, + "_native_value_api", + lambda: SimpleNamespace(require_non_sensitive_value=lambda _: None), + ) + observed = server._form_boolean_observation(target, 30041) + assert observed.value is expected and observed.detail is None + assert calls == [10015] + + +@pytest.mark.parametrize("property_id", [30041, 30022]) +def test_unanswerable_availability_still_refuses(monkeypatch, property_id): + def fail(pattern_id): + raise RuntimeError("COM error") + + target = SimpleNamespace( + GetPropertyValueEx=lambda prop, ignore: _UNSUPPORTED, + Element=SimpleNamespace(GetCurrentPattern=fail), + ) + monkeypatch.setattr( + server, + "_native_value_api", + lambda: SimpleNamespace(require_non_sensitive_value=lambda _: None), + ) + observed = server._form_boolean_observation(target, property_id) + assert observed.value is None + assert observed.detail.payload()["outcome"] == "non_bool" + + +def test_availability_fallback_stops_when_the_guard_refuses(monkeypatch): + calls = [] + element = SimpleNamespace( + GetCurrentPattern=lambda pattern_id: calls.append(pattern_id) or object() + ) + target = SimpleNamespace( + GetPropertyValueEx=lambda prop, ignore: _UNSUPPORTED, Element=element + ) + count = [] + + def guard(_): + count.append(1) + if len(count) > 2: + raise native_value.ValueUnavailable("password_status_unavailable") + + monkeypatch.setattr( + server, + "_native_value_api", + lambda: SimpleNamespace(require_non_sensitive_value=guard), + ) + observed = server._form_boolean_observation(target, 30041) + assert observed.value is None and calls == [] diff --git a/packages/flow/tests/test_native_value_completeness.py b/packages/flow/tests/test_native_value_completeness.py index 70b3ed503e..18f22ed0b5 100644 --- a/packages/flow/tests/test_native_value_completeness.py +++ b/packages/flow/tests/test_native_value_completeness.py @@ -388,7 +388,12 @@ def __getattr__(self, name): not result.complete and result.reason == "password_or_password_status_unavailable" ) - assert target.calls == [] + # An unsupported (non-boolean) status asks only for the control's own + # window handle, for Win32 EDIT password evidence; nothing else is read. + if status is True or status == "error": + assert target.calls == [] + else: + assert set(target.calls) == {"NativeWindowHandle"} @pytest.mark.parametrize("stage", ["pattern_lookup", "pattern_call", "readability"]) From d495cc202ee764caf8b6cf1761d08dd0e1ea0438 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:22:26 -0500 Subject: [PATCH 29/34] fix(win-agent): bind alternate native evidence to proven provider states --- .../backends/win_agent/native_value.py | 110 ++++++++++++++---- .../backends/win_agent/server.py | 18 +-- .../flow/tests/test_approval_form_fields.py | 80 ++++++++++++- .../tests/test_form_projection_refusal.py | 10 +- .../flow/tests/test_native_sensitive_reads.py | 86 ++++++++++++-- .../tests/test_native_value_completeness.py | 8 +- 6 files changed, 261 insertions(+), 51 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 d710840e30..557a78bd60 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -152,7 +152,10 @@ def plain_edit(self, hwnd: int) -> bool: return False if not _edit_class(name.value): return False - if self._user.GetWindowLongW(hwnd, -16) & ES_PASSWORD: # GWL_STYLE + # A zero GWL_STYLE is valid only when the call left no Win32 error. + ctypes.set_last_error(0) + style = self._user.GetWindowLongW(hwnd, -16) # GWL_STYLE + if (style == 0 and ctypes.get_last_error() != 0) or style & ES_PASSWORD: return False return self._message(hwnd, EM_GETPASSWORDCHAR) == 0 @@ -225,33 +228,94 @@ def _identity(control: Any) -> tuple[int, int, tuple[int, ...]]: return hwnd, pid, tuple(runtime) -def require_non_sensitive_value(control: Any) -> None: - """Refuse text access unless the current password status is exactly False. +def is_uia_not_supported(raw: object) -> bool: + """Accept only UI Automation's reserved NotSupported COM object.""" + if raw is None: + return False + try: + from comtypes import IUnknown - Missing, exceptional and non-boolean states do not authorize a getter. - All value, capability and preview consumers share this rule. Call again - after any provider call and immediately before each text getter; a prior - result or negotiated protocol version is never authority for a later read. - """ + if not isinstance(raw, ctypes.POINTER(IUnknown)) or not raw: + return False + from uiautomation.uiautomation import _AutomationClient + + # Compare through UIA. An arbitrary VT_UNKNOWN is not the sentinel. + answer = _AutomationClient.instance().IUIAutomation.CheckNotSupported(raw) + return type(answer) in (int, bool) and answer == 1 + except Exception: + return False + + +def pattern_presence(pattern: object) -> bool | None: + """Interpret the typed COM output from a successful GetCurrentPattern.""" + if pattern is None: + return False + try: + from comtypes import IUnknown + + if isinstance(pattern, ctypes.POINTER(IUnknown)): + return bool(pattern) + except Exception: + pass + return None + + +# These UIA node types can carry a caption or structural metadata. A type +# alone never establishes that its value pattern is absent. +_STRUCTURAL_TYPES = frozenset({ + "WindowControl", "PaneControl", "GroupControl", "TitleBarControl", + "ButtonControl", "SplitButtonControl", "TextControl", "ToolBarControl", + "MenuBarControl", "MenuControl", "MenuItemControl", "StatusBarControl", + "CheckBoxControl", "RadioButtonControl", "TabControl", "TabItemControl", +}) + + +def _known_non_value_structure(control: Any, get_property: Callable[..., Any]) -> bool: + if control.ControlTypeName not in _STRUCTURAL_TYPES: + return False + available = get_property(30043, 1) # UIA_IsValuePatternAvailablePropertyId + if available is not False: + if not is_uia_not_supported(available): + return False + # A successful null ValuePattern is absence. Errors and malformed + # answers cannot authorize even a caption. + if pattern_presence(control.Element.GetCurrentPattern(10002)) is not False: + return False + # The capability/type lookup was a provider call: recheck sensitivity + # immediately before allowing the caller's structural metadata access. + status = get_property(IS_PASSWORD_PROPERTY, 1) + if status is False or is_uia_not_supported(status): + return True + raise ValueUnavailable("password_or_password_status_unavailable") + + +def _require_non_sensitive(control: Any, *, structural: bool) -> None: try: - # CurrentIsPassword/Control.IsPassword can return a default FALSE for - # unsupported status. Request the raw property with defaults ignored; - # a reserved unsupported object is unknown, not non-sensitive. Some - # providers (the WinForms TextBox proxies) do not support IsPassword - # at all; then only Win32 evidence from the control's own EDIT window - # (no ES_PASSWORD style, no password character) allows the read. - method = getattr(control, "GetPropertyValueEx", None) - if not callable(method): - raise ValueUnavailable("password_status_unavailable") + method = control.GetPropertyValueEx raw = method(IS_PASSWORD_PROPERTY, 1) if type(raw) is bool: - allowed = raw is False - else: - allowed = _native_plain_edit(control) + if raw is False: + return + elif is_uia_not_supported(raw): + if structural and _known_non_value_structure(control, method): + return + if _native_plain_edit(control): + status = method(IS_PASSWORD_PROPERTY, 1) + if status is False or is_uia_not_supported(status): + return except Exception: - allowed = False - if not allowed: - raise ValueUnavailable("password_or_password_status_unavailable") + pass + raise ValueUnavailable("password_or_password_status_unavailable") + + +def require_non_sensitive_value(control: Any) -> None: + """Require affirmative non-sensitive evidence before any semantic value read.""" + _require_non_sensitive(control, structural=False) + + +def require_non_sensitive_structure(control: Any) -> None: + """Allow proven non-value structural metadata; never grants a value read.""" + _require_non_sensitive(control, structural=True) def observe_complete_value( diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 6d4f4b5ec6..f7fd743219 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -1225,12 +1225,12 @@ def incomplete(stage: str, error: Exception | None = None): # turn a partial query into unique value authority. try: native_api = _native_value_api() - native_api.require_non_sensitive_value(control) + native_api.require_non_sensitive_structure(control) facts = { key: _read_control_value(control, key, None) for key in ("AutomationId", "Name", "ControlTypeName") } - _native_value_api().require_non_sensitive_value(control) + _native_value_api().require_non_sensitive_structure(control) if any(not isinstance(value, str) for value in facts.values()): return incomplete("selector_property") possible = all( @@ -1625,7 +1625,7 @@ def _native_value_api() -> Any: def _read_control_value(control: object, name: str, default: Any) -> Any: """Metadata for a semantic value read, without a sensitivity-order gap.""" - guard = _native_value_api().require_non_sensitive_value + guard = _native_value_api().require_non_sensitive_structure guard(control) value = _control_value(control, name, default) guard(control) @@ -2788,7 +2788,7 @@ def refused(phase: str, outcome: str) -> _FormBooleanObservation: return _FormBooleanObservation(None, _FormPropertyDetail(name, phase, outcome)) try: - guard = _native_value_api().require_non_sensitive_value + guard = _native_value_api().require_non_sensitive_structure guard(control) except Exception: # noqa: BLE001 - no provider exception data return refused("guard_before_lookup", "guard_refused") @@ -2812,6 +2812,8 @@ def refused(phase: str, outcome: str) -> _FormBooleanObservation: # itself: UIA's GetCurrentPattern returns the pattern exactly when it # is supported. Only that exact answer counts; anything else refuses. outcome = "none" if available is None else "non_bool" + if not _native_value_api().is_uia_not_supported(available): + return refused("result_kind", outcome) available = _form_pattern_support(control, property_id, guard) if available is None: return refused("result_kind", outcome) @@ -2844,7 +2846,7 @@ def _form_pattern_support( pattern = method(pattern_id) guard(control) # comtypes answers a NULL interface pointer for an unsupported pattern. - return bool(pattern) + return _native_value_api().pattern_presence(pattern) except Exception: # noqa: BLE001 - no provider exception data return None @@ -2936,9 +2938,11 @@ class _FormStateObservation: def _form_field_state(control: object) -> _FormStateObservation: """Known absent patterns differ from unknown, with first-refusal detail.""" - guard = _native_value_api().require_non_sensitive_value def read(capability: str, attribute: str) -> Any: + # A structural guard can inspect availability, never a toggle or + # selection value. Keep the full guard adjacent to each state read. + guard = _native_value_api().require_non_sensitive_value guard(control) method = _control_value(control, capability, None) guard(control) @@ -3234,7 +3238,7 @@ def _window_form_fields( return _form_refused("uia_setup", "uia", "root_unavailable") if window is None: return _form_refused("uia_setup", "uia", "root_unavailable") - guard = _native_value_api().require_non_sensitive_value + guard = _native_value_api().require_non_sensitive_structure try: guard(window) title = " ".join(str(_control_value(window, "Name", "") or "").split()) diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index a498d5e4bd..8ca609efb0 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -443,6 +443,10 @@ def __init__(self, left, top, right, bottom): self.left, self.top, self.right, self.bottom = left, top, right, bottom +_UNSUPPORTED_PROPERTY = object() +_DEFAULT_PASSWORD = object() + + class _Control: next_hwnd = 100 @@ -457,7 +461,7 @@ def __init__( children=(), selected=None, toggle=None, - password=False, + password=_DEFAULT_PASSWORD, ): self.NativeWindowHandle = _Control.next_hwnd _Control.next_hwnd += 1 @@ -466,6 +470,14 @@ def __init__( self.ClassName = "SyntheticNativeControl" self.parent = None self.native_override = None + if password is _DEFAULT_PASSWORD: + # Non-value providers need not implement IsPassword, even on the + # window root. A synthetic value provider answers explicitly. + password = ( + _UNSUPPORTED_PROPERTY + if value is None and control_type in {"WindowControl", "ButtonControl", "PaneControl", "TextControl"} + else False + ) self.IsPassword = password self._selected = selected self._toggle = toggle @@ -574,6 +586,7 @@ def _agent(monkeypatch, window, desktop=None): monkeypatch.setattr(agent_server, "_user32_factory", lambda: desktop or _Desktop()) import openadapt_flow.backends.win_agent.native_value as native + monkeypatch.setattr(native, "is_uia_not_supported", lambda raw: raw is _UNSUPPORTED_PROPERTY) controls = {} def attach(control, parent=None): @@ -833,6 +846,71 @@ def failed(): assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["window"] is None +def test_unsupported_password_on_nonvalue_root_and_button_keeps_real_fields(monkeypatch): + class CaptionOnly(_Control): + value_calls = 0 + + def GetValuePattern(self): + self.value_calls += 1 + raise AssertionError("a structural button has no value") + + button = CaptionOnly("ButtonControl", name="Synthetic caption") + field = _Control("EditControl", value="synthetic field") + field.AutomationId = "field" + root = _window(button, field) + perform = _agent(monkeypatch, root) + assert root.GetPropertyValueEx(30019, 1) is _UNSUPPORTED_PROPERTY + assert button.GetPropertyValueEx(30019, 1) is _UNSUPPORTED_PROPERTY + projection = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert [(f["kind"], f["text"]) for f in projection["fields"]] == [ + ("text", "Synthetic caption"), ("edit", "synthetic field") + ] + sys.modules["uiautomation"].GetRootControl = lambda: root + read = perform("read", {"locator": {"automation_id": "field"}}) + assert read["complete"] and read["text"] == "synthetic field" + assert button.value_calls == 0 + + +@pytest.mark.parametrize("capability", [True, None, "malformed"]) +def test_unproved_value_or_capability_on_structural_type_blocks_projection(monkeypatch, capability): + class Container(_Control): + content_reads = 0 + + @property + def Name(self): + self.content_reads += 1 + return "private fixture label" + + @Name.setter + def Name(self, ignored): + pass + + def GetValuePattern(self): + self.content_reads += 1 + raise AssertionError("an unknown value must remain unread") + + def GetPropertyValueEx(self, prop, ignore): + if prop == 30043: + return capability + return super().GetPropertyValueEx(prop, ignore) + + pane = Container("PaneControl", children=[_Control("EditControl", value="child")]) + perform = _agent(monkeypatch, _window(pane)) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert answer["window"] is None and answer["fields"] == [] + assert pane.content_reads == 0 + + +def test_nonvalue_structural_permission_never_reads_a_toggle_value(monkeypatch): + calls = [] + button = _Control("ButtonControl", name="Toggle", toggle=1) + button.GetTogglePattern = lambda: calls.append("toggle") + perform = _agent(monkeypatch, _window(button)) + answer = perform("window-form-fields", {"hwnd": 7, "pid": 10}) + assert answer["window"] is None and answer["fields"] == [] + assert calls == [] + + def test_a_value_container_does_not_hide_its_descendant_fields(monkeypatch): child = _Control("EditControl", value="actual field", bounds=(20, 44, 500, 70)) document = _Control( diff --git a/packages/flow/tests/test_form_projection_refusal.py b/packages/flow/tests/test_form_projection_refusal.py index 0d5fbcd462..cecfca7e2a 100644 --- a/packages/flow/tests/test_form_projection_refusal.py +++ b/packages/flow/tests/test_form_projection_refusal.py @@ -430,7 +430,7 @@ def __getattr__(self, key): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_value=guard), + lambda: SimpleNamespace(require_non_sensitive_structure=guard, is_uia_not_supported=lambda _: False), ) observation = server._form_boolean_observation(Target(), property_id) assert observation.value is None @@ -439,8 +439,6 @@ def __getattr__(self, key): "phase": phase, "outcome": outcome, } - if phase == "result_kind" and property_id in server._FORM_PATTERN_IDS: - guards += 1 # the guard before the pattern-support lookup assert calls == {"guard": guards, "lookup": lookups, "query": queries} assert MARKER not in json.dumps(observation.detail.payload()) @@ -461,7 +459,7 @@ def guard(_): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_value=guard), + lambda: SimpleNamespace(require_non_sensitive_structure=guard, is_uia_not_supported=lambda _: False), ) observed = server._form_boolean_observation(target, property_id) assert observed.value is value and observed.detail is None @@ -482,7 +480,7 @@ def query(prop, ignore): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_value=lambda _: None), + lambda: SimpleNamespace(require_non_sensitive_structure=lambda _: None, is_uia_not_supported=lambda _: False), ) observed = server._form_field_state(target) assert not observed.complete and observed.state is None @@ -506,7 +504,7 @@ def query(prop, ignore): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_value=lambda _: None), + lambda: SimpleNamespace(require_non_sensitive_structure=lambda _: None, is_uia_not_supported=lambda _: False), ) observed = server._form_field_state(target) assert not observed.complete and observed.reason == "state_capability_changed" diff --git a/packages/flow/tests/test_native_sensitive_reads.py b/packages/flow/tests/test_native_sensitive_reads.py index 8dceaef8dd..f72e547ecf 100644 --- a/packages/flow/tests/test_native_sensitive_reads.py +++ b/packages/flow/tests/test_native_sensitive_reads.py @@ -1,5 +1,7 @@ """All native previews, probes and reads share one current sensitivity guard.""" +import ctypes +import sys from types import SimpleNamespace import pytest @@ -11,7 +13,7 @@ WindowsBackend, ) from openadapt_flow.ir import StructuralLocator -from tests.test_approval_form_fields import _agent, _Control, _window +from tests.test_approval_form_fields import _agent, _Control, _UNSUPPORTED_PROPERTY, _window class CountedControl(_Control): @@ -703,7 +705,7 @@ def post(path, payload): # (the WinForms TextBox proxies on the hosted runner answer VT_UNKNOWN). from openadapt_flow.backends.win_agent import native_value # noqa: E402 -_UNSUPPORTED = object() +_UNSUPPORTED = _UNSUPPORTED_PROPERTY class _Evidence: @@ -728,7 +730,10 @@ def _unsupported_status_control(raw=_UNSUPPORTED, hwnd=4242): "raw,hwnd,plain,allowed", [ (_UNSUPPORTED, 4242, True, True), - (None, 4242, True, True), + (None, 4242, True, False), + (object(), 4242, True, False), + ("False", 4242, True, False), + (0, 4242, True, False), (_UNSUPPORTED, 4242, False, False), (_UNSUPPORTED, 4242, RuntimeError("timeout"), False), (_UNSUPPORTED, 0, True, False), @@ -743,6 +748,7 @@ def test_unsupported_password_status_needs_win32_edit_evidence( ): evidence = _Evidence(plain) monkeypatch.setattr(native_value, "_PASSWORD_EVIDENCE", [evidence]) + monkeypatch.setattr(native_value, "is_uia_not_supported", lambda value: value is _UNSUPPORTED) control = _unsupported_status_control(raw, hwnd) if allowed: native_value.require_non_sensitive_value(control) @@ -750,7 +756,7 @@ def test_unsupported_password_status_needs_win32_edit_evidence( with pytest.raises(native_value.ValueUnavailable): native_value.require_non_sensitive_value(control) # A supported boolean is the provider's answer; no Win32 fallback for it. - fallback = type(raw) is not bool and isinstance(hwnd, int) and hwnd > 0 + fallback = raw is _UNSUPPORTED and isinstance(hwnd, int) and hwnd > 0 assert evidence.hwnds == ([hwnd] if fallback else []) @@ -788,12 +794,63 @@ def test_edit_class_names(name, edit): assert native_value._edit_class(name) is edit +class _Unknown(ctypes.Structure): + pass + + +def test_only_uias_authenticated_unknown_is_the_unsupported_sentinel(monkeypatch): + token, foreign = ctypes.pointer(_Unknown()), ctypes.pointer(_Unknown()) + calls = [] + + def check(raw): + calls.append(raw) + return int(raw is token) + + client = SimpleNamespace(IUIAutomation=SimpleNamespace(CheckNotSupported=check)) + monkeypatch.setitem(sys.modules, "comtypes", SimpleNamespace(IUnknown=_Unknown)) + monkeypatch.setitem( + sys.modules, "uiautomation.uiautomation", + SimpleNamespace(_AutomationClient=SimpleNamespace(instance=lambda: client)), + ) + for malformed in (None, 0, False, "unknown", object(), ctypes.POINTER(_Unknown)()): + assert not native_value.is_uia_not_supported(malformed) + assert calls == [] + assert native_value.is_uia_not_supported(token) + assert not native_value.is_uia_not_supported(foreign) + assert calls == [token, foreign] + + +@pytest.mark.parametrize("style,error,allowed", [(0, 0, True), (0, 5, False), (0x20, 0, False)]) +def test_plain_edit_requires_a_successful_style_read(monkeypatch, style, error, allowed): + last = [99] + messages = [] + + def get_class(hwnd, out, cap): + out.value = "Edit" + return 4 + + def get_style(hwnd, index): + assert index == -16 and last == [0] + last[:] = [error] + return style + + monkeypatch.setattr(ctypes, "set_last_error", lambda n: last.__setitem__(0, n), raising=False) + monkeypatch.setattr(ctypes, "get_last_error", lambda: last[0], raising=False) + reader = object.__new__(native_value.Win32TextReader) + reader._user = SimpleNamespace(GetClassNameW=get_class, GetWindowLongW=get_style) + reader.owner = lambda hwnd: None + reader._message = lambda hwnd, msg: messages.append(msg) or 0 + assert reader.plain_edit(123) is allowed + assert messages == ([native_value.EM_GETPASSWORDCHAR] if allowed else []) + + @pytest.mark.parametrize( - "pattern,expected", [(object(), True), (None, False), (0, False)] + "pattern,expected", [(ctypes.pointer(_Unknown()), True), (None, False), (ctypes.POINTER(_Unknown)(), False)] ) def test_unsupported_availability_uses_the_exact_pattern_answer( monkeypatch, pattern, expected ): + monkeypatch.setitem(sys.modules, "comtypes", SimpleNamespace(IUnknown=_Unknown)) calls = [] element = SimpleNamespace( GetCurrentPattern=lambda pattern_id: calls.append(pattern_id) or pattern @@ -804,13 +861,26 @@ def test_unsupported_availability_uses_the_exact_pattern_answer( monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_value=lambda _: None), + lambda: SimpleNamespace(require_non_sensitive_structure=lambda _: None, is_uia_not_supported=lambda value: value is _UNSUPPORTED, pattern_presence=native_value.pattern_presence), ) observed = server._form_boolean_observation(target, 30041) assert observed.value is expected and observed.detail is None assert calls == [10015] +@pytest.mark.parametrize("raw", [None, 0, "false", object()]) +def test_unclassified_availability_never_looks_up_a_pattern(monkeypatch, raw): + calls = [] + control = SimpleNamespace( + GetPropertyValueEx=lambda *_: raw, + Element=SimpleNamespace(GetCurrentPattern=lambda key: calls.append(key)), + ) + monkeypatch.setattr(native_value, "require_non_sensitive_structure", lambda _: None) + observed = server._form_boolean_observation(control, 30041) + assert observed.value is None and observed.detail is not None + assert calls == [] + + @pytest.mark.parametrize("property_id", [30041, 30022]) def test_unanswerable_availability_still_refuses(monkeypatch, property_id): def fail(pattern_id): @@ -823,7 +893,7 @@ def fail(pattern_id): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_value=lambda _: None), + lambda: SimpleNamespace(require_non_sensitive_structure=lambda _: None, is_uia_not_supported=lambda value: value is _UNSUPPORTED, pattern_presence=native_value.pattern_presence), ) observed = server._form_boolean_observation(target, property_id) assert observed.value is None @@ -848,7 +918,7 @@ def guard(_): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_value=guard), + lambda: SimpleNamespace(require_non_sensitive_structure=guard, is_uia_not_supported=lambda value: value is _UNSUPPORTED, pattern_presence=native_value.pattern_presence), ) observed = server._form_boolean_observation(target, 30041) assert observed.value is None and calls == [] diff --git a/packages/flow/tests/test_native_value_completeness.py b/packages/flow/tests/test_native_value_completeness.py index 5d92249fbb..800778f5bb 100644 --- a/packages/flow/tests/test_native_value_completeness.py +++ b/packages/flow/tests/test_native_value_completeness.py @@ -401,12 +401,8 @@ def __getattr__(self, name): not result.complete and result.reason == "password_or_password_status_unavailable" ) - # An unsupported (non-boolean) status asks only for the control's own - # window handle, for Win32 EDIT password evidence; nothing else is read. - if status is True or status == "error": - assert target.calls == [] - else: - assert set(target.calls) == {"NativeWindowHandle"} + # These are missing or malformed statuses rather than UIA's sentinel. + assert target.calls == [] @pytest.mark.parametrize("stage", ["pattern_lookup", "pattern_call", "readability"]) From 3b88e336b583a3ed62c7b91dd0968aaf83cd7872 Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Sat, 21 Nov 2026 13:34:40 -0500 Subject: [PATCH 30/34] test(flow): bind the synthetic UIA sentinel in refusal fixtures --- .../tests/test_form_projection_refusal.py | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/flow/tests/test_form_projection_refusal.py b/packages/flow/tests/test_form_projection_refusal.py index cecfca7e2a..0704059d71 100644 --- a/packages/flow/tests/test_form_projection_refusal.py +++ b/packages/flow/tests/test_form_projection_refusal.py @@ -9,11 +9,12 @@ import pytest -from openadapt_flow.backends.win_agent import server +from openadapt_flow.backends.win_agent import native_value, server from tests.test_approval_form_fields import ( _Control, _Desktop, _Init, + _UNSUPPORTED_PROPERTY, _window, _windows_backend, ) @@ -21,6 +22,15 @@ MARKER = "fixture-content-must-not-be-returned" +@pytest.fixture(autouse=True) +def synthetic_uia_sentinel(monkeypatch): + # These tests call the server directly. Authenticate the same synthetic + # NotSupported object as the shared agent fixture does. + monkeypatch.setattr( + native_value, "is_uia_not_supported", lambda raw: raw is _UNSUPPORTED_PROPERTY + ) + + def context(*children, hwnd=7, pid=10, cleanup_error=False): window = _window(*children) window.NativeWindowHandle, window.ProcessId = hwnd, pid @@ -81,7 +91,9 @@ def test_closed_refusal_discards_partial_fields_and_provider_content( fault, channel, reason ): target = _Control( - "EditControl" if fault == "required_value" else "TextControl", name=MARKER + "EditControl" if fault == "required_value" else "TextControl", + name=MARKER, + password=False, ) original = target.GetPropertyValueEx @@ -248,7 +260,7 @@ def test_limit_receipt_discards_partial_fields_without_a_recovery_walk( def test_interleaved_requests_cannot_share_or_overwrite_refusal_identity(): def request(number): - target = _Control("TextControl") + target = _Control("TextControl", password=False) original = target.GetPropertyValueEx property_id = (30022, 30041, 30036, 30043)[number % 4] category = { @@ -528,7 +540,7 @@ def query(prop, ignore): def test_request_refusal_preserves_property_detail_with_ordinal_without_content( property_id, channel, reason ): - target = _Control("TextControl", name=MARKER) + target = _Control("TextControl", name=MARKER, password=False) original = target.GetPropertyValueEx target.GetPropertyValueEx = lambda prop, ignore: ( None if prop == property_id else original(prop, ignore) From 9585e76dafde7e7da1bf13447694179ccbb78a91 Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Sat, 21 Nov 2026 14:02:35 -0500 Subject: [PATCH 31/34] test(win-agent): distinguish strict census sensitivity refusals in guest diagnostics --- .../backends/win_agent/native_value.py | 56 ++++++++++++++++--- .../backends/win_agent/server.py | 5 ++ .../test_structural_value_completeness.py | 54 +++++++++++++++--- 3 files changed, 101 insertions(+), 14 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 557a78bd60..a8debdc59d 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -10,6 +10,7 @@ import hashlib import time from dataclasses import asdict, dataclass +from enum import Enum from typing import Any, Callable, Protocol MAX_UTF16_UNITS = 65536 @@ -25,9 +26,23 @@ def utf16_bytes(value: str) -> bytes: return value.encode("utf-16-le", errors="surrogatepass") +class SensitivityStage(Enum): + """Fixed guest-only diagnostics for the strict census; never provider data.""" + + PROPERTY_QUERY = "sensitivity_property_query" + PROVIDER_REFUSAL = "sensitivity_provider_refusal" + MISSING_STATUS = "sensitivity_missing_status" + UNRECOGNIZED_STATUS = "sensitivity_unrecognized_status" + STRUCTURE_QUERY = "sensitivity_structure_query" + NATIVE_EDIT = "sensitivity_native_edit" + RECHECK = "sensitivity_recheck" + + class ValueUnavailable(Exception): """A specific absence of completeness evidence; never carries field text.""" + census_stage: SensitivityStage | None = None + @dataclass(frozen=True) class NativeOwner: @@ -262,12 +277,26 @@ def pattern_presence(pattern: object) -> bool | None: # These UIA node types can carry a caption or structural metadata. A type # alone never establishes that its value pattern is absent. -_STRUCTURAL_TYPES = frozenset({ - "WindowControl", "PaneControl", "GroupControl", "TitleBarControl", - "ButtonControl", "SplitButtonControl", "TextControl", "ToolBarControl", - "MenuBarControl", "MenuControl", "MenuItemControl", "StatusBarControl", - "CheckBoxControl", "RadioButtonControl", "TabControl", "TabItemControl", -}) +_STRUCTURAL_TYPES = frozenset( + { + "WindowControl", + "PaneControl", + "GroupControl", + "TitleBarControl", + "ButtonControl", + "SplitButtonControl", + "TextControl", + "ToolBarControl", + "MenuBarControl", + "MenuControl", + "MenuItemControl", + "StatusBarControl", + "CheckBoxControl", + "RadioButtonControl", + "TabControl", + "TabItemControl", + } +) def _known_non_value_structure(control: Any, get_property: Callable[..., Any]) -> bool: @@ -290,22 +319,35 @@ def _known_non_value_structure(control: Any, get_property: Callable[..., Any]) - def _require_non_sensitive(control: Any, *, structural: bool) -> None: + stage = SensitivityStage.PROPERTY_QUERY try: method = control.GetPropertyValueEx raw = method(IS_PASSWORD_PROPERTY, 1) if type(raw) is bool: if raw is False: return + stage = SensitivityStage.PROVIDER_REFUSAL elif is_uia_not_supported(raw): + stage = SensitivityStage.STRUCTURE_QUERY if structural and _known_non_value_structure(control, method): return + stage = SensitivityStage.NATIVE_EDIT if _native_plain_edit(control): + stage = SensitivityStage.RECHECK status = method(IS_PASSWORD_PROPERTY, 1) if status is False or is_uia_not_supported(status): return + else: + stage = ( + SensitivityStage.MISSING_STATUS + if raw is None + else SensitivityStage.UNRECOGNIZED_STATUS + ) except Exception: pass - raise ValueUnavailable("password_or_password_status_unavailable") + error = ValueUnavailable("password_or_password_status_unavailable") + error.census_stage = stage + raise error def require_non_sensitive_value(control: Any) -> None: diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index f7fd743219..8405a28e52 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -1204,6 +1204,11 @@ def incomplete(stage: str, error: Exception | None = None): error, native_api.ValueUnavailable ): stage = "sensitivity" + # Older standalone helpers report the coarse stage. Only the + # matching helper's enum may supply a more precise log label. + detail = getattr(error, "census_stage", None) + if type(detail) is getattr(native_api, "SensitivityStage", None): + stage = detail.value try: print( f"[win-agent] strict census stop: {stage}", diff --git a/packages/flow/tests/test_structural_value_completeness.py b/packages/flow/tests/test_structural_value_completeness.py index 07a05874d2..c56406b712 100644 --- a/packages/flow/tests/test_structural_value_completeness.py +++ b/packages/flow/tests/test_structural_value_completeness.py @@ -195,24 +195,61 @@ def test_unqualified_scope_and_name_only_sources_never_become_values( assert answer["text"] is None and answer["complete"] is False -@pytest.mark.parametrize("stage", ["sensitivity", "children_error", "depth_limit"]) +@pytest.mark.parametrize( + "stage", + [ + "sensitivity_property_query", + "sensitivity_provider_refusal", + "sensitivity_missing_status", + "sensitivity_unrecognized_status", + "sensitivity_structure_query", + "sensitivity_native_edit", + "sensitivity_recheck", + "children_error", + "depth_limit", + ], +) def test_census_trace_records_only_the_stopping_stage(monkeypatch, capsys, stage): import sys import openadapt_flow.backends.win_agent.server as server + from openadapt_flow.backends.win_agent import native_value + from tests.test_approval_form_fields import _UNSUPPORTED_PROPERTY control = _Control("EditControl", value="synthetic fixture content") control.AutomationId = "field" window = _window(control) perform = _agent(monkeypatch, window) sys.modules["uiautomation"].GetRootControl = lambda: window - if stage == "sensitivity": - control.GetPropertyValueEx = lambda *_: None + calls = [] + + def fail(*_): + raise RuntimeError("private provider exception") + + def property_value(property_id, _): + calls.append(property_id) + if stage == "sensitivity_property_query": + fail() + if stage == "sensitivity_provider_refusal": + return True + if stage == "sensitivity_missing_status": + return None + if stage == "sensitivity_unrecognized_status": + return "private provider answer" + if stage == "sensitivity_structure_query" and property_id == 30043: + fail() + if stage == "sensitivity_recheck" and len(calls) == 2: + return True + return _UNSUPPORTED_PROPERTY + + if stage.startswith("sensitivity_"): + control.GetPropertyValueEx = property_value + if stage == "sensitivity_structure_query": + control.ControlTypeName = "PaneControl" + monkeypatch.setattr( + native_value, "_native_plain_edit", lambda _: stage == "sensitivity_recheck" + ) elif stage == "children_error": - - def fail(): - raise RuntimeError("private provider exception") - control.GetChildren = fail else: monkeypatch.setattr(server, "_MAX_UIA_DEPTH", 0) @@ -222,8 +259,11 @@ def fail(): refusal = perform("read", request) assert refusal["reason"] == "not_unique" and not refusal["complete"] assert capsys.readouterr().err == "" + original_calls = list(calls) + calls.clear() monkeypatch.setenv("OAFLOW_AGENT_TRACE_CENSUS", "1") assert perform("read", request) == refusal + assert calls == original_calls assert capsys.readouterr().err.splitlines() == [ f"[win-agent] strict census stop: {stage}" ] From cdf8b2024869f4404b59582de270326580bcd059 Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Sat, 21 Nov 2026 14:15:12 -0500 Subject: [PATCH 32/34] test(win-agent): report both evidence outcomes for a refused native edit census --- .../backends/win_agent/native_value.py | 103 ++++++++++++++--- .../backends/win_agent/server.py | 8 ++ .../test_structural_value_completeness.py | 109 +++++++++++++++++- 3 files changed, 201 insertions(+), 19 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 a8debdc59d..98d1a09821 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -26,6 +26,25 @@ def utf16_bytes(value: str) -> bytes: return value.encode("utf-16-le", errors="surrogatepass") +class StructureEvidence(Enum): + NON_VALUE = "non_value" + OTHER_TYPE = "other_type" + VALUE_PRESENT = "value_present" + VALUE_UNKNOWN = "value_unknown" + + +class EditEvidence(Enum): + PLAIN = "plain" + NO_HANDLE = "no_handle" + NON_EDIT = "non_edit" + CLASS_UNAVAILABLE = "class_unavailable" + STYLE_UNAVAILABLE = "style_unavailable" + OWNER_UNAVAILABLE = "owner_unavailable" + MASK_QUERY_UNAVAILABLE = "mask_query_unavailable" + PROTECTED = "protected" + UNAVAILABLE = "unavailable" + + class SensitivityStage(Enum): """Fixed guest-only diagnostics for the strict census; never provider data.""" @@ -42,6 +61,14 @@ class ValueUnavailable(Exception): """A specific absence of completeness evidence; never carries field text.""" census_stage: SensitivityStage | None = None + structure_evidence: StructureEvidence | None = None + edit_evidence: EditEvidence | None = None + + def native_edit_census_label(self) -> str: + structure, edit = self.structure_evidence, self.edit_evidence + if type(structure) is StructureEvidence and type(edit) is EditEvidence: + return f"sensitivity_native_edit/{structure.value}/{edit.value}" + return SensitivityStage.NATIVE_EDIT.value @dataclass(frozen=True) @@ -161,18 +188,23 @@ def plain_edit(self, hwnd: int) -> bool: ES_PASSWORD, and EM_GETPASSWORDCHAR answers 0 within the timeout. Any other class, a failed call or a password character is False. """ + return self._plain_edit_evidence(hwnd) is EditEvidence.PLAIN + + def _plain_edit_evidence(self, hwnd: int) -> EditEvidence: self.owner(hwnd) name = ctypes.create_unicode_buffer(257) if not 0 < self._user.GetClassNameW(hwnd, name, 257) < 257: - return False + return EditEvidence.CLASS_UNAVAILABLE if not _edit_class(name.value): - return False + return EditEvidence.NON_EDIT # A zero GWL_STYLE is valid only when the call left no Win32 error. ctypes.set_last_error(0) style = self._user.GetWindowLongW(hwnd, -16) # GWL_STYLE - if (style == 0 and ctypes.get_last_error() != 0) or style & ES_PASSWORD: - return False - return self._message(hwnd, EM_GETPASSWORDCHAR) == 0 + if style == 0 and ctypes.get_last_error() != 0: + return EditEvidence.STYLE_UNAVAILABLE + if style & ES_PASSWORD or self._message(hwnd, EM_GETPASSWORDCHAR) != 0: + return EditEvidence.PROTECTED + return EditEvidence.PLAIN def read(self, owner: NativeOwner, *, guard: Callable[[], None]) -> NativeRead: def unchanged() -> None: @@ -213,16 +245,38 @@ def _edit_class(name: str) -> bool: _PASSWORD_EVIDENCE: list[Any] = [] -def _native_plain_edit(control: Any) -> bool: +def _native_edit_evidence(control: Any) -> EditEvidence: """Win32 evidence for a provider that does not support IsPassword.""" hwnd = control.NativeWindowHandle if not _positive_int(hwnd): - return False + return EditEvidence.NO_HANDLE if not _PASSWORD_EVIDENCE: _PASSWORD_EVIDENCE.append(Win32TextReader()) reader = _PASSWORD_EVIDENCE[0] + if type(reader) is Win32TextReader: + probe = getattr(reader, "_plain_edit_evidence", None) + if callable(probe): + try: + evidence = probe(hwnd) + except ValueUnavailable as exc: + # The native reader already distinguishes these failed calls. + # Never emit its exception or anything returned by a provider. + if exc.args == ("native_text_timeout_or_failure",): + return EditEvidence.MASK_QUERY_UNAVAILABLE + if exc.args in ( + ("native_window_unavailable_or_not_unicode",), + ("native_owner_unavailable",), + ): + return EditEvidence.OWNER_UNAVAILABLE + return EditEvidence.UNAVAILABLE + return ( + evidence if type(evidence) is EditEvidence else EditEvidence.UNAVAILABLE + ) + # Readers with only the original boolean interface still use that proof. plain = getattr(reader, "plain_edit", None) - return callable(plain) and plain(hwnd) is True + if callable(plain) and plain(hwnd) is True: + return EditEvidence.PLAIN + return EditEvidence.UNAVAILABLE def _positive_int(value: object) -> bool: @@ -299,27 +353,36 @@ def pattern_presence(pattern: object) -> bool | None: ) -def _known_non_value_structure(control: Any, get_property: Callable[..., Any]) -> bool: +def _structure_evidence( + control: Any, get_property: Callable[..., Any] +) -> StructureEvidence: if control.ControlTypeName not in _STRUCTURAL_TYPES: - return False + return StructureEvidence.OTHER_TYPE available = get_property(30043, 1) # UIA_IsValuePatternAvailablePropertyId if available is not False: if not is_uia_not_supported(available): - return False + if available is True: + return StructureEvidence.VALUE_PRESENT + return StructureEvidence.VALUE_UNKNOWN # A successful null ValuePattern is absence. Errors and malformed # answers cannot authorize even a caption. - if pattern_presence(control.Element.GetCurrentPattern(10002)) is not False: - return False + present = pattern_presence(control.Element.GetCurrentPattern(10002)) + if present is True: + return StructureEvidence.VALUE_PRESENT + if present is not False: + return StructureEvidence.VALUE_UNKNOWN # The capability/type lookup was a provider call: recheck sensitivity # immediately before allowing the caller's structural metadata access. status = get_property(IS_PASSWORD_PROPERTY, 1) if status is False or is_uia_not_supported(status): - return True + return StructureEvidence.NON_VALUE raise ValueUnavailable("password_or_password_status_unavailable") def _require_non_sensitive(control: Any, *, structural: bool) -> None: stage = SensitivityStage.PROPERTY_QUERY + structure = None + edit = EditEvidence.UNAVAILABLE try: method = control.GetPropertyValueEx raw = method(IS_PASSWORD_PROPERTY, 1) @@ -329,10 +392,13 @@ def _require_non_sensitive(control: Any, *, structural: bool) -> None: stage = SensitivityStage.PROVIDER_REFUSAL elif is_uia_not_supported(raw): stage = SensitivityStage.STRUCTURE_QUERY - if structural and _known_non_value_structure(control, method): - return + if structural: + structure = _structure_evidence(control, method) + if structure is StructureEvidence.NON_VALUE: + return stage = SensitivityStage.NATIVE_EDIT - if _native_plain_edit(control): + edit = _native_edit_evidence(control) + if edit is EditEvidence.PLAIN: stage = SensitivityStage.RECHECK status = method(IS_PASSWORD_PROPERTY, 1) if status is False or is_uia_not_supported(status): @@ -347,6 +413,9 @@ def _require_non_sensitive(control: Any, *, structural: bool) -> None: pass error = ValueUnavailable("password_or_password_status_unavailable") error.census_stage = stage + if stage is SensitivityStage.NATIVE_EDIT: + error.structure_evidence = structure + error.edit_evidence = edit raise error diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 8405a28e52..8fadde9e93 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -1209,6 +1209,14 @@ def incomplete(stage: str, error: Exception | None = None): detail = getattr(error, "census_stage", None) if type(detail) is getattr(native_api, "SensitivityStage", None): stage = detail.value + if detail is native_api.SensitivityStage.NATIVE_EDIT: + label = getattr( + native_api.ValueUnavailable, + "native_edit_census_label", + None, + ) + if label is not None: + stage = label(error) try: print( f"[win-agent] strict census stop: {stage}", diff --git a/packages/flow/tests/test_structural_value_completeness.py b/packages/flow/tests/test_structural_value_completeness.py index c56406b712..973a3ed0d1 100644 --- a/packages/flow/tests/test_structural_value_completeness.py +++ b/packages/flow/tests/test_structural_value_completeness.py @@ -203,7 +203,7 @@ def test_unqualified_scope_and_name_only_sources_never_become_values( "sensitivity_missing_status", "sensitivity_unrecognized_status", "sensitivity_structure_query", - "sensitivity_native_edit", + "sensitivity_native_edit/other_type/unavailable", "sensitivity_recheck", "children_error", "depth_limit", @@ -247,7 +247,13 @@ def property_value(property_id, _): if stage == "sensitivity_structure_query": control.ControlTypeName = "PaneControl" monkeypatch.setattr( - native_value, "_native_plain_edit", lambda _: stage == "sensitivity_recheck" + native_value, + "_native_edit_evidence", + lambda _: ( + native_value.EditEvidence.PLAIN + if stage == "sensitivity_recheck" + else native_value.EditEvidence.UNAVAILABLE + ), ) elif stage == "children_error": control.GetChildren = fail @@ -269,6 +275,105 @@ def property_value(property_id, _): ] +@pytest.mark.parametrize( + "structure,edit", + [ + ("other_type", "no_handle"), + ("value_present", "non_edit"), + ("value_unknown", "class_unavailable"), + ("other_type", "style_unavailable"), + ("value_present", "password_style"), + ("value_unknown", "password_char"), + ("other_type", "owner_error"), + ("value_present", "message_error"), + ], +) +def test_native_edit_census_reports_both_decisions( + monkeypatch, capsys, structure, edit +): + import ctypes + import sys + + from openadapt_flow.backends.win_agent import native_value + from tests.test_approval_form_fields import _UNSUPPORTED_PROPERTY + + calls = [] + reader_type = native_value.Win32TextReader + control = _Control( + "EditControl" if structure == "other_type" else "PaneControl", + value="private synthetic value", + ) + control.AutomationId = "field" + window = _window(control) + perform = _agent(monkeypatch, window) + sys.modules["uiautomation"].GetRootControl = lambda: window + + def property_value(prop, _): + calls.append(("property", prop)) + if prop == native_value.IS_PASSWORD_PROPERTY: + return _UNSUPPORTED_PROPERTY + assert prop == 30043 + return True if structure == "value_present" else object() + + def owner(_): + calls.append("owner") + if edit == "owner_error": + raise native_value.ValueUnavailable("native_owner_unavailable") + + def class_name(_, buffer, size): + calls.append("class") + if edit == "class_unavailable": + return 0 + buffer.value = "Button" if edit == "non_edit" else "Edit" + return len(buffer.value) + + def style(*_): + calls.append("style") + return native_value.ES_PASSWORD if edit == "password_style" else 0 + + def password_char(*_): + calls.append("password_char") + if edit == "message_error": + raise native_value.ValueUnavailable("native_text_timeout_or_failure") + return int(edit == "password_char") + + control.GetPropertyValueEx = property_value + if edit == "no_handle": + control.NativeWindowHandle = 0 + reader = object.__new__(reader_type) + reader.owner = owner + reader._user = SimpleNamespace(GetClassNameW=class_name, GetWindowLongW=style) + reader._message = password_char + monkeypatch.setattr(native_value, "Win32TextReader", reader_type) + monkeypatch.setattr(native_value, "_PASSWORD_EVIDENCE", [reader]) + monkeypatch.setattr(ctypes, "set_last_error", lambda _: None, raising=False) + monkeypatch.setattr( + ctypes, + "get_last_error", + lambda: int(edit == "style_unavailable"), + raising=False, + ) + request = {"locator": {"automation_id": "field"}} + monkeypatch.delenv("OAFLOW_AGENT_TRACE_CENSUS", raising=False) + refusal = perform("read", request) + assert refusal["reason"] == "not_unique" and not refusal["complete"] + assert capsys.readouterr().err == "" + original_calls = list(calls) + calls.clear() + monkeypatch.setenv("OAFLOW_AGENT_TRACE_CENSUS", "1") + assert perform("read", request) == refusal + assert calls == original_calls + outcome = { + "password_style": "protected", + "password_char": "protected", + "owner_error": "owner_unavailable", + "message_error": "mask_query_unavailable", + }.get(edit, edit) + assert capsys.readouterr().err.splitlines() == [ + f"[win-agent] strict census stop: sensitivity_native_edit/{structure}/{outcome}" + ] + + def test_row_previews_cannot_authorize_inventory_even_when_empty(): payload = { **complete("value"), From 9b0774770d62784d4e6bea51a498e8b2be6876ad Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Sat, 21 Nov 2026 15:05:57 -0500 Subject: [PATCH 33/34] style(flow): format native provider and projection tests --- .../flow/tests/test_approval_form_fields.py | 19 +++++-- .../tests/test_form_projection_refusal.py | 18 +++++-- .../flow/tests/test_native_sensitive_reads.py | 51 +++++++++++++++---- 3 files changed, 69 insertions(+), 19 deletions(-) diff --git a/packages/flow/tests/test_approval_form_fields.py b/packages/flow/tests/test_approval_form_fields.py index 8ca609efb0..80a1706a9a 100644 --- a/packages/flow/tests/test_approval_form_fields.py +++ b/packages/flow/tests/test_approval_form_fields.py @@ -475,7 +475,9 @@ def __init__( # window root. A synthetic value provider answers explicitly. password = ( _UNSUPPORTED_PROPERTY - if value is None and control_type in {"WindowControl", "ButtonControl", "PaneControl", "TextControl"} + if value is None + and control_type + in {"WindowControl", "ButtonControl", "PaneControl", "TextControl"} else False ) self.IsPassword = password @@ -586,7 +588,9 @@ def _agent(monkeypatch, window, desktop=None): monkeypatch.setattr(agent_server, "_user32_factory", lambda: desktop or _Desktop()) import openadapt_flow.backends.win_agent.native_value as native - monkeypatch.setattr(native, "is_uia_not_supported", lambda raw: raw is _UNSUPPORTED_PROPERTY) + monkeypatch.setattr( + native, "is_uia_not_supported", lambda raw: raw is _UNSUPPORTED_PROPERTY + ) controls = {} def attach(control, parent=None): @@ -846,7 +850,9 @@ def failed(): assert perform("window-form-fields", {"hwnd": 7, "pid": 10})["window"] is None -def test_unsupported_password_on_nonvalue_root_and_button_keeps_real_fields(monkeypatch): +def test_unsupported_password_on_nonvalue_root_and_button_keeps_real_fields( + monkeypatch, +): class CaptionOnly(_Control): value_calls = 0 @@ -863,7 +869,8 @@ def GetValuePattern(self): assert button.GetPropertyValueEx(30019, 1) is _UNSUPPORTED_PROPERTY projection = perform("window-form-fields", {"hwnd": 7, "pid": 10}) assert [(f["kind"], f["text"]) for f in projection["fields"]] == [ - ("text", "Synthetic caption"), ("edit", "synthetic field") + ("text", "Synthetic caption"), + ("edit", "synthetic field"), ] sys.modules["uiautomation"].GetRootControl = lambda: root read = perform("read", {"locator": {"automation_id": "field"}}) @@ -872,7 +879,9 @@ def GetValuePattern(self): @pytest.mark.parametrize("capability", [True, None, "malformed"]) -def test_unproved_value_or_capability_on_structural_type_blocks_projection(monkeypatch, capability): +def test_unproved_value_or_capability_on_structural_type_blocks_projection( + monkeypatch, capability +): class Container(_Control): content_reads = 0 diff --git a/packages/flow/tests/test_form_projection_refusal.py b/packages/flow/tests/test_form_projection_refusal.py index 0704059d71..193fa2c9d8 100644 --- a/packages/flow/tests/test_form_projection_refusal.py +++ b/packages/flow/tests/test_form_projection_refusal.py @@ -442,7 +442,9 @@ def __getattr__(self, key): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_structure=guard, is_uia_not_supported=lambda _: False), + lambda: SimpleNamespace( + require_non_sensitive_structure=guard, is_uia_not_supported=lambda _: False + ), ) observation = server._form_boolean_observation(Target(), property_id) assert observation.value is None @@ -471,7 +473,9 @@ def guard(_): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_structure=guard, is_uia_not_supported=lambda _: False), + lambda: SimpleNamespace( + require_non_sensitive_structure=guard, is_uia_not_supported=lambda _: False + ), ) observed = server._form_boolean_observation(target, property_id) assert observed.value is value and observed.detail is None @@ -492,7 +496,10 @@ def query(prop, ignore): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_structure=lambda _: None, is_uia_not_supported=lambda _: False), + lambda: SimpleNamespace( + require_non_sensitive_structure=lambda _: None, + is_uia_not_supported=lambda _: False, + ), ) observed = server._form_field_state(target) assert not observed.complete and observed.state is None @@ -516,7 +523,10 @@ def query(prop, ignore): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_structure=lambda _: None, is_uia_not_supported=lambda _: False), + lambda: SimpleNamespace( + require_non_sensitive_structure=lambda _: None, + is_uia_not_supported=lambda _: False, + ), ) observed = server._form_field_state(target) assert not observed.complete and observed.reason == "state_capability_changed" diff --git a/packages/flow/tests/test_native_sensitive_reads.py b/packages/flow/tests/test_native_sensitive_reads.py index f72e547ecf..6f48db1059 100644 --- a/packages/flow/tests/test_native_sensitive_reads.py +++ b/packages/flow/tests/test_native_sensitive_reads.py @@ -13,7 +13,12 @@ WindowsBackend, ) from openadapt_flow.ir import StructuralLocator -from tests.test_approval_form_fields import _agent, _Control, _UNSUPPORTED_PROPERTY, _window +from tests.test_approval_form_fields import ( + _agent, + _Control, + _UNSUPPORTED_PROPERTY, + _window, +) class CountedControl(_Control): @@ -748,7 +753,9 @@ def test_unsupported_password_status_needs_win32_edit_evidence( ): evidence = _Evidence(plain) monkeypatch.setattr(native_value, "_PASSWORD_EVIDENCE", [evidence]) - monkeypatch.setattr(native_value, "is_uia_not_supported", lambda value: value is _UNSUPPORTED) + monkeypatch.setattr( + native_value, "is_uia_not_supported", lambda value: value is _UNSUPPORTED + ) control = _unsupported_status_control(raw, hwnd) if allowed: native_value.require_non_sensitive_value(control) @@ -809,7 +816,8 @@ def check(raw): client = SimpleNamespace(IUIAutomation=SimpleNamespace(CheckNotSupported=check)) monkeypatch.setitem(sys.modules, "comtypes", SimpleNamespace(IUnknown=_Unknown)) monkeypatch.setitem( - sys.modules, "uiautomation.uiautomation", + sys.modules, + "uiautomation.uiautomation", SimpleNamespace(_AutomationClient=SimpleNamespace(instance=lambda: client)), ) for malformed in (None, 0, False, "unknown", object(), ctypes.POINTER(_Unknown)()): @@ -820,8 +828,12 @@ def check(raw): assert calls == [token, foreign] -@pytest.mark.parametrize("style,error,allowed", [(0, 0, True), (0, 5, False), (0x20, 0, False)]) -def test_plain_edit_requires_a_successful_style_read(monkeypatch, style, error, allowed): +@pytest.mark.parametrize( + "style,error,allowed", [(0, 0, True), (0, 5, False), (0x20, 0, False)] +) +def test_plain_edit_requires_a_successful_style_read( + monkeypatch, style, error, allowed +): last = [99] messages = [] @@ -834,7 +846,9 @@ def get_style(hwnd, index): last[:] = [error] return style - monkeypatch.setattr(ctypes, "set_last_error", lambda n: last.__setitem__(0, n), raising=False) + monkeypatch.setattr( + ctypes, "set_last_error", lambda n: last.__setitem__(0, n), raising=False + ) monkeypatch.setattr(ctypes, "get_last_error", lambda: last[0], raising=False) reader = object.__new__(native_value.Win32TextReader) reader._user = SimpleNamespace(GetClassNameW=get_class, GetWindowLongW=get_style) @@ -845,7 +859,12 @@ def get_style(hwnd, index): @pytest.mark.parametrize( - "pattern,expected", [(ctypes.pointer(_Unknown()), True), (None, False), (ctypes.POINTER(_Unknown)(), False)] + "pattern,expected", + [ + (ctypes.pointer(_Unknown()), True), + (None, False), + (ctypes.POINTER(_Unknown)(), False), + ], ) def test_unsupported_availability_uses_the_exact_pattern_answer( monkeypatch, pattern, expected @@ -861,7 +880,11 @@ def test_unsupported_availability_uses_the_exact_pattern_answer( monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_structure=lambda _: None, is_uia_not_supported=lambda value: value is _UNSUPPORTED, pattern_presence=native_value.pattern_presence), + lambda: SimpleNamespace( + require_non_sensitive_structure=lambda _: None, + is_uia_not_supported=lambda value: value is _UNSUPPORTED, + pattern_presence=native_value.pattern_presence, + ), ) observed = server._form_boolean_observation(target, 30041) assert observed.value is expected and observed.detail is None @@ -893,7 +916,11 @@ def fail(pattern_id): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_structure=lambda _: None, is_uia_not_supported=lambda value: value is _UNSUPPORTED, pattern_presence=native_value.pattern_presence), + lambda: SimpleNamespace( + require_non_sensitive_structure=lambda _: None, + is_uia_not_supported=lambda value: value is _UNSUPPORTED, + pattern_presence=native_value.pattern_presence, + ), ) observed = server._form_boolean_observation(target, property_id) assert observed.value is None @@ -918,7 +945,11 @@ def guard(_): monkeypatch.setattr( server, "_native_value_api", - lambda: SimpleNamespace(require_non_sensitive_structure=guard, is_uia_not_supported=lambda value: value is _UNSUPPORTED, pattern_presence=native_value.pattern_presence), + lambda: SimpleNamespace( + require_non_sensitive_structure=guard, + is_uia_not_supported=lambda value: value is _UNSUPPORTED, + pattern_presence=native_value.pattern_presence, + ), ) observed = server._form_boolean_observation(target, 30041) assert observed.value is None and calls == [] From d7768a1e6e66e1a039bb56e30a705e410be9c528 Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Sat, 21 Nov 2026 15:22:53 -0500 Subject: [PATCH 34/34] fix(flow): look up Windows-only ctypes last-error functions at runtime --- .../flow/openadapt_flow/backends/win_agent/native_value.py | 4 ++-- 1 file changed, 2 insertions(+), 2 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 98d1a09821..55bfc238b7 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/native_value.py +++ b/packages/flow/openadapt_flow/backends/win_agent/native_value.py @@ -198,9 +198,9 @@ def _plain_edit_evidence(self, hwnd: int) -> EditEvidence: if not _edit_class(name.value): return EditEvidence.NON_EDIT # A zero GWL_STYLE is valid only when the call left no Win32 error. - ctypes.set_last_error(0) + getattr(ctypes, "set_last_error")(0) style = self._user.GetWindowLongW(hwnd, -16) # GWL_STYLE - if style == 0 and ctypes.get_last_error() != 0: + if style == 0 and getattr(ctypes, "get_last_error")() != 0: return EditEvidence.STYLE_UNAVAILABLE if style & ES_PASSWORD or self._message(hwnd, EM_GETPASSWORDCHAR) != 0: return EditEvidence.PROTECTED