From b08964b13ac1cce14d96165d9ba2b5c056123d7b Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 21:29:04 -0500 Subject: [PATCH 1/8] feat(flow): bind native keyboard input to one-shot focus leases --- .github/workflows/desktop-replay.yml | 58 +- packages/flow/docs/design/DECOMPOSITION.md | 4 +- .../flow/docs/design/NATIVE_KEYBOARD_LEASE.md | 50 ++ packages/flow/openadapt_flow/backend.py | 30 + .../backends/win_agent/keyboard_lease.py | 315 +++++++++ .../backends/win_agent/server.py | 234 ++++++- .../backends/windows_backend.py | 74 ++- .../backends/windows_keyboard_lease.py | 217 +++++++ .../flow/openadapt_flow/compiler/compile.py | 10 + .../openadapt_flow/compiler/native_focus.py | 130 ++++ .../flow/openadapt_flow/input_evidence.py | 51 ++ packages/flow/openadapt_flow/ir.py | 32 +- packages/flow/openadapt_flow/native_focus.py | 99 +++ packages/flow/openadapt_flow/recorder.py | 18 +- .../runtime/keyboard_delivery.py | 226 +++++++ .../flow/openadapt_flow/runtime/replayer.py | 114 ++-- packages/flow/scripts/desktop/winrm_lab.py | 6 +- .../tests/e2e/test_native_keyboard_lease.py | 612 ++++++++++++++++++ .../flow/tests/test_native_focus_keyboard.py | 342 ++++++++++ .../flow/tests/test_native_keyboard_edges.py | 166 +++++ .../flow/tests/test_native_keyboard_lease.py | 201 ++++++ .../flow/tests/test_native_keyboard_retry.py | 196 ++++++ .../test_windows_keyboard_lease_client.py | 255 ++++++++ 23 files changed, 3317 insertions(+), 123 deletions(-) create mode 100644 packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md create mode 100644 packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py create mode 100644 packages/flow/openadapt_flow/backends/windows_keyboard_lease.py create mode 100644 packages/flow/openadapt_flow/compiler/native_focus.py create mode 100644 packages/flow/openadapt_flow/input_evidence.py create mode 100644 packages/flow/openadapt_flow/native_focus.py create mode 100644 packages/flow/openadapt_flow/runtime/keyboard_delivery.py create mode 100644 packages/flow/tests/e2e/test_native_keyboard_lease.py create mode 100644 packages/flow/tests/test_native_focus_keyboard.py create mode 100644 packages/flow/tests/test_native_keyboard_edges.py create mode 100644 packages/flow/tests/test_native_keyboard_lease.py create mode 100644 packages/flow/tests/test_native_keyboard_retry.py create mode 100644 packages/flow/tests/test_windows_keyboard_lease_client.py diff --git a/.github/workflows/desktop-replay.yml b/.github/workflows/desktop-replay.yml index 9185099a0e..e6e1f18350 100644 --- a/.github/workflows/desktop-replay.yml +++ b/.github/workflows/desktop-replay.yml @@ -11,7 +11,9 @@ name: Desktop replay # as a continue-on-error step, so it reports but does not fail the job # (packages/flow/tests/e2e/test_windows_hosted_governed.py). A gating # step after it fails the job on any unsafe write the run made -# (scripts/ci/check_windows_governed_safety.py). +# (scripts/ci/check_windows_governed_safety.py). A separate gating proof +# checks one-shot native keyboard leases with real TYPE, KEY and HOTKEY +# receipts, UIA field read-back, planted lease faults and unchanged SQLite rows. # - freerdp: a FreeRDP transport round trip on Linux, not a replay. xfreerdp3 # connects over loopback to freerdp-shadow-cli3 serving an Xvfb display, and # FreeRDPBackend looks up three accounts in a synthetic read-only ledger app @@ -26,6 +28,7 @@ on: - packages/flow/scripts/desktop/pn_db.py - packages/flow/scripts/desktop/patient_notes.ps1 - packages/flow/tests/e2e/test_windows_hosted_replay.py + - packages/flow/tests/e2e/test_native_keyboard_lease.py - packages/flow/tests/e2e/test_windows_hosted_governed.py - packages/flow/tests/_approver_keys.py - packages/flow/tests/conftest.py @@ -57,7 +60,9 @@ jobs: replay: name: windows replay (Patient Notes, WindowsBackend) runs-on: windows-latest - timeout-minutes: 25 + timeout-minutes: 30 + env: + EXPECTED_SOURCE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} defaults: run: working-directory: packages/flow @@ -65,6 +70,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} persist-credentials: false - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: @@ -89,6 +95,42 @@ jobs: 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 + - name: Native keyboard leases (real input, read-back and planted refusals) + timeout-minutes: 6 + env: + OAFLOW_WINDOWS_HOSTED_E2E: "1" + OAFLOW_NATIVE_KEYBOARD_LEASE_EVIDENCE: ${{ runner.temp }}/nkl/evidence.json + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/nkl" + { + git rev-parse HEAD + git rev-parse "HEAD^{tree}" + printf 'expected=%s run=%s attempt=%s\n' "$EXPECTED_SOURCE_SHA" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" + } | tee "$RUNNER_TEMP/nkl/source.log" + test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA" + pytest -v -rs -p no:cacheprovider --basetemp="$RUNNER_TEMP/nkl/cases" \ + tests/e2e/test_native_keyboard_lease.py \ + --junitxml="$RUNNER_TEMP/nkl/junit.xml" 2>&1 | tee "$RUNNER_TEMP/nkl/pytest.log" + python - <<'PYTHON' + import json + import os + from pathlib import Path + import xml.etree.ElementTree as ET + root = Path(os.environ["RUNNER_TEMP"]) / "nkl" + cases = list(ET.parse(root / "junit.xml").getroot().iter("testcase")) + assert len(cases) == 1 + assert cases[0].get("name") == "test_native_keyboard_lease_actual_delivery_and_refusal" + assert not any(cases[0].find(tag) is not None for tag in ("skipped", "failure", "error")) + proof = json.loads((root / "evidence.json").read_text()) + expected = {"type", "key", "hotkey", "stale_frame", "fresh_after_zero_input", "stale_focus", "replaced_target", "consumed_lease", "uncertain_ack"} + assert len(proof["cases"]) == len(expected) + assert {case["case"] for case in proof["cases"]} == expected + assert proof["passed"] is True and proof["agent_terminated"] is True and proof["fixture_terminated"] is True + assert proof["head"] == os.environ["EXPECTED_SOURCE_SHA"] + assert proof["rows_before"] == proof["rows_after"] + print(json.dumps({"native_lease_cases": len(expected), "skipped": 0, "rows_unchanged": True})) + PYTHON - name: Record, compile and replay, judged from the record env: OAFLOW_WINDOWS_HOSTED_E2E: "1" @@ -144,6 +186,16 @@ jobs: path: | ${{ runner.temp }}/windows-replay-evidence.json ${{ runner.temp }}/windows-governed-evidence.json + ${{ runner.temp }}/nkl/*.json + ${{ runner.temp }}/nkl/*.xml + ${{ runner.temp }}/nkl/*.log + ${{ runner.temp }}/nkl/cases/**/evidence.json + ${{ runner.temp }}/nkl/cases/**/*.png + ${{ runner.temp }}/nkl/cases/**/agent.log + ${{ runner.temp }}/nkl/cases/**/lease-replaced.json + ${{ runner.temp }}/nkl/cases/**/patient_notes.ps1 + ${{ runner.temp }}/nkl/cases/**/pn_db.py + ${{ runner.temp }}/nkl/cases/**/patients.db ${{ runner.temp }}/wg/**/report.json ${{ runner.temp }}/wg/**/agent.log ${{ runner.temp }}/wg/**/item-approval/* @@ -227,7 +279,7 @@ jobs: mkdir -p "$EVIDENCE_DIR" { git rev-parse HEAD - git rev-parse HEAD^{tree} + git rev-parse "HEAD^{tree}" printf 'expected=%s run=%s attempt=%s\n' "$EXPECTED_SOURCE_SHA" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" cat /etc/os-release uname -a diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index d66f767b64..d783f6aec3 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -603,10 +603,10 @@ PR #2280 raised `replayer.py` by 12 lines: the call sites of the clock-text chec | File | Line budget | |---|---:| -| `packages/flow/openadapt_flow/runtime/replayer.py` | 20094 | +| `packages/flow/openadapt_flow/runtime/replayer.py` | 20090 | | `packages/flow/openadapt_flow/__main__.py` | 14570 | | `packages/flow/openadapt_flow/qualification.py` | 5963 | -| `packages/flow/openadapt_flow/ir.py` | 6711 | +| `packages/flow/openadapt_flow/ir.py` | 6677 | | `packages/desktop/openadapt_desktop/dispatch.py` | 6524 | | `packages/capture/openadapt_capture/recorder.py` | 4836 | | `packages/flow/openadapt_flow/interactive_recorder.py` | 4620 | diff --git a/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md b/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md new file mode 100644 index 0000000000..6dc6076040 --- /dev/null +++ b/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md @@ -0,0 +1,50 @@ +# Native keyboard focus leases + +Native keyboard input has three entry points: text, a key and a chord. A locator +or earlier focusing click alone cannot show which live control received them. +A form can replace its focused control while keeping its label, geometry and +value, and a frame can change after identity verification but before input. + +The recorder passively observes the actual focused UI Automation control for +all three entry points. Compilation uses that event's own before frame and the +same operator-selected identity crop as pointer actions. Missing observation +leaves the action unanchored; malformed observation refuses compilation. + +An authenticated agent that advertises `native_keyboard_lease_v1` issues one +15-second lease over a unique live focused control, runtime fingerprint, +application/executable/session/environment and exact PNG bytes. Issuing a lease +invalidates its predecessor. Delivery consumes it before checking bindings. +Unicode clipboard preparation finishes before final checks. Every physical +keyboard edge checks focus, context and the delivery deadline. Uncertain calls +release held keys and produce no positive acknowledgement. A key that +intentionally changes focus can therefore be reported uncertain. + +The agent alone creates a typed delivery receipt after the actual input path +returns. The client requires its operation and native target fingerprint to +match. Replayed leases, changed focus, invalid frames and changed context refuse. +Lost or malformed acknowledgements are uncertain and are never retried. + +A stale-frame response permits at most two keyboard-only reacquisitions. This +requires an authenticated response for the consumed lease proving zero keyboard +input, real changed-pixel geometry, full target/identity/context/authorization +revalidation, the same runtime target fingerprint, and an unchanged readable +field baseline for text. Effectful, API-bound and irreversible actions do not +use this retry. The earlier focusing click is never repeated. Exact PNG equality +still gates delivery; no caret or focus pixels are ignored. Reports retain the +refused lease hash, geometry and keyboard phase through checkpoint/resume. + +## Evidence and limits + +The opt-in Windows CI proof uses a synthetic WinForms app and an independent +SQLite reader. It requires text, Enter and a chord; plants stale frames, changed +focus, same-form control replacement, consumed-token replay and a lost actual +acknowledgement; and retains delegated HTTP envelopes and native evidence. A +Mac skip is collection evidence only. The PR records the actual Windows result. +The shared runtime has property and entry-point tests; full Windows +qualification remains a separate draft until its signed campaign passes. + +No app names or app-specific branches are added to the engine. The defect class +is temporal attribution of keyboard input across all native entry points. +Same-form replacement, replay and lost acknowledgement are held-out cases beyond +the unreceipted Enter/stale-frame campaign failures that motivated the work. +This advances independently verifiable action receipts and refusal evidence. diff --git a/packages/flow/openadapt_flow/backend.py b/packages/flow/openadapt_flow/backend.py index c3711a9a96..0f21c7cdb9 100644 --- a/packages/flow/openadapt_flow/backend.py +++ b/packages/flow/openadapt_flow/backend.py @@ -116,6 +116,27 @@ def __init__( self.frame_size = frame_size +class KeyboardFrameChangedBeforeInput(FreshActuationRequired): + """A known one-shot keyboard lease refused before its keyboard gesture. + + Earlier phases (such as a focusing click) may have happened. Only the + keyboard phase may be reacquired, after complete fresh revalidation. + """ + + def __init__( + self, *, lease_sha256: str, target_fingerprint: str, **kwargs: Any + ) -> None: + import re + + if not re.fullmatch(r"[a-f0-9]{64}", lease_sha256) or not re.fullmatch( + r"[a-f0-9]{64}", target_fingerprint + ): + raise ValueError("keyboard lease evidence requires exact digests") + super().__init__(**kwargs) + self.lease_sha256 = lease_sha256 + self.target_fingerprint = target_fingerprint + + @runtime_checkable class SystemOfRecordBackend(Protocol): """Optional system-of-record observation a backend MAY expose. @@ -495,6 +516,15 @@ def cancel_focused_element_lease(self) -> None: ... +@runtime_checkable +class NativeKeyboardLeaseBackend(Protocol): + """A backend exposes actual native focus and its current one-shot lease.""" + + def native_keyboard_lease_available(self) -> bool: ... + + def guarded_keyboard_target_fingerprint(self) -> Optional[str]: ... + + @runtime_checkable class GuardedKeyboardActionBackend(Protocol): """Optional browser-local focus/record lease for consequential keyboard I/O. diff --git a/packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py b/packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py new file mode 100644 index 0000000000..d85ca6f361 --- /dev/null +++ b/packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py @@ -0,0 +1,315 @@ +"""One-shot native keyboard leases over real focus, context and exact frames. + +This module is also copied next to the standalone in-guest agent. It imports +only the standard library and accepts the agent's ordinary observation/input +functions. A refusal receipt is produced only before its input callback runs. +""" + +from __future__ import annotations + +import base64 +import hashlib +import re +import struct +import time +import uuid +from typing import Any, Callable + +_HEX = re.compile(r"^[a-f0-9]{64}$") +_TOKEN = re.compile(r"^[a-f0-9]{32}$") +_PNG = b"\x89PNG\r\n\x1a\n" + + +class KeyboardLeaseError(RuntimeError): + """A bounded observation failure, with no delivery assertion.""" + + +class KeyboardLeaseRefused(KeyboardLeaseError): + """A consumed known lease refused before its keyboard input callback.""" + + def __init__( + self, + reason: str, + lease_id: str, + operation: str, + frame_change: dict[str, Any] | None = None, + ) -> None: + self.reason, self.lease_id, self.operation = reason, lease_id, operation + self.frame_change = frame_change + super().__init__(reason) + + def payload(self) -> dict[str, Any]: + result = { + "status": "refused", + "reason": self.reason, + "lease_id": self.lease_id, + "operation": self.operation, + "no_keyboard_input_delivered": True, + } + if self.frame_change is not None: + result["frame_change"] = self.frame_change + return result + + +def _target(value: Any) -> dict[str, Any]: + if not isinstance(value, dict) or value.get("status") != "ok": + raise KeyboardLeaseError("focused_target_unavailable") + target = value.get("target") + if ( + not isinstance(target, dict) + or not isinstance(target.get("fingerprint"), str) + or not _HEX.fullmatch(target["fingerprint"]) + ): + raise KeyboardLeaseError("focused_target_unavailable") + point, bounds = target.get("point"), target.get("bounds") + if ( + not isinstance(point, list) + or len(point) != 2 + or not isinstance(bounds, list) + or len(bounds) != 4 + or any( + isinstance(v, bool) or not isinstance(v, int) or abs(v) > 32768 + for v in [*point, *bounds] + ) + or not (bounds[0] <= point[0] < bounds[2] and bounds[1] <= point[1] < bounds[3]) + ): + raise KeyboardLeaseError("focused_target_geometry_unavailable") + return target + + +def _context(value: Any) -> dict[str, Any]: + if not isinstance(value, dict) or value.get("status") != "ok": + raise KeyboardLeaseError("context_unavailable") + result = { + name: value.get(name) + for name in ( + "application", + "application_version", + "session", + "environment", + "workflow_state", + ) + } + if ( + not isinstance(result["application"], str) + or not result["application"] + or any( + not isinstance(result[name], str) or not result[name] + for name in ("application_version", "session", "environment") + ) + ): + raise KeyboardLeaseError("context_unavailable") + return result + + +def _frame(value: Any) -> bytes: + if ( + not isinstance(value, bytes) + or len(value) < 24 + or len(value) > 32 * 1024 * 1024 + or not value.startswith(_PNG) + ): + raise KeyboardLeaseError("frame_unavailable") + width, height = struct.unpack(">II", value[16:24]) + if not (0 < width <= 32768 and 0 < height <= 32768 and width * height <= 16777216): + raise KeyboardLeaseError("frame_geometry_unavailable") + return value + + +def keyboard_operation(payload: Any) -> str: + if not isinstance(payload, dict): + raise KeyboardLeaseError("invalid_keyboard_input") + action = payload.get("action") + if action == "type_text": + if ( + set(payload) - {"action", "text", "interval_s"} + or not isinstance(payload.get("text"), str) + or len(payload["text"]) > 65536 + ): + raise KeyboardLeaseError("invalid_keyboard_input") + interval = payload.get("interval_s", 0.05) + if ( + isinstance(interval, bool) + or not isinstance(interval, (int, float)) + or not 0 <= interval <= 1 + ): + raise KeyboardLeaseError("invalid_keyboard_input") + return "physical_type_text" + if action == "press": + keys = payload.get("keys") + if ( + set(payload) != {"action", "keys"} + or not isinstance(keys, list) + or not 1 <= len(keys) <= 4 + or any(not isinstance(key, str) or not 1 <= len(key) <= 32 for key in keys) + ): + raise KeyboardLeaseError("invalid_keyboard_input") + return "physical_press" + raise KeyboardLeaseError("invalid_keyboard_input") + + +def frame_change(before: bytes, after: bytes) -> dict[str, Any] | None: + from io import BytesIO + + from PIL import Image, ImageChops + + try: + with Image.open(BytesIO(before)) as a, Image.open(BytesIO(after)) as b: + if a.size != b.size: + return None + delta = ImageChops.difference(a.convert("RGB"), b.convert("RGB")) + bbox = delta.getbbox() + if bbox is None: + return None + red, green, blue = delta.split() + nonzero = ImageChops.lighter(ImageChops.lighter(red, green), blue) + count = a.width * a.height - nonzero.histogram()[0] + return { + "changed_pixel_count": count, + "changed_bbox": [ + bbox[0], + bbox[1], + bbox[2] - bbox[0], + bbox[3] - bbox[1], + ], + "frame_size": list(a.size), + } + except (OSError, ValueError): + return None + + +class KeyboardLeaseController: + """A bounded lease names the actual focused element and captured desktop.""" + + def __init__( + self, + uia: Callable[..., dict[str, Any]], + capture: Callable[[], bytes], + context: Callable[[], dict[str, Any]], + deliver: Callable[..., dict[str, Any]], + *, + clock: Callable[[], float] = time.monotonic, + lifetime_s: float = 15.0, + prepare: Callable[[dict[str, Any]], None] | None = None, + ) -> None: + self._uia, self._capture, self._context, self._deliver = ( + uia, + capture, + context, + deliver, + ) + self._clock, self._lifetime_s = clock, lifetime_s + self._prepare = prepare + self._delivering: tuple[dict[str, Any], dict[str, Any], float] | None = None + self._pending: ( + tuple[str, float, dict[str, Any], dict[str, Any], bytes] | None + ) = None + + def issue(self) -> dict[str, Any]: + # The agent is single-threaded. A new observation invalidates its prior + # lease, and no input callback is invoked while observing. + self._pending = None + before = _target(self._uia("focused-target", {})) + context = _context(self._context()) + png = _frame(self._capture()) + after = _target(self._uia("focused-target", {})) + if before["fingerprint"] != after["fingerprint"] or context != _context( + self._context() + ): + raise KeyboardLeaseError("keyboard_observation_changed") + token = uuid.uuid4().hex + digest = hashlib.sha256(png).hexdigest() + self._pending = ( + token, + self._clock() + self._lifetime_s, + after, + context, + png, + ) + return { + "status": "ok", + "schema": "openadapt.native-keyboard-lease/v1", + "lease_id": token, + "frame_sha256": digest, + "frame_png": base64.b64encode(png).decode("ascii"), + "target": after, + "context": context, + } + + def deliver( + self, lease_id: str, expected_frame_sha256: str, payload: Any + ) -> dict[str, Any]: + pending, self._pending = self._pending, None + operation = keyboard_operation(payload) + if ( + not isinstance(lease_id, str) + or not _TOKEN.fullmatch(lease_id) + or pending is None + or pending[0] != lease_id + ): + raise KeyboardLeaseError("keyboard_lease_not_owned") + _, deadline, target, context, before_png = pending + frame_sha = hashlib.sha256(before_png).hexdigest() + + def refuse(reason: str) -> None: + raise KeyboardLeaseRefused(reason, lease_id, operation) + + if self._clock() > deadline: + refuse("expired") + if expected_frame_sha256 != frame_sha: + refuse("unverified_frame") + if self._prepare is not None: + self._prepare(payload) + if context != _context(self._context()): + refuse("stale_context") + current = _target(self._uia("focused-target", {})) + if current["fingerprint"] != target["fingerprint"]: + refuse("stale_focus") + current_png = _frame(self._capture()) + if hashlib.sha256(current_png).hexdigest() != frame_sha: + raise KeyboardLeaseRefused( + "stale_frame", + lease_id, + operation, + frame_change(before_png, current_png), + ) + # Any exception after this boundary is uncertain. It must never be + # wrapped in the zero-keyboard-input refusal contract. + if self._clock() > deadline: + refuse("expired") + self._delivering = (target, context, deadline) + try: + result = self._deliver(payload) + finally: + self._delivering = None + receipt = result if isinstance(result, dict) else None + if ( + not isinstance(receipt, dict) + or receipt.get("status") != "delivered" + or receipt.get("operation") != operation + or receipt.get("native") is not False + or not isinstance(receipt.get("receipt_id"), str) + or not isinstance(receipt.get("delivered_at"), str) + or receipt.get("outcome_verified") is not False + ): + raise RuntimeError( + "keyboard delivery receipt unavailable after delivery boundary" + ) + return { + "status": "ok", + "lease_id": lease_id, + "receipt": {**receipt, "target_fingerprint": target["fingerprint"]}, + } + + def require_current_target(self) -> None: + """After delivery may begin, any focus/context change is uncertain.""" + if self._delivering is None: + raise RuntimeError("keyboard delivery has no active focus lease") + target, context, deadline = self._delivering + if ( + self._clock() > deadline + or _target(self._uia("focused-target", {}))["fingerprint"] + != target["fingerprint"] + or _context(self._context()) != context + ): + raise RuntimeError("keyboard target changed during delivery") diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index f81f8849a0..2242134de8 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -350,7 +350,65 @@ def _delivery_receipt( } -def _perform_input(payload: dict[str, Any]) -> dict[str, Any]: +def _prepare_keyboard_input(data: dict[str, Any]) -> None: + """Prepare Unicode paste before the final leased frame/context checks.""" + text = data.get("text") + if ( + data.get("action") != "type_text" + or not isinstance(text, str) + or not text + or text.isascii() + ): + return + encoded = base64.b64encode(text.encode("utf-8")).decode("ascii") + command = ( + "Set-Clipboard -Value ([Text.Encoding]::UTF8.GetString(" + f"[Convert]::FromBase64String('{encoded}')))" + ) + result = subprocess.run( + ["powershell", "-NoProfile", "-Command", command], + capture_output=True, + timeout=10, + creationflags=0x08000000, + ) + if result.returncode != 0: + raise RuntimeError("Unicode keyboard preparation failed") + + +def _guarded_key_chord(gui: Any, keys: list[str], guard: Any) -> None: + """Guard each physical edge; release held keys after uncertain delivery. + + A key can intentionally move focus. A changed target then makes delivery + uncertain, including after the final edge; it never authorizes a retry. + Cleanup emits releases only, even when the live target cannot be read. + """ + held: list[str] = [] + try: + for key in keys: + guard() + # A throwing native call might already have sent its edge. + held.append(key) + gui.keyDown(key, _pause=False) + guard() + for key in reversed(keys): + guard() + gui.keyUp(key, _pause=False) + held.pop() + guard() + finally: + for key in reversed(held): + try: + gui.keyUp(key, _pause=False) + except Exception: # noqa: BLE001 - preserve the original uncertainty + pass + + +def _perform_input( + payload: dict[str, Any], + *, + keyboard_guard: Any = None, + clipboard_prepared: bool = False, +) -> dict[str, Any]: """Execute one bounded physical-input request in the interactive session.""" data = _exact_object( payload, @@ -460,6 +518,8 @@ def _perform_input(payload: dict[str, Any]) -> dict[str, Any]: ) def require_foreground() -> None: + if callable(keyboard_guard): + keyboard_guard() if _foreground_window_identity() != foreground: raise AgentRequestError( 409, @@ -470,26 +530,21 @@ def require_foreground() -> None: if text.isascii(): for index, char in enumerate(text): require_foreground() - pyautogui.write(char, interval=0, _pause=False) + if callable(keyboard_guard): + _guarded_key_chord(pyautogui, [char], require_foreground) + else: + pyautogui.write(char, interval=0, _pause=False) require_foreground() if index + 1 < len(text): time.sleep(float(interval)) else: - encoded = base64.b64encode(text.encode("utf-8")).decode("ascii") - ps = ( - "Set-Clipboard -Value ([Text.Encoding]::UTF8.GetString(" - f"[Convert]::FromBase64String('{encoded}')))" - ) - completed = subprocess.run( - ["powershell", "-NoProfile", "-Command", ps], - capture_output=True, - timeout=10, - ) - if completed.returncode != 0: - raise RuntimeError("Set-Clipboard failed") - time.sleep(0.2) + if not clipboard_prepared: + _prepare_keyboard_input(data) require_foreground() - pyautogui.hotkey("ctrl", "v") + if callable(keyboard_guard): + _guarded_key_chord(pyautogui, ["ctrl", "v"], require_foreground) + else: + pyautogui.hotkey("ctrl", "v") require_foreground() return _delivery_receipt("physical_type_text", native=False) @@ -508,7 +563,9 @@ def require_foreground() -> None: import pyautogui # noqa: PLC0415 - Windows-only, lazy by design pyautogui.FAILSAFE = False - if len(keys) == 1: + if callable(keyboard_guard): + _guarded_key_chord(pyautogui, keys, keyboard_guard) + elif len(keys) == 1: pyautogui.press(keys[0]) else: pyautogui.hotkey(*keys) @@ -934,6 +991,59 @@ def _uia_field_label(control: object) -> Optional[str]: return name or None +def _focused_target(auto: Any) -> Optional[dict[str, Any]]: + """The actual visible, uniquely named focused control, without its value.""" + try: + focused = auto.GetFocusedControl() + except Exception: # noqa: BLE001 - no observation, no target evidence + return None + node = focused + target = None + for _ in range(6): + if node is None: + return None + if str(_control_value(node, "ControlTypeName", "")) in _ACTIONABLE_TYPES: + target = node + break + node = _parent(node) + if target is None: + return None + candidate = _candidate(target) + if candidate is None: + return None + locator = { + key: candidate.get(key) + for key in ("automation_id", "role", "name", "window_name") + } + found, truncated = _find_candidates(locator, auto) + if ( + truncated + or len(found) != 1 + or not hmac.compare_digest(found[0][1]["fingerprint"], candidate["fingerprint"]) + ): + return None + if not _hits_target(auto, target, candidate): + return None + # Focus may change while enumerating the tree: the second live read must + # identify the same runtime control, not merely the same label. + try: + current = auto.GetFocusedControl() + except Exception: # noqa: BLE001 + return None + if ( + current is None + or _runtime_id(current) != _runtime_id(focused) + or not _runtime_id(focused) + ): + return None + latest = _candidate(target) + if latest is None or not hmac.compare_digest( + latest["fingerprint"], candidate["fingerprint"] + ): + return None + return candidate + + def _focused_field_label(auto: Any) -> Optional[str]: """Label of the one focused UIA control, or None.""" @@ -1526,6 +1636,10 @@ def _perform_uia_initialized( locator = None return {"status": "ok", "locator": locator} + if operation == "focused-target": + _exact_object(payload, label=operation) + return {"status": "ok", "target": _focused_target(auto)} + if operation == "focused-field-label": _exact_object(payload, required=frozenset(), label=operation) return {"status": "ok", "label": _focused_field_label(auto)} @@ -2813,6 +2927,45 @@ def make_handler_class( deterministic fake frame (no mss / no live desktop). """ + keyboards = None + keyboard_errors: tuple[type[Exception], ...] = () + keyboard_refusals: tuple[type[Exception], ...] = () + if config.authed(): + try: + from openadapt_flow.backends.win_agent.keyboard_lease import ( + KeyboardLeaseController, + KeyboardLeaseError, + KeyboardLeaseRefused, + ) + except ModuleNotFoundError: + from win_agent_keyboard_lease import ( # type: ignore[no-redef,import-not-found] + KeyboardLeaseController, + KeyboardLeaseError, + KeyboardLeaseRefused, + ) + keyboard_errors, keyboard_refusals = ( + (KeyboardLeaseError,), + (KeyboardLeaseRefused,), + ) + + def deliver_keyboard(data: dict[str, Any]) -> dict[str, Any]: + assert keyboards is not None + if input_fn is _perform_input: + return _perform_input( + data, + keyboard_guard=keyboards.require_current_target, + clipboard_prepared=True, + ) + return input_fn(data) + + keyboards = KeyboardLeaseController( + uia_fn, + grab_fn, + context_fn, + deliver_keyboard, + prepare=_prepare_keyboard_input if input_fn is _perform_input else None, + ) + class AgentHandler(BaseHTTPRequestHandler): server_version = "OAFlowWinAgent/1.0" @@ -2862,11 +3015,17 @@ def do_GET(self) -> None: # noqa: N802 - stdlib naming "context_identity_v1", "context_environment_v1", "typed_input_v1", + *( + ["native_keyboard_lease_v1"] + if keyboards is not None + else [] + ), "guarded_input_v1", "uia_v1", "uia_read_v1", "window_bounds_v1", "uia_authoring_tree_v1", + "native_focus_v1", *( ["legacy_waa_input_v1"] if config.allow_legacy_exec @@ -2910,12 +3069,20 @@ def do_POST(self) -> None: # noqa: N802 - stdlib naming "/window/bounds": ("uia", "window-bounds"), "/uia/text-at-point": ("uia", "text-at-point"), "/uia/focused-field-label": ("uia", "focused-field-label"), + "/uia/focused-target": ("uia", "focused-target"), "/uia/identity-candidates-at": ("uia", "identity-candidates-at"), "/uia/find": ("uia", "find"), "/uia/act": ("uia", "act"), "/uia/read": ("uia", "read"), "/uia/tree": ("uia", "tree"), } + if keyboards is not None: + typed_routes.update( + { + "/keyboard/lease": ("keyboard-lease", "observe"), + "/keyboard/input": ("keyboard-lease", "deliver"), + } + ) is_legacy = self.path == "/execute_windows" and config.allow_legacy_exec if self.path not in typed_routes and not is_legacy: self._send_json(404, {"status": "error", "error": "not found"}) @@ -2974,6 +3141,26 @@ def do_POST(self) -> None: # noqa: N802 - stdlib naming if self.path in typed_routes: kind, operation = typed_routes[self.path] try: + if kind == "keyboard-lease": + assert keyboards is not None + if operation == "observe": + _exact_object(data, label="keyboard lease observation") + result = keyboards.issue() + else: + request = _exact_object( + data, + required=frozenset( + {"lease_id", "expected_frame_sha256", "input"} + ), + label="keyboard lease input", + ) + result = keyboards.deliver( + request["lease_id"], + request["expected_frame_sha256"], + request["input"], + ) + self._send_json(200, result) + return if kind == "context": _exact_object(data, label="context identity request") if kind == "guarded-input": @@ -3104,6 +3291,19 @@ def do_POST(self) -> None: # noqa: N802 - stdlib naming if kind == "context" else uia_fn(operation, data) ) + except keyboard_refusals as exc: + self._send_json(409, exc.payload()) # type: ignore[attr-defined] + return + except keyboard_errors: + self._send_json( + 409, + { + "status": "error", + "code": "keyboard_lease_unavailable", + "error": "native keyboard lease refused", + }, + ) + return except AgentRequestError as exc: self._send_json( exc.status, diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index 82ba18bd3c..c551437ec8 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -354,6 +354,8 @@ def __init__( self._guarded_coordinate: Optional[ tuple[tuple[int, int], dict[str, Optional[str]]] ] = None + self._keyboard_lease_client: Any = None + self._keyboard_lease_enabled: Optional[bool] = None self._guarded_keyboard: Optional[ tuple[tuple[int, int], dict[str, Optional[str]]] ] = None @@ -1118,6 +1120,22 @@ def owned_window_over( return None return dict(window) + def focus_identity(self) -> Optional[dict[str, Any]]: + """Passive native focused-target evidence, without reading its value. + + This intentionally uses a native namespace instead of browser DOM id + counts, so the compiler cannot turn it into a browser focus condition. + """ + from openadapt_flow.native_focus import from_native_candidate + + response = self._post_typed_read("/uia/focused-target", {}) + if not response.available or response.payload is None: + return None + target = from_native_candidate(response.payload.get("target")) + return ( + None if target is None else {"native_focus": target.model_dump(mode="json")} + ) + def element_identity_at(self, x: int, y: int) -> Optional[dict]: """Return the UIA identity of the element under (x, y), or None. @@ -1572,12 +1590,42 @@ def arm_guarded_coordinate(self, x: int, y: int) -> None: def cancel_guarded_coordinate(self) -> None: self._guarded_coordinate = None + def _focused_keyboard_leases(self) -> Any: + if self._keyboard_lease_enabled is None: + self._keyboard_lease_enabled = ( + "native_keyboard_lease_v1" in self.agent_capabilities() + ) + if not self._keyboard_lease_enabled: + return None + if self._keyboard_lease_client is None: + from openadapt_flow.backends.windows_keyboard_lease import ( + NativeKeyboardLeaseClient, + ) + + def post(path: str, data: dict[str, Any]) -> Any: + return self._session.post( + f"{self.server_url}{path}", json=data, **self._request_kwargs() + ) + + def before_input() -> None: + if self._qualification_input_guard is not None: + self._qualification_input_guard() + + self._keyboard_lease_client = NativeKeyboardLeaseClient(post, before_input) + return self._keyboard_lease_client + def guarded_keyboard_frame(self) -> bytes: - return self.screenshot() + leases = self._focused_keyboard_leases() + return leases.frame() if leases is not None else self.screenshot() def arm_guarded_keyboard(self, x: int, y: int) -> None: """Bind the resolved focused element and live context before identity.""" + leases = self._focused_keyboard_leases() + if leases is not None: + self._guarded_keyboard = None + leases.arm(int(x), int(y)) + return self.cancel_guarded_keyboard() point = (int(x), int(y)) width, height = self.viewport @@ -1589,6 +1637,8 @@ def arm_guarded_keyboard(self, x: int, y: int) -> None: def cancel_guarded_keyboard(self) -> None: self._guarded_keyboard = None + if self._keyboard_lease_client is not None: + self._keyboard_lease_client.cancel() @staticmethod def _guarded_receipt( @@ -1706,12 +1756,29 @@ def drag_guarded( ) return self._guarded_receipt(response, "physical_drag") + def native_keyboard_lease_available(self) -> bool: + return self._focused_keyboard_leases() is not None + + def guarded_keyboard_target_fingerprint(self) -> Optional[str]: + leases = self._focused_keyboard_leases() + return leases.target_fingerprint() if leases is not None else None + def type_text_guarded( self, text: str, *, expected_frame_sha256: str, ) -> ActionDeliveryReceipt: + leases = self._focused_keyboard_leases() + if leases is not None: + return leases.deliver( + { + "action": "type_text", + "text": text, + "interval_s": self._type_interval_s, + }, + expected_frame_sha256, + ) pending = self._guarded_keyboard self._guarded_keyboard = None if pending is None: @@ -1740,6 +1807,11 @@ def press_guarded( *, expected_frame_sha256: str, ) -> ActionDeliveryReceipt: + leases = self._focused_keyboard_leases() + if leases is not None: + return leases.deliver( + {"action": "press", "keys": normalize_chord(key)}, expected_frame_sha256 + ) pending = self._guarded_keyboard self._guarded_keyboard = None if pending is None: diff --git a/packages/flow/openadapt_flow/backends/windows_keyboard_lease.py b/packages/flow/openadapt_flow/backends/windows_keyboard_lease.py new file mode 100644 index 0000000000..258915bcec --- /dev/null +++ b/packages/flow/openadapt_flow/backends/windows_keyboard_lease.py @@ -0,0 +1,217 @@ +"""Client for an authenticated native keyboard lease, with no silent fallback.""" + +from __future__ import annotations + +import base64 +import hashlib +import re +import struct +from typing import Any, Callable + +from openadapt_flow.backend import ( + ActionDeliveryUncertain, + KeyboardFrameChangedBeforeInput, + StructuralResolutionRefused, +) +from openadapt_flow.backends.win_agent.keyboard_lease import ( + _context, + _frame, + _target, + keyboard_operation, +) +from openadapt_flow.ir import ActionDeliveryReceipt + + +class NativeKeyboardLeaseClient: + def __init__( + self, + post: Callable[[str, dict[str, Any]], Any], + before_input: Callable[[], None], + ) -> None: + self._post, self._before_input = post, before_input + self._observed: dict[str, Any] | None = None + self._armed: dict[str, Any] | None = None + + def target_fingerprint(self) -> str | None: + return self._armed["target"]["fingerprint"] if self._armed else None + + def cancel(self) -> None: + self._observed = self._armed = None + + def frame(self) -> bytes: + self.cancel() + try: + response = self._post("/keyboard/lease", {}) + data = response.json() + if ( + response.status_code != 200 + or not isinstance(data, dict) + or set(data) + != { + "status", + "schema", + "lease_id", + "frame_sha256", + "frame_png", + "target", + "context", + } + ): + raise ValueError("invalid lease envelope") + if ( + data["status"] != "ok" + or data["schema"] != "openadapt.native-keyboard-lease/v1" + or not isinstance(data["lease_id"], str) + or not re.fullmatch(r"[a-f0-9]{32}", data["lease_id"]) + ): + raise ValueError("invalid lease identity") + target = _target({"status": "ok", "target": data["target"]}) + _context({"status": "ok", **data["context"]}) + if ( + not isinstance(data["frame_png"], str) + or len(data["frame_png"]) > 45 * 1024 * 1024 + ): + raise ValueError("invalid lease frame") + png = _frame(base64.b64decode(data["frame_png"], validate=True)) + if hashlib.sha256(png).hexdigest() != data["frame_sha256"]: + raise ValueError("lease frame digest mismatch") + self._observed = {**data, "target": target} + return png + except Exception as exc: + raise StructuralResolutionRefused( + "native keyboard lease observation unavailable" + ) from exc + + def arm(self, x: int, y: int) -> None: + if self._observed is None: + self.frame() + lease, self._observed = self._observed, None + self._armed = None + assert lease is not None + left, top, right, bottom = lease["target"]["bounds"] + if not (left <= x < right and top <= y < bottom): + raise StructuralResolutionRefused( + "native keyboard focus does not contain the resolved target" + ) + self._armed = lease + + def deliver( + self, payload: dict[str, Any], expected_frame_sha256: str + ) -> ActionDeliveryReceipt: + lease, self._armed = self._armed, None + if lease is None: + raise StructuralResolutionRefused( + "native keyboard input has no armed lease" + ) + operation = keyboard_operation(payload) + self._before_input() + try: + response = self._post( + "/keyboard/input", + { + "lease_id": lease["lease_id"], + "expected_frame_sha256": expected_frame_sha256, + "input": payload, + }, + ) + data = response.json() + except Exception as exc: + raise ActionDeliveryUncertain( + operation=operation, native=False, cause_type=type(exc).__name__ + ) from exc + if response.status_code == 409 and isinstance(data, dict): + required = { + "status", + "reason", + "lease_id", + "operation", + "no_keyboard_input_delivered", + } + valid = ( + set(data) in (required, required | {"frame_change"}) + and data["status"] == "refused" + and data["lease_id"] == lease["lease_id"] + and data["operation"] == operation + and data["no_keyboard_input_delivered"] is True + and isinstance(data["reason"], str) + and data["reason"] + in { + "expired", + "unverified_frame", + "stale_context", + "stale_focus", + "stale_frame", + } + ) + if valid: + change = data.get("frame_change") + if ( + data["reason"] == "stale_frame" + and isinstance(change, dict) + and set(change) + == {"changed_pixel_count", "changed_bbox", "frame_size"} + ): + try: + count = change["changed_pixel_count"] + if isinstance(count, bool) or not isinstance(count, int): + raise ValueError("invalid changed pixel count") + bbox, size = change["changed_bbox"], change["frame_size"] + if ( + not isinstance(bbox, list) + or len(bbox) != 4 + or not isinstance(size, list) + or len(size) != 2 + or any( + isinstance(v, bool) or not isinstance(v, int) + for v in [*bbox, *size] + ) + or size + != list( + struct.unpack( + ">II", base64.b64decode(lease["frame_png"])[16:24] + ) + ) + or count > bbox[2] * bbox[3] + ): + raise ValueError("invalid native frame-change evidence") + refused = KeyboardFrameChangedBeforeInput( + operation=operation, + changed_pixel_count=count, + changed_bbox=tuple(bbox), + frame_size=tuple(size), + lease_sha256=hashlib.sha256( + lease["lease_id"].encode() + ).hexdigest(), + target_fingerprint=lease["target"]["fingerprint"], + ) + except (KeyError, TypeError, ValueError): + pass + else: + raise refused + raise StructuralResolutionRefused( + "native keyboard lease refused before input: " + data["reason"] + ) + if ( + response.status_code == 200 + and isinstance(data, dict) + and set(data) == {"status", "lease_id", "receipt"} + and data["status"] == "ok" + and data["lease_id"] == lease["lease_id"] + ): + try: + receipt = ActionDeliveryReceipt.model_validate(data["receipt"]) + if ( + receipt.operation != operation + or receipt.native + or receipt.outcome_verified + or receipt.target_fingerprint != lease["target"]["fingerprint"] + ): + raise ValueError("mismatched actual keyboard receipt") + return receipt + except (TypeError, ValueError): + pass + raise ActionDeliveryUncertain( + operation=operation, + native=False, + cause_type="KeyboardLeaseAcknowledgementInvalid", + ) diff --git a/packages/flow/openadapt_flow/compiler/compile.py b/packages/flow/openadapt_flow/compiler/compile.py index 4ddef86b01..9d7833b349 100644 --- a/packages/flow/openadapt_flow/compiler/compile.py +++ b/packages/flow/openadapt_flow/compiler/compile.py @@ -3232,6 +3232,16 @@ def cached_lines(i: int, suffix: str, png: bytes) -> list[OcrLine]: if event.get("closes_surface") is True: stamped.closes_surface = True + from openadapt_flow.compiler.native_focus import anchor_native_keyboard + + pending = anchor_native_keyboard( + pending, + bundle=bundle, + meta_identifier_region=meta_identifier_region, + reference_date=reference_date, + cached_lines=cached_lines, + ) + # Native HTML evidence binds the whole focus-only CLICK + TYPE + Enter # gesture. Replaying the popup-opening click separately would leave it open. absorbed_step_aliases: dict[str, str] = {} diff --git a/packages/flow/openadapt_flow/compiler/native_focus.py b/packages/flow/openadapt_flow/compiler/native_focus.py new file mode 100644 index 0000000000..2ae9a04217 --- /dev/null +++ b/packages/flow/openadapt_flow/compiler/native_focus.py @@ -0,0 +1,130 @@ +"""Compile native keyboard anchors from the event's observed focused target. + +No previous click is inferred. Missing focus evidence leaves the action +unanchored; malformed native evidence refuses compilation. Identity is armed +only by the same record-context rules and marked crop used for pointer steps. +""" + +from __future__ import annotations + +from datetime import date +from pathlib import Path +from typing import Any, Callable + +from openadapt_flow import sealed_set +from openadapt_flow.ir import Anchor, Region +from openadapt_flow.native_focus import NativeFocusTarget +from openadapt_flow.runtime.identity import ( + band_region, + context_from_lines, + identifier_text_from_lines, +) +from openadapt_flow.vision import imgops + + +def anchor_native_keyboard( + pending: list[Any], + *, + bundle: Path, + meta_identifier_region: Region | None, + reference_date: date | None, + cached_lines: Callable[..., Any], +) -> list[Any]: + from openadapt_flow.compiler.compile import ( + MIN_OCR_CONFIDENCE, + _crop_png, + _discriminative_crop_region, + _emit_identifier_crop, + _identity_unarmed_reason, + _marked_identifier_region, + ) + + result = [] + for step, before_png, after_png, event in pending: + focus = event.get("focus_before") + raw = focus.get("native_focus") if isinstance(focus, dict) else None + if event.get("kind") not in {"type", "key", "hotkey"} or raw is None: + result.append((step, before_png, after_png, event)) + continue + try: + target = NativeFocusTarget.model_validate(raw) + except ValueError as exc: + raise ValueError( + f"invalid native focus evidence for {step.id}: {exc}" + ) from exc + if before_png is None: + raise ValueError(f"native focus event {step.id} has no before frame") + frame = imgops.decode_bgr(before_png) + if frame is None: + raise ValueError( + f"native focus event {step.id} has an invalid before frame" + ) + size = (int(frame.shape[1]), int(frame.shape[0])) + x, y, width, height = target.region + if x < 0 or y < 0 or x + width > size[0] or y + height > size[1]: + raise ValueError( + f"native focus rectangle for {step.id} is outside its before frame" + ) + point = target.point + crop_region = _discriminative_crop_region(frame, point) + template = f"templates/{step.id}.png" + sealed_set.write_bytes(bundle / template, _crop_png(before_png, crop_region)) + lines = cached_lines(int(event["i"]), "before", before_png) + band = band_region(point, crop_region[3], size) + context = context_from_lines( + lines, + exclude_region=crop_region, + band=band, + point=point, + min_confidence=MIN_OCR_CONFIDENCE, + reference_date=reference_date, + ) + marked = _marked_identifier_region( + event.get("identifier_region"), source=f"event {event['i']}" + ) + identifier, region, missing = _emit_identifier_crop( + bundle, + step.id, + before_png, + frame_size=size, + marked_region=marked if marked is not None else meta_identifier_region, + context_text=context, + structured_identity=None, + frame_lines=lines, + crop_region=crop_region, + click=point, + reference_date=reference_date, + ) + if region is not None: + marked_context = identifier_text_from_lines( + lines, + region=region, + min_confidence=MIN_OCR_CONFIDENCE, + reference_date=reference_date, + ) + if marked_context is not None: + context = marked_context + armed = context is not None or identifier is not None + anchor = Anchor( + template=template, + region=crop_region, + click_point=point, + structural=target.structural_locator(), + context_text=context, + identifier_crop=identifier, + identifier_region=region, + ) + step = step.model_copy( + update={ + "anchor": anchor, + "identity_armed": armed, + "identity_unarmed_reason": None + if armed + else _identity_unarmed_reason( + lines, band=band, exclude_region=crop_region + ), + "identifier_crop_missing_reason": missing, + } + ) + result.append((step, before_png, after_png, event)) + return result diff --git a/packages/flow/openadapt_flow/input_evidence.py b/packages/flow/openadapt_flow/input_evidence.py new file mode 100644 index 0000000000..16484bfe14 --- /dev/null +++ b/packages/flow/openadapt_flow/input_evidence.py @@ -0,0 +1,51 @@ +"""Bounded pre-input refusal evidence retained across report/resume paths.""" + +from __future__ import annotations + +from typing import Literal, Optional + +from pydantic import BaseModel, Field, model_serializer, model_validator + +Region = tuple[int, int, int, int] + + +class FreshActuationEvent(BaseModel): + """PHI-free evidence for one pre-input actuation-frame mismatch. + + Step retries require no earlier input edge. Keyboard-phase retries require + an authenticated consumed lease proving no keyboard input crossed; an + earlier focusing click is never repeated. Only geometry and hashes remain. + """ + + attempt: int = Field(ge=1) + operation: str = Field(min_length=1, max_length=64, pattern=r"^[a-z][a-z0-9_]*$") + changed_pixel_count: int = Field(ge=1) + changed_bbox: Region + frame_size: tuple[int, int] + target_intersection: Optional[bool] = None + identity_intersection: Optional[bool] = None + retried: bool + phase: Literal["step", "keyboard"] = "step" + lease_sha256: Optional[str] = Field(default=None, pattern=r"^[a-f0-9]{64}$") + + @model_serializer(mode="wrap") + def _legacy_shape(self, handler): + result = handler(self) + if self.phase == "step": + result.pop("phase", None) + result.pop("lease_sha256", None) + return result + + @model_validator(mode="after") + def _valid_geometry(self) -> "FreshActuationEvent": + if (self.phase == "keyboard") != (self.lease_sha256 is not None): + raise ValueError("keyboard retry evidence requires its consumed lease hash") + frame_width, frame_height = self.frame_size + x, y, width, height = self.changed_bbox + if frame_width <= 0 or frame_height <= 0: + raise ValueError("fresh-actuation frame size must be positive") + if x < 0 or y < 0 or width <= 0 or height <= 0: + raise ValueError("fresh-actuation bounding box must be positive") + if x + width > frame_width or y + height > frame_height: + raise ValueError("fresh-actuation bounding box exceeds the frame") + return self diff --git a/packages/flow/openadapt_flow/ir.py b/packages/flow/openadapt_flow/ir.py index b016e03830..f720a6b0a2 100644 --- a/packages/flow/openadapt_flow/ir.py +++ b/packages/flow/openadapt_flow/ir.py @@ -43,6 +43,7 @@ ) from openadapt_flow.approval_mode.model import ApprovalModeItemEvidence +from openadapt_flow.input_evidence import FreshActuationEvent as FreshActuationEvent from openadapt_flow.qualification_faults import FaultMutationReceipt from openadapt_flow.records.schema import ( FieldRead, @@ -4208,37 +4209,6 @@ class ActionDeliveryUncertainty(BaseModel): resolved_by_contract: bool = False -class FreshActuationEvent(BaseModel): - """PHI-free evidence for one pre-input actuation-frame mismatch. - - The runtime records only the number and geometry of changed pixels. It - does not retain the rejected frame or its pixel values. ``retried`` is - true only when no earlier input edge crossed for this workflow step and a - bounded reacquisition remained available. - """ - - attempt: int = Field(ge=1) - operation: str = Field(min_length=1, max_length=64, pattern=r"^[a-z][a-z0-9_]*$") - changed_pixel_count: int = Field(ge=1) - changed_bbox: Region - frame_size: tuple[int, int] - target_intersection: Optional[bool] = None - identity_intersection: Optional[bool] = None - retried: bool - - @model_validator(mode="after") - def _valid_geometry(self) -> "FreshActuationEvent": - frame_width, frame_height = self.frame_size - x, y, width, height = self.changed_bbox - if frame_width <= 0 or frame_height <= 0: - raise ValueError("fresh-actuation frame size must be positive") - if x < 0 or y < 0 or width <= 0 or height <= 0: - raise ValueError("fresh-actuation bounding box must be positive") - if x + width > frame_width or y + height > frame_height: - raise ValueError("fresh-actuation bounding box exceeds the frame") - return self - - class IdentitySignalEvidence(BaseModel): """PHI-free audit evidence for one qualified identity signal.""" diff --git a/packages/flow/openadapt_flow/native_focus.py b/packages/flow/openadapt_flow/native_focus.py new file mode 100644 index 0000000000..cc3b943e9c --- /dev/null +++ b/packages/flow/openadapt_flow/native_focus.py @@ -0,0 +1,99 @@ +"""Bounded passive native focus evidence shared by capture and compilation. + +The observed runtime fingerprint proves teach-time uniqueness only. A compiled +anchor keeps the stable locator; replay must obtain a new guarded live lease. +""" + +from __future__ import annotations + +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, StrictInt, model_validator + +from openadapt_flow.ir import StructuralLocator + + +class NativeFocusLocator(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + automation_id: str | None = Field(default=None, min_length=1, max_length=512) + role: str | None = Field(default=None, min_length=1, max_length=64) + name: str | None = Field(default=None, min_length=1, max_length=512) + window_name: str | None = Field(default=None, min_length=1, max_length=512) + + @model_validator(mode="after") + def exact_locator(self) -> "NativeFocusLocator": + if not self.automation_id and not (self.role and self.name): + raise ValueError("native focus needs AutomationId or exact role/name") + return self + + +class NativeFocusTarget(BaseModel): + model_config = ConfigDict(extra="forbid") + schema_version: Literal["openadapt.native-focus/v1"] = "openadapt.native-focus/v1" + locator: NativeFocusLocator + point: tuple[StrictInt, StrictInt] + region: tuple[StrictInt, StrictInt, StrictInt, StrictInt] + target_fingerprint: str = Field(pattern=r"^[a-f0-9]{64}$") + candidate_count: Literal[1] + complete: Literal[True] + + @model_validator(mode="before") + @classmethod + def exact_observation(cls, data: Any) -> Any: + if isinstance(data, dict) and ( + not isinstance(data.get("candidate_count"), int) + or isinstance(data.get("candidate_count"), bool) + or data.get("candidate_count") != 1 + or data.get("complete") is not True + ): + raise ValueError("native focus must be one complete, unique observation") + return data + + @model_validator(mode="after") + def bounded_geometry(self) -> "NativeFocusTarget": + x, y, width, height = self.region + if any(abs(value) > 32768 for value in (*self.point, *self.region)): + raise ValueError("native focus geometry is out of bounds") + if ( + width <= 0 + or height <= 0 + or not (x <= self.point[0] < x + width and y <= self.point[1] < y + height) + ): + raise ValueError("native focus point must be within its positive rectangle") + return self + + def structural_locator(self) -> StructuralLocator: + return StructuralLocator.model_validate(self.locator.model_dump()) + + +def from_native_candidate(candidate: Any) -> NativeFocusTarget | None: + if not isinstance(candidate, dict): + return None + bounds = candidate.get("bounds") + if ( + not isinstance(bounds, list) + or len(bounds) != 4 + or any(isinstance(v, bool) or not isinstance(v, int) for v in bounds) + ): + return None + try: + return NativeFocusTarget.model_validate( + { + "locator": { + key: candidate.get(key) + for key in ("automation_id", "role", "name", "window_name") + }, + "point": candidate.get("point"), + "region": [ + bounds[0], + bounds[1], + bounds[2] - bounds[0], + bounds[3] - bounds[1], + ], + "target_fingerprint": candidate.get("fingerprint"), + "candidate_count": 1, + "complete": True, + } + ) + except ValueError: + return None diff --git a/packages/flow/openadapt_flow/recorder.py b/packages/flow/openadapt_flow/recorder.py index ecf2ac1398..c67c0806d6 100644 --- a/packages/flow/openadapt_flow/recorder.py +++ b/packages/flow/openadapt_flow/recorder.py @@ -49,6 +49,7 @@ from __future__ import annotations +import copy import io import json import time @@ -890,7 +891,7 @@ def _record_action(self, event: dict[str, Any], act: Callable[[], None]) -> None structural_before = self._structural_state() # Who has the focus before and after a key press, for a key that moves # the focus and changes nothing visible (the ``focus_on`` - # postcondition). Key events only. + # postcondition), and the receiving target of native text input. focus_before = self._focus_identity(event) # Structured identity of the clicked target (DOM / a11y text), when # the backend exposes it: captured on the BEFORE frame, before the @@ -1014,13 +1015,12 @@ def _record_action(self, event: dict[str, Any], act: Callable[[], None]) -> None quiet_before=quiet_before, ) if focus_before is not None: + # Preserve the actual input target even when the input navigates + # or closes the window and its after-focus is no longer readable. + event = {**event, "focus_before": focus_before} focus_after = self._focus_identity(event) if focus_after is not None: - event = { - **event, - "focus_before": focus_before, - "focus_after": focus_after, - } + event = {**event, "focus_after": focus_after} opened = self._claim_new_pages(self._i) if opened: event = {**event, "opens": opened} @@ -1363,18 +1363,18 @@ def _identity_census_at(self, x: int, y: int) -> Optional[dict[str, Any]]: return census if isinstance(census, dict) else None def _focus_identity(self, event: dict[str, Any]) -> Optional[dict[str, Any]]: - """The focused element's identity around a key event, if readable.""" + """The focused element before/after keyboard input, if readable.""" - if event.get("kind") not in ("key", "hotkey"): + if event.get("kind") not in ("type", "key", "hotkey"): return None reader = getattr(self._backend, "focus_identity", None) if not callable(reader): return None try: value = reader() + return copy.deepcopy(value) if isinstance(value, dict) else None except Exception: return None - return value if isinstance(value, dict) else None def _structural_state(self) -> dict[str, Any]: """Structural observations the backend can provide right now. diff --git a/packages/flow/openadapt_flow/runtime/keyboard_delivery.py b/packages/flow/openadapt_flow/runtime/keyboard_delivery.py new file mode 100644 index 0000000000..c7b8fc74e4 --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/keyboard_delivery.py @@ -0,0 +1,226 @@ +"""Bounded keyboard-only retries following a typed zero-input lease refusal. + +The caller performs every target, identity, context and authorization check +again. Unknown failures and partial delivery never enter this retry path. +""" + +from __future__ import annotations + +import hashlib +from pathlib import Path +from typing import TYPE_CHECKING, Callable, Mapping, TypeVar + +from openadapt_flow.backend import ( + KeyboardFrameChangedBeforeInput, + NativeKeyboardLeaseBackend, + StructuralResolutionRefused, +) +from openadapt_flow.ir import ( + ActionDeliveryReceipt, + ActionKind, + FreshActuationEvent, + Resolution, + Step, + StepResult, + Workflow, +) +from openadapt_flow.run_gate import is_consequential +from openadapt_flow.runtime.authorization import RuntimeParamScalar + +if TYPE_CHECKING: + from openadapt_flow.runtime.replayer import Replayer + +T = TypeVar("T") + + +def deliver_with_revalidation( + deliver: Callable[[], T], + revalidate: Callable[[KeyboardFrameChangedBeforeInput], bool], + record: Callable[[KeyboardFrameChangedBeforeInput, bool, int], None], +) -> T: + for attempt in range(1, 4): + try: + return deliver() + except KeyboardFrameChangedBeforeInput as exc: + try: + retry = attempt < 3 and revalidate(exc) + except Exception: + record(exc, False, attempt) + raise + record(exc, retry, attempt) + if not retry: + raise StructuralResolutionRefused( + "native keyboard exact-frame lease changed before input; bounded revalidation exhausted or refused" + ) from exc + raise AssertionError("bounded keyboard delivery loop escaped") + + +def native_keyboard_delivery( + replay: "Replayer", + *, + step: Step, + workflow: Workflow, + params: Mapping[str, RuntimeParamScalar], + bundle_dir: Path, + run_dir: Path, + result: StepResult, + resolution: Resolution | None, + frame: bytes, + baseline: str | None, + call: Callable[[str], ActionDeliveryReceipt], +) -> tuple[ActionDeliveryReceipt, Resolution | None, bytes]: + """Retry only the refused keyboard phase, without a focusing click. + + Reversible transient edits can be re-observed. Effectful, API-bound, + irreversible and otherwise consequential actions have no retry here. + Every replacement frame must prove the same focused runtime element, + record identity and context through the ordinary full revalidation path. + """ + + rejected_resolution, rejected_region = resolution, replay._active_delivery_region + + def revalidate(exc: KeyboardFrameChangedBeforeInput) -> bool: + nonlocal resolution, frame, rejected_resolution, rejected_region + rejected_resolution = replay._active_delivery_resolution + rejected_region = replay._active_delivery_region + if ( + step.anchor is None + or resolution is None + or step.effects + or step.api_binding is not None + or step.risk != "reversible" + or is_consequential(step, workflow) + or not isinstance(replay.backend, NativeKeyboardLeaseBackend) + ): + return False + refusal = replay._fresh_actuation_authorization_refusal(workflow, params, step) + if refusal is not None: + return False + fresh, region, png, error = replay._revalidate_consequential_actuation( + step, + resolution, + None, + frame, + params, + workflow, + bundle_dir, + result, + run_dir=run_dir, + arm_keyboard=True, + ) + if error is not None or fresh is None: + replay._cancel_guarded_keyboard() + return False + if ( + replay.backend.guarded_keyboard_target_fingerprint() + != exc.target_fingerprint + ): + replay._cancel_guarded_keyboard() + return False + if step.action is ActionKind.TYPE and ( + baseline is None or replay._text_value_at(fresh.point) != baseline + ): + replay._cancel_guarded_keyboard() + return False + if region is not None: + fresh = replay._retain_visual_resolution_evidence( + workflow=workflow, + anchor=step.anchor, + resolution=fresh, + matched_region=region, + frame_png=png, + bundle_dir=bundle_dir, + run_dir=run_dir, + allow_target_ocr=False, + ) + resolution, frame = fresh, png + result.resolution = fresh + evidence_step_id = ( + Path(result.before_png).name.removesuffix("_before.png") + if result.before_png + else step.id + ) + result.before_png = replay._save_step_png( + run_dir, evidence_step_id, "before", png + ) + return True + + def deliver() -> ActionDeliveryReceipt: + nonlocal rejected_resolution, rejected_region + rejected_resolution = replay._active_delivery_resolution + rejected_region = replay._active_delivery_region + refusal = replay._delivery_authorization_refusal(workflow, params, step, result) + if refusal is not None: + raise StructuralResolutionRefused(refusal) + replay._require_qualification_environment_current() + return replay._deliver_backend_call( + result, lambda: call(hashlib.sha256(frame).hexdigest()) + ) + + def record( + exc: KeyboardFrameChangedBeforeInput, retried: bool, attempt: int + ) -> None: + result.fresh_actuation_events.append( + replay._fresh_actuation_event( + exc, + step=step, + workflow=workflow, + resolution=rejected_resolution, + matched_region=rejected_region, + retried=retried, + attempt=attempt, + ) + ) + + receipt = deliver_with_revalidation(deliver, revalidate, record) + return receipt, resolution, frame + + +def fresh_actuation_event( + replay: "Replayer", + exc, + *, + step, + workflow, + resolution, + matched_region, + retried: bool, + attempt: int, +) -> FreshActuationEvent: + target_region = matched_region + if target_region is None and step.anchor is not None: + target_region = replay._translate_recorded_region( + step, resolution, step.anchor.region + ) + target_intersection = ( + replay._regions_intersect(exc.changed_bbox, target_region) + if target_region is not None + else None + ) + identity_regions = replay._fresh_actuation_identity_regions( + step, workflow, resolution + ) + identity_intersection = ( + any( + replay._regions_intersect(exc.changed_bbox, region) + for region in identity_regions + ) + if identity_regions + else None + ) + return FreshActuationEvent( + attempt=attempt, + operation=exc.operation, + changed_pixel_count=exc.changed_pixel_count, + changed_bbox=exc.changed_bbox, + frame_size=exc.frame_size, + target_intersection=target_intersection, + identity_intersection=identity_intersection, + retried=retried, + phase="keyboard" + if isinstance(exc, KeyboardFrameChangedBeforeInput) + else "step", + lease_sha256=exc.lease_sha256 + if isinstance(exc, KeyboardFrameChangedBeforeInput) + else None, + ) diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 6993034d1b..56ae82f1eb 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -83,6 +83,7 @@ GuardedKeyboardActionBackend, GuardedRemotePointerActionBackend, GuardedSelectOptionBackend, + NativeKeyboardLeaseBackend, NativeSelectBackend, PreparedPointerActuationBackend, RemoteActuationBackend, @@ -179,6 +180,7 @@ from openadapt_flow.runtime import identity as identity_mod from openadapt_flow.runtime import identity_census as census_mod from openadapt_flow.runtime import identity_looks as looks_mod +from openadapt_flow.runtime import keyboard_delivery as keyboard_delivery_mod from openadapt_flow.runtime.authorization import ( GovernedRunAuthorization, RuntimeParamScalar, @@ -11432,6 +11434,14 @@ def _unbound_submit_refusal( f"{step.submit_binding_unbound_reason} — refusing to act; run aborted" ) + def _native_keyboard_lease_required(self, step: Step) -> bool: + return bool( + step.action in (ActionKind.TYPE, ActionKind.KEY, ActionKind.HOTKEY) + and step.anchor is not None + and isinstance(self.backend, NativeKeyboardLeaseBackend) + and self.backend.native_keyboard_lease_available() + ) + def _step_needs_consequential_revalidation( self, step: Step, workflow: Workflow ) -> bool: @@ -11466,6 +11476,8 @@ def _step_needs_consequential_revalidation( # fresh remote lease for those actions only during the fault run, # so ordinary demo replay keeps its reversible fast path. return True + if self._native_keyboard_lease_required(step): + return True if self._step_requires_remote_guarded_actuation(step, workflow): return True return self._step_is_consequential( @@ -11503,7 +11515,7 @@ def _requires_atomic_identity_keyboard( ) -> bool: """Whether keyboard delivery must stay bound to the verified focus.""" - return ( + return self._native_keyboard_lease_required(step) or ( step.action in ( ActionKind.KEY, @@ -11827,7 +11839,8 @@ def _revalidate_consequential_actuation( if isinstance(self.backend, RemoteActuationBackend) else ( cast( - GuardedKeyboardActionBackend, self.backend + GuardedKeyboardActionBackend, + self.backend, ).guarded_keyboard_frame() if ( guarded_keyboard_backend @@ -12424,36 +12437,15 @@ def _fresh_actuation_event( retried: bool, attempt: int, ) -> FreshActuationEvent: - target_region = matched_region - if target_region is None and step.anchor is not None: - target_region = self._translate_recorded_region( - step, resolution, step.anchor.region - ) - target_intersection = ( - self._regions_intersect(exc.changed_bbox, target_region) - if target_region is not None - else None - ) - identity_regions = self._fresh_actuation_identity_regions( - step, workflow, resolution - ) - identity_intersection = ( - any( - self._regions_intersect(exc.changed_bbox, region) - for region in identity_regions - ) - if identity_regions - else None - ) - return FreshActuationEvent( - attempt=attempt, - operation=exc.operation, - changed_pixel_count=exc.changed_pixel_count, - changed_bbox=exc.changed_bbox, - frame_size=exc.frame_size, - target_intersection=target_intersection, - identity_intersection=identity_intersection, + return keyboard_delivery_mod.fresh_actuation_event( + self, + exc, + step=step, + workflow=workflow, + resolution=resolution, + matched_region=matched_region, retried=retried, + attempt=attempt, ) def _active_program_frame_refusal( @@ -14406,20 +14398,22 @@ def _act_without_dialog( and isinstance(self.backend, GuardedKeyboardActionBackend) ) if guarded_type: - refusal = self._delivery_authorization_refusal( - workflow, params, step, result - ) - if refusal is not None: - return refusal - self._require_qualification_environment_current() - result.delivery_receipt = self._deliver_backend_call( - result, - lambda: cast( - GuardedKeyboardActionBackend, self.backend - ).type_text_guarded( - text, - expected_frame_sha256=hashlib.sha256(before_png).hexdigest(), - ), + result.delivery_receipt, resolution, before_png = ( + keyboard_delivery_mod.native_keyboard_delivery( + self, + step=step, + workflow=workflow, + params=params, + bundle_dir=bundle_dir, + run_dir=run_dir, + result=result, + resolution=resolution, + frame=before_png, + baseline=baseline_field_value, + call=lambda digest: cast( + GuardedKeyboardActionBackend, self.backend + ).type_text_guarded(text, expected_frame_sha256=digest), + ) ) result.actuation = "guarded_keyboard" elif requires_atomic_keyboard and not isinstance( @@ -14484,20 +14478,22 @@ def _act_without_dialog( and isinstance(self.backend, GuardedKeyboardActionBackend) ) if guarded_key: - refusal = self._delivery_authorization_refusal( - workflow, params, step, result - ) - if refusal is not None: - return refusal - self._require_qualification_environment_current() - result.delivery_receipt = self._deliver_backend_call( - result, - lambda: cast( - GuardedKeyboardActionBackend, self.backend - ).press_guarded( - key, - expected_frame_sha256=hashlib.sha256(before_png).hexdigest(), - ), + result.delivery_receipt, resolution, before_png = ( + keyboard_delivery_mod.native_keyboard_delivery( + self, + step=step, + workflow=workflow, + params=params, + bundle_dir=bundle_dir, + run_dir=run_dir, + result=result, + resolution=resolution, + frame=before_png, + baseline=None, + call=lambda digest: cast( + GuardedKeyboardActionBackend, self.backend + ).press_guarded(key, expected_frame_sha256=digest), + ) ) result.actuation = "guarded_keyboard" elif requires_atomic_keyboard and not isinstance( diff --git a/packages/flow/scripts/desktop/winrm_lab.py b/packages/flow/scripts/desktop/winrm_lab.py index 0e337c874e..aff8fff00f 100644 --- a/packages/flow/scripts/desktop/winrm_lab.py +++ b/packages/flow/scripts/desktop/winrm_lab.py @@ -529,7 +529,9 @@ def launch_agent( from openadapt_flow.backends.parallels_vm import ( # noqa: PLC0415 AgentEndpoint, ) - from openadapt_flow.backends.win_agent import server as agent_server # noqa: PLC0415 + from openadapt_flow.backends.win_agent import ( + server as agent_server, # noqa: PLC0415 + ) from openadapt_flow.backends.win_agent.tls import ( # noqa: PLC0415 generate_self_signed_cert, ) @@ -549,6 +551,8 @@ def launch_agent( Path(server_path or agent_server.__file__), rf"{guest_dir}\win_agent_server.py", ) + keyboard_helper = Path(agent_server.__file__).with_name("keyboard_lease.py") + self.push_file(keyboard_helper, rf"{guest_dir}\win_agent_keyboard_lease.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/e2e/test_native_keyboard_lease.py b/packages/flow/tests/e2e/test_native_keyboard_lease.py new file mode 100644 index 0000000000..8e4d9a04d8 --- /dev/null +++ b/packages/flow/tests/e2e/test_native_keyboard_lease.py @@ -0,0 +1,612 @@ +"""Real, authenticated Windows keyboard leases over a synthetic WinForms record. + +No qualification driver or fabricated input receipt participates. The field's +UIA value and the app's independent SQLite record decide what changed. The +transport observer delegates every request unchanged; it can discard one real +acknowledgement to test the uncertainty boundary. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import os +import platform +import subprocess +import time +from pathlib import Path +from typing import Any + +import pytest + +from openadapt_flow.backend import ( + ActionDeliveryUncertain, + KeyboardFrameChangedBeforeInput, + StructuralResolutionRefused, +) +from openadapt_flow.ir import ActionDeliveryReceipt, StructuralLocator +from tests.e2e.test_windows_hosted_replay import RUN_E2E, _Host, _points + +pytestmark = [ + pytest.mark.skipif( + not RUN_E2E, + reason="opt-in hosted Windows e2e; set OAFLOW_WINDOWS_HOSTED_E2E=1 on Windows", + ), + pytest.mark.timeout(300), +] + +EVIDENCE_ENV = "OAFLOW_NATIVE_KEYBOARD_LEASE_EVIDENCE" +REPOSITORY = Path(__file__).resolve().parents[4] + +# This hook belongs only to the copied synthetic fixture. It recreates the +# focused textbox in the same form, retaining its visible and stable locator +# attributes while the old native handle remains alive but detached. An old +# HWND therefore cannot be immediately reused for the replacement control. +REPLACE_HOOK = r""" +$retiredLeaseControls = New-Object System.Collections.ArrayList +$leaseTimer = New-Object System.Windows.Forms.Timer +$leaseTimer.Interval = 40 +$leaseTimer.Add_Tick({ + $commandPath = Join-Path $PSScriptRoot "lease-command" + if (-not (Test-Path $commandPath)) { return } + $command = [IO.File]::ReadAllText($commandPath) + Remove-Item $commandPath + if ($command -ne "replace-note") { throw "Unknown lease fixture command" } + $old = $script:noteBox + $oldHandle = $old.Handle.ToInt64() + $new = New-Object System.Windows.Forms.TextBox + $new.Name = $old.Name + $new.AccessibleName = $old.AccessibleName + $new.Multiline = $old.Multiline + $new.Location = $old.Location + $new.Size = $old.Size + $new.Font = $old.Font + $new.BackColor = $old.BackColor + $new.ForeColor = $old.ForeColor + $new.TabIndex = $old.TabIndex + $new.Text = $old.Text + $form.Controls.Add($new) + $newHandle = $new.Handle.ToInt64() + $old.Name = "retiredLeaseTextbox" + $old.AccessibleName = "retiredLeaseTextbox" + $form.Controls.Remove($old) + $old.Hide() + [void]$script:retiredLeaseControls.Add($old) + $script:noteBox = $new + $new.BringToFront() + [void]$new.Focus() + $new.SelectionStart = $new.TextLength + $ack = @{ old_handle=$oldHandle; new_handle=$newHandle; + form_handle=$form.Handle.ToInt64(); name=$new.Name; + value=$new.Text; focused=$new.Focused } + $ack | ConvertTo-Json | Set-Content (Join-Path $PSScriptRoot "lease-replaced.json") +}) +$leaseTimer.Start() +""" + + +def _sha(value: bytes) -> str: + return hashlib.sha256(value).hexdigest() + + +def _redacted(value: Any) -> Any: + """Keep raw technical envelopes, excluding reusable lease tokens/frames.""" + result = copy.deepcopy(value) + if isinstance(result, dict): + token = result.pop("lease_id", None) + if isinstance(token, str): + result["lease_id_sha256"] = _sha(token.encode()) + frame = result.pop("frame_png", None) + if isinstance(frame, str): + result["frame_png_retained_separately"] = True + return result + + +class _Transport: + def __init__(self, backend, monkeypatch, evidence: dict[str, Any]) -> None: + original = backend._session.post + self.last_input: dict[str, Any] | None = None + self.drop_next_ack = False + self.inputs = 0 + self.events = evidence["transport"] = [] + + def post(url, **kwargs): + response = original(url, **kwargs) + path = url.removeprefix(backend.server_url) + if path in {"/keyboard/lease", "/keyboard/input"}: + request = kwargs["json"] + event = { + "path": path, + "request": _redacted(request), + "http_status": response.status_code, + "response": _redacted(response.json()), + } + self.events.append(event) + if path == "/keyboard/input": + self.inputs += 1 + self.last_input = copy.deepcopy(request) + if self.drop_next_ack and response.status_code == 200: + from requests import ConnectionError + + self.drop_next_ack = False + event["injected_fault"] = "discard_actual_acknowledgement" + raise ConnectionError("synthetic acknowledgement loss") + return response + + monkeypatch.setattr(backend._session, "post", post) + + +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) + return result["text"] + + +def _values(backend) -> dict[str, str]: + return {aid: _read(backend, aid) for aid in ("searchBox", "noteBox")} + + +def _wait_value(backend, automation_id: str, expected: str) -> None: + deadline = time.monotonic() + 15 + while _read(backend, automation_id) != expected: + assert ( + time.monotonic() < deadline + ), f"UIA {automation_id} did not reach {expected!r}" + time.sleep(0.05) + + +def _validate(backend, host, baseline, header, context, expected) -> dict[str, Any]: + """Resolve anew and independently validate all bindings, including retries.""" + handle = backend.locate_structural(StructuralLocator(automation_id="noteBox")) + assert handle is not None and handle.candidate_count == 1 + observation = backend.focus_identity() + assert observation is not None + target = observation["native_focus"] + assert target["locator"]["automation_id"] == "noteBox" + assert target["target_fingerprint"] == handle.target_fingerprint + assert tuple(target["point"]) == tuple(handle.point) + assert _read(backend, "patientHeader") == header + assert backend._guard_context() == context + assert _values(backend) == expected + assert host.rows() == baseline + return { + "target": target, + "context": context, + "record_header": header, + "values": expected, + "rows_unchanged": True, + } + + +def _lease(backend, host, root, name, baseline, header, context, expected): + before = _validate(backend, host, baseline, header, context, expected) + png = backend.guarded_keyboard_frame() + (root / f"{name}.png").write_bytes(png) + after = _validate(backend, host, baseline, header, context, expected) + assert before["target"] == after["target"] + backend.arm_guarded_keyboard(*after["target"]["point"]) + return _sha(png), after + + +def _deliver( + backend, + host, + root, + evidence, + name, + action, + argument, + baseline, + header, + context, + before, + after, +): + """Only typed, zero-input stale frames can reacquire a complete lease.""" + attempts = [] + case = {"case": name, "attempts": attempts} + evidence["cases"].append(case) + for attempt in range(6): + digest, validation = _lease( + backend, host, root, f"{name}-{attempt}", baseline, header, context, before + ) + row = {"fresh_validation": validation, "frame_sha256": digest} + attempts.append(row) + try: + receipt = ( + backend.type_text_guarded(argument, expected_frame_sha256=digest) + if action == "type" + else backend.press_guarded(argument, expected_frame_sha256=digest) + ) + except KeyboardFrameChangedBeforeInput as exc: + row["zero_keyboard_input_refusal"] = { + "type": type(exc).__name__, + "operation": exc.operation, + "changed_pixel_count": exc.changed_pixel_count, + "changed_bbox": exc.changed_bbox, + "frame_size": exc.frame_size, + "lease_sha256": exc.lease_sha256, + "target_fingerprint": exc.target_fingerprint, + } + # No focusing click or keyboard preparation is repeated. The next + # attempt rechecks real focus, target, record, context and DB, then + # obtains and fully revalidates an entirely new leased frame. + assert _values(backend) == before and host.rows() == baseline + continue + assert receipt.status == "delivered" and receipt.native is False + assert receipt.outcome_verified is False + assert receipt.target_fingerprint == validation["target"]["target_fingerprint"] + row["actual_receipt"] = receipt.model_dump(mode="json") + _wait_value(backend, "noteBox", after["noteBox"]) + assert _values(backend) == after and host.rows() == baseline + case["after"] = {"values": _values(backend), "rows": host.rows()} + return receipt + raise AssertionError(f"{name}: exact desktop frame changed on all six fresh leases") + + +def _refuse( + backend, + host, + transport, + evidence, + name, + digest, + expected, + baseline, + reason, + *, + typed_frame=False, +): + case: dict[str, Any] = {"case": name, "before": expected} + evidence["cases"].append(case) + previous = transport.inputs + error_type = ( + KeyboardFrameChangedBeforeInput if typed_frame else StructuralResolutionRefused + ) + with pytest.raises(error_type) as error: + backend.type_text_guarded("UNEXPECTED INPUT", expected_frame_sha256=digest) + assert transport.inputs == previous + 1 + raw = transport.events[-1] + assert raw["response"]["reason"] == reason + assert raw["response"]["no_keyboard_input_delivered"] is True + assert _values(backend) == expected and host.rows() == baseline + case.update( + { + "exception_type": type(error.value).__name__, + "refusal": raw, + "after": {"values": _values(backend), "rows": host.rows()}, + } + ) + + +def test_native_keyboard_lease_actual_delivery_and_refusal(tmp_path, monkeypatch): + evidence: dict[str, Any] = { + "schema": "openadapt.native-keyboard-lease-proof/v1", + "platform": platform.platform(), + "cases": [], + "head": subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=REPOSITORY, text=True + ).strip(), + "tree": subprocess.check_output( + ["git", "rev-parse", "HEAD^{tree}"], cwd=REPOSITORY, text=True + ).strip(), + "expected_source": os.environ.get("EXPECTED_SOURCE_SHA"), + "run_id": os.environ.get("GITHUB_RUN_ID"), + "run_attempt": os.environ.get("GITHUB_RUN_ATTEMPT"), + } + host = _Host(tmp_path) + app = tmp_path / "patient_notes.ps1" + source = app.read_text() + assert source.count("[void]$form.ShowDialog()") == 1 + app.write_text( + source.replace( + "[void]$form.ShowDialog()", REPLACE_HOOK + "\n[void]$form.ShowDialog()" + ) + ) + evidence["fixture_sha256"] = _sha(app.read_bytes()) + try: + backend = host.start_agent() + capabilities = backend.agent_capabilities() + evidence["capabilities"] = sorted(capabilities) + assert { + "native_focus_v1", + "native_keyboard_lease_v1", + "context_environment_v1", + } <= capabilities + transport = _Transport(backend, monkeypatch, evidence) + host.launch_app() + points = _points(backend) + baseline = evidence["rows_before"] = host.rows() + target = next(row for row in baseline if row["id"] == 1) + header = f"Patient: {target['first']} {target['last']} ({target['dob']})" + backend.click(*points["searchBox"]) + backend.type_text(target["first"]) + backend.press("enter") + _wait_value(backend, "patientHeader", header) + backend.click(*points["noteBox"]) + context = backend._guard_context() + before = {"searchBox": target["first"], "noteBox": ""} + typed = {**before, "noteBox": "lease proof"} + _deliver( + backend, + host, + tmp_path, + evidence, + "type", + "type", + "lease proof", + baseline, + header, + context, + before, + typed, + ) + # Keep the exact real request in memory to test a consumed token later. + replay = copy.deepcopy(transport.last_input) + assert replay is not None + newline = {**typed, "noteBox": "lease proof\r\n"} + _deliver( + backend, + host, + tmp_path, + evidence, + "key", + "press", + "enter", + baseline, + header, + context, + typed, + newline, + ) + backend.press("ctrl+a") # explicit synthetic setup, not a leased retry + _deliver( + backend, + host, + tmp_path, + evidence, + "hotkey", + "press", + "ctrl+x", + baseline, + header, + context, + newline, + before, + ) + + # A visible value change after observation keeps the same native focus. + digest, observed = _lease( + backend, host, tmp_path, "planted-frame", baseline, header, context, before + ) + backend.type_text("external change") + changed = {**before, "noteBox": "external change"} + _wait_value(backend, "noteBox", changed["noteBox"]) + deadline = time.monotonic() + 5 + while True: + planted_png = backend.screenshot() + if _sha(planted_png) != digest: + (tmp_path / "planted-frame-after.png").write_bytes(planted_png) + break + assert ( + time.monotonic() < deadline + ), "planted input never changed visible pixels" + time.sleep(0.05) + assert ( + backend.focus_identity()["native_focus"]["target_fingerprint"] + == observed["target"]["target_fingerprint"] + ) + _refuse( + backend, + host, + transport, + evidence, + "stale_frame", + digest, + changed, + baseline, + "stale_frame", + typed_frame=True, + ) + # Reacquiring after this typed refusal performs the entire validation + # sequence; the new input is visibly appended exactly once. + retry_after = {**changed, "noteBox": "external change verified"} + _deliver( + backend, + host, + tmp_path, + evidence, + "fresh_after_zero_input", + "type", + " verified", + baseline, + header, + context, + changed, + retry_after, + ) + + digest, _ = _lease( + backend, + host, + tmp_path, + "planted-focus", + baseline, + header, + context, + retry_after, + ) + backend.click(*points["searchBox"]) + _refuse( + backend, + host, + transport, + evidence, + "stale_focus", + digest, + retry_after, + baseline, + "stale_focus", + ) + backend.click(*points["noteBox"]) + + digest, observed = _lease( + backend, + host, + tmp_path, + "planted-replacement", + baseline, + header, + context, + retry_after, + ) + (tmp_path / "lease-command").write_text("replace-note") + acknowledgement = tmp_path / "lease-replaced.json" + deadline = time.monotonic() + 10 + while not acknowledgement.is_file(): + assert time.monotonic() < deadline, "fixture did not replace its textbox" + time.sleep(0.05) + ack = json.loads(acknowledgement.read_text(encoding="utf-8-sig")) + assert ack["old_handle"] != ack["new_handle"] and ack["focused"] is True + replaced = backend.focus_identity()["native_focus"] + assert replaced["locator"] == observed["target"]["locator"] + assert replaced["region"] == observed["target"]["region"] + assert ( + replaced["target_fingerprint"] != observed["target"]["target_fingerprint"] + ) + evidence["replacement"] = { + "fixture": ack, + "before": observed["target"], + "after": replaced, + } + _refuse( + backend, + host, + transport, + evidence, + "replaced_target", + digest, + retry_after, + baseline, + "stale_focus", + ) + + # A consumed token is tested at the real endpoint, not by re-arming a + # client object. Unknown lease failures carry no zero-input contract. + previous = transport.inputs + response = backend._session.post( + backend.server_url + "/keyboard/input", + json=replay, + **backend._request_kwargs(), + ) + assert transport.inputs == previous + 1 + assert ( + response.status_code == 409 + and response.json()["code"] == "keyboard_lease_unavailable" + ) + assert "no_keyboard_input_delivered" not in response.json() + assert _values(backend) == retry_after and host.rows() == baseline + evidence["cases"].append( + { + "case": "consumed_lease", + "response": transport.events[-1], + "after": {"values": _values(backend), "rows": host.rows()}, + } + ) + + # Lose a real successful acknowledgement. The client must surface + # uncertainty after one request and must never retry the input. + transport.drop_next_ack = True + uncertain = {"case": "uncertain_ack", "attempts": []} + evidence["cases"].append(uncertain) + for attempt in range(6): + digest, validation = _lease( + backend, + host, + tmp_path, + f"lost-ack-{attempt}", + baseline, + header, + context, + retry_after, + ) + previous = transport.inputs + try: + backend.type_text_guarded(" uncertain", expected_frame_sha256=digest) + except KeyboardFrameChangedBeforeInput: + assert ( + transport.events[-1]["response"]["no_keyboard_input_delivered"] + is True + ) + assert _values(backend) == retry_after and host.rows() == baseline + uncertain["attempts"].append( + { + "fresh_validation": validation, + "zero_input_refusal": transport.events[-1], + } + ) + continue + except ActionDeliveryUncertain: + # Only this discarded 200 acknowledgement can explain this + # positive case. No catch or retry follows an uncertain input. + assert transport.events[-1]["http_status"] == 200 + assert ( + transport.events[-1]["injected_fault"] + == "discard_actual_acknowledgement" + ) + assert transport.inputs == previous + 1 + raw_receipt = ActionDeliveryReceipt.model_validate( + transport.events[-1]["response"]["receipt"] + ) + assert raw_receipt.operation == "physical_type_text" + assert ( + raw_receipt.target_fingerprint + == validation["target"]["target_fingerprint"] + ) + assert ( + raw_receipt.native is False + and raw_receipt.outcome_verified is False + ) + uncertain["attempts"].append( + { + "fresh_validation": validation, + "actual_response_discarded": transport.events[-1], + } + ) + break + raise AssertionError("lost acknowledgement was reported as delivered") + else: + raise AssertionError( + "lost-ack case never acquired an unchanged exact frame" + ) + _wait_value(backend, "noteBox", retry_after["noteBox"] + " uncertain") + assert host.rows() == baseline + uncertain["after"] = {"values": _values(backend), "rows": host.rows()} + evidence["passed"] = True + finally: + try: + evidence["rows_after"] = ( + host.rows() if (tmp_path / "patients.db").exists() else None + ) + except Exception as exc: + evidence["final_oracle_error"] = type(exc).__name__ + fixture_process = host.app + try: + host.close() + finally: + evidence["agent_terminated"] = ( + host.agent is None or host.agent.poll() is not None + ) + evidence["fixture_terminated"] = ( + fixture_process is None or fixture_process.poll() is not None + ) + for destination in ( + tmp_path / "evidence.json", + Path( + os.environ.get(EVIDENCE_ENV, tmp_path / "published-evidence.json") + ), + ): + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(json.dumps(evidence, indent=2) + "\n") diff --git a/packages/flow/tests/test_native_focus_keyboard.py b/packages/flow/tests/test_native_focus_keyboard.py new file mode 100644 index 0000000000..e68a83ab93 --- /dev/null +++ b/packages/flow/tests/test_native_focus_keyboard.py @@ -0,0 +1,342 @@ +"""Observed native focus is required for keyboard anchors and cannot be inferred.""" + +from __future__ import annotations + +import io +import json + +import pytest +from PIL import Image, ImageDraw + +from openadapt_flow.backends.win_agent import AgentConfig +from openadapt_flow.backends.win_agent.server import ( + AgentRequestError, + _focused_target, + _perform_uia_initialized, +) +from openadapt_flow.backends.windows_backend import WindowsBackend +from openadapt_flow.compiler import compile_recording +from openadapt_flow.compiler.native_focus import anchor_native_keyboard +from openadapt_flow.ir import ActionKind, Step +from openadapt_flow.native_focus import NativeFocusTarget, from_native_candidate +from openadapt_flow.recorder import Recorder +from tests.test_recorder import FakeBackend +from tests.test_win_agent_server import RunningAgent, _fake_uia_module, _FakeControl + +LOCATOR = { + "automation_id": "entry", + "role": "textbox", + "name": "Entry", + "window_name": "Editor", +} +CANDIDATE = { + **LOCATOR, + "bounds": [400, 200, 800, 300], + "point": [600, 250], + "fingerprint": "a" * 64, +} + + +def observed(): + target = from_native_candidate(CANDIDATE) + assert target is not None + return {"native_focus": target.model_dump(mode="json")} + + +def png(): + image = Image.new("RGB", (1280, 800), "white") + draw = ImageDraw.Draw(image) + draw.rectangle((400, 200, 800, 300), outline="black") + draw.text((15, 15), "Synthetic record identity 314159", fill="black") + out = io.BytesIO() + image.save(out, format="PNG") + return out.getvalue() + + +def focused_auto(*, duplicate=False): + first = _FakeControl( + "EditControl", + automation_id="entry", + name="Entry", + runtime_id=(1, 2), + bounds=(400, 200, 800, 300), + ) + controls = [first] + if duplicate: + controls.append( + _FakeControl( + "EditControl", + automation_id="entry", + name="Entry", + runtime_id=(1, 3), + bounds=(400, 320, 800, 420), + ) + ) + auto = _fake_uia_module(*controls) + auto.GetFocusedControl = lambda: first + return auto, first + + +def test_focused_target_is_unique_visible_and_reobserved(): + auto, first = focused_auto() + candidate = _focused_target(auto) + assert candidate is not None and candidate["automation_id"] == "entry" + assert candidate["point"] == [600, 250] + assert _perform_uia_initialized(auto, "focused-target", {})["target"] == candidate + with pytest.raises(AgentRequestError) as caught: + _perform_uia_initialized(auto, "focused-target", {"command": "anything"}) + assert caught.value.status == 400 and caught.value.code == "invalid_schema" + assert first.invocations == 0 + + +@pytest.mark.parametrize( + "fault", + [ + "missing", + "ambiguous", + "moved", + "moved_geometry", + "covered", + "no_runtime_id", + "truncated", + ], +) +def test_focus_observation_declines_missing_ambiguous_moved_or_covered_focus( + fault, monkeypatch +): + auto, first = focused_auto(duplicate=fault == "ambiguous") + if fault == "missing": + auto.GetFocusedControl = lambda: None + if fault == "moved": + other = _FakeControl("EditControl", automation_id="other", runtime_id=(8, 8)) + values = iter([first, other]) + auto.GetFocusedControl = lambda: next(values) + if fault == "moved_geometry": + reads = [] + + def focused(): + reads.append(True) + if len(reads) == 2: + first.BoundingRectangle.left += 1 + return first + + auto.GetFocusedControl = focused + if fault == "covered": + auto.ControlFromPoint = lambda *_: _FakeControl( + "ButtonControl", runtime_id=(8, 8) + ) + if fault == "no_runtime_id": + first.runtime_id = () + if fault == "truncated": + monkeypatch.setattr( + "openadapt_flow.backends.win_agent.server._find_candidates", + lambda *_: ([], True), + ) + assert _focused_target(auto) is None + assert first.invocations == 0 + + +def test_backend_passive_focus_round_trip_contains_no_value(): + calls = [] + + def uia(operation, data): + calls.append((operation, data)) + return {"status": "ok", "target": dict(CANDIDATE)} + + agent = RunningAgent( + AgentConfig(host="127.0.0.1", port=0, token="test"), + uia_fn=uia, + ) + try: + with pytest.warns(UserWarning, match="plaintext"): + backend = WindowsBackend(agent.url, auth_token="test") + assert backend.focus_identity() == observed() + finally: + agent.close() + assert calls == [("focused-target", {})] + assert "value" not in json.dumps(observed()) + + +@pytest.mark.parametrize( + "field,value", + [ + ("candidate_count", True), + ("candidate_count", 2), + ("complete", 1), + ("target_fingerprint", "bad"), + ("point", [True, 250]), + ("region", [400, 200, 0, 100]), + ], +) +def test_recorded_focus_contract_refuses_malformed_data(field, value): + data = observed()["native_focus"] + data[field] = value + with pytest.raises(ValueError): + NativeFocusTarget.model_validate(data) + + +@pytest.mark.parametrize("kind", ["type", "key", "hotkey"]) +def test_recorder_freezes_input_focus_even_when_after_focus_is_unavailable( + tmp_path, kind +): + class Backend(FakeBackend): + def __init__(self): + super().__init__() + self.target = observed() + self.after = False + + def focus_identity(self): + return None if self.after else self.target + + def press(self, key): + self.target["native_focus"]["locator"]["automation_id"] = ( + "changed-after-action" + ) + self.after = True + + def type_text(self, text): + self.press("text") + + backend = Backend() + rec = Recorder(backend, tmp_path / "recording") + if kind == "type": + rec.type_text("synthetic") + elif kind == "hotkey": + rec.hotkey(["Ctrl"], "Enter") + else: + rec.press("Enter") + recording = rec.finish() + event = json.loads((recording / "events.jsonl").read_text().splitlines()[0]) + assert event["focus_before"]["native_focus"]["locator"]["automation_id"] == "entry" + assert "focus_after" not in event + + +@pytest.mark.parametrize("kind", ["type", "key", "hotkey"]) +def test_compile_actual_focus_before_into_an_armed_keyboard_anchor( + tmp_path, monkeypatch, kind +): + import openadapt_flow.compiler.compile as compiler + + monkeypatch.setattr(compiler, "ocr", lambda *_args, **_kwargs: []) + recording = tmp_path / "recording" + (recording / "frames").mkdir(parents=True) + event = {"i": 0, "kind": kind, "t": 1, "focus_before": observed()} + if kind == "type": + event["text"] = "synthetic" + else: + event["key"] = "Enter" + if kind == "hotkey": + event["modifiers"] = ["Ctrl"] + (recording / "events.jsonl").write_text(json.dumps(event) + "\n") + (recording / "meta.json").write_text( + json.dumps( + { + "id": "native-focus-test", + "created_at": "2026-11-19T00:00:00Z", + "viewport": [1280, 800], + "surface": "windows", + "params": {}, + "identifier_region": [10, 10, 220, 30], + } + ) + ) + for suffix in ["before", "after"]: + (recording / "frames" / f"0000_{suffix}.png").write_bytes(png()) + bundle = tmp_path / "bundle" + workflow = compile_recording(recording, bundle, name="native-keyboard") + step = workflow.steps[0] + assert step.anchor is not None and step.identity_armed + assert step.anchor.structural.automation_id == "entry" + assert step.anchor.click_point == (600, 250) + assert step.anchor.identifier_region == (10, 10, 220, 30) + assert step.anchor.identifier_crop + assert "target_fingerprint" not in step.anchor.structural.model_dump() + assert "a" * 64 not in step.model_dump_json() + + +def test_compile_never_infers_native_focus_from_a_previous_click_or_after_observation( + tmp_path, +): + step = Step(id="key", action=ActionKind.KEY, key="Enter", intent="press Enter") + event = {"i": 1, "kind": "key", "focus_after": observed()} + result = anchor_native_keyboard( + [(step, png(), png(), event)], + bundle=tmp_path, + meta_identifier_region=None, + reference_date=None, + cached_lines=lambda *_: [], + ) + assert result[0][0].anchor is None + + +def test_keyboard_focus_model_preserves_each_before_target_across_action_sequences( + tmp_path, +): + (tmp_path / "bundle" / "templates").mkdir(parents=True) + from hypothesis import given, settings + from hypothesis import strategies as st + + @settings(max_examples=20, deadline=None) + @given( + st.lists( + st.tuples( + st.sampled_from(["type", "key", "hotkey"]), + st.integers(min_value=0, max_value=5), + st.booleans(), + ), + min_size=1, + max_size=6, + ) + ) + def sequence(actions): + pending = [] + expected = [] + for index, (kind, target_id, available) in enumerate(actions): + focus = observed() + focus["native_focus"]["locator"]["automation_id"] = f"entry-{target_id}" + event = {"i": index, "kind": kind, "focus_after": observed()} + if available: + event["focus_before"] = focus + step = Step( + id=f"step_{index}", + action=ActionKind.TYPE + if kind == "type" + else ActionKind.KEY + if kind == "key" + else ActionKind.HOTKEY, + text="synthetic" if kind == "type" else None, + key="Enter" if kind != "type" else None, + modifiers=["Ctrl"] if kind == "hotkey" else [], + intent="keyboard input", + ) + pending.append((step, png(), png(), event)) + expected.append(f"entry-{target_id}" if available else None) + compiled = anchor_native_keyboard( + pending, + bundle=tmp_path / "bundle", + meta_identifier_region=(10, 10, 220, 30), + reference_date=None, + cached_lines=lambda *_: [], + ) + for (step, *_), target in zip(compiled, expected, strict=True): + assert ( + step.anchor.structural.automation_id if step.anchor else None + ) == target + assert bool(step.identity_armed) == (target is not None) + + sequence() + + +def test_recorder_declines_a_focus_observation_that_cannot_be_frozen(tmp_path): + class Unreadable: + def __deepcopy__(self, _memo): + raise RuntimeError("observation object is no longer readable") + + backend = FakeBackend() + backend.focus_identity = lambda: {"native_focus": Unreadable()} + rec = Recorder(backend, tmp_path / "recording") + rec.press("Enter") + recording = rec.finish() + event = json.loads((recording / "events.jsonl").read_text().splitlines()[0]) + assert "focus_before" not in event + assert backend.calls == [("key", "Enter")] diff --git a/packages/flow/tests/test_native_keyboard_edges.py b/packages/flow/tests/test_native_keyboard_edges.py new file mode 100644 index 0000000000..983c352aa7 --- /dev/null +++ b/packages/flow/tests/test_native_keyboard_edges.py @@ -0,0 +1,166 @@ +"""One lease guard model for physical key edges and uncertain cleanup.""" + +from __future__ import annotations + +import sys +from types import SimpleNamespace + +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +from openadapt_flow.backends.win_agent import server +from openadapt_flow.ir import ActionDeliveryReceipt + + +class _Keys: + def __init__(self): + self.held: set[str] = set() + self.edges: list[tuple[str, str]] = [] + self.fail_edge: tuple[str, str] | None = None + + def _edge(self, kind, key): + self.edges.append((kind, key)) + if kind == "down": + self.held.add(key) + else: + self.held.discard(key) + if self.fail_edge == (kind, key): + self.fail_edge = None # a throwing call might already have sent it + raise OSError("synthetic native edge acknowledgement loss") + + def keyDown(self, key, *, _pause): + assert _pause is False + self._edge("down", key) + + def keyUp(self, key, *, _pause): + assert _pause is False + self._edge("up", key) + + +@pytest.mark.parametrize( + "keys", [["enter"], ["ctrl", "x"], ["ctrl", "shift", "alt", "s"]] +) +def test_focus_loss_at_every_guard_boundary_stops_down_edges_and_releases(keys): + for fail_at in range(4 * len(keys)): + gui = _Keys() + observations = 0 + edges_at_loss = None + + def guard(): + nonlocal observations, edges_at_loss + current = observations + observations += 1 + if current == fail_at: + edges_at_loss = list(gui.edges) + raise RuntimeError("synthetic target changed") + + with pytest.raises(RuntimeError, match="target changed"): + server._guarded_key_chord(gui, keys, guard) + assert observations == fail_at + 1 + assert not gui.held + assert edges_at_loss is not None + # Cleanup can only release keys; it cannot emit any new down edge. + assert all(kind == "up" for kind, _ in gui.edges[len(edges_at_loss) :]) + + +@given( + st.lists( + st.sampled_from(["ctrl", "shift", "alt", "x", "enter"]), + min_size=1, + max_size=4, + unique=True, + ) +) +@settings(max_examples=35, deadline=None) +def test_successful_chord_guards_every_edge_and_releases_in_reverse_order(keys): + gui = _Keys() + snapshots = [] + server._guarded_key_chord(gui, keys, lambda: snapshots.append(tuple(gui.edges))) + expected = [("down", key) for key in keys] + [("up", key) for key in reversed(keys)] + assert gui.edges == expected and not gui.held + assert len(snapshots) == 2 * len(expected) + for index, edge in enumerate(expected): + assert snapshots[2 * index] == tuple(expected[:index]) + assert snapshots[2 * index + 1] == tuple(expected[: index + 1]) + + +@pytest.mark.parametrize( + "failing_edge", [("down", "ctrl"), ("down", "x"), ("up", "x"), ("up", "ctrl")] +) +def test_native_edge_exception_is_uncertain_and_cleanup_releases_held_modifiers( + failing_edge, +): + gui = _Keys() + gui.fail_edge = failing_edge + with pytest.raises(OSError, match="acknowledgement loss"): + server._guarded_key_chord(gui, ["ctrl", "x"], lambda: None) + assert not gui.held + failed_index = gui.edges.index(failing_edge) + assert all(kind == "up" for kind, _ in gui.edges[failed_index + 1 :]) + + +PAYLOADS = [ + ({"action": "press", "keys": ["enter"]}, ["enter"], "physical_press"), + ({"action": "press", "keys": ["ctrl", "x"]}, ["ctrl", "x"], "physical_press"), + ( + {"action": "type_text", "text": "Ab", "interval_s": 0}, + ["A", "b"], + "physical_type_text", + ), + ({"action": "type_text", "text": "é"}, ["ctrl", "v"], "physical_type_text"), +] + + +def _install_gui(monkeypatch, gui): + def forbidden(*args, **kwargs): + raise AssertionError("leased input bypassed the guarded key-edge model") + + monkeypatch.setitem( + sys.modules, + "pyautogui", + SimpleNamespace( + keyDown=gui.keyDown, + keyUp=gui.keyUp, + write=forbidden, + press=forbidden, + hotkey=forbidden, + ), + ) + monkeypatch.setattr(server, "_foreground_window_identity", lambda: (1, 2)) + + +@pytest.mark.parametrize("payload,keys,operation", PAYLOADS) +def test_every_leased_keyboard_entry_point_uses_real_receipt_after_guarded_edges( + monkeypatch, payload, keys, operation +): + gui = _Keys() + _install_gui(monkeypatch, gui) + observations = [] + raw = server._perform_input( + payload, + keyboard_guard=lambda: observations.append(tuple(gui.edges)), + clipboard_prepared=True, + ) + receipt = ActionDeliveryReceipt.model_validate(raw) + assert receipt.operation == operation and receipt.native is False + assert receipt.outcome_verified is False + assert not gui.held and observations[-1] == tuple(gui.edges) + assert [key for kind, key in gui.edges if kind == "down"] == keys + + +@pytest.mark.parametrize("payload,keys,operation", PAYLOADS) +def test_focus_change_inside_any_keyboard_entry_point_emits_no_receipt_or_later_down_edge( + monkeypatch, payload, keys, operation +): + gui = _Keys() + _install_gui(monkeypatch, gui) + + def guard(): + if gui.edges: + raise RuntimeError("synthetic focus moved inside gesture") + + with pytest.raises(RuntimeError, match="inside gesture"): + server._perform_input(payload, keyboard_guard=guard, clipboard_prepared=True) + assert gui.edges == [("down", keys[0]), ("up", keys[0])] + assert not gui.held diff --git a/packages/flow/tests/test_native_keyboard_lease.py b/packages/flow/tests/test_native_keyboard_lease.py new file mode 100644 index 0000000000..a5b3c2c11c --- /dev/null +++ b/packages/flow/tests/test_native_keyboard_lease.py @@ -0,0 +1,201 @@ +"""One-shot keyboard authority: only observed target/context/frame may receive input.""" + +from __future__ import annotations + +import struct +from copy import deepcopy + +import pytest + +from openadapt_flow.backends.win_agent.keyboard_lease import ( + KeyboardLeaseController, + KeyboardLeaseError, + KeyboardLeaseRefused, +) + +PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 8 + struct.pack(">II", 640, 480) + + +class Surface: + def __init__(self): + self.target = { + "fingerprint": "a" * 64, + "point": [20, 20], + "bounds": [10, 10, 100, 40], + "role": "textbox", + } + self.context = { + "status": "ok", + "application": "test-runtime", + "application_version": "sha256:" + "a" * 64, + "session": "b" * 64, + "environment": "c" * 64, + "workflow_state": None, + } + self.frame, self.now, self.calls = PNG, 0.0, [] + self.error = None + self.controller = KeyboardLeaseController( + self.uia, + lambda: self.frame, + lambda: dict(self.context), + self.deliver, + clock=lambda: self.now, + ) + + def uia(self, operation, payload): + assert operation == "focused-target" and payload == {} + return {"status": "ok", "target": deepcopy(self.target)} + + def deliver(self, payload): + self.calls.append(payload) + if self.error: + raise self.error + from openadapt_flow.backends.win_agent.server import _delivery_receipt + + return _delivery_receipt( + "physical_type_text" + if payload["action"] == "type_text" + else "physical_press", + native=False, + ) + + +@pytest.mark.parametrize( + "payload", + [ + {"action": "type_text", "text": "example"}, + {"action": "press", "keys": ["enter"]}, + {"action": "press", "keys": ["ctrl", "s"]}, + ], +) +def test_actual_acknowledgement_binds_exact_target_and_consumes_lease(payload): + surface = Surface() + lease = surface.controller.issue() + assert not surface.calls + delivered = surface.controller.deliver( + lease["lease_id"], lease["frame_sha256"], payload + ) + assert delivered["receipt"]["target_fingerprint"] == lease["target"]["fingerprint"] + assert surface.calls == [payload] + with pytest.raises(KeyboardLeaseError, match="not_owned"): + surface.controller.deliver(lease["lease_id"], lease["frame_sha256"], payload) + assert surface.calls == [payload] + + +@pytest.mark.parametrize( + "change", ["frame", "focus", "context", "expired", "unverified"] +) +def test_every_changed_binding_returns_zero_keyboard_input_only_before_delivery(change): + surface = Surface() + lease = surface.controller.issue() + expected = lease["frame_sha256"] + reason = { + "frame": "stale_frame", + "focus": "stale_focus", + "context": "stale_context", + "expired": "expired", + "unverified": "unverified_frame", + }[change] + if change == "frame": + surface.frame += b"changed" + if change == "focus": + surface.target["fingerprint"] = "d" * 64 + if change == "context": + surface.context["session"] = "d" * 64 + if change == "expired": + surface.now = 16 + if change == "unverified": + expected = "d" * 64 + with pytest.raises(KeyboardLeaseRefused) as error: + surface.controller.deliver( + lease["lease_id"], expected, {"action": "type_text", "text": "example"} + ) + assert error.value.reason == reason + assert error.value.payload()["no_keyboard_input_delivered"] is True + assert not surface.calls + with pytest.raises(KeyboardLeaseError, match="not_owned"): + surface.controller.deliver( + lease["lease_id"], + lease["frame_sha256"], + {"action": "press", "keys": ["enter"]}, + ) + + +def test_later_observation_invalidates_prior_lease_and_callback_failure_is_uncertain(): + surface = Surface() + first = surface.controller.issue() + second = surface.controller.issue() + with pytest.raises(KeyboardLeaseError, match="not_owned"): + surface.controller.deliver( + first["lease_id"], + first["frame_sha256"], + {"action": "press", "keys": ["enter"]}, + ) + # A rejected request consumed the current lease too; no replay after an unknown token. + with pytest.raises(KeyboardLeaseError, match="not_owned"): + surface.controller.deliver( + second["lease_id"], + second["frame_sha256"], + {"action": "press", "keys": ["enter"]}, + ) + lease = surface.controller.issue() + surface.error = OSError("delivery may have begun") + with pytest.raises(OSError): + surface.controller.deliver( + lease["lease_id"], + lease["frame_sha256"], + {"action": "press", "keys": ["enter"]}, + ) + assert len(surface.calls) == 1 + + +@pytest.mark.parametrize( + "bad", + [ + {"action": "click"}, + {"action": "type_text", "text": "x" * 65537}, + {"action": "press", "keys": [True]}, + {"action": "type_text", "text": "x", "interval_s": True}, + ], +) +def test_malformed_keyboard_data_never_reaches_input(bad): + surface = Surface() + lease = surface.controller.issue() + with pytest.raises(KeyboardLeaseError): + surface.controller.deliver(lease["lease_id"], lease["frame_sha256"], bad) + assert not surface.calls + + +def test_deadline_during_actual_delivery_is_uncertain_not_zero_input(): + surface = Surface() + def deliver(payload): + surface.calls.append(payload) + surface.now = 20.0 + surface.controller.require_current_target() + raise AssertionError("expired delivery cannot acknowledge") + surface.controller._deliver = deliver + lease = surface.controller.issue() + with pytest.raises(RuntimeError) as caught: + surface.controller.deliver(lease["lease_id"], lease["frame_sha256"], {"action": "press", "keys": ["enter"]}) + assert not isinstance(caught.value, KeyboardLeaseRefused) + assert len(surface.calls) == 1 + + +def test_changed_frame_geometry_is_measured_from_actual_pixels(): + from io import BytesIO + + from PIL import Image + + from openadapt_flow.backends.win_agent.keyboard_lease import frame_change + + def png(image): + stream = BytesIO() + image.save(stream, format="PNG") + return stream.getvalue() + before = Image.new("RGB", (10, 10), "white") + after = before.copy() + after.putpixel((2, 3), (255, 255, 254)) + assert frame_change(png(before), png(after)) == { + "changed_pixel_count": 1, "changed_bbox": [2, 3, 1, 1], "frame_size": [10, 10] + } + assert frame_change(png(before), png(before)) is None diff --git a/packages/flow/tests/test_native_keyboard_retry.py b/packages/flow/tests/test_native_keyboard_retry.py new file mode 100644 index 0000000000..cfa56664dd --- /dev/null +++ b/packages/flow/tests/test_native_keyboard_retry.py @@ -0,0 +1,196 @@ +"""Temporal lease class: bounded zero-input retry, no partial/unknown retry.""" + +from __future__ import annotations + +import pytest +from hypothesis import given +from hypothesis import strategies as st + +from openadapt_flow.backend import ( + ActionDeliveryUncertain, + KeyboardFrameChangedBeforeInput, + StructuralResolutionRefused, +) +from openadapt_flow.ir import FreshActuationEvent +from openadapt_flow.runtime.keyboard_delivery import deliver_with_revalidation + + +def changed(operation="physical_type_text"): + return KeyboardFrameChangedBeforeInput( + operation=operation, + changed_pixel_count=1, + changed_bbox=(1, 1, 1, 1), + frame_size=(20, 10), + lease_sha256="a" * 64, + target_fingerprint="b" * 64, + ) + + +@given( + st.integers(min_value=0, max_value=8), + st.sampled_from(["physical_type_text", "physical_press"]), +) +def test_class_retry_bound_and_single_delivery(mismatches, operation): + attempts, deliveries, checks, evidence = [], [], [], [] + + def deliver(): + attempts.append(True) + if len(attempts) <= mismatches: + raise changed(operation) + deliveries.append(True) + return "actual-ack" + + def revalidate(exc): + checks.append(exc.target_fingerprint) + return True + + if mismatches < 3: + assert ( + deliver_with_revalidation( + deliver, revalidate, lambda *args: evidence.append(args) + ) + == "actual-ack" + ) + else: + with pytest.raises(StructuralResolutionRefused): + deliver_with_revalidation( + deliver, revalidate, lambda *args: evidence.append(args) + ) + assert len(attempts) == min(mismatches + 1, 3) + assert len(deliveries) == int(mismatches < 3) + assert len(checks) == min(mismatches, 2) + assert [entry[1] for entry in evidence] == ( + [True] * min(mismatches, 2) + ([False] if mismatches >= 3 else []) + ) + + +@pytest.mark.parametrize( + "failure", + [ + TimeoutError("lost acknowledgement"), + ActionDeliveryUncertain( + operation="physical_press", native=False, cause_type="partial_chord" + ), + StructuralResolutionRefused("changed focus"), + ], +) +def test_unknown_partial_or_different_refusal_never_revalidated(failure): + calls = [] + + def deliver(): + calls.append("input-boundary") + raise failure + + with pytest.raises(type(failure)): + deliver_with_revalidation( + deliver, + lambda _: calls.append("forbidden"), + lambda *_: calls.append("forbidden"), + ) + assert calls == ["input-boundary"] + + +def test_full_revalidation_refusal_stops_without_second_input(): + calls = [] + + def deliver(): + calls.append("input-boundary") + raise changed() + + with pytest.raises(StructuralResolutionRefused): + deliver_with_revalidation( + deliver, + lambda _: False, + lambda _, retry, attempt: calls.append((retry, attempt)), + ) + assert calls == ["input-boundary", (False, 1)] + + +def test_keyboard_phase_evidence_roundtrips_and_legacy_shape_stays_exact(): + fields = dict( + attempt=1, + operation="physical_type_text", + changed_pixel_count=1, + changed_bbox=(1, 1, 1, 1), + frame_size=(20, 10), + retried=True, + ) + legacy = FreshActuationEvent(**fields) + assert ( + "phase" not in legacy.model_dump() and "lease_sha256" not in legacy.model_dump() + ) + keyboard = FreshActuationEvent(**fields, phase="keyboard", lease_sha256="a" * 64) + assert ( + FreshActuationEvent.model_validate_json(keyboard.model_dump_json()) == keyboard + ) + with pytest.raises(ValueError): + FreshActuationEvent(**fields, phase="keyboard") + with pytest.raises(ValueError): + FreshActuationEvent(**fields, lease_sha256="a" * 64) + + +@pytest.mark.parametrize("action", ["type", "key", "hotkey"]) +def test_runtime_revalidates_only_keyboard_phase_without_repeating_focus( + tmp_path, action +): + from openadapt_flow.ir import ActionKind, Step, Workflow + from openadapt_flow.runtime.replayer import Replayer + from tests.test_replayer import FakeBackend, FakeVision, Match, click_step, make_png + + class NativeLeasedBackend(FakeBackend): + observations = 0 + attempted = 0 + + def native_keyboard_lease_available(self): + return True + + def guarded_keyboard_target_fingerprint(self): + return "b" * 64 if self._guarded_keyboard_point is not None else None + + def guarded_keyboard_frame(self): + self.observations += 1 + return self._frame + + def type_text_guarded(self, text, **kwargs): + self.attempted += 1 + if self.attempted == 1: + self._guarded_keyboard_point = None + raise changed() + return super().type_text_guarded(text, **kwargs) + + def press_guarded(self, key, **kwargs): + self.attempted += 1 + if self.attempted == 1: + self._guarded_keyboard_point = None + raise changed("physical_press") + return super().press_guarded(key, **kwargs) + + bundle = tmp_path / "bundle" + (bundle / "templates").mkdir(parents=True) + (bundle / "templates/btn.png").write_bytes(make_png((50, 20))) + backend = NativeLeasedBackend() + vision = FakeVision() + vision.template_results = [Match((110, 105), (100, 100, 50, 20)) for _ in range(8)] + step = Step( + id="keyboard", + intent="edit transient field", + action=ActionKind(action), + anchor=click_step(ocr_text="Field").anchor, + text="example" if action == "type" else None, + key="a" if action != "type" else None, + modifiers=["ctrl"] if action == "hotkey" else [], + ) + replay = Replayer(backend, vision=vision) + report = replay.run( + Workflow(name="test", steps=[step]), bundle_dir=bundle, run_dir=tmp_path / "run" + ) + assert report.success is True, report.results[0].error + assert backend.attempted == 2 + assert len([edge for edge in backend.actions if edge[0] == "click"]) == int( + action == "type" + ) + assert len([edge for edge in backend.actions if edge[0] in {"press", "type"}]) == 1 + assert backend.observations == 2 + event = report.results[0].fresh_actuation_events[0] + assert event.phase == "keyboard" and event.retried is True + assert event.lease_sha256 == "a" * 64 diff --git a/packages/flow/tests/test_windows_keyboard_lease_client.py b/packages/flow/tests/test_windows_keyboard_lease_client.py new file mode 100644 index 0000000000..0130e5ab6c --- /dev/null +++ b/packages/flow/tests/test_windows_keyboard_lease_client.py @@ -0,0 +1,255 @@ +"""Untrusted lease acknowledgements cannot create retry or delivery authority.""" + +from __future__ import annotations + +import copy +from io import BytesIO +from types import SimpleNamespace + +import pytest +from PIL import Image + +from openadapt_flow.backend import ( + ActionDeliveryUncertain, + KeyboardFrameChangedBeforeInput, + StructuralResolutionRefused, +) +from openadapt_flow.backends.win_agent.keyboard_lease import ( + KeyboardLeaseController, + KeyboardLeaseRefused, +) +from openadapt_flow.backends.win_agent.server import _delivery_receipt +from openadapt_flow.backends.windows_keyboard_lease import NativeKeyboardLeaseClient + + +class _Peer: + """Real controller + receipt factory, with a bounded synthetic desktop.""" + + def __init__(self): + stream = BytesIO() + Image.new("RGB", (64, 48), "white").save(stream, format="PNG") + self.png = stream.getvalue() + self.target = { + "fingerprint": "a" * 64, + "point": [20, 20], + "bounds": [10, 10, 50, 40], + } + self.context = { + "status": "ok", + "application": "synthetic-runtime", + "application_version": "sha256:" + "b" * 64, + "session": "c" * 64, + "environment": "d" * 64, + "workflow_state": None, + } + self.sent, self.delivered = [], [] + self.corrupt = lambda path, value: value + self.controller = KeyboardLeaseController( + lambda operation, data: { + "status": "ok", + "target": copy.deepcopy(self.target), + }, + lambda: self.png, + lambda: dict(self.context), + self.input, + ) + self.client = NativeKeyboardLeaseClient(self.post, lambda: None) + + def input(self, payload): + self.delivered.append(copy.deepcopy(payload)) + return _delivery_receipt( + "physical_type_text" + if payload["action"] == "type_text" + else "physical_press", + native=False, + ) + + def post(self, path, data): + self.sent.append((path, copy.deepcopy(data))) + try: + result = ( + self.controller.issue() + if path == "/keyboard/lease" + else self.controller.deliver( + data["lease_id"], data["expected_frame_sha256"], data["input"] + ) + ) + status = 200 + except KeyboardLeaseRefused as exc: + result, status = exc.payload(), 409 + result = self.corrupt(path, result) + return SimpleNamespace(status_code=status, json=lambda: result) + + def arm(self): + import hashlib + + frame = self.client.frame() + self.client.arm(20, 20) + return hashlib.sha256(frame).hexdigest() + + +INPUTS = [ + {"action": "type_text", "text": "synthetic"}, + {"action": "press", "keys": ["enter"]}, + {"action": "press", "keys": ["ctrl", "x"]}, +] + + +@pytest.mark.parametrize("payload", INPUTS) +def test_real_acknowledgement_is_single_use_and_bound_to_actual_target(payload): + peer = _Peer() + digest = peer.arm() + receipt = peer.client.deliver(payload, digest) + assert receipt.target_fingerprint == peer.target["fingerprint"] + assert receipt.status == "delivered" and receipt.outcome_verified is False + assert peer.delivered == [payload] + with pytest.raises(StructuralResolutionRefused, match="no armed lease"): + peer.client.deliver(payload, digest) + assert peer.delivered == [payload] and len(peer.sent) == 2 + + +@pytest.mark.parametrize( + "change", ["extra", "digest", "context", "target", "png", "geometry"] +) +def test_malformed_observation_never_arms_input(change): + peer = _Peer() + + def corrupt(path, result): + assert path == "/keyboard/lease" + if change == "extra": + result["untrusted"] = True + elif change == "digest": + result["frame_sha256"] = "e" * 64 + elif change == "context": + result["context"]["application_version"] = None + elif change == "target": + result["target"]["fingerprint"] = "untrusted" + elif change == "png": + result["frame_png"] = "not base64" + else: + result["target"]["point"] = [True, 20] + return result + + peer.corrupt = corrupt + with pytest.raises(StructuralResolutionRefused, match="observation unavailable"): + peer.client.frame() + with pytest.raises(StructuralResolutionRefused, match="no armed lease"): + peer.client.deliver(INPUTS[0], "a" * 64) + assert not peer.delivered and len(peer.sent) == 1 + + +@pytest.mark.parametrize("payload", INPUTS) +@pytest.mark.parametrize( + "change", + ["target", "operation", "native", "outcome", "lease", "extra", "status", "missing"], +) +def test_bad_acknowledgement_is_uncertain_after_exactly_one_actual_delivery( + payload, change +): + peer = _Peer() + digest = peer.arm() + + def corrupt(path, result): + assert path == "/keyboard/input" + if change == "target": + result["receipt"]["target_fingerprint"] = "e" * 64 + elif change == "operation": + result["receipt"]["operation"] = "physical_click" + elif change == "native": + result["receipt"]["native"] = True + elif change == "outcome": + result["receipt"]["outcome_verified"] = True + elif change == "lease": + result["lease_id"] = "e" * 32 + elif change == "extra": + result["receipt"]["delivery_attested"] = True + elif change == "status": + result["receipt"]["status"] = "refused" + else: + del result["receipt"]["receipt_id"] + return result + + peer.corrupt = corrupt + with pytest.raises(ActionDeliveryUncertain): + peer.client.deliver(payload, digest) + assert peer.delivered == [payload] + with pytest.raises(StructuralResolutionRefused, match="no armed lease"): + peer.client.deliver(payload, digest) + assert peer.delivered == [payload] and len(peer.sent) == 2 + + +@pytest.mark.parametrize("payload", INPUTS) +def test_lost_actual_acknowledgement_never_repeats_or_rearms_input(payload): + peer = _Peer() + digest = peer.arm() + + def lose_response(path, result): + assert path == "/keyboard/input" + raise ConnectionError("synthetic response lost after actual input") + + peer.corrupt = lose_response + with pytest.raises(ActionDeliveryUncertain): + peer.client.deliver(payload, digest) + assert peer.delivered == [payload] + with pytest.raises(StructuralResolutionRefused): + peer.client.deliver(payload, digest) + assert peer.delivered == [payload] and len(peer.sent) == 2 + + +@pytest.mark.parametrize("payload", INPUTS) +def test_real_pixel_change_is_zero_input_and_consumes_the_lease(payload): + peer = _Peer() + digest = peer.arm() + stream = BytesIO() + Image.new("RGB", (64, 48), "black").save(stream, format="PNG") + peer.png = stream.getvalue() + with pytest.raises(KeyboardFrameChangedBeforeInput) as error: + peer.client.deliver(payload, digest) + assert error.value.changed_pixel_count == 64 * 48 + assert error.value.changed_bbox == (0, 0, 64, 48) + assert error.value.target_fingerprint == peer.target["fingerprint"] + assert not peer.delivered + with pytest.raises(StructuralResolutionRefused): + peer.client.deliver(payload, digest) + assert not peer.delivered and len(peer.sent) == 2 + + +@pytest.mark.parametrize( + "change", ["zero", "bool_count", "bbox", "oversized", "no_input", "wrong_lease"] +) +def test_malformed_refusal_never_creates_a_retryable_frame_change(change): + peer = _Peer() + digest = peer.arm() + peer.png += b"different PNG encoding" + + def corrupt(path, result): + assert path == "/keyboard/input" + result["frame_change"] = { + "changed_pixel_count": 1, + "changed_bbox": [0, 0, 1, 1], + "frame_size": [64, 48], + } + if change == "zero": + result["frame_change"]["changed_pixel_count"] = 0 + elif change == "bool_count": + result["frame_change"]["changed_pixel_count"] = True + elif change == "bbox": + result["frame_change"]["changed_bbox"] = [64, 0, 1, 1] + elif change == "oversized": + result["frame_change"]["changed_pixel_count"] = 64 * 48 + 1 + elif change == "no_input": + result["no_keyboard_input_delivered"] = False + else: + result["lease_id"] = "e" * 32 + return result + + peer.corrupt = corrupt + expected = ( + ActionDeliveryUncertain + if change in {"no_input", "wrong_lease"} + else StructuralResolutionRefused + ) + with pytest.raises(expected) as error: + peer.client.deliver(INPUTS[0], digest) + assert not isinstance(error.value, KeyboardFrameChangedBeforeInput) + assert not peer.delivered and len(peer.sent) == 2 From 2c88abeb4d9367ddc44771126f68fb0e3fedfa33 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 21:45:18 -0500 Subject: [PATCH 2/8] test(flow): retain bounded native keyboard uncertainty diagnostics --- .../backends/win_agent/keyboard_lease.py | 56 ++++++++++++-- .../backends/win_agent/server.py | 29 +++++++- .../tests/e2e/test_native_keyboard_lease.py | 20 +++-- .../flow/tests/test_native_keyboard_lease.py | 74 ++++++++++++++++++- 4 files changed, 163 insertions(+), 16 deletions(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py b/packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py index d85ca6f361..58c6ec9d0a 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py +++ b/packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py @@ -24,6 +24,23 @@ class KeyboardLeaseError(RuntimeError): """A bounded observation failure, with no delivery assertion.""" +class KeyboardDeliveryUncertain(RuntimeError): + """Bounded diagnostics after the keyboard delivery boundary; never retryable.""" + + def __init__(self, reason: str, checks: int, elapsed_ms: int) -> None: + self.reason, self.checks, self.elapsed_ms = reason, checks, elapsed_ms + super().__init__("native keyboard delivery became uncertain") + + def payload(self) -> dict[str, Any]: + return { + "status": "error", + "code": "keyboard_delivery_uncertain", + "reason": self.reason, + "guard_checks": self.checks, + "elapsed_ms": self.elapsed_ms, + } + + class KeyboardLeaseRefused(KeyboardLeaseError): """A consumed known lease refused before its keyboard input callback.""" @@ -200,6 +217,7 @@ def __init__( ) self._clock, self._lifetime_s = clock, lifetime_s self._prepare = prepare + self._guard_checks, self._delivery_started = 0, 0.0 self._delivering: tuple[dict[str, Any], dict[str, Any], float] | None = None self._pending: ( tuple[str, float, dict[str, Any], dict[str, Any], bytes] | None @@ -278,6 +296,7 @@ def refuse(reason: str) -> None: if self._clock() > deadline: refuse("expired") self._delivering = (target, context, deadline) + self._guard_checks, self._delivery_started = 0, self._clock() try: result = self._deliver(payload) finally: @@ -306,10 +325,33 @@ def require_current_target(self) -> None: if self._delivering is None: raise RuntimeError("keyboard delivery has no active focus lease") target, context, deadline = self._delivering - if ( - self._clock() > deadline - or _target(self._uia("focused-target", {}))["fingerprint"] - != target["fingerprint"] - or _context(self._context()) != context - ): - raise RuntimeError("keyboard target changed during delivery") + self._guard_checks += 1 + + def uncertain(reason: str) -> None: + raise KeyboardDeliveryUncertain( + reason, + self._guard_checks, + max( + 0, + min( + 3_600_000, int((self._clock() - self._delivery_started) * 1000) + ), + ), + ) + + if self._clock() > deadline: + uncertain("deadline_during_input") + try: + current = _target(self._uia("focused-target", {})) + except KeyboardLeaseError: + uncertain("focused_target_unavailable_during_input") + return + if current["fingerprint"] != target["fingerprint"]: + uncertain("focused_target_changed_during_input") + try: + current_context = _context(self._context()) + except KeyboardLeaseError: + uncertain("context_unavailable_during_input") + return + if current_context != context: + uncertain("context_changed_during_input") diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 2242134de8..5d3d570c08 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -2930,19 +2930,23 @@ def make_handler_class( keyboards = None keyboard_errors: tuple[type[Exception], ...] = () keyboard_refusals: tuple[type[Exception], ...] = () + keyboard_uncertain: tuple[type[Exception], ...] = () if config.authed(): try: from openadapt_flow.backends.win_agent.keyboard_lease import ( + KeyboardDeliveryUncertain, KeyboardLeaseController, KeyboardLeaseError, KeyboardLeaseRefused, ) except ModuleNotFoundError: from win_agent_keyboard_lease import ( # type: ignore[no-redef,import-not-found] + KeyboardDeliveryUncertain, KeyboardLeaseController, KeyboardLeaseError, KeyboardLeaseRefused, ) + keyboard_uncertain = (KeyboardDeliveryUncertain,) keyboard_errors, keyboard_refusals = ( (KeyboardLeaseError,), (KeyboardLeaseRefused,), @@ -3291,6 +3295,9 @@ def do_POST(self) -> None: # noqa: N802 - stdlib naming if kind == "context" else uia_fn(operation, data) ) + except keyboard_uncertain as exc: + self._send_json(500, exc.payload()) # type: ignore[attr-defined] + return except keyboard_refusals as exc: self._send_json(409, exc.payload()) # type: ignore[attr-defined] return @@ -3310,7 +3317,27 @@ def do_POST(self) -> None: # noqa: N802 - stdlib naming {"status": "error", "code": exc.code, "error": str(exc)}, ) return - except Exception: # noqa: BLE001 - bounded generic error, no traceback/PHI + except Exception as exc: # noqa: BLE001 - bounded generic error, no traceback/PHI + if kind == "keyboard-lease": + allowed = ( + RuntimeError, + OSError, + TypeError, + ValueError, + KeyError, + ) + self._send_json( + 500, + { + "status": "error", + "code": "keyboard_delivery_uncertain", + "reason": "unclassified_native_failure", + "failure_type": type(exc).__name__ + if type(exc) in allowed + else "Exception", + }, + ) + return self._send_json( 500, { diff --git a/packages/flow/tests/e2e/test_native_keyboard_lease.py b/packages/flow/tests/e2e/test_native_keyboard_lease.py index 8e4d9a04d8..71daa076ea 100644 --- a/packages/flow/tests/e2e/test_native_keyboard_lease.py +++ b/packages/flow/tests/e2e/test_native_keyboard_lease.py @@ -112,6 +112,7 @@ def __init__(self, backend, monkeypatch, evidence: dict[str, Any]) -> None: self.events = evidence["transport"] = [] def post(url, **kwargs): + started = time.monotonic() response = original(url, **kwargs) path = url.removeprefix(backend.server_url) if path in {"/keyboard/lease", "/keyboard/input"}: @@ -120,6 +121,7 @@ def post(url, **kwargs): "path": path, "request": _redacted(request), "http_status": response.status_code, + "elapsed_ms": int((time.monotonic() - started) * 1000), "response": _redacted(response.json()), } self.events.append(event) @@ -151,9 +153,9 @@ def _values(backend) -> dict[str, str]: def _wait_value(backend, automation_id: str, expected: str) -> None: deadline = time.monotonic() + 15 while _read(backend, automation_id) != expected: - assert ( - time.monotonic() < deadline - ), f"UIA {automation_id} did not reach {expected!r}" + assert time.monotonic() < deadline, ( + f"UIA {automation_id} did not reach {expected!r}" + ) time.sleep(0.05) @@ -390,9 +392,9 @@ def test_native_keyboard_lease_actual_delivery_and_refusal(tmp_path, monkeypatch if _sha(planted_png) != digest: (tmp_path / "planted-frame-after.png").write_bytes(planted_png) break - assert ( - time.monotonic() < deadline - ), "planted input never changed visible pixels" + assert time.monotonic() < deadline, ( + "planted input never changed visible pixels" + ) time.sleep(0.05) assert ( backend.focus_identity()["native_focus"]["target_fingerprint"] @@ -586,6 +588,12 @@ def test_native_keyboard_lease_actual_delivery_and_refusal(tmp_path, monkeypatch uncertain["after"] = {"values": _values(backend), "rows": host.rows()} evidence["passed"] = True finally: + try: + evidence["final_values"] = _values(backend) + evidence["final_context"] = backend._guard_context() + (tmp_path / "final.png").write_bytes(backend.screenshot()) + except Exception as exc: + evidence["final_field_observation_error"] = type(exc).__name__ try: evidence["rows_after"] = ( host.rows() if (tmp_path / "patients.db").exists() else None diff --git a/packages/flow/tests/test_native_keyboard_lease.py b/packages/flow/tests/test_native_keyboard_lease.py index a5b3c2c11c..596e751639 100644 --- a/packages/flow/tests/test_native_keyboard_lease.py +++ b/packages/flow/tests/test_native_keyboard_lease.py @@ -168,16 +168,30 @@ def test_malformed_keyboard_data_never_reaches_input(bad): def test_deadline_during_actual_delivery_is_uncertain_not_zero_input(): surface = Surface() + def deliver(payload): surface.calls.append(payload) surface.now = 20.0 surface.controller.require_current_target() raise AssertionError("expired delivery cannot acknowledge") + surface.controller._deliver = deliver lease = surface.controller.issue() with pytest.raises(RuntimeError) as caught: - surface.controller.deliver(lease["lease_id"], lease["frame_sha256"], {"action": "press", "keys": ["enter"]}) + surface.controller.deliver( + lease["lease_id"], + lease["frame_sha256"], + {"action": "press", "keys": ["enter"]}, + ) assert not isinstance(caught.value, KeyboardLeaseRefused) + assert caught.value.payload() == { + "status": "error", + "code": "keyboard_delivery_uncertain", + "reason": "deadline_during_input", + "guard_checks": 1, + "elapsed_ms": 20000, + } + assert "no_keyboard_input_delivered" not in caught.value.payload() assert len(surface.calls) == 1 @@ -192,10 +206,66 @@ def png(image): stream = BytesIO() image.save(stream, format="PNG") return stream.getvalue() + before = Image.new("RGB", (10, 10), "white") after = before.copy() after.putpixel((2, 3), (255, 255, 254)) assert frame_change(png(before), png(after)) == { - "changed_pixel_count": 1, "changed_bbox": [2, 3, 1, 1], "frame_size": [10, 10] + "changed_pixel_count": 1, + "changed_bbox": [2, 3, 1, 1], + "frame_size": [10, 10], } assert frame_change(png(before), png(before)) is None + + +@pytest.mark.parametrize("typed", [True, False]) +def test_http_uncertainty_diagnostics_never_attest_zero_input_or_expose_contents(typed): + import requests + + from openadapt_flow.backends.win_agent.keyboard_lease import ( + KeyboardDeliveryUncertain, + ) + from openadapt_flow.backends.win_agent.server import AgentConfig + from tests.test_win_agent_server import RunningAgent + + surface = Surface() + + def fail(payload): + surface.calls.append(payload) + if typed: + raise KeyboardDeliveryUncertain("deadline_during_input", 4, 15001) + raise TypeError("SECRET INPUT CONTENT") + + agent = RunningAgent( + AgentConfig(host="127.0.0.1", port=0, token="unit-token"), + grab_fn=lambda: PNG, + uia_fn=surface.uia, + context_fn=lambda: surface.context, + input_fn=fail, + ) + headers = {"Authorization": "Bearer unit-token"} + try: + lease = requests.post( + agent.url + "/keyboard/lease", json={}, headers=headers, timeout=2 + ).json() + response = requests.post( + agent.url + "/keyboard/input", + headers=headers, + timeout=2, + json={ + "lease_id": lease["lease_id"], + "expected_frame_sha256": lease["frame_sha256"], + "input": {"action": "press", "keys": ["enter"]}, + }, + ) + assert response.status_code == 500 + data = response.json() + assert data["code"] == "keyboard_delivery_uncertain" + assert "no_keyboard_input_delivered" not in data and "receipt" not in data + assert "SECRET" not in response.text + assert data["reason"] == ( + "deadline_during_input" if typed else "unclassified_native_failure" + ) + assert len(surface.calls) == 1 + finally: + agent.close() From 49c07d7c75a632e656888450fd8a74a42c4dd90d Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 21:53:13 -0500 Subject: [PATCH 3/8] fix(flow): bind keyboard edges without repeating desktop resolution --- .../flow/docs/design/NATIVE_KEYBOARD_LEASE.md | 7 ++- .../backends/win_agent/keyboard_lease.py | 6 ++- .../backends/win_agent/server.py | 46 +++++++++++------ .../flow/tests/test_native_focus_keyboard.py | 42 ++++++++++++++++ .../flow/tests/test_native_keyboard_lease.py | 50 +++++++++++++++++++ 5 files changed, 134 insertions(+), 17 deletions(-) diff --git a/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md b/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md index 6dc6076040..3bf88620de 100644 --- a/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md +++ b/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md @@ -15,7 +15,12 @@ An authenticated agent that advertises `native_keyboard_lease_v1` issues one application/executable/session/environment and exact PNG bytes. Issuing a lease invalidates its predecessor. Delivery consumes it before checking bindings. Unicode clipboard preparation finishes before final checks. Every physical -keyboard edge checks focus, context and the delivery deadline. Uncertain calls +keyboard edge checks actual focus twice, the current locator, RuntimeId/process, +HWND/class, bounds and hit-test, plus context and the delivery deadline. Full +locator uniqueness census remains mandatory at issuance and final pre-input +handoff. The edge check compares the already-bound runtime fingerprint; it +never re-resolves the desktop or chooses another matching control. Replacement +of a control or context during input becomes uncertain and cannot be retried. Uncertain calls release held keys and produce no positive acknowledgement. A key that intentionally changes focus can therefore be reported uncertain. diff --git a/packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py b/packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py index 58c6ec9d0a..80f153e225 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py +++ b/packages/flow/openadapt_flow/backends/win_agent/keyboard_lease.py @@ -208,6 +208,7 @@ def __init__( clock: Callable[[], float] = time.monotonic, lifetime_s: float = 15.0, prepare: Callable[[dict[str, Any]], None] | None = None, + current_focus: Callable[[], dict[str, Any]] | None = None, ) -> None: self._uia, self._capture, self._context, self._deliver = ( uia, @@ -217,6 +218,7 @@ def __init__( ) self._clock, self._lifetime_s = clock, lifetime_s self._prepare = prepare + self._current_focus = current_focus or (lambda: self._uia("focused-target", {})) self._guard_checks, self._delivery_started = 0, 0.0 self._delivering: tuple[dict[str, Any], dict[str, Any], float] | None = None self._pending: ( @@ -342,7 +344,7 @@ def uncertain(reason: str) -> None: if self._clock() > deadline: uncertain("deadline_during_input") try: - current = _target(self._uia("focused-target", {})) + current = _target(self._current_focus()) except KeyboardLeaseError: uncertain("focused_target_unavailable_during_input") return @@ -355,3 +357,5 @@ def uncertain(reason: str) -> None: return if current_context != context: uncertain("context_changed_during_input") + if self._clock() > deadline: + uncertain("deadline_during_input") diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 5d3d570c08..617fc93c85 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -991,8 +991,15 @@ def _uia_field_label(control: object) -> Optional[str]: return name or None -def _focused_target(auto: Any) -> Optional[dict[str, Any]]: - """The actual visible, uniquely named focused control, without its value.""" +def _focused_target( + auto: Any, *, verify_locator_uniqueness: bool = True +) -> Optional[dict[str, Any]]: + """Read actual focus; census at observation/handoff, runtime identity at edges. + + A lease already names one exact native runtime element. Per-edge checks + re-read focus twice, locator, RuntimeId/process/HWND/class, bounds and hit + test. They do not resolve a locator again or choose a replacement target. + """ try: focused = auto.GetFocusedControl() except Exception: # noqa: BLE001 - no observation, no target evidence @@ -1011,17 +1018,20 @@ def _focused_target(auto: Any) -> Optional[dict[str, Any]]: candidate = _candidate(target) if candidate is None: return None - locator = { - key: candidate.get(key) - for key in ("automation_id", "role", "name", "window_name") - } - found, truncated = _find_candidates(locator, auto) - if ( - truncated - or len(found) != 1 - or not hmac.compare_digest(found[0][1]["fingerprint"], candidate["fingerprint"]) - ): - return None + if verify_locator_uniqueness: + locator = { + key: candidate.get(key) + for key in ("automation_id", "role", "name", "window_name") + } + found, truncated = _find_candidates(locator, auto) + if ( + truncated + or len(found) != 1 + or not hmac.compare_digest( + found[0][1]["fingerprint"], candidate["fingerprint"] + ) + ): + return None if not _hits_target(auto, target, candidate): return None # Focus may change while enumerating the tree: the second live read must @@ -1636,9 +1646,14 @@ def _perform_uia_initialized( locator = None return {"status": "ok", "locator": locator} - if operation == "focused-target": + if operation in {"focused-target", "focused-runtime-target"}: _exact_object(payload, label=operation) - return {"status": "ok", "target": _focused_target(auto)} + return { + "status": "ok", + "target": _focused_target( + auto, verify_locator_uniqueness=operation == "focused-target" + ), + } if operation == "focused-field-label": _exact_object(payload, required=frozenset(), label=operation) @@ -2968,6 +2983,7 @@ def deliver_keyboard(data: dict[str, Any]) -> dict[str, Any]: context_fn, deliver_keyboard, prepare=_prepare_keyboard_input if input_fn is _perform_input else None, + current_focus=lambda: uia_fn("focused-runtime-target", {}), ) class AgentHandler(BaseHTTPRequestHandler): diff --git a/packages/flow/tests/test_native_focus_keyboard.py b/packages/flow/tests/test_native_focus_keyboard.py index e68a83ab93..097cfaa431 100644 --- a/packages/flow/tests/test_native_focus_keyboard.py +++ b/packages/flow/tests/test_native_focus_keyboard.py @@ -340,3 +340,45 @@ def __deepcopy__(self, _memo): event = json.loads((recording / "events.jsonl").read_text().splitlines()[0]) assert "focus_before" not in event assert backend.calls == [("key", "Enter")] + + +def test_edge_probe_rechecks_actual_fingerprint_and_hit_test_without_locator_search( + monkeypatch, +): + from openadapt_flow.backends.win_agent import server + + auto, first = focused_auto() + admitted = _focused_target(auto) + + def forbidden(*args): + raise AssertionError("an input edge cannot resolve a locator again") + + monkeypatch.setattr(server, "_find_candidates", forbidden) + + def read(): + return _perform_uia_initialized(auto, "focused-runtime-target", {})["target"] + + assert read() == admitted + first.runtime_id = (9, 9) + assert read()["fingerprint"] != admitted["fingerprint"] + first.runtime_id = (1, 2) + first.BoundingRectangle.left += 1 + assert read()["fingerprint"] != admitted["fingerprint"] + auto.ControlFromPoint = lambda *_: _FakeControl("ButtonControl", runtime_id=(8, 8)) + assert read() is None + + +def test_edge_probe_refuses_focus_replacement_during_its_double_read(): + auto, first = focused_auto() + other = _FakeControl( + "EditControl", + automation_id="entry", + name="Entry", + runtime_id=(9, 9), + bounds=(400, 200, 800, 300), + ) + reads = iter([first, other]) + auto.GetFocusedControl = lambda: next(reads) + assert ( + _perform_uia_initialized(auto, "focused-runtime-target", {})["target"] is None + ) diff --git a/packages/flow/tests/test_native_keyboard_lease.py b/packages/flow/tests/test_native_keyboard_lease.py index 596e751639..ef4ca22ec5 100644 --- a/packages/flow/tests/test_native_keyboard_lease.py +++ b/packages/flow/tests/test_native_keyboard_lease.py @@ -269,3 +269,53 @@ def fail(payload): assert len(surface.calls) == 1 finally: agent.close() + + +@pytest.mark.parametrize("change", ["runtime_target", "context", "deadline"]) +def test_handoff_census_and_edge_observation_share_one_bound_identity(change): + from openadapt_flow.backends.win_agent.keyboard_lease import ( + KeyboardDeliveryUncertain, + ) + from openadapt_flow.backends.win_agent.server import _delivery_receipt + + surface = Surface() + full, edges = [], [] + + def census(operation, data): + full.append(operation) + return surface.uia(operation, data) + + def current(): + edges.append(True) + return surface.uia("focused-target", {}) + + def deliver(payload): + surface.calls.append(payload) + surface.controller.require_current_target() + if change == "runtime_target": + surface.target["fingerprint"] = "f" * 64 + elif change == "context": + surface.context["session"] = "f" * 64 + else: + surface.now = 20 + surface.controller.require_current_target() + return _delivery_receipt("physical_press", native=False) + + surface.controller = KeyboardLeaseController( + census, + lambda: PNG, + lambda: dict(surface.context), + deliver, + clock=lambda: surface.now, + current_focus=current, + ) + lease = surface.controller.issue() + with pytest.raises(KeyboardDeliveryUncertain) as error: + surface.controller.deliver( + lease["lease_id"], + lease["frame_sha256"], + {"action": "press", "keys": ["enter"]}, + ) + assert full == ["focused-target"] * 3 + assert len(surface.calls) == 1 and edges + assert "no_keyboard_input_delivered" not in error.value.payload() From b2362c225a0d977be0738132505089d5d78cdb5b Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 22:22:38 -0500 Subject: [PATCH 4/8] fix(flow): retain exact native keyboard values and authorized input frames --- .github/workflows/desktop-replay.yml | 53 ++- .../flow/docs/design/NATIVE_KEYBOARD_LEASE.md | 20 + .../backends/win_agent/server.py | 120 ++++- .../backends/windows_backend.py | 25 ++ .../backends/windows_keyboard_lease.py | 60 +++ .../runtime/keyboard_delivery.py | 18 +- .../tests/e2e/test_native_keyboard_lease.py | 411 +++++++++++++++++- .../flow/tests/test_native_editable_value.py | 149 +++++++ .../flow/tests/test_native_keyboard_retry.py | 90 ++++ 9 files changed, 932 insertions(+), 14 deletions(-) create mode 100644 packages/flow/tests/test_native_editable_value.py diff --git a/.github/workflows/desktop-replay.yml b/.github/workflows/desktop-replay.yml index e6e1f18350..3aa2fd6b50 100644 --- a/.github/workflows/desktop-replay.yml +++ b/.github/workflows/desktop-replay.yml @@ -110,7 +110,7 @@ jobs: } | tee "$RUNNER_TEMP/nkl/source.log" test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA" pytest -v -rs -p no:cacheprovider --basetemp="$RUNNER_TEMP/nkl/cases" \ - tests/e2e/test_native_keyboard_lease.py \ + tests/e2e/test_native_keyboard_lease.py::test_native_keyboard_lease_actual_delivery_and_refusal \ --junitxml="$RUNNER_TEMP/nkl/junit.xml" 2>&1 | tee "$RUNNER_TEMP/nkl/pytest.log" python - <<'PYTHON' import json @@ -131,6 +131,45 @@ jobs: assert proof["rows_before"] == proof["rows_after"] print(json.dumps({"native_lease_cases": len(expected), "skipped": 0, "rows_unchanged": True})) PYTHON + - name: Exact editable values and bounded runtime TYPE retry + timeout-minutes: 6 + env: + OAFLOW_WINDOWS_HOSTED_E2E: "1" + OAFLOW_NATIVE_EDITABLE_VALUE_EVIDENCE: ${{ runner.temp }}/nkl-editable/evidence.json + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/nkl-editable" + { + git rev-parse HEAD + git rev-parse "HEAD^{tree}" + printf 'expected=%s run=%s attempt=%s\n' "$EXPECTED_SOURCE_SHA" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" + } | tee "$RUNNER_TEMP/nkl-editable/source.log" + test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA" + pytest -v -rs -p no:cacheprovider --basetemp="$RUNNER_TEMP/nkl-editable/cases" \ + tests/e2e/test_native_keyboard_lease.py::test_native_editable_values_and_runtime_type_retry \ + --junitxml="$RUNNER_TEMP/nkl-editable/junit.xml" 2>&1 | tee "$RUNNER_TEMP/nkl-editable/pytest.log" + python - <<'PYTHON' + import json + import os + from pathlib import Path + import xml.etree.ElementTree as ET + root = Path(os.environ["RUNNER_TEMP"]) / "nkl-editable" + cases = list(ET.parse(root / "junit.xml").getroot().iter("testcase")) + assert len(cases) == 1 + assert cases[0].get("name") == "test_native_editable_values_and_runtime_type_retry" + assert not any(cases[0].find(tag) is not None for tag in ("skipped", "failure", "error")) + proof = json.loads((root / "evidence.json").read_text()) + assert proof["head"] == os.environ["EXPECTED_SOURCE_SHA"] + assert proof["passed"] is True and proof["agent_terminated"] is True and proof["fixture_terminated"] is True + assert proof["rows_before"] == proof["rows_after"] + assert len(proof["observations"]) == 8 + assert len(proof["runtime"]) == 2 and {case["case"] for case in proof["runtime"]} == {"success", "uncertain"} + for case in proof["runtime"]: + assert case["planted"] and case["input_attempts"][0]["response"]["no_keyboard_input_delivered"] is True + assert case["retained_attempt_frame_sha256"] == case["input_attempts"][-1]["request"]["expected_frame_sha256"] + assert case["rows_after"] == proof["rows_before"] + print(json.dumps({"editable_observation_cases": 8, "runtime_type_cases": 2, "skipped": 0, "rows_unchanged": True})) + PYTHON - name: Record, compile and replay, judged from the record env: OAFLOW_WINDOWS_HOSTED_E2E: "1" @@ -186,6 +225,18 @@ jobs: path: | ${{ runner.temp }}/windows-replay-evidence.json ${{ runner.temp }}/windows-governed-evidence.json + ${{ runner.temp }}/nkl-editable/*.json + ${{ runner.temp }}/nkl-editable/*.xml + ${{ runner.temp }}/nkl-editable/*.log + ${{ runner.temp }}/nkl-editable/cases/**/*.png + ${{ runner.temp }}/nkl-editable/cases/**/editable-value-evidence.json + ${{ runner.temp }}/nkl-editable/cases/**/agent.log + ${{ runner.temp }}/nkl-editable/cases/**/patient_notes.ps1 + ${{ runner.temp }}/nkl-editable/cases/**/patients.db + ${{ runner.temp }}/nkl-editable/cases/**/report.json + ${{ runner.temp }}/nkl-editable/cases/**/runtime-recording/*.json + ${{ runner.temp }}/nkl-editable/cases/**/runtime-recording/*.jsonl + ${{ runner.temp }}/nkl-editable/cases/**/runtime-bundle/workflow.json ${{ runner.temp }}/nkl/*.json ${{ runner.temp }}/nkl/*.xml ${{ runner.temp }}/nkl/*.log diff --git a/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md b/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md index 3bf88620de..131cea0ac1 100644 --- a/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md +++ b/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md @@ -37,6 +37,10 @@ field baseline for text. Effectful, API-bound and irreversible actions do not use this retry. The earlier focusing click is never repeated. Exact PNG equality still gates delivery; no caret or focus pixels are ignored. Reports retain the refused lease hash, geometry and keyboard phase through checkpoint/resume. +The report before-frame is saved from the actual authorized keyboard frame +immediately before each input attempt, including the first attempt and an +uncertain acknowledgement after partial delivery. Earlier focusing observations +do not stand in for that later input boundary. ## Evidence and limits @@ -53,3 +57,19 @@ is temporal attribution of keyboard input across all native entry points. Same-form replacement, replay and lost acknowledgement are held-out cases beyond the unreceipted Enter/stale-frame campaign failures that motivated the work. This advances independently verifiable action receipts and refusal evidence. + +## Exact editable-value observation + +`text_value_at` and `focused_text_value` use one complete ValuePattern contract +at `/uia/editable-value`. A readable empty string is a value. Password or unknown +password state, read-only or unknown editability, missing/ambiguous focus, +replacement, changed value and oversized values refuse. No accessible Name, +MSAA value, normalized text or truncated prefix substitutes for the exact +value. Both value reads are bounded by actual focus/runtime fingerprint and +geometry/hit-test observations. Current observed, armed and consumed keyboard +bindings remain authoritative for the read-back. This supplies the unchanged +baseline required by bounded zero-input retries; unknown stays a refusal. + +The full-value/empty semantics match the separately reviewed approval projection +in #2291. Its helper is not on this branch's base; merge integration should reuse +a shared helper without importing that whole held approval change here. diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 617fc93c85..3001ee6f7f 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -991,9 +991,9 @@ def _uia_field_label(control: object) -> Optional[str]: return name or None -def _focused_target( +def _focused_target_control( auto: Any, *, verify_locator_uniqueness: bool = True -) -> Optional[dict[str, Any]]: +) -> Optional[tuple[object, dict[str, Any]]]: """Read actual focus; census at observation/handoff, runtime identity at edges. A lease already names one exact native runtime element. Per-edge checks @@ -1051,7 +1051,118 @@ def _focused_target( latest["fingerprint"], candidate["fingerprint"] ): return None - return candidate + return target, candidate + + +def _focused_target( + auto: Any, *, verify_locator_uniqueness: bool = True +) -> Optional[dict[str, Any]]: + observed = _focused_target_control( + auto, verify_locator_uniqueness=verify_locator_uniqueness + ) + return observed[1] if observed is not None else None + + +def _complete_editable_value(control: object) -> tuple[Optional[str], Optional[str]]: + """Full ValuePattern observation; empty is readable, never Name/MSAA. + + This shares #2291's full exact ValuePattern/empty-vs-unavailable contract. + Editable input additionally requires observed non-password/non-read-only. + """ + if _control_value(control, "IsPassword", None) is not False: + return None, "password_or_password_status_unavailable" + if _control_value(control, "ControlTypeName", None) != "EditControl": + return None, "not_editable_value_control" + method = _control_value(control, "GetValuePattern", None) + if not callable(method): + return None, "value_pattern_unavailable" + try: + pattern = method() + if getattr(pattern, "IsReadOnly", None) is not False: + return None, "read_only_or_read_only_status_unavailable" + value = getattr(pattern, "Value", None) + except Exception: + return None, "value_unavailable" + if _control_value(control, "IsPassword", None) is not False: + return None, "password_or_password_status_unavailable" + try: + still_editable = getattr(pattern, "IsReadOnly", None) is False + except Exception: + still_editable = False + if not still_editable: + return None, "read_only_or_read_only_status_unavailable" + if not isinstance(value, str): + return None, "value_unavailable" + if len(value) > _MAX_TEXT_CHARS: + return None, "value_exceeds_limit" + return value, None + + +def _editable_value_observation(auto: Any, payload: dict[str, Any]) -> dict[str, Any]: + data = _exact_object( + payload, + optional=frozenset({"x", "y", "expected_fingerprint"}), + label="editable-value", + ) + if ("x" in data) != ("y" in data): + raise AgentRequestError( + 400, "invalid_schema", "editable value point requires x and y" + ) + point = ( + (_bounded_int(data["x"], "x"), _bounded_int(data["y"], "y")) + if "x" in data + else None + ) + expected = data.get("expected_fingerprint") + if expected is not None and ( + not isinstance(expected, str) or not re.fullmatch(r"[a-f0-9]{64}", expected) + ): + raise AgentRequestError( + 400, "invalid_schema", "editable value binding requires exact fingerprint" + ) + + def unavailable(reason: str) -> dict[str, Any]: + return {"status": "unavailable", "complete": False, "reason": reason} + + observed = _focused_target_control(auto) + if observed is None: + return unavailable("focused_target_unavailable_or_ambiguous") + control, candidate = observed + fingerprint = candidate["fingerprint"] + if expected is not None and not hmac.compare_digest(expected, fingerprint): + return unavailable("bound_target_changed") + left, top, right, bottom = candidate["bounds"] + if point is not None and not ( + left <= point[0] < right and top <= point[1] < bottom + ): + return unavailable("point_outside_focused_target") + value, reason = _complete_editable_value(control) + if reason is not None: + return unavailable(reason) + # Do not re-resolve a locator into another object. Re-read actual focus, + # runtime identity, geometry/hit-test and the same full value. + after = _focused_target_control(auto, verify_locator_uniqueness=False) + if after is None or not hmac.compare_digest(after[1]["fingerprint"], fingerprint): + return unavailable("observation_changed") + after_value, reason = _complete_editable_value(after[0]) + if reason is not None: + return unavailable(reason) + final = _focused_target_control(auto, verify_locator_uniqueness=False) + if ( + after_value != value + or final is None + or not hmac.compare_digest(final[1]["fingerprint"], fingerprint) + ): + return unavailable("observation_changed") + return { + "status": "ok", + "schema": "openadapt.native-editable-value/v1", + "complete": True, + "value": value, + "target_fingerprint": fingerprint, + "bounds": candidate["bounds"], + "point": candidate["point"], + } def _focused_field_label(auto: Any) -> Optional[str]: @@ -1554,6 +1665,8 @@ def _perform_uia_initialized( auto: Any, operation: str, payload: dict[str, Any] ) -> dict[str, Any]: """Perform one typed UIA operation in an initialized COM apartment.""" + if operation == "editable-value": + return _editable_value_observation(auto, payload) if operation == "authoring-tree": _exact_object(payload, label=operation) return _authoring_tree(auto) @@ -3089,6 +3202,7 @@ def do_POST(self) -> None: # noqa: N802 - stdlib naming "/window/bounds": ("uia", "window-bounds"), "/uia/text-at-point": ("uia", "text-at-point"), "/uia/focused-field-label": ("uia", "focused-field-label"), + "/uia/editable-value": ("uia", "editable-value"), "/uia/focused-target": ("uia", "focused-target"), "/uia/identity-candidates-at": ("uia", "identity-candidates-at"), "/uia/find": ("uia", "find"), diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index c551437ec8..12c254978f 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -1756,6 +1756,31 @@ def drag_guarded( ) return self._guarded_receipt(response, "physical_drag") + def editable_value_observation( + self, x: int | None = None, y: int | None = None + ) -> dict[str, Any] | None: + """Exact non-password editable value from the bound actual native focus. + + Empty is observed. Missing/ambiguous/unreadable/changed values are None; + this never substitutes an accessible Name or a truncated prefix. + """ + if (x is None) != (y is None): + return None + leases = self._focused_keyboard_leases() + if leases is None: + return None + return leases.editable_value_observation( + (int(x), int(y)) if x is not None and y is not None else None + ) + + def text_value_at(self, x: int, y: int) -> Optional[str]: + observed = self.editable_value_observation(x, y) + return observed["value"] if observed is not None else None + + def focused_text_value(self) -> Optional[str]: + observed = self.editable_value_observation() + return observed["value"] if observed is not None else None + def native_keyboard_lease_available(self) -> bool: return self._focused_keyboard_leases() is not None diff --git a/packages/flow/openadapt_flow/backends/windows_keyboard_lease.py b/packages/flow/openadapt_flow/backends/windows_keyboard_lease.py index 258915bcec..f65f931993 100644 --- a/packages/flow/openadapt_flow/backends/windows_keyboard_lease.py +++ b/packages/flow/openadapt_flow/backends/windows_keyboard_lease.py @@ -31,12 +31,71 @@ def __init__( self._post, self._before_input = post, before_input self._observed: dict[str, Any] | None = None self._armed: dict[str, Any] | None = None + self._last_target_fingerprint: str | None = None def target_fingerprint(self) -> str | None: return self._armed["target"]["fingerprint"] if self._armed else None + def editable_value_observation( + self, point: tuple[int, int] | None = None + ) -> dict[str, Any] | None: + expected = ( + self.target_fingerprint() + or (self._observed["target"]["fingerprint"] if self._observed else None) + or self._last_target_fingerprint + ) + payload: dict[str, Any] = ( + {"expected_fingerprint": expected} if expected is not None else {} + ) + if point is not None: + payload.update(x=point[0], y=point[1]) + try: + response = self._post("/uia/editable-value", payload) + data = response.json() + if ( + response.status_code != 200 + or not isinstance(data, dict) + or set(data) + != { + "status", + "schema", + "complete", + "value", + "target_fingerprint", + "bounds", + "point", + } + or data["status"] != "ok" + or data["schema"] != "openadapt.native-editable-value/v1" + or data["complete"] is not True + or not isinstance(data["value"], str) + or len(data["value"]) > 65536 + ): + return None + target = _target( + { + "status": "ok", + "target": { + "fingerprint": data["target_fingerprint"], + "bounds": data["bounds"], + "point": data["point"], + }, + } + ) + if expected is not None and target["fingerprint"] != expected: + return None + left, top, right, bottom = target["bounds"] + if point is not None and not ( + left <= point[0] < right and top <= point[1] < bottom + ): + return None + return data + except Exception: + return None + def cancel(self) -> None: self._observed = self._armed = None + self._last_target_fingerprint = None def frame(self) -> bytes: self.cancel() @@ -104,6 +163,7 @@ def deliver( "native keyboard input has no armed lease" ) operation = keyboard_operation(payload) + self._last_target_fingerprint = lease["target"]["fingerprint"] self._before_input() try: response = self._post( diff --git a/packages/flow/openadapt_flow/runtime/keyboard_delivery.py b/packages/flow/openadapt_flow/runtime/keyboard_delivery.py index c7b8fc74e4..0c2e50c383 100644 --- a/packages/flow/openadapt_flow/runtime/keyboard_delivery.py +++ b/packages/flow/openadapt_flow/runtime/keyboard_delivery.py @@ -135,14 +135,6 @@ def revalidate(exc: KeyboardFrameChangedBeforeInput) -> bool: ) resolution, frame = fresh, png result.resolution = fresh - evidence_step_id = ( - Path(result.before_png).name.removesuffix("_before.png") - if result.before_png - else step.id - ) - result.before_png = replay._save_step_png( - run_dir, evidence_step_id, "before", png - ) return True def deliver() -> ActionDeliveryReceipt: @@ -153,6 +145,16 @@ def deliver() -> ActionDeliveryReceipt: if refusal is not None: raise StructuralResolutionRefused(refusal) replay._require_qualification_environment_current() + # This frame authorizes this keyboard attempt, including an uncertain + # acknowledgement. A focusing click may have changed the earlier frame. + evidence_step_id = ( + Path(result.before_png).name.removesuffix("_before.png") + if result.before_png + else step.id + ) + result.before_png = replay._save_step_png( + run_dir, evidence_step_id, "before", frame + ) return replay._deliver_backend_call( result, lambda: call(hashlib.sha256(frame).hexdigest()) ) diff --git a/packages/flow/tests/e2e/test_native_keyboard_lease.py b/packages/flow/tests/e2e/test_native_keyboard_lease.py index 71daa076ea..eadbed7616 100644 --- a/packages/flow/tests/e2e/test_native_keyboard_lease.py +++ b/packages/flow/tests/e2e/test_native_keyboard_lease.py @@ -8,6 +8,7 @@ from __future__ import annotations +import base64 import copy import hashlib import json @@ -109,13 +110,18 @@ def __init__(self, backend, monkeypatch, evidence: dict[str, Any]) -> None: self.last_input: dict[str, Any] | None = None self.drop_next_ack = False self.inputs = 0 + self.before_keyboard_input = None + self.lease_evidence_dir: Path | None = None self.events = evidence["transport"] = [] def post(url, **kwargs): started = time.monotonic() - response = original(url, **kwargs) path = url.removeprefix(backend.server_url) - if path in {"/keyboard/lease", "/keyboard/input"}: + planted = None + if path == "/keyboard/input" and self.before_keyboard_input is not None: + planted = self.before_keyboard_input(copy.deepcopy(kwargs["json"])) + response = original(url, **kwargs) + if path in {"/keyboard/lease", "/keyboard/input", "/uia/editable-value"}: request = kwargs["json"] event = { "path": path, @@ -124,6 +130,21 @@ def post(url, **kwargs): "elapsed_ms": int((time.monotonic() - started) * 1000), "response": _redacted(response.json()), } + if planted is not None: + event["planted_fixture_change"] = planted + if ( + path == "/keyboard/lease" + and response.status_code == 200 + and self.lease_evidence_dir is not None + ): + self.lease_evidence_dir.mkdir(parents=True, exist_ok=True) + destination = ( + self.lease_evidence_dir / f"lease-{len(self.events):04d}.png" + ) + png = base64.b64decode(response.json()["frame_png"], validate=True) + destination.write_bytes(png) + event["retained_frame"] = str(destination) + event["retained_frame_sha256"] = _sha(png) self.events.append(event) if path == "/keyboard/input": self.inputs += 1 @@ -618,3 +639,389 @@ def test_native_keyboard_lease_actual_delivery_and_refusal(tmp_path, monkeypatch ): destination.parent.mkdir(parents=True, exist_ok=True) destination.write_text(json.dumps(evidence, indent=2) + "\n") + + +# Additional controls and repaint commands exist only in this proof's copied +# synthetic app. None carries a save handler or changes the SQLite record. +OBSERVATION_HOOK = r""" +$form.Size = New-Object System.Drawing.Size(960, 560) +$leaseFields = @{} +function Add-LeaseField($id, $y, $text, $password, $readOnly) { + $box = New-Object System.Windows.Forms.TextBox + $box.Name = $id + $box.AccessibleName = $id + $box.Location = New-Object System.Drawing.Point(650, $y) + $box.Size = New-Object System.Drawing.Size(180, 24) + $box.MaxLength = 100000 + $box.UseSystemPasswordChar = $password + $box.ReadOnly = $readOnly + $box.Text = $text + $form.Controls.Add($box) + $script:leaseFields[$id + '-' + $y] = $box +} +Add-LeaseField "leasePassword" 100 "synthetic password fixture" $true $false +Add-LeaseField "leaseLong" 140 (('x' * 8192) + '-END') $false $false +Add-LeaseField "leaseOversized" 180 ('x' * 65537) $false $false +Add-LeaseField "leaseReadOnly" 220 "read only synthetic fixture" $false $true +Add-LeaseField "leaseDuplicate" 260 "first duplicate" $false $false +Add-LeaseField "leaseDuplicate" 300 "second duplicate" $false $false +$leaseButton = New-Object System.Windows.Forms.Button +$leaseButton.Name = "leaseNotEditable" +$leaseButton.AccessibleName = "Display name must not become a value" +$leaseButton.Text = "Display name must not become a value" +$leaseButton.Location = New-Object System.Drawing.Point(650, 340) +$leaseButton.Size = New-Object System.Drawing.Size(250, 30) +$form.Controls.Add($leaseButton) +$leaseFields['button'] = $leaseButton +$form.Add_Shown({ + $points = @{} + foreach ($key in $script:leaseFields.Keys) { + $control = $script:leaseFields[$key] + $p = $control.PointToScreen((New-Object System.Drawing.Point([int]($control.Width / 2), [int]($control.Height / 2)))) + $points[$key] = @($p.X, $p.Y) + } + $temporary = Join-Path $PSScriptRoot 'lease-observation-points.tmp' + [IO.File]::WriteAllText($temporary, ($points | ConvertTo-Json)) + [IO.File]::Move($temporary, (Join-Path $PSScriptRoot 'lease-observation-points.json')) +}) +$leaseObservationTimer = New-Object System.Windows.Forms.Timer +$leaseObservationTimer.Interval = 40 +$leaseObservationTimer.Add_Tick({ + $commandPath = Join-Path $PSScriptRoot 'lease-observation-command' + if (-not (Test-Path $commandPath)) { return } + $command = [IO.File]::ReadAllText($commandPath) + Remove-Item $commandPath + switch ($command) { + 'clear-note' { $script:noteBox.Text = ''; [void]$script:noteBox.Focus(); $script:noteBox.SelectionStart = 0 } + 'paint-success' { $script:status.Text = 'Synthetic lease repaint success' } + 'paint-uncertain' { $script:status.Text = 'Synthetic lease repaint uncertain' } + default { throw 'Unknown observation fixture command' } + } + $ack = @{ command=$command; note_value=$script:noteBox.Text; status=$script:status.Text; + form_handle=$form.Handle.ToInt64(); note_handle=$script:noteBox.Handle.ToInt64() } + $temporary = Join-Path $PSScriptRoot 'lease-observation-ack.tmp' + [IO.File]::WriteAllText($temporary, ($ack | ConvertTo-Json)) + [IO.File]::Move($temporary, (Join-Path $PSScriptRoot 'lease-observation-ack.json')) +}) +$leaseObservationTimer.Start() +""" + + +def _fixture_command(root: Path, command: str) -> dict[str, Any]: + acknowledgement = root / "lease-observation-ack.json" + acknowledgement.unlink(missing_ok=True) + temporary = root / "lease-observation-command.tmp" + temporary.write_text(command) + temporary.replace(root / "lease-observation-command") + deadline = time.monotonic() + 10 + while not acknowledgement.is_file(): + assert time.monotonic() < deadline, f"fixture command {command} timed out" + time.sleep(0.05) + result = json.loads(acknowledgement.read_text(encoding="utf-8-sig")) + assert result["command"] == command + return result + + +def _editable_positive(backend, transport, aid, point, expected): + backend.click(*point) + handle = backend.locate_structural(StructuralLocator(automation_id=aid)) + assert handle is not None and handle.candidate_count == 1 + observed = backend.editable_value_observation(*point) + assert observed is not None + assert observed == { + "status": "ok", + "schema": "openadapt.native-editable-value/v1", + "complete": True, + "value": expected, + "target_fingerprint": handle.target_fingerprint, + "bounds": [ + handle.region[0], + handle.region[1], + handle.region[0] + handle.region[2], + handle.region[1] + handle.region[3], + ], + "point": list(handle.point), + } + assert backend.text_value_at(*point) == expected + assert backend.focused_text_value() == expected + wire = [ + event for event in transport.events if event["path"] == "/uia/editable-value" + ][-3:] + assert len(wire) == 3 and all(event["response"] == observed for event in wire) + return { + "case": aid, + "length": len(expected), + "value_sha256": _sha(expected.encode()), + "observation": observed, + } + + +def test_native_editable_values_and_runtime_type_retry(tmp_path, monkeypatch): + """Exact values enable only a fully revalidated, zero-input TYPE retry.""" + from openadapt_flow.compiler import compile_recording + from openadapt_flow.ir import Workflow + from openadapt_flow.recorder import Recorder + from openadapt_flow.runtime import Replayer + + evidence: dict[str, Any] = { + "schema": "openadapt.native-editable-runtime-proof/v1", + "head": subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=REPOSITORY, text=True + ).strip(), + "tree": subprocess.check_output( + ["git", "rev-parse", "HEAD^{tree}"], cwd=REPOSITORY, text=True + ).strip(), + "run_id": os.environ.get("GITHUB_RUN_ID"), + "observations": [], + "runtime": [], + } + host = _Host(tmp_path) + app = tmp_path / "patient_notes.ps1" + source = app.read_text() + assert source.count("[void]$form.ShowDialog()") == 1 + app.write_text( + source.replace( + "[void]$form.ShowDialog()", OBSERVATION_HOOK + "\n[void]$form.ShowDialog()" + ) + ) + evidence["fixture_sha256"] = _sha(app.read_bytes()) + try: + backend = host.start_agent() + evidence["capabilities"] = sorted(backend.agent_capabilities()) + assert "native_editable_value_v1" in evidence["capabilities"] + transport = _Transport(backend, monkeypatch, evidence) + transport.lease_evidence_dir = tmp_path / "runtime-lease-frames" + host.launch_app() + points = _points(backend) + positions = tmp_path / "lease-observation-points.json" + deadline = time.monotonic() + 15 + while not positions.is_file(): + assert time.monotonic() < deadline, "observation fixture did not start" + time.sleep(0.05) + extras = json.loads(positions.read_text(encoding="utf-8-sig")) + baseline = evidence["rows_before"] = host.rows() + target = next(row for row in baseline if row["id"] == 1) + header = f"Patient: {target['first']} {target['last']} ({target['dob']})" + backend.click(*points["searchBox"]) + backend.type_text(target["first"]) + backend.press("enter") + _wait_value(backend, "patientHeader", header) + evidence["observations"].append( + _editable_positive(backend, transport, "noteBox", points["noteBox"], "") + ) + exact = " exact café value " + backend.type_text(exact) + _wait_value(backend, "noteBox", exact) + evidence["observations"].append( + _editable_positive(backend, transport, "noteBox", points["noteBox"], exact) + ) + evidence["observations"].append( + _editable_positive( + backend, + transport, + "leaseLong", + extras["leaseLong-140"], + "x" * 8192 + "-END", + ) + ) + + unavailable_reasons = { + "leasePassword-100": "password_or_password_status_unavailable", + "leaseOversized-180": "value_exceeds_limit", + "leaseReadOnly-220": "read_only_or_read_only_status_unavailable", + "leaseDuplicate-260": "focused_target_unavailable_or_ambiguous", + "button": "not_editable_value_control", + } + for name, reason in unavailable_reasons.items(): + point = extras[name] + backend.click(*point) + assert backend.editable_value_observation(*point) is None + assert backend.text_value_at(*point) is None + assert backend.focused_text_value() is None + wire = [ + event + for event in transport.events + if event["path"] == "/uia/editable-value" + ][-3:] + assert len(wire) == 3 + for event in wire: + raw = event["response"] + assert event["http_status"] == 200 + assert set(raw) == {"status", "complete", "reason"} + assert raw["status"] == "unavailable" and raw["complete"] is False + assert raw["reason"] == reason + evidence["observations"].append({"case": name, "unavailable": wire}) + assert host.rows() == baseline + + # This is a real observed demonstration. The operator-selected record + # header comes from its actual UIA bounds on the captured before frame. + _fixture_command(tmp_path, "clear-note") + header_handle = backend.locate_structural( + StructuralLocator(automation_id="patientHeader") + ) + assert header_handle is not None + assert _read(backend, "patientHeader") == header + text = "lease runtime" + recorder = Recorder(backend, tmp_path / "runtime-recording") + before_png = backend.screenshot() + before_focus = backend.focus_identity() + assert before_focus is not None + backend.type_text(text) + _wait_value(backend, "noteBox", text) + after_focus = backend.focus_identity() + recorder.record_observed( + { + "kind": "type", + "text": text, + "focus_before": before_focus, + "focus_after": after_focus, + "identifier_region": list(header_handle.region), + }, + before_png=before_png, + after_png=backend.screenshot(), + structural_before={}, + ) + recording = recorder.finish() + bundle = tmp_path / "runtime-bundle" + workflow = compile_recording(recording, bundle, name="native-editable-runtime") + assert len(workflow.steps) == 1 + step = workflow.steps[0] + assert step.action.value == "type" and step.risk == "reversible" + assert ( + step.anchor is not None + and step.identity_armed + and step.anchor.identifier_crop + ) + assert step.anchor.structural.automation_id == "noteBox" + assert not step.effects and step.api_binding is None + + for outcome in ("success", "uncertain"): + _fixture_command(tmp_path, "clear-note") + assert backend.text_value_at(*points["noteBox"]) == "" + assert backend.focused_text_value() == "" + assert _read(backend, "patientHeader") == header and host.rows() == baseline + case: dict[str, Any] = {"case": outcome, "planted": []} + evidence["runtime"].append(case) + start = len(transport.events) + + def repaint_once(request): + if case["planted"]: + return None + expected = request["expected_frame_sha256"] + ack = _fixture_command(tmp_path, "paint-" + outcome) + assert ack["note_value"] == "" + planted_png = backend.screenshot() + assert _sha(planted_png) != expected + destination = tmp_path / f"runtime-{outcome}-planted.png" + destination.write_bytes(planted_png) + planted = { + "ack": ack, + "frame_sha256": _sha(planted_png), + "frame": str(destination), + } + case["planted"].append(planted) + return planted + + transport.before_keyboard_input = repaint_once + transport.drop_next_ack = outcome == "uncertain" + run_dir = tmp_path / f"runtime-{outcome}" + report = Replayer(backend, use_structural=True).run( + Workflow.load(bundle), + bundle_dir=bundle, + run_dir=run_dir, + ) + transport.before_keyboard_input = None + case["report"] = report.model_dump(mode="json") + assert len(report.results) == 1 + result = report.results[0] + events = transport.events[start:] + inputs = [event for event in events if event["path"] == "/keyboard/input"] + case["input_attempts"] = inputs + assert 2 <= len(inputs) <= 3 + assert inputs[0]["http_status"] == 409 + assert inputs[0]["response"]["reason"] == "stale_frame" + assert inputs[0]["response"]["no_keyboard_input_delivered"] is True + assert inputs[0]["planted_fixture_change"] == case["planted"][0] + accepted = [event for event in inputs if event["http_status"] == 200] + assert len(accepted) == 1 and inputs[-1] is accepted[0] + for refused in inputs[:-1]: + assert refused["response"]["no_keyboard_input_delivered"] is True + assert result.fresh_actuation_events + assert all( + event.phase == "keyboard" and event.retried + for event in result.fresh_actuation_events + ) + actual = accepted[0] + receipt = ActionDeliveryReceipt.model_validate( + actual["response"]["receipt"] + ) + assert receipt.operation == "physical_type_text" and receipt.native is False + assert backend.text_value_at(*points["noteBox"]) == text + assert backend.focused_text_value() == text + assert _read(backend, "patientHeader") == header and host.rows() == baseline + assert result.before_png is not None + retained = run_dir / result.before_png + assert retained.is_file() + assert ( + _sha(retained.read_bytes()) + == actual["request"]["expected_frame_sha256"] + ) + frames = [ + event + for event in transport.events + if event["path"] == "/keyboard/lease" + and event.get("retained_frame_sha256") + == actual["request"]["expected_frame_sha256"] + ] + assert ( + frames + and Path(frames[-1]["retained_frame"]).read_bytes() + == retained.read_bytes() + ) + rejected_sha = inputs[0]["request"]["expected_frame_sha256"] + assert any( + event.get("retained_frame_sha256") == rejected_sha + and Path(event["retained_frame"]).is_file() + for event in events + if event["path"] == "/keyboard/lease" + ) + case["retained_attempt_frame_sha256"] = _sha(retained.read_bytes()) + case["before_png"] = str(retained) + case["rows_after"] = host.rows() + if outcome == "success": + assert report.success is True, result.error + assert result.delivery_receipt == receipt + assert result.delivery_uncertainty is None + else: + assert report.success is False + assert result.delivery_uncertainty is not None + assert actual["injected_fault"] == "discard_actual_acknowledgement" + evidence["passed"] = True + finally: + try: + evidence["rows_after"] = ( + host.rows() if (tmp_path / "patients.db").exists() else None + ) + except Exception as exc: + evidence["final_oracle_error"] = type(exc).__name__ + fixture_process = host.app + try: + host.close() + finally: + evidence["agent_terminated"] = ( + host.agent is None or host.agent.poll() is not None + ) + evidence["fixture_terminated"] = ( + fixture_process is None or fixture_process.poll() is not None + ) + for destination in ( + tmp_path / "editable-value-evidence.json", + Path( + os.environ.get( + "OAFLOW_NATIVE_EDITABLE_VALUE_EVIDENCE", + tmp_path / "published-editable-evidence.json", + ) + ), + ): + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(json.dumps(evidence, indent=2) + "\n") diff --git a/packages/flow/tests/test_native_editable_value.py b/packages/flow/tests/test_native_editable_value.py new file mode 100644 index 0000000000..a3dede2b94 --- /dev/null +++ b/packages/flow/tests/test_native_editable_value.py @@ -0,0 +1,149 @@ +"""One exact ValuePattern contract for focused and point-bound text readers.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +from hypothesis import given +from hypothesis import strategies as st + +from openadapt_flow.backends.win_agent.server import ( + AgentConfig, + _editable_value_observation, + _focused_target, + _perform_uia_initialized, +) +from openadapt_flow.backends.windows_backend import WindowsBackend +from tests.test_native_focus_keyboard import focused_auto, png +from tests.test_win_agent_server import RunningAgent + + +def editable(value=""): + auto, control = focused_auto() + control.IsPassword = False + pattern = SimpleNamespace(Value=value, IsReadOnly=False) + control.GetValuePattern = lambda: pattern + return auto, control, pattern + + +@given(st.text(max_size=9000)) +def test_exact_value_including_empty_unicode_whitespace_is_not_normalized_or_truncated( + value, +): + auto, control, pattern = editable(value) + observed = _editable_value_observation(auto, {}) + assert observed["status"] == "ok" and observed["complete"] is True + assert observed["value"] == value + assert observed["target_fingerprint"] == _focused_target(auto)["fingerprint"] + assert control.invocations == 0 + + +@pytest.mark.parametrize( + "kind", + [ + "password", + "password_unknown", + "readonly", + "readonly_unknown", + "pattern", + "nonstring", + "oversized", + "ambiguous", + "wrong_point", + "wrong_binding", + "changing_value", + "replacement", + ], +) +def test_incomplete_or_changed_observation_returns_no_value_and_no_name_fallback(kind): + auto, control, pattern = editable("exact") + data = {} + if kind == "password": + control.IsPassword = True + elif kind == "password_unknown": + control.IsPassword = None + elif kind == "readonly": + pattern.IsReadOnly = True + elif kind == "readonly_unknown": + pattern.IsReadOnly = None + elif kind == "pattern": + control.GetValuePattern = lambda: None + elif kind == "nonstring": + pattern.Value = None + elif kind == "oversized": + pattern.Value = "x" * 65537 + elif kind == "ambiguous": + auto, control = focused_auto(duplicate=True) + control.IsPassword = False + control.GetValuePattern = lambda: pattern + elif kind == "wrong_point": + data = {"x": 0, "y": 0} + elif kind == "wrong_binding": + data = {"expected_fingerprint": "f" * 64} + elif kind in {"changing_value", "replacement"}: + calls = [] + + def changing(): + calls.append(True) + if len(calls) == 2: + if kind == "changing_value": + pattern.Value = "changed" + else: + control.runtime_id = (9, 9) + return pattern + + control.GetValuePattern = changing + result = _editable_value_observation(auto, data) + assert result["status"] == "unavailable" and result["complete"] is False + assert "value" not in result and "name" not in result + + +def test_long_complete_value_matches_rdp_full_value_semantics(): + auto, _, _ = editable("prefix" + "x" * 8196 + "suffix") + assert _editable_value_observation(auto, {})["value"].endswith("suffix") + + +def test_actual_http_getter_siblings_share_exact_value_and_lease_binding(): + auto, control, pattern = editable("") + agent = RunningAgent( + AgentConfig(host="127.0.0.1", port=0, token="unit-token"), + grab_fn=png, + context_fn=lambda: { + "status": "ok", + "application": "test-runtime", + "application_version": "sha256:" + "a" * 64, + "session": "b" * 64, + "environment": "c" * 64, + "workflow_state": None, + }, + uia_fn=lambda operation, data: _perform_uia_initialized(auto, operation, data), + ) + try: + backend = WindowsBackend(agent.url, auth_token="unit-token") + point = tuple(_focused_target(auto)["point"]) + assert backend.text_value_at(*point) == "" + assert backend.focused_text_value() == "" + assert backend.editable_value_observation()["complete"] is True + pattern.Value = " exact \u00e9 " + assert ( + backend.text_value_at(*point) + == backend.focused_text_value() + == pattern.Value + ) + backend.guarded_keyboard_frame() + backend.arm_guarded_keyboard(*point) + control.runtime_id = (9, 9) + assert ( + backend.text_value_at(*point) is None + and backend.focused_text_value() is None + ) + backend.cancel_guarded_keyboard() + assert backend.focused_text_value() == pattern.Value + control.IsPassword = True + assert ( + backend.text_value_at(*point) is None + and backend.focused_text_value() is None + ) + finally: + agent.close() diff --git a/packages/flow/tests/test_native_keyboard_retry.py b/packages/flow/tests/test_native_keyboard_retry.py index cfa56664dd..4b2cae9536 100644 --- a/packages/flow/tests/test_native_keyboard_retry.py +++ b/packages/flow/tests/test_native_keyboard_retry.py @@ -194,3 +194,93 @@ def press_guarded(self, key, **kwargs): event = report.results[0].fresh_actuation_events[0] assert event.phase == "keyboard" and event.retried is True assert event.lease_sha256 == "a" * 64 + + +@pytest.mark.parametrize("action", ["type", "key", "hotkey"]) +@pytest.mark.parametrize("stale", [False, True]) +@pytest.mark.parametrize("lost_ack", [False, True]) +def test_report_retains_actual_keyboard_attempt_frame_even_with_lost_ack( + tmp_path, action, stale, lost_ack +): + from openadapt_flow.ir import ActionKind, Step, Workflow + from openadapt_flow.runtime.replayer import Replayer + from tests.test_replayer import FakeBackend, FakeVision, Match, click_step, make_png + + class Native(FakeBackend): + attempts = 0 + delivered_frames = [] + + def native_keyboard_lease_available(self): + return True + + def guarded_keyboard_target_fingerprint(self): + return "b" * 64 if self._guarded_keyboard_point is not None else None + + def click(self, *args, **kwargs): + super().click(*args, **kwargs) + self._frame = make_png(color=(220, 230, 240)) + + def guarded_keyboard_frame(self): + if action != "type" and self.attempts == 0: + self._frame = make_png(color=(220, 230, 240)) + return self._frame + + def deliver(self, call): + self.attempts += 1 + if stale and self.attempts == 1: + self._guarded_keyboard_point = None + self._frame = make_png(color=(200, 210, 220)) + raise changed( + "physical_type_text" if action == "type" else "physical_press" + ) + self.delivered_frames.append(self._frame) + receipt = call() + if lost_ack: + raise ActionDeliveryUncertain( + operation=receipt.operation, + native=False, + cause_type="SyntheticLostAcknowledgement", + ) + return receipt + + def type_text_guarded(self, text, **kwargs): + return self.deliver( + lambda: super(Native, self).type_text_guarded(text, **kwargs) + ) + + def press_guarded(self, key, **kwargs): + return self.deliver( + lambda: super(Native, self).press_guarded(key, **kwargs) + ) + + bundle = tmp_path / "bundle" + (bundle / "templates").mkdir(parents=True) + (bundle / "templates/btn.png").write_bytes(make_png((50, 20))) + backend, vision = Native(), FakeVision() + backend.delivered_frames = [] + vision.template_results = [Match((110, 105), (100, 100, 50, 20)) for _ in range(8)] + step = Step( + id="keyboard", + intent="edit transient field", + action=ActionKind(action), + anchor=click_step(ocr_text="Field").anchor, + text="example" if action == "type" else None, + key="a" if action != "type" else None, + modifiers=["ctrl"] if action == "hotkey" else [], + ) + report = Replayer(backend, vision=vision).run( + Workflow(name="source", steps=[step]), + bundle_dir=bundle, + run_dir=tmp_path / "run", + ) + result = report.results[0] + assert report.success is (not lost_ack), result.error + assert len(backend.delivered_frames) == 1 + assert ( + tmp_path / "run" / result.before_png + ).read_bytes() == backend.delivered_frames[0] + assert backend.delivered_frames[0] != make_png() + assert bool(result.delivery_uncertainty) is lost_ack + assert len(result.fresh_actuation_events) == int(stale) + assert backend.attempts == 1 + int(stale) + assert len([x for x in backend.actions if x[0] == "click"]) == int(action == "type") From 92585a2702b0b137f87aec22c45e32d818beb71c Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 22:29:05 -0500 Subject: [PATCH 5/8] fix(flow): advertise the exact native editable-value capability --- packages/flow/openadapt_flow/backends/win_agent/server.py | 2 +- packages/flow/tests/test_native_editable_value.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 3001ee6f7f..c35ca405c0 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -3149,7 +3149,7 @@ def do_GET(self) -> None: # noqa: N802 - stdlib naming "context_environment_v1", "typed_input_v1", *( - ["native_keyboard_lease_v1"] + ["native_keyboard_lease_v1", "native_editable_value_v1"] if keyboards is not None else [] ), diff --git a/packages/flow/tests/test_native_editable_value.py b/packages/flow/tests/test_native_editable_value.py index a3dede2b94..ad39d8cc2f 100644 --- a/packages/flow/tests/test_native_editable_value.py +++ b/packages/flow/tests/test_native_editable_value.py @@ -121,6 +121,7 @@ def test_actual_http_getter_siblings_share_exact_value_and_lease_binding(): ) try: backend = WindowsBackend(agent.url, auth_token="unit-token") + assert "native_editable_value_v1" in backend.agent_capabilities() point = tuple(_focused_target(auto)["point"]) assert backend.text_value_at(*point) == "" assert backend.focused_text_value() == "" From 1634f59e5828c17daea2eefd5f8e53b1f46d5f59 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 23:10:15 -0500 Subject: [PATCH 6/8] 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 c20e88077147e86152ca92f5826e3dc908e28f78 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 23:15:42 -0500 Subject: [PATCH 7/8] Require shared completeness proof for editable native observations --- .github/workflows/desktop-replay.yml | 12 +++ .../flow/docs/design/NATIVE_KEYBOARD_LEASE.md | 32 ++++-- .../openadapt_flow/backends/parallels_vm.py | 6 ++ .../backends/win_agent/server.py | 76 ++++---------- .../backends/windows_backend.py | 2 + .../backends/windows_keyboard_lease.py | 6 +- .../openadapt_flow/rl_env/windows_guest.py | 5 + packages/flow/scripts/desktop/winrm_lab.py | 7 +- .../tests/e2e/test_native_keyboard_lease.py | 99 ++++++++++++++++--- .../flow/tests/test_native_editable_value.py | 93 ++++++++++++++++- 10 files changed, 252 insertions(+), 86 deletions(-) diff --git a/.github/workflows/desktop-replay.yml b/.github/workflows/desktop-replay.yml index 3aa2fd6b50..6e53357fa7 100644 --- a/.github/workflows/desktop-replay.yml +++ b/.github/workflows/desktop-replay.yml @@ -163,6 +163,17 @@ jobs: assert proof["passed"] is True and proof["agent_terminated"] is True and proof["fixture_terminated"] is True assert proof["rows_before"] == proof["rows_after"] assert len(proof["observations"]) == 8 + positives = [case for case in proof["observations"] if "observation" in case] + assert len(positives) == 2 and {case["length"] for case in positives} == {0, 20} + for case in positives: + assert case["managed_before"] == case["managed_after"] + assert case["observation"]["schema"] == "openadapt.native-editable-value/v2" + assert case["observation"]["completeness_proof"]["method"] == "uia-value+wm-gettext" + long_case = next(case for case in proof["observations"] if case["case"] == "leaseLong-140") + assert long_case["managed_before"] == long_case["managed_after"] == proof["managed_initial"]["leaseLong"] + assert long_case["managed_before"]["live_length"] == 8196 + for event in long_case["unavailable"]: + assert event["response"] == {"status": "unavailable", "complete": False, "reason": "provider_native_value_disagreement"} assert len(proof["runtime"]) == 2 and {case["case"] for case in proof["runtime"]} == {"success", "uncertain"} for case in proof["runtime"]: assert case["planted"] and case["input_attempts"][0]["response"]["no_keyboard_input_delivered"] is True @@ -230,6 +241,7 @@ jobs: ${{ runner.temp }}/nkl-editable/*.log ${{ runner.temp }}/nkl-editable/cases/**/*.png ${{ runner.temp }}/nkl-editable/cases/**/editable-value-evidence.json + ${{ runner.temp }}/nkl-editable/cases/**/lease-stored-initial.json ${{ runner.temp }}/nkl-editable/cases/**/agent.log ${{ runner.temp }}/nkl-editable/cases/**/patient_notes.ps1 ${{ runner.temp }}/nkl-editable/cases/**/patients.db diff --git a/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md b/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md index 131cea0ac1..f0ebb16bdb 100644 --- a/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md +++ b/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md @@ -60,16 +60,30 @@ This advances independently verifiable action receipts and refusal evidence. ## Exact editable-value observation -`text_value_at` and `focused_text_value` use one complete ValuePattern contract -at `/uia/editable-value`. A readable empty string is a value. Password or unknown +`text_value_at` and `focused_text_value` consume the same v2 observation at +`/uia/editable-value`. A readable empty string is a value. Password or unknown password state, read-only or unknown editability, missing/ambiguous focus, replacement, changed value and oversized values refuse. No accessible Name, MSAA value, normalized text or truncated prefix substitutes for the exact -value. Both value reads are bounded by actual focus/runtime fingerprint and -geometry/hit-test observations. Current observed, armed and consumed keyboard -bindings remain authoritative for the read-back. This supplies the unchanged -baseline required by bounded zero-input retries; unknown stays a refusal. +value. Current observed, armed and consumed keyboard bindings remain +authoritative for read-back; unknown stays a refusal. -The full-value/empty semantics match the separately reviewed approval projection -in #2291. Its helper is not on this branch's base; merge integration should reuse -a shared helper without importing that whole held approval change here. +A full-looking ValuePattern string alone does not establish completeness. The +native diagnostic independently measured live stored lengths of 4,097 and +8,196 UTF-16 units while the UIA wire returned 4,096. The canonical +`win_agent/native_value.py` helper now requires two stable Unicode +WM_GETTEXTLENGTH/WM_GETTEXT extent/full reads and two exact UIA reads to agree. +It checks caller scope, UIA HWND/PID/RuntimeId and native HWND/PID/thread around +each read, uses bounded buffers and message deadlines, and preserves exact +UTF-16 bytes. Missing native handles, unknown readability, incomplete copies, +timeouts, changed identities or source disagreement are incomplete. Native text +never silently replaces a disagreeing UIA value. + +Positive v2 observations carry a closed completeness proof with source method, +owner, UTF-16 extent/hash and both read counts. Clients require that proof and +the v2 capability; a legacy complete flag cannot authorize a baseline. Empty may +be complete for editable input while remaining unmasked in approval projection. +The same shared helper commit is the prerequisite for #2291's separate approval +consumer. Incomplete or unsupported values cannot fall back to OCR that omits +an unseen suffix. This branch does not import that whole approval change or +claim its qualification. diff --git a/packages/flow/openadapt_flow/backends/parallels_vm.py b/packages/flow/openadapt_flow/backends/parallels_vm.py index b338313f64..c9da4a6525 100644 --- a/packages/flow/openadapt_flow/backends/parallels_vm.py +++ b/packages/flow/openadapt_flow/backends/parallels_vm.py @@ -739,6 +739,12 @@ def launch_agent( 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) + for helper in ("keyboard_lease", "native_value"): + self.push_file( + os.path.join(os.path.dirname(server), helper + ".py"), + f"{GUEST_DIR}/win_agent_{helper}.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 c35ca405c0..c3a71581bb 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -1063,41 +1063,6 @@ def _focused_target( return observed[1] if observed is not None else None -def _complete_editable_value(control: object) -> tuple[Optional[str], Optional[str]]: - """Full ValuePattern observation; empty is readable, never Name/MSAA. - - This shares #2291's full exact ValuePattern/empty-vs-unavailable contract. - Editable input additionally requires observed non-password/non-read-only. - """ - if _control_value(control, "IsPassword", None) is not False: - return None, "password_or_password_status_unavailable" - if _control_value(control, "ControlTypeName", None) != "EditControl": - return None, "not_editable_value_control" - method = _control_value(control, "GetValuePattern", None) - if not callable(method): - return None, "value_pattern_unavailable" - try: - pattern = method() - if getattr(pattern, "IsReadOnly", None) is not False: - return None, "read_only_or_read_only_status_unavailable" - value = getattr(pattern, "Value", None) - except Exception: - return None, "value_unavailable" - if _control_value(control, "IsPassword", None) is not False: - return None, "password_or_password_status_unavailable" - try: - still_editable = getattr(pattern, "IsReadOnly", None) is False - except Exception: - still_editable = False - if not still_editable: - return None, "read_only_or_read_only_status_unavailable" - if not isinstance(value, str): - return None, "value_unavailable" - if len(value) > _MAX_TEXT_CHARS: - return None, "value_exceeds_limit" - return value, None - - def _editable_value_observation(auto: Any, payload: dict[str, Any]) -> dict[str, Any]: data = _exact_object( payload, @@ -1136,29 +1101,30 @@ def unavailable(reason: str) -> dict[str, Any]: left <= point[0] < right and top <= point[1] < bottom ): return unavailable("point_outside_focused_target") - value, reason = _complete_editable_value(control) - if reason is not None: - return unavailable(reason) - # Do not re-resolve a locator into another object. Re-read actual focus, - # runtime identity, geometry/hit-test and the same full value. - after = _focused_target_control(auto, verify_locator_uniqueness=False) - if after is None or not hmac.compare_digest(after[1]["fingerprint"], fingerprint): - return unavailable("observation_changed") - after_value, reason = _complete_editable_value(after[0]) - if reason is not None: - return unavailable(reason) - final = _focused_target_control(auto, verify_locator_uniqueness=False) - if ( - after_value != value - or final is None - or not hmac.compare_digest(final[1]["fingerprint"], fingerprint) - ): + try: + from openadapt_flow.backends.win_agent.native_value import ( + observe_complete_value, + ) + except ModuleNotFoundError: + from win_agent_native_value import observe_complete_value # type: ignore[no-redef,import-not-found] + + 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 + + result = observe_complete_value( + control, identity=current_binding, require_editable=True + ) + if not result.complete or result.proof is None or result.value is None: + return unavailable(result.reason or "value_observation_unavailable") + if current_binding() != fingerprint: return unavailable("observation_changed") return { "status": "ok", - "schema": "openadapt.native-editable-value/v1", + "schema": "openadapt.native-editable-value/v2", "complete": True, - "value": value, + "value": result.value, + "completeness_proof": result.proof.payload(), "target_fingerprint": fingerprint, "bounds": candidate["bounds"], "point": candidate["point"], @@ -3149,7 +3115,7 @@ def do_GET(self) -> None: # noqa: N802 - stdlib naming "context_environment_v1", "typed_input_v1", *( - ["native_keyboard_lease_v1", "native_editable_value_v1"] + ["native_keyboard_lease_v1", "native_editable_value_v2"] if keyboards is not None else [] ), diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index 12c254978f..1b6d52b418 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -1766,6 +1766,8 @@ def editable_value_observation( """ if (x is None) != (y is None): return None + if "native_editable_value_v2" not in self.agent_capabilities(): + return None leases = self._focused_keyboard_leases() if leases is None: return None diff --git a/packages/flow/openadapt_flow/backends/windows_keyboard_lease.py b/packages/flow/openadapt_flow/backends/windows_keyboard_lease.py index f65f931993..ab13f9d1fc 100644 --- a/packages/flow/openadapt_flow/backends/windows_keyboard_lease.py +++ b/packages/flow/openadapt_flow/backends/windows_keyboard_lease.py @@ -19,6 +19,7 @@ _target, keyboard_operation, ) +from openadapt_flow.backends.win_agent.native_value import valid_value_proof from openadapt_flow.ir import ActionDeliveryReceipt @@ -61,15 +62,16 @@ def editable_value_observation( "schema", "complete", "value", + "completeness_proof", "target_fingerprint", "bounds", "point", } or data["status"] != "ok" - or data["schema"] != "openadapt.native-editable-value/v1" + or data["schema"] != "openadapt.native-editable-value/v2" or data["complete"] is not True or not isinstance(data["value"], str) - or len(data["value"]) > 65536 + or not valid_value_proof(data["value"], data["completeness_proof"]) ): return None target = _target( diff --git a/packages/flow/openadapt_flow/rl_env/windows_guest.py b/packages/flow/openadapt_flow/rl_env/windows_guest.py index 033862e1b5..5dabd722dd 100644 --- a/packages/flow/openadapt_flow/rl_env/windows_guest.py +++ b/packages/flow/openadapt_flow/rl_env/windows_guest.py @@ -682,6 +682,11 @@ def launch_agent( check=False, ) self.push_file(Path(agent_server.__file__), rf"{GUEST_DIR}\win_agent_server.py") + for helper in ("keyboard_lease", "native_value"): + self.push_file( + Path(agent_server.__file__).with_name(helper + ".py"), + rf"{GUEST_DIR}\win_agent_{helper}.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 aff8fff00f..ce53323c8a 100644 --- a/packages/flow/scripts/desktop/winrm_lab.py +++ b/packages/flow/scripts/desktop/winrm_lab.py @@ -551,8 +551,11 @@ def launch_agent( Path(server_path or agent_server.__file__), rf"{guest_dir}\win_agent_server.py", ) - keyboard_helper = Path(agent_server.__file__).with_name("keyboard_lease.py") - self.push_file(keyboard_helper, rf"{guest_dir}\win_agent_keyboard_lease.py") + for helper in ("keyboard_lease", "native_value"): + self.push_file( + Path(agent_server.__file__).with_name(helper + ".py"), + rf"{guest_dir}\win_agent_{helper}.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/e2e/test_native_keyboard_lease.py b/packages/flow/tests/e2e/test_native_keyboard_lease.py index eadbed7616..e69a8084a3 100644 --- a/packages/flow/tests/e2e/test_native_keyboard_lease.py +++ b/packages/flow/tests/e2e/test_native_keyboard_lease.py @@ -673,6 +673,24 @@ def test_native_keyboard_lease_actual_delivery_and_refusal(tmp_path, monkeypatch $leaseButton.Size = New-Object System.Drawing.Size(250, 30) $form.Controls.Add($leaseButton) $leaseFields['button'] = $leaseButton +function Get-LeaseStoredValues { + $controls = @{ noteBox=$script:noteBox; leaseLong=$script:leaseFields['leaseLong-140']; + leaseOversized=$script:leaseFields['leaseOversized-180'] } + $values = @{} + foreach ($id in $controls.Keys) { + $control = $controls[$id] + $text = [string]$control.Text + $bytes = [Text.Encoding]::UTF8.GetBytes($text) + $hasher = [Security.Cryptography.SHA256]::Create() + try { $hash = ([BitConverter]::ToString($hasher.ComputeHash($bytes))).Replace('-', '').ToLowerInvariant() } + finally { $hasher.Dispose() } + $point = $control.PointToScreen([Drawing.Point]::new([int]($control.Width / 2), [int]($control.Height / 2))) + $values[$id] = @{ live_length=$text.Length; sha256=$hash; + suffix=$text.Substring([Math]::Max(0, $text.Length - 16)); + hwnd=$control.Handle.ToInt64(); pid=$PID; point=@($point.X, $point.Y) } + } + return $values +} $form.Add_Shown({ $points = @{} foreach ($key in $script:leaseFields.Keys) { @@ -683,6 +701,9 @@ def test_native_keyboard_lease_actual_delivery_and_refusal(tmp_path, monkeypatch $temporary = Join-Path $PSScriptRoot 'lease-observation-points.tmp' [IO.File]::WriteAllText($temporary, ($points | ConvertTo-Json)) [IO.File]::Move($temporary, (Join-Path $PSScriptRoot 'lease-observation-points.json')) + $temporary = Join-Path $PSScriptRoot 'lease-stored-initial.tmp' + [IO.File]::WriteAllText($temporary, ((Get-LeaseStoredValues) | ConvertTo-Json -Depth 5)) + [IO.File]::Move($temporary, (Join-Path $PSScriptRoot 'lease-stored-initial.json')) }) $leaseObservationTimer = New-Object System.Windows.Forms.Timer $leaseObservationTimer.Interval = 40 @@ -695,12 +716,14 @@ def test_native_keyboard_lease_actual_delivery_and_refusal(tmp_path, monkeypatch 'clear-note' { $script:noteBox.Text = ''; [void]$script:noteBox.Focus(); $script:noteBox.SelectionStart = 0 } 'paint-success' { $script:status.Text = 'Synthetic lease repaint success' } 'paint-uncertain' { $script:status.Text = 'Synthetic lease repaint uncertain' } + 'snapshot-observation' { } default { throw 'Unknown observation fixture command' } } $ack = @{ command=$command; note_value=$script:noteBox.Text; status=$script:status.Text; - form_handle=$form.Handle.ToInt64(); note_handle=$script:noteBox.Handle.ToInt64() } + form_handle=$form.Handle.ToInt64(); note_handle=$script:noteBox.Handle.ToInt64(); + stored_values=(Get-LeaseStoredValues) } $temporary = Join-Path $PSScriptRoot 'lease-observation-ack.tmp' - [IO.File]::WriteAllText($temporary, ($ack | ConvertTo-Json)) + [IO.File]::WriteAllText($temporary, ($ack | ConvertTo-Json -Depth 5)) [IO.File]::Move($temporary, (Join-Path $PSScriptRoot 'lease-observation-ack.json')) }) $leaseObservationTimer.Start() @@ -722,15 +745,28 @@ def _fixture_command(root: Path, command: str) -> dict[str, Any]: return result -def _editable_positive(backend, transport, aid, point, expected): +def _stored_snapshot(root: Path, aid: str, expected: str) -> dict[str, Any]: + observed = _fixture_command(root, "snapshot-observation")["stored_values"][aid] + assert observed["live_length"] == len(expected.encode("utf-16-le")) // 2 + assert observed["suffix"] == expected[-16:] + assert observed["sha256"] == _sha(expected.encode("utf-8")) + assert type(observed["hwnd"]) is int and observed["hwnd"] > 0 + assert type(observed["pid"]) is int and observed["pid"] > 0 + return observed + + +def _editable_positive(backend, transport, root, aid, point, expected): backend.click(*point) + managed_before = _stored_snapshot(root, aid, expected) handle = backend.locate_structural(StructuralLocator(automation_id=aid)) assert handle is not None and handle.candidate_count == 1 observed = backend.editable_value_observation(*point) assert observed is not None + proof = observed["completeness_proof"] + assert type(proof["thread"]) is int and proof["thread"] > 0 assert observed == { "status": "ok", - "schema": "openadapt.native-editable-value/v1", + "schema": "openadapt.native-editable-value/v2", "complete": True, "value": expected, "target_fingerprint": handle.target_fingerprint, @@ -741,6 +777,17 @@ def _editable_positive(backend, transport, aid, point, expected): handle.region[1] + handle.region[3], ], "point": list(handle.point), + "completeness_proof": { + "schema": "openadapt.native-value-completeness/v1", + "method": "uia-value+wm-gettext", + "hwnd": managed_before["hwnd"], + "pid": managed_before["pid"], + "thread": proof["thread"], + "utf16_units": len(expected.encode("utf-16-le")) // 2, + "sha256_utf16le": _sha(expected.encode("utf-16-le")), + "native_reads": 2, + "uia_reads": 2, + }, } assert backend.text_value_at(*point) == expected assert backend.focused_text_value() == expected @@ -748,10 +795,14 @@ def _editable_positive(backend, transport, aid, point, expected): event for event in transport.events if event["path"] == "/uia/editable-value" ][-3:] assert len(wire) == 3 and all(event["response"] == observed for event in wire) + managed_after = _stored_snapshot(root, aid, expected) + assert managed_before == managed_after return { "case": aid, "length": len(expected), "value_sha256": _sha(expected.encode()), + "managed_before": managed_before, + "managed_after": managed_after, "observation": observed, } @@ -788,7 +839,7 @@ def test_native_editable_values_and_runtime_type_retry(tmp_path, monkeypatch): try: backend = host.start_agent() evidence["capabilities"] = sorted(backend.agent_capabilities()) - assert "native_editable_value_v1" in evidence["capabilities"] + assert "native_editable_value_v2" in evidence["capabilities"] transport = _Transport(backend, monkeypatch, evidence) transport.lease_evidence_dir = tmp_path / "runtime-lease-frames" host.launch_app() @@ -807,25 +858,28 @@ def test_native_editable_values_and_runtime_type_retry(tmp_path, monkeypatch): backend.press("enter") _wait_value(backend, "patientHeader", header) evidence["observations"].append( - _editable_positive(backend, transport, "noteBox", points["noteBox"], "") + _editable_positive( + backend, transport, tmp_path, "noteBox", points["noteBox"], "" + ) ) exact = " exact café value " backend.type_text(exact) _wait_value(backend, "noteBox", exact) - evidence["observations"].append( - _editable_positive(backend, transport, "noteBox", points["noteBox"], exact) - ) evidence["observations"].append( _editable_positive( - backend, - transport, - "leaseLong", - extras["leaseLong-140"], - "x" * 8192 + "-END", + backend, transport, tmp_path, "noteBox", points["noteBox"], exact ) ) - + initial_values = tmp_path / "lease-stored-initial.json" + deadline = time.monotonic() + 10 + while not initial_values.is_file(): + assert time.monotonic() < deadline, "managed initial snapshot unavailable" + time.sleep(0.05) + evidence["managed_initial"] = json.loads( + initial_values.read_text(encoding="utf-8-sig") + ) unavailable_reasons = { + "leaseLong-140": "provider_native_value_disagreement", "leasePassword-100": "password_or_password_status_unavailable", "leaseOversized-180": "value_exceeds_limit", "leaseReadOnly-220": "read_only_or_read_only_status_unavailable", @@ -835,6 +889,14 @@ def test_native_editable_values_and_runtime_type_retry(tmp_path, monkeypatch): for name, reason in unavailable_reasons.items(): point = extras[name] backend.click(*point) + stored = None + if name in {"leaseLong-140", "leaseOversized-180"}: + aid = "leaseLong" if name == "leaseLong-140" else "leaseOversized" + expected = ( + "x" * 8192 + "-END" if name == "leaseLong-140" else "x" * 65537 + ) + stored = _stored_snapshot(tmp_path, aid, expected) + assert stored == evidence["managed_initial"][aid] assert backend.editable_value_observation(*point) is None assert backend.text_value_at(*point) is None assert backend.focused_text_value() is None @@ -850,7 +912,12 @@ def test_native_editable_values_and_runtime_type_retry(tmp_path, monkeypatch): assert set(raw) == {"status", "complete", "reason"} assert raw["status"] == "unavailable" and raw["complete"] is False assert raw["reason"] == reason - evidence["observations"].append({"case": name, "unavailable": wire}) + observation = {"case": name, "unavailable": wire} + if stored is not None: + stored_after = _stored_snapshot(tmp_path, aid, expected) + assert stored == stored_after + observation.update(managed_before=stored, managed_after=stored_after) + evidence["observations"].append(observation) assert host.rows() == baseline # This is a real observed demonstration. The operator-selected record diff --git a/packages/flow/tests/test_native_editable_value.py b/packages/flow/tests/test_native_editable_value.py index ad39d8cc2f..5ac8e595fa 100644 --- a/packages/flow/tests/test_native_editable_value.py +++ b/packages/flow/tests/test_native_editable_value.py @@ -8,6 +8,12 @@ from hypothesis import given from hypothesis import strategies as st +from openadapt_flow.backends.win_agent import native_value +from openadapt_flow.backends.win_agent.native_value import ( + NativeOwner, + NativeRead, + utf16_bytes, +) from openadapt_flow.backends.win_agent.server import ( AgentConfig, _editable_value_observation, @@ -18,12 +24,34 @@ from tests.test_native_focus_keyboard import focused_auto, png from tests.test_win_agent_server import RunningAgent +_native_controls = {} + + +@pytest.fixture(autouse=True) +def independent_native_protocol(monkeypatch): + class Reader: + def owner(self, hwnd): + control, _ = _native_controls[hwnd] + return NativeOwner(hwnd, control.ProcessId, 9876) + + def read(self, owner): + control, pattern = _native_controls[owner.hwnd] + value = getattr(control, "native_stored_value", pattern.Value) + units = len(utf16_bytes(value)) // 2 if isinstance(value, str) else 0 + return NativeRead(owner, units, units, value) + + monkeypatch.setattr(native_value, "Win32TextReader", Reader) + yield + _native_controls.clear() + def editable(value=""): auto, control = focused_auto() control.IsPassword = False pattern = SimpleNamespace(Value=value, IsReadOnly=False) control.GetValuePattern = lambda: pattern + control.NativeWindowHandle = 12345 + _native_controls[control.NativeWindowHandle] = (control, pattern) return auto, control, pattern @@ -99,7 +127,7 @@ def changing(): assert "value" not in result and "name" not in result -def test_long_complete_value_matches_rdp_full_value_semantics(): +def test_long_fake_provider_native_agreement_is_complete_without_length_guessing(): auto, _, _ = editable("prefix" + "x" * 8196 + "suffix") assert _editable_value_observation(auto, {})["value"].endswith("suffix") @@ -121,7 +149,7 @@ def test_actual_http_getter_siblings_share_exact_value_and_lease_binding(): ) try: backend = WindowsBackend(agent.url, auth_token="unit-token") - assert "native_editable_value_v1" in backend.agent_capabilities() + assert "native_editable_value_v2" in backend.agent_capabilities() point = tuple(_focused_target(auto)["point"]) assert backend.text_value_at(*point) == "" assert backend.focused_text_value() == "" @@ -148,3 +176,64 @@ def test_actual_http_getter_siblings_share_exact_value_and_lease_binding(): ) finally: agent.close() + + +@pytest.mark.parametrize( + "field", ["schema", "missing_proof", "hash", "extent", "read_count"] +) +def test_http_getter_siblings_reject_legacy_or_unproven_complete_flags(field): + auto, _, _ = editable("exact") + + def altered(operation, data): + result = _perform_uia_initialized(auto, operation, data) + if operation == "editable-value" and result.get("status") == "ok": + if field == "schema": + result["schema"] = "openadapt.native-editable-value/v1" + elif field == "missing_proof": + result.pop("completeness_proof") + else: + key, value = { + "hash": ("sha256_utf16le", "0" * 64), + "extent": ("utf16_units", 0), + "read_count": ("native_reads", True), + }[field] + result["completeness_proof"][key] = value + return result + + agent = RunningAgent( + AgentConfig(host="127.0.0.1", port=0, token="unit-token"), + grab_fn=png, + uia_fn=altered, + ) + try: + backend = WindowsBackend(agent.url, auth_token="unit-token") + point = tuple(_focused_target(auto)["point"]) + assert backend.editable_value_observation() is None + assert backend.focused_text_value() is None + assert backend.text_value_at(*point) is None + finally: + agent.close() + + +def test_confirmed_provider_prefix_is_unavailable_across_all_text_readers(): + auto, control, _ = editable("x" * 4096) + control.native_stored_value = "x" * 8192 + "-END" + result = _editable_value_observation(auto, {}) + assert result == { + "status": "unavailable", + "complete": False, + "reason": "provider_native_value_disagreement", + } + agent = RunningAgent( + AgentConfig(host="127.0.0.1", port=0, token="unit-token"), + grab_fn=png, + uia_fn=lambda op, data: _perform_uia_initialized(auto, op, data), + ) + try: + backend = WindowsBackend(agent.url, auth_token="unit-token") + point = tuple(_focused_target(auto)["point"]) + assert backend.editable_value_observation() is None + assert backend.focused_text_value() is None + assert backend.text_value_at(*point) is None + finally: + agent.close() From 0f9b592387cc5b1cc1a6b38a60978ec792c91cd9 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 23:42:48 -0500 Subject: [PATCH 8/8] Bind keyboard result receipts only to the current input phase --- .github/workflows/desktop-replay.yml | 8 +++++ .../flow/docs/design/NATIVE_KEYBOARD_LEASE.md | 8 +++++ .../runtime/keyboard_delivery.py | 5 +++ .../tests/e2e/test_native_keyboard_lease.py | 20 ++++++++++- .../flow/tests/test_native_keyboard_retry.py | 35 +++++++++++++++++-- 5 files changed, 73 insertions(+), 3 deletions(-) diff --git a/.github/workflows/desktop-replay.yml b/.github/workflows/desktop-replay.yml index 6e53357fa7..e0c46ac1f2 100644 --- a/.github/workflows/desktop-replay.yml +++ b/.github/workflows/desktop-replay.yml @@ -179,6 +179,14 @@ jobs: assert case["planted"] and case["input_attempts"][0]["response"]["no_keyboard_input_delivered"] is True assert case["retained_attempt_frame_sha256"] == case["input_attempts"][-1]["request"]["expected_frame_sha256"] assert case["rows_after"] == proof["rows_before"] + assert len(case["preparation_events"]) == 1 + result = case["report"]["results"][0] + if case["case"] == "uncertain": + assert result["delivery_receipt"] is None + assert result["delivery_uncertainty"]["operation"] == "physical_type_text" + assert result["delivery_uncertainty"]["retried"] is False + else: + assert result["delivery_receipt"] == case["input_attempts"][-1]["response"]["receipt"] print(json.dumps({"editable_observation_cases": 8, "runtime_type_cases": 2, "skipped": 0, "rows_unchanged": True})) PYTHON - name: Record, compile and replay, judged from the record diff --git a/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md b/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md index f0ebb16bdb..37c3dc611f 100644 --- a/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md +++ b/packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md @@ -29,6 +29,14 @@ returns. The client requires its operation and native target fingerprint to match. Replayed leases, changed focus, invalid frames and changed context refuse. Lost or malformed acknowledgements are uncertain and are never retried. +Entering the shared TYPE/KEY/HOTKEY phase clears any earlier preparation +receipt from the current-action field. A successful focusing gesture cannot +stand in for a later keyboard acknowledgement. Lost acknowledgement leaves no +current-action receipt and retains explicit physical-operation uncertainty. +The earlier preparation still counts toward delivery_attempted; raw transport +proof may retain its genuine focus acknowledgement separately. No new report +schema or fabricated keyboard receipt is introduced. + A stale-frame response permits at most two keyboard-only reacquisitions. This requires an authenticated response for the consumed lease proving zero keyboard input, real changed-pixel geometry, full target/identity/context/authorization diff --git a/packages/flow/openadapt_flow/runtime/keyboard_delivery.py b/packages/flow/openadapt_flow/runtime/keyboard_delivery.py index 0c2e50c383..5e8c4c83a9 100644 --- a/packages/flow/openadapt_flow/runtime/keyboard_delivery.py +++ b/packages/flow/openadapt_flow/runtime/keyboard_delivery.py @@ -77,6 +77,11 @@ def native_keyboard_delivery( record identity and context through the ordinary full revalidation path. """ + # A completed focusing gesture is preparation, not this keyboard action. + # Enter the shared TYPE/KEY/HOTKEY phase without its positive receipt; + # only the caller's actual keyboard acknowledgement may populate it. + # Keep delivery_attempted: earlier preparation may already have had effect. + result.delivery_receipt = None rejected_resolution, rejected_region = resolution, replay._active_delivery_region def revalidate(exc: KeyboardFrameChangedBeforeInput) -> bool: diff --git a/packages/flow/tests/e2e/test_native_keyboard_lease.py b/packages/flow/tests/e2e/test_native_keyboard_lease.py index e69a8084a3..4c61bff537 100644 --- a/packages/flow/tests/e2e/test_native_keyboard_lease.py +++ b/packages/flow/tests/e2e/test_native_keyboard_lease.py @@ -121,7 +121,12 @@ def post(url, **kwargs): if path == "/keyboard/input" and self.before_keyboard_input is not None: planted = self.before_keyboard_input(copy.deepcopy(kwargs["json"])) response = original(url, **kwargs) - if path in {"/keyboard/lease", "/keyboard/input", "/uia/editable-value"}: + if path in { + "/keyboard/lease", + "/keyboard/input", + "/uia/editable-value", + "/uia/act", + }: request = kwargs["json"] event = { "path": path, @@ -1004,6 +1009,16 @@ def repaint_once(request): events = transport.events[start:] inputs = [event for event in events if event["path"] == "/keyboard/input"] case["input_attempts"] = inputs + # Retain genuine focus acknowledgement as non-authorizing raw + # transport evidence, separately from the current keyboard result. + preparation = [ + event + for event in events + if event["path"] == "/uia/act" + and event["response"].get("receipt", {}).get("operation") == "uia_focus" + ] + assert len(preparation) == 1 + case["preparation_events"] = preparation assert 2 <= len(inputs) <= 3 assert inputs[0]["http_status"] == 409 assert inputs[0]["response"]["reason"] == "stale_frame" @@ -1062,6 +1077,9 @@ def repaint_once(request): else: assert report.success is False assert result.delivery_uncertainty is not None + assert result.delivery_uncertainty.operation == "physical_type_text" + assert result.delivery_uncertainty.retried is False + assert result.delivery_receipt is None assert actual["injected_fault"] == "discard_actual_acknowledgement" evidence["passed"] = True finally: diff --git a/packages/flow/tests/test_native_keyboard_retry.py b/packages/flow/tests/test_native_keyboard_retry.py index 4b2cae9536..5e88428bde 100644 --- a/packages/flow/tests/test_native_keyboard_retry.py +++ b/packages/flow/tests/test_native_keyboard_retry.py @@ -200,9 +200,10 @@ def press_guarded(self, key, **kwargs): @pytest.mark.parametrize("stale", [False, True]) @pytest.mark.parametrize("lost_ack", [False, True]) def test_report_retains_actual_keyboard_attempt_frame_even_with_lost_ack( - tmp_path, action, stale, lost_ack + tmp_path, action, stale, lost_ack, monkeypatch ): - from openadapt_flow.ir import ActionKind, Step, Workflow + from openadapt_flow.ir import ActionDeliveryReceipt, ActionKind, Step, Workflow + from openadapt_flow.runtime import keyboard_delivery as keyboard_delivery_mod from openadapt_flow.runtime.replayer import Replayer from tests.test_replayer import FakeBackend, FakeVision, Match, click_step, make_png @@ -268,6 +269,26 @@ def press_guarded(self, key, **kwargs): key="a" if action != "type" else None, modifiers=["ctrl"] if action == "hotkey" else [], ) + # A preceding native focusing phase may have an actual positive receipt. + # It must never stand in for the later keyboard call, even after a typed + # zero-keyboard-input refusal and bounded full revalidation. + preparation_receipt = ActionDeliveryReceipt( + receipt_id="actual-prior-focus", + operation="uia_focus", + native=True, + target_fingerprint="b" * 64, + delivered_at="2026-07-25T00:00:00+00:00", + ) + original_delivery = keyboard_delivery_mod.native_keyboard_delivery + + def with_preparation(replay, **kwargs): + kwargs["result"].delivery_receipt = preparation_receipt + kwargs["result"].delivery_attempted = True + return original_delivery(replay, **kwargs) + + monkeypatch.setattr( + keyboard_delivery_mod, "native_keyboard_delivery", with_preparation + ) report = Replayer(backend, vision=vision).run( Workflow(name="source", steps=[step]), bundle_dir=bundle, @@ -281,6 +302,16 @@ def press_guarded(self, key, **kwargs): ).read_bytes() == backend.delivered_frames[0] assert backend.delivered_frames[0] != make_png() assert bool(result.delivery_uncertainty) is lost_ack + operation = "physical_type_text" if action == "type" else "physical_press" + if lost_ack: + assert result.delivery_receipt is None + assert result.delivery_uncertainty.operation == operation + assert result.delivery_uncertainty.retried is False + else: + assert result.delivery_receipt is not None + assert result.delivery_receipt.operation == operation + assert result.delivery_receipt != preparation_receipt + assert result.delivery_attempted is True assert len(result.fresh_actuation_events) == int(stale) assert backend.attempts == 1 + int(stale) assert len([x for x in backend.actions if x[0] == "click"]) == int(action == "type")