Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 126 additions & 3 deletions .github/workflows/desktop-replay.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -59,14 +62,17 @@ 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
shell: bash
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:
Expand All @@ -91,6 +97,100 @@ jobs:
mkdir -p runs
pytest -v -rs -p no:cacheprovider tests/test_windows_attempt_ledger.py \
tests/test_approval_form_window.py tests/test_binary_file_descriptors.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::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
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: 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
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
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
env:
OAFLOW_WINDOWS_HOSTED_E2E: "1"
Expand Down Expand Up @@ -146,6 +246,29 @@ 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/**/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
${{ 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
${{ 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/*
Expand Down Expand Up @@ -229,7 +352,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
Expand Down
4 changes: 2 additions & 2 deletions packages/flow/docs/design/DECOMPOSITION.md
Original file line number Diff line number Diff line change
Expand Up @@ -605,10 +605,10 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh
<!-- size-ratchet:begin -->
| 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` | 14331 |
| `packages/flow/openadapt_flow/qualification.py` | 5963 |
| `packages/flow/openadapt_flow/ir.py` | 6865 |
| `packages/flow/openadapt_flow/ir.py` | 6830 |
| `packages/desktop/openadapt_desktop/dispatch.py` | 6524 |
| `packages/capture/openadapt_capture/recorder.py` | 4836 |
| `packages/flow/openadapt_flow/interactive_recorder.py` | 4808 |
Expand Down
97 changes: 97 additions & 0 deletions packages/flow/docs/design/NATIVE_KEYBOARD_LEASE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# 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 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.

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.

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
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.
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

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.

## Exact editable-value observation

`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. Current observed, armed and consumed keyboard bindings remain
authoritative for read-back; unknown stays a refusal.

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.
30 changes: 30 additions & 0 deletions packages/flow/openadapt_flow/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,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.
Expand Down Expand Up @@ -533,6 +554,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.
Expand Down
6 changes: 6 additions & 0 deletions packages/flow/openadapt_flow/backends/parallels_vm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
[
Expand Down
Loading
Loading