diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 22980da815..6ec3bf4cfc 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -192,9 +192,11 @@ improvising or retrying when something is off. | Check that the saved record matches its source document, not only the parameters: intake keeps each value's line, a second reading must agree before a guarded save, and a round trip compares the read-back with the document | Released | Synthetic (MockMed, text referral) | `openadapt_flow/provenance.py`, `intake`, `verify-run --provenance`, guarded save | | Check one write from Python, without the CLI: one API (`openadapt_flow.verifier`: `begin_write`, `verify_write`; 2.4.1's `capture` form still works, deprecated) with one outcome (`CONFIRMED`, `REFUTED`, `UNCERTAIN`), the receipt, which parts were checked, and the result's scope (read path, stores read, time window, what it doesn't cover) | Released | Synthetic (SQLite; MockMed's fault server over real HTTP) | `openadapt_flow/verifier.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md) | | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | +| Fail closed by construction: one verdict kernel (`openadapt_flow.verdict`: obligations fixed from the plan, `settle`, allow-list codes, run binding, trust labels) that never passes an empty set, a short read, a raised probe, another run's result or an unknown code; a fail-open harness that runs 15 generic mutations against every registered `@verdict_site` and checks the verdict at three levels (refuted, not checked, held); and a CI ratchet that fails when the repository-wide count of a hand-written fold kind rises, including swallowed exceptions and "nothing else changed" tests over a possibly partial read | On main | Synthetic: the harness flags 14 fail-open bugs rebuilt from this repository's history (pinned pre-fix copies) plus one live connector site, and passes every fix; 8 registered sites (the hard-invariant layer, the version check, `verify-run`'s folds and the receipt's line judge and tally among them) and 2 owned; 12 of 12 kernel mutants killed | [FAIL_CLOSED.md](packages/flow/docs/FAIL_CLOSED.md), `packages/flow/tests/failopen`, `packages/flow/scripts/check_verdict_folds.py` | +| Steps drawn as links, tabs or menu items, and the commit point learned from the demonstration: a step's role (commit, navigate, in place) comes from the writes the backend counted, never its words; a commit holds only on exactly the demonstrated writes, and a backend that cannot count writes never attempts one | On main ([#2499](https://github.com/OpenAdaptAI/OpenAdapt/pull/2499)) | Synthetic: a web form, an EMR-like chart, a SaaS settings page (headless Chromium) and a spreadsheet-like grid with no browser | `openadapt_flow.gui.steps`, `packages/flow/tests/gui` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | -| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. A field the server is seen rewriting between `NULL` and `""` gets a `null_empty` codec, learned per field by the probe or from the trace, so that change alone is not a clobber; any other change on the field still is. The wire tap counts a GraphQL query (on `/graphql` or `/$graphql`) and a batch of `GET`s as reads. Another `POST` counts as a read only when it matches a read route declared as data; `probe_read_routes` learns those by replaying a trace on a sandbox reset to its pre-trace state and requiring that a whole-store digest not change. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | +| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. A field the server is seen rewriting between `NULL` and `""` gets a `null_empty` codec, learned per field by the probe or from the trace, so that change alone is not a clobber; any other change on the field still is. The wire tap counts a GraphQL query (on `/graphql` or `/$graphql`) and a batch of `GET`s as reads. Another `POST` counts as a read only when it matches a read route declared as data; `probe_read_routes` learns those by replaying a trace on a sandbox reset to its pre-trace state and requiring that a whole-store digest not change. An app whose calls all go to one RPC endpoint gets a lens whose read and write carry their arguments in the body (`body_template`), whose record is found at a path such as `result.0`, and whose 2xx answer with an `error` member counts as a failed call; induction learns it from a read that returns the named records and a write that a later read confirms, and reads back the fields the trace itself read. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Verify a write to an API or SaaS system with no database to diff: `openadapt proxy --api systems.tx.yaml` serves `api_read` and `api_write` beside the SQL tools on the same MCP endpoint and keeps the API credentials out of the agent's environment. Each write is sent once under a key derived from the task and the record, never the payload. A retry returns the first result, a regenerated payload is refused, and a crash between the send and the ledger is recovered by finding the write. The key goes out as `Idempotency-Key` where the API honors one, or as a FHIR conditional create. The record is then read back and judged with the tx codecs, including `null_empty`. The system's own event or audit log is read from an id-placed cursor, and the write's own event must appear with no other resource changed by the same credentials. A FHIR `AuditEvent` search, an event stream and a REST activity feed are all declared as data in the tx file. Every outcome gets a `record/run/v1` receipt. Scope is the resource and the actor: changes by other callers, and changes the log doesn't record, aren't checked. A whole-record (`replace`) update or a delete over another caller's edit is refused by the server when the route declares a `precondition` (`If-Match` from the read's `ETag` or a version field) with enforcement evidence: a probe recorded in the pack, or one the adapter runs once per route. Without a precondition it is never `VERIFIED`, only `COMPLETED_UNVERIFIED` (`unconditional_write`; `precondition_unproven` without evidence), and `api_write` reports it as an error. A retry that returns a stored result is capped the same way | [#2437](https://github.com/OpenAdaptAI/OpenAdapt/pull/2437), stacked on [#2428](https://github.com/OpenAdaptAI/OpenAdapt/pull/2428) | Real apps (Medplum 5.2.8 `AuditEvent`, Gitea 1.24.6 activity feed, synthetic data): 0 of 400 clean writes stopped on each; Medplum rerun with its `If-Match` probe recorded in the pack, 400 of 400 `VERIFIED`. Every planted fault the log exposes was stopped: wrong value, duplicate, partial write and same-actor collateral change, 50 of 50 per class, except that on Medplum a duplicate update no longer lands (the server refused all 50 second PUTs with 412). Known misses: a collateral title edit on Gitea, which its feed doesn't record (0 of 50 stopped), and another caller's change on either system (0 of 50). 50 of 50 regenerated-payload retries were refused on each. Stripe not run (no test-mode key) | [API_VERIFICATION.md](packages/flow/docs/API_VERIFICATION.md), [benchmark/api_scoped](packages/flow/benchmark/api_scoped/RESULTS.md), `openadapt_flow/txplan/scoped.py`, `openadapt_flow/txplan/audit.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](packages/flow/docs/RECONCILE.md), [results](packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | @@ -275,6 +277,7 @@ improvising or retrying when something is off. | Lift look-alike identity stops with a complete known-ID list | Released | Synthetic (rendered record list) | `openadapt-flow known-ids` | | Take extra looks before stopping on a look-alike record ID: fresh frames, the known-ID list, and a select-and-copy of the ID where the surface allows it | Released ([#1333](https://github.com/OpenAdaptAI/OpenAdapt/pull/1333)) | Synthetic (dense record list in a browser) | `runtime.identity_copy_look` in deployment.yaml; [IDENTITY_LOOKS.md](packages/flow/benchmark/identity_looks/IDENTITY_LOOKS.md) | | Check an icon-only click target's hover response (highlight, tooltip) before clicking on a pixel surface, and re-check the target and identity regions on a fresh frame right before every pixel click | Released ([#1334](https://github.com/OpenAdaptAI/OpenAdapt/pull/1334)) | Synthetic (in-process kiosk) | `Recorder(capture_hover=True)`; [hover_identity](packages/flow/benchmark/hover_identity/README.md) | +| Chrome MV3 Co-Pilot Extension (`sidePanel` live run/conflict/receipt UI, run-scoped child pop-up / estimator window tracking & focus return, zero-credential-capture sign-in / MFA pause & resume with native-host ack, and Chrome Web Store submission package) | Experimental, PR [#2575](https://github.com/OpenAdaptAI/OpenAdapt/pull/2575) | Real native-host pause/resume handler tests + Node VM extension tests + CWS packager validation (`packages/flow/tests/test_chrome_extension_cws.py`); headless Chrome E2E pending | [chrome_extension](packages/flow/chrome_extension/), [STORE_LISTING.md](packages/flow/chrome_extension/STORE_LISTING.md), [package_chrome_extension.py](scripts/package_chrome_extension.py) | ## The fastest layer the app allows @@ -283,6 +286,7 @@ improvising or retrying when something is off. | Page structure (DOM, UI Automation, Accessibility) first, then template, OCR and geometry | Released | Real apps on the web; synthetic on Windows and macOS | [RESOLUTION_LADDER.md](packages/flow/docs/RESOLUTION_LADDER.md) | | Run a step as a direct API call (`ApiActuator`, `ApiBinding`) | Released, hand-authored bindings | Synthetic benchmarks | `runtime/actuators/api.py` | | Capture a recording's network traffic and compile a clean save into an API step, with the same record check | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic patients on a local OpenEMR test copy | network capture, `ApiBinding` | +| Keep captured bodies off disk: `network.jsonl` and saved wire-tap HARs keep only declared field values (a recording's `--param` and `--identifier` fields; a wire policy's id and version fields) and a per-capture keyed hash of everything else, including URL query values; HTML, text and binary bodies keep only size and hash, taken from the bytes as sent (only a body labelled JSON, or with no content type, is parsed as JSON); the recording's `app_url` query and URL-valued HAR headers are minimized too, and a HAR marked minimized that carries a raw body is refused on load. Raw bodies (`--capture-network-bodies raw`, `save_har(raw_bodies=True)`), which API step proposals need, are refused unless sealed at rest or plaintext is explicitly allowed (`OPENADAPT_FLOW_PLAINTEXT_AT_REST`, warned and logged). Not covered: URL path segments and header values beyond credential redaction | On main (this PR) | Synthetic PHI in request and response bodies, absent from every file after decryption in raw, percent, JSON-escaped, base64 and gzip forms; positive controls with raw | `openadapt_flow/capture_privacy.py`, [NETWORK_CAPTURE.md](packages/flow/docs/NETWORK_CAPTURE.md#bodies-minimized-by-default) | | Fall back from the API step to page structure when the API is unavailable, before anything is sent | Released ([#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269)) | Synthetic | [#1269](https://github.com/OpenAdaptAI/OpenAdapt/pull/1269) | | Run a form's own script before an API save instead of refusing the form: field handlers, `onsubmit`, submit listeners and custom validate.js rules (OpenEMR's `pastDate`) run on the run's values in a scratch copy of the session with every write blocked, and the save is sent only when the page lets the submit through and would send the same body | On main | Synthetic (headless Chromium against a local test page) | [API_TIER.md](packages/flow/docs/API_TIER.md#what-happens-at-run-time), `runtime/actuators/form_eval.py` | | Compare paired GUI/API database changes with `api admit --footprint`: changed rows retain their identity and before/after values, and unexplained field differences refuse. Variation alone does not establish server ownership. | This PR | Synthetic headless Chromium and SQLite; generated insert ID/time differences conservatively refuse | `openadapt_flow/api_footprint.py` | @@ -352,6 +356,7 @@ improvising or retrying when something is off. | Try `openadapt wrap` with one command: `uvx --python 3.12 'openadapt[wrap]@latest' wrap --example` (the `wrap` extra brings the agent SDK; the base launcher leaves it out) starts a bundled synthetic clinic app (MockMed) on 127.0.0.1, has OpenAdapt's built-in Claude agent save one note in a headless browser, reads the save back, compiles the run, runs a canary, and admits it with a throwaway key made in the example's own folder (the proposed checks are confirmed automatically, which only a synthetic app allows). Then a new note runs the compiled program over its emitted MCP server with no model calls, and it prints the app's record and the cost of both runs. It needs `ANTHROPIC_API_KEY` (or `OPENAI_API_KEY` with `--provider openai`, `--model` and reviewed `--price` values); the task is packaged data (`openadapt_flow/wrap/examples/`). Because the data is synthetic, screenshots go to the model unscrubbed under the recorded opt-out. Emitted MCP tools now run the program off the server's event loop, so a compiled browser program runs when called over MCP (it failed with Playwright's "Sync API inside the asyncio loop" error before) | In PR | Synthetic (the bundled app, headless Chromium and the real `build_agent` Claude loop with its token-count reservation and spend cap; CI uses a scripted model client in place of the Anthropic SDK). One real run (Claude Opus 5.5, macOS, before release): run 1 made 5 model calls for $0.15 and was admitted; run 2 made none and was read back `VERIFIED` ([benchmark/wrap_example](packages/flow/benchmark/wrap_example/real-run-2026-11-21.json)) | [WRAP.md](packages/flow/docs/WRAP.md), `openadapt_flow.wrap.example`, `openadapt_flow.compile_agent.run_compiled_tool`, `packages/flow/tests/e2e/test_wrap_example_e2e.py` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory, and no compiled pixel check covers a withheld field's black box (it is clipped clear of it or dropped). Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | On main ([#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294), merged 2026-11-20) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | Sign-ins with a second factor: a `second_factor` step (`code` for a text-message, email or authenticator code, `approval` for a push approval) waits for a person when it runs, through the runner's control plane, a local command, or the run's own terminal when it has one (on a POSIX terminal or the Windows console; the code is never echoed, and normal input comes back however the read ends). Before anyone is asked, the focused field must be an empty `autocomplete="one-time-code"` input and the page draws it as dots; after the answer the same field must still have focus and be empty. The code is filled once into that element (a field split into one box per character is refused), never retried, and never stored, logged, shown to a model or drawn on screen. No source, a late or malformed answer, a decline, a field that changed, or a backend that can't bind the field stops the step before typing with a closed `second_factor_*` code; an older runtime refuses the bundle. Over the control plane the code is sealed in the person's browser to a one-step key the control plane can't open. The wrap recorder finds a code field from `autocomplete="one-time-code"` alone; it doesn't detect push approvals, and only the local browser backend can take a code | In PR | Synthetic (a notes app with an authenticator page in headless Chromium through the real wrap path: first run, canary, admission, publish staging, a cached run and a declined run, with a byte scan for the TOTP secret and recent codes; headless-browser tests that two codes render the same pixels and that a focus change, a prefilled field or an auto-submitting page are handled; unit tests for every source, late answers, the step shape and every refusal; pty tests that a terminal prompt hides the code, restores echo after a timeout and answers the next prompt; the Windows console reader's deadline and discard logic on a fake keyboard). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, `openadapt_flow.runtime.second_factor_step`, [SECOND_FACTOR.md](packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.py`, `packages/flow/tests/test_second_factor_browser.py`, `packages/flow/tests/test_second_factor_terminal.py`, `packages/flow/tests/test_second_factor_console.py`, `packages/flow/tests/e2e/test_wrap_second_factor_e2e.py` | +| Wrap any agent process: `openadapt wrap --task TASK --param ... -- COMMAND` starts the command for the first run with `OPENADAPT_MCP_URL` (a streamable-HTTP MCP endpoint on 127.0.0.1), `OPENADAPT_MCP_TOKEN` (a random per-run bearer token, compared in constant time, never printed) and `OPENADAPT_TASK`. The endpoint's tools (`observe`, `click`, `type_text`, `press_key`, `scroll`, `finish`) go through compile-agent's harness: the save gate, the read-back after every save, the task's origin limits and the recorder. The command gets no browser handle (no DevTools endpoint), so the draft carries the signed capture admission requires; the endpoint closes when the command exits, a nonzero exit makes no program and is passed through as wrap's exit status, and the command's process group is stopped after `--command-timeout`. Run 1's cost is reported as unknown (the command's model calls are its own). `openadapt wrap run --task TASK` runs only the admitted program, never an agent | In PR | Synthetic (an outside Python process with the `mcp` client SDK and no model does the bundled clinic task through the endpoint in headless Chromium: save gate, read-back, canary, admission by a registered admitter key under a signed teach authorization, then the emitted tool with no model calls; a failing command and a request without the token make no program) | [WRAP.md](packages/flow/docs/WRAP.md#wrap-your-own-agent), `openadapt_flow.wrap.process`, `packages/flow/examples/wrap_command/agent.py`, `packages/flow/tests/e2e/test_wrap_command_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](packages/flow/docs/AGENT_FRAMEWORKS.md) | | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | | Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks. The approval card shows each field's value now, the value the held save sends (read by the app's `write_adapter`; without one the card says the values were not read and not checked before saving, and shows a screenshot and the form's values on screen taken when the save is held; with neither a value nor a readable screenshot no approval is offered and the run ends `ESCALATED` `values_unread`), the task's value beside it and its source; each save gets a ledger row with no values whose outcome follows the guard's own verdict, and a 0600 diff; the read-back goes through a `ReadbackProvider` where only an independent read can verify | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)); card values, ledger row and `ReadbackProvider` in PR [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults; the approval card in headless Chromium with and without MockMed's write adapter) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](packages/flow/docs/GUARD_AN_AGENT.md) | diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0317-steps-drawn-as-links-tabs-or-menu-items-and-the.md b/capabilities/04-the-core-a-checked-entry-every-time/0317-steps-drawn-as-links-tabs-or-menu-items-and-the.md new file mode 100644 index 0000000000..71c9fa8a0f --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0317-steps-drawn-as-links-tabs-or-menu-items-and-the.md @@ -0,0 +1 @@ +| Steps drawn as links, tabs or menu items, and the commit point learned from the demonstration: a step's role (commit, navigate, in place) comes from the writes the backend counted, never its words; a commit holds only on exactly the demonstrated writes, and a backend that cannot count writes never attempts one | On main ([#2499](https://github.com/OpenAdaptAI/OpenAdapt/pull/2499)) | Synthetic: a web form, an EMR-like chart, a SaaS settings page (headless Chromium) and a spreadsheet-like grid with no browser | `openadapt_flow.gui.steps`, `packages/flow/tests/gui` | diff --git a/capabilities/CAPABILITIES.md.sha256 b/capabilities/CAPABILITIES.md.sha256 index 258d840f6a..a92d0aaaf1 100644 --- a/capabilities/CAPABILITIES.md.sha256 +++ b/capabilities/CAPABILITIES.md.sha256 @@ -1 +1 @@ -5828c214b5d23d77e08c7a6feb1f7e58b220467ca05894d87d2fddc6bd91f96f +6df073cac92b3e1998b04f9e83520994614d253611d8f1f6597499ba8746651e diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index fe01a77ff0..c75eb8811d 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -73,6 +73,12 @@ ### Features +- Links, tabs and menu items can be steps (`openadapt_flow.gui.steps`). Each + demonstrated click gets its role from what the backend counted: a commit + when it wrote, a navigation when the screen changed with no write. A live + commit holds only on exactly the demonstrated writes. `openadapt_flow.gui` + is a neutral view of a screen (role, name, state, containers) with adapters + for a browser page, an accessibility tree and a `form_tx` snapshot. - One verdict kernel, `openadapt_flow.verdict`, for every check that turns evidence into held, refuted or not checked. It fixes the obligations from the plan first, settles results against them, and never passes an empty diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index 236df580f5..fc9ec70c56 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -291,6 +291,8 @@ Done: - [x] `receipt_record._tally_lines` (C2 C3): fix: a line check nobody listed keeps the run from VERIFIED and counts as not checked. - [x] `tx/wire_tap.relay_redirect_location` (C6): registered after #2470. +- [x] `gui.steps.judge_step` (C3 C5): new. A commit holds only on exactly + the demonstrated writes; an unlisted step role is not checked. Next, most bug-prone first: diff --git a/packages/flow/openadapt_flow/gui/__init__.py b/packages/flow/openadapt_flow/gui/__init__.py new file mode 100644 index 0000000000..bbcddd672a --- /dev/null +++ b/packages/flow/openadapt_flow/gui/__init__.py @@ -0,0 +1,22 @@ +"""General GUI mechanisms over one neutral view of a screen. + +Programs that fill forms keep meeting the same few interface shapes in every +kind of app: a portal, an EMR chart, a spreadsheet grid, a SaaS settings page. +This package handles each shape once, over :mod:`openadapt_flow.gui.model` +(controls with a role, a name, a state and the containers they sit in), so no +mechanism depends on a browser or names an application: + +- :mod:`openadapt_flow.gui.steps`: a link, a tab or a button can be a step, + and the step that commits is the one the demonstration showed writing. + +Per-app facts (which control, which words, how many writes) are pack data, +learned from a demonstration or declared by the pack author. The engine holds +no word lists of its own. + +Adapters turn a backend's view into a :class:`~openadapt_flow.gui.model.Screen`: +:mod:`openadapt_flow.gui.dom` for a browser page, +:mod:`openadapt_flow.gui.adapters` for an accessibility tree (desktop, +spreadsheet) or a ``form_tx`` snapshot. + +Stdlib only, apart from the browser adapter. +""" diff --git a/packages/flow/openadapt_flow/gui/adapters.py b/packages/flow/openadapt_flow/gui/adapters.py new file mode 100644 index 0000000000..bfa4380fa5 --- /dev/null +++ b/packages/flow/openadapt_flow/gui/adapters.py @@ -0,0 +1,222 @@ +"""Turn other backends' views into a :class:`~openadapt_flow.gui.model.Screen`. + +- :func:`screen_from_tree`: an accessibility tree (UI Automation, AX, AT-SPI, + or a spreadsheet's cell grid exported as one). Each node is a mapping with + ``role``, ``name`` and optional ``handle``, ``value``, ``checked``, + ``disabled``, ``readonly``, ``target``, ``text`` and ``children``. Nodes + whose role is a container role (:data:`CONTAINER_ROLES`) become containers + of the controls under them; a ``dialog`` node also becomes a + :class:`~openadapt_flow.gui.model.Dialog`. +- :func:`screen_from_form_snapshot`: a ``form_tx`` ``FormSnapshot``, read by + attribute so this module does not import ``form_tx``. That snapshot keeps + section and row text, not container handles, so the containers it gives are + named by their text and carry no structure beyond it. + +Role names are mapped through :data:`TREE_ROLES`; an unknown role is +``other`` and never acts as a control a mechanism can use. +""" + +from __future__ import annotations + +from typing import Any, Mapping, Optional + +from openadapt_flow.gui.model import ROLES, Container, Control, Dialog, Screen + +__all__ = [ + "CONTAINER_ROLES", + "TREE_ROLES", + "screen_from_form_snapshot", + "screen_from_tree", +] + +#: Accessibility role names from common trees, mapped to :data:`ROLES`. +TREE_ROLES: Mapping[str, str] = { + "edit": "textbox", + "text field": "textbox", + "textfield": "textbox", + "entry": "textbox", + "searchbox": "textbox", + "spinbutton": "textbox", + "check box": "checkbox", + "check_box": "checkbox", + "toggle button": "switch", + "radio button": "radio", + "radiobutton": "radio", + "combo box": "combobox", + "popupbutton": "combobox", + "list": "listbox", + "push button": "button", + "hyperlink": "link", + "tab item": "tab", + "tabitem": "tab", + "page tab": "tab", + "menu item": "menuitem", + "dataitem": "cell", + "data item": "cell", + "gridcell": "cell", + "table cell": "cell", + "static text": "text", + "statictext": "text", + "label": "text", +} + +#: Tree roles that hold controls rather than being one, and their kind. +CONTAINER_ROLES: Mapping[str, str] = { + "group": "group", + "grouping": "group", + "pane": "region", + "region": "region", + "section": "region", + "form": "form", + "dialog": "dialog", + "window": "region", + "row": "row", + "dataitem row": "row", + "list item": "item", + "listitem": "item", + "table": "region", + "grid": "region", + "sheet": "region", +} + + +def _role(raw: object) -> str: + key = " ".join(str(raw or "").split()).casefold() + if key in ROLES: + return key + return TREE_ROLES.get(key, "other") + + +def screen_from_tree( + root: Mapping[str, Any], + *, + location: str = "", + title: str = "", + complete: bool = True, +) -> Screen: + """Flatten ``root`` into a :class:`Screen`. A node without ``handle`` gets + its index path (``0/2/1``), which is stable only while the tree is.""" + + controls: list[Control] = [] + dialogs: list[Dialog] = [] + texts: list[str] = [] + + def walk( + node: Mapping[str, Any], + path: str, + boxes: tuple[Container, ...], + dialog: str, + ) -> None: + handle = str(node.get("handle") or path) + raw_role = " ".join(str(node.get("role") or "").split()).casefold() + name = str(node.get("name") or "") + kind = CONTAINER_ROLES.get(raw_role) + if node.get("text"): + texts.append(str(node["text"])) + if kind is not None: + box = Container(handle, kind, name, str(node.get("text") or name)) + boxes = boxes + (box,) + if kind == "dialog" and raw_role == "dialog": + dialogs.append(Dialog(handle, name, str(node.get("text") or ""))) + dialog = handle + else: + role = _role(raw_role) + if role != "other": + checked = node.get("checked") + controls.append( + Control( + handle=handle, + role=role, + name=name, + value=str(node.get("value") or ""), + checked=None if checked is None else bool(checked), + disabled=bool(node.get("disabled")), + readonly=bool(node.get("readonly")), + required=bool(node.get("required")), + containers=boxes, + dialog=dialog, + target=str(node.get("target") or ""), + error=str(node.get("error") or ""), + ) + ) + for i, child in enumerate(node.get("children") or ()): + walk(child, f"{path}/{i}", boxes, dialog) + + walk(root, "0", (), "") + return Screen( + controls=tuple(controls), + dialogs=tuple(dialogs), + location=location, + title=title or str(root.get("name") or ""), + text="\n".join(texts), + complete=complete, + ) + + +def _snapshot_role(ctrl: Any) -> str: + role = _role(getattr(ctrl, "role", "")) + if role != "other": + return role + tag = str(getattr(ctrl, "tag", "")).casefold() + kind = str(getattr(ctrl, "input_type", "")).casefold() + if tag == "a": + return "link" + if tag == "button" or kind in ("submit", "button", "reset", "image"): + return "button" + if tag == "select": + return "combobox" + if kind in ("checkbox", "radio"): + return kind + if tag in ("input", "textarea"): + return "textbox" + return "other" + + +def screen_from_form_snapshot(snapshot: Any) -> Screen: + """A ``form_tx`` snapshot as a :class:`Screen`. Containers are the + control's section text and row text, named by that text.""" + + controls = [] + for ctrl in getattr(snapshot, "controls", ()) or (): + if not getattr(ctrl, "visible", True) or getattr(ctrl, "is_secret", False): + continue + boxes: list[Container] = [] + section = str(getattr(ctrl, "section_text", "") or "") + if section: + boxes.append(Container(f"section:{section}", "region", section, section)) + row = str(getattr(ctrl, "row_text", "") or "") + if row: + boxes.append(Container(f"row:{row}", "row", "", row)) + modal = str(getattr(ctrl, "modal_container", "") or "") + checked: Optional[bool] = getattr(ctrl, "checked", None) + controls.append( + Control( + handle=str(getattr(ctrl, "dom_selector")), + role=_snapshot_role(ctrl), + name=str(getattr(ctrl, "label_text", "") or ""), + value=str(getattr(ctrl, "current_value", "") or ""), + checked=checked, + disabled=bool(getattr(ctrl, "disabled", False)), + readonly=bool(getattr(ctrl, "readonly", False)), + required=bool(getattr(ctrl, "required", False)), + containers=tuple(boxes), + dialog=modal, + error=str(getattr(ctrl, "error_text", "") or ""), + ) + ) + dialogs = tuple( + Dialog( + str(getattr(m, "container_selector", "")), + str(getattr(m, "modal_id", "")), + str(getattr(m, "message_text", "") or ""), + ) + for m in getattr(snapshot, "active_modals", ()) or () + ) + return Screen( + controls=tuple(controls), + dialogs=dialogs, + location=str(getattr(snapshot, "url_origin_and_path", "") or ""), + title=str(getattr(snapshot, "title", "") or ""), + text=str(getattr(snapshot, "page_text", "") or ""), + errors=tuple(getattr(snapshot, "banner_errors", ()) or ()), + ) diff --git a/packages/flow/openadapt_flow/gui/dom.py b/packages/flow/openadapt_flow/gui/dom.py new file mode 100644 index 0000000000..27c30b52b0 --- /dev/null +++ b/packages/flow/openadapt_flow/gui/dom.py @@ -0,0 +1,492 @@ +"""Read a browser page as a :class:`~openadapt_flow.gui.model.Screen`, and act on it. + +:data:`OBSERVE_JS` walks the page once and returns every visible control a +person can act on, links included (``a[href]`` and ``role="link"``), with its +role, accessible name, value, checked state, the containers it sits in and +the dialog that holds it. Roles come from the element's ARIA role, else from +its tag and type, never from its text. + +:class:`PageActuator` drives a Playwright ``Page`` (sync API) and counts +writes: every request whose method is not GET, HEAD or OPTIONS, plus GET +requests whose path matches a pattern the pack declares (an app whose commit +is a plain link). Nothing else counts, so a page that saves by some other +route shows no write, and no write means no commit. + +A write counts only when it answered 2xx or 3xx, and the actuator keeps what +each counted write returned (:meth:`PageActuator.write_outcomes`): ``"2xx"``, +or ``"redirect "`` for a 3xx, so a replay that is bounced to a sign-in +page does not pass for one that saved. A 4xx or 5xx, a 3xx with no +``Location``, and a request that failed are write errors. The page's own +origin is read when an action starts and cleared when :meth:`PageActuator.observe` +has read the settled page, so a later response is not judged against it. + +The redirect key (:func:`location_key`) is the ``Location`` path, without a +trailing slash, then ``?`` and the query's ``key=value`` pairs, decoded, +re-quoted and sorted (a blank value kept, a repeated key kept once per +value). Only the fragment is dropped, so ``/register?status=saved`` and +``/register?status=session-expired`` differ, as do ``?page=done`` and +``?page=login``. A target on another origin than the request's is prefixed +with that origin. An id the server mints is replaced by ``{id}`` before the +two are compared: a path segment that is all digits, a UUID, or 16 or more +hex characters, and a query value that is a UUID or 16 or more hex +characters. So a post-redirect-get to the new record (``/records/101`` in +the demo, ``/records/102`` on replay) matches, and ``/records/{id}`` still +differs from ``/login``. Words are never replaced. + +An outcome learned before this format (``"3xx "``, path only) is not +compared: :func:`~openadapt_flow.gui.steps.take_step` does not click such a +commit, and :func:`~openadapt_flow.gui.steps.judge_step` does not check it. + +Known limits: + +- A query value that is all digits is kept as it is, because a number in a + query is as often a result code (``?saved=1`` vs ``?saved=0``) as a + record id. A redirect to ``?id=101`` in the demo and ``?id=102`` on replay + is refuted on every run, failing closed. +- A page that starts a ``fetch()`` write and then navigates away aborts its + own request (``net::ERR_ABORTED``). That shows as a write error, so such a + step is refuted on every run, failing closed, even when the server got the + write. + +Handles are CSS paths (``#id`` when the id is unique, else ``nth-of-type`` +steps), computed without touching the page. +""" + +from __future__ import annotations + +import re +from typing import Any, Optional, Sequence + +from openadapt_flow.gui.model import ROLES, Container, Control, Dialog, Screen + +__all__ = ["OBSERVE_JS", "REDIRECT", "PageActuator", "location_key", "screen_from_dom"] + +#: Cap on the page text kept; a longer page is a partial read. +TEXT_CAP = 20000 + +OBSERVE_JS = r"""(textCap) => { + const clean = (s) => String(s || '').replace(/\s+/g, ' ').trim(); + const visible = (el) => { + if (!el.isConnected) return false; + const st = getComputedStyle(el); + if (st.visibility === 'hidden' || st.display === 'none') return false; + if (el.closest('[hidden], [aria-hidden="true"]')) return false; + return el.getClientRects().length > 0; + }; + const path = (el) => { + if (el.id && document.querySelectorAll('#' + CSS.escape(el.id)).length === 1) + return '#' + CSS.escape(el.id); + const parts = []; + let node = el; + while (node && node.nodeType === 1 && node !== document.documentElement) { + if (node.id && document.querySelectorAll('#' + CSS.escape(node.id)).length === 1) { + parts.unshift('#' + CSS.escape(node.id)); + return parts.join(' > '); + } + const tag = node.tagName.toLowerCase(); + let i = 1; + for (let s = node.previousElementSibling; s; s = s.previousElementSibling) + if (s.tagName === node.tagName) i++; + parts.unshift(tag + ':nth-of-type(' + i + ')'); + node = node.parentElement; + } + return 'html > ' + parts.join(' > '); + }; + const byIds = (ids) => clean(String(ids || '').split(/\s+/).map((id) => { + const n = id && document.getElementById(id); + return n ? n.textContent : ''; + }).join(' ')); + const ownText = (el) => { + const c = el.cloneNode(true); + for (const x of c.querySelectorAll('input, select, textarea')) x.remove(); + return clean(c.textContent); + }; + const roleOf = (el) => { + const aria = (el.getAttribute('role') || '').toLowerCase(); + const map = {textbox: 'textbox', searchbox: 'textbox', checkbox: 'checkbox', + switch: 'switch', radio: 'radio', combobox: 'combobox', listbox: 'listbox', + button: 'button', link: 'link', tab: 'tab', menuitem: 'menuitem', + gridcell: 'cell', cell: 'cell', spinbutton: 'textbox'}; + if (map[aria]) return map[aria]; + const tag = el.tagName.toLowerCase(); + if (tag === 'a') return el.hasAttribute('href') ? 'link' : null; + if (tag === 'button') return 'button'; + if (tag === 'select') return el.multiple ? 'listbox' : 'combobox'; + if (tag === 'textarea') return 'textbox'; + if (tag === 'input') { + const t = (el.getAttribute('type') || 'text').toLowerCase(); + if (t === 'hidden' || t === 'file') return null; + if (t === 'checkbox') return 'checkbox'; + if (t === 'radio') return 'radio'; + if (['submit', 'button', 'reset', 'image'].includes(t)) return 'button'; + return 'textbox'; + } + if (el.isContentEditable && el.getAttribute('contenteditable') !== null) return 'textbox'; + return null; + }; + const nameOf = (el, role) => { + const aria = clean(el.getAttribute('aria-label')) || byIds(el.getAttribute('aria-labelledby')); + if (aria) return aria; + if (el.id) { + const lab = document.querySelector('label[for="' + CSS.escape(el.id) + '"]'); + if (lab) return ownText(lab); + } + const wrap = el.closest('label'); + if (wrap) return ownText(wrap); + if (['button', 'link', 'tab', 'menuitem'].includes(role)) { + if (el.tagName === 'INPUT') return clean(el.value); + return clean(el.textContent) || clean(el.getAttribute('title')); + } + return clean(el.getAttribute('title')) || clean(el.getAttribute('placeholder')) + || clean(el.getAttribute('name')); + }; + const KINDS = [['fieldset', 'group'], ['[role="group"]', 'group'], + ['[role="dialog"], [role="alertdialog"], dialog', 'dialog'], + ['[role="region"], section', 'region'], ['form', 'form'], + ['tr, [role="row"]', 'row'], ['li, [role="listitem"], article', 'item']]; + const containerName = (node, kind) => { + const aria = clean(node.getAttribute('aria-label')) || byIds(node.getAttribute('aria-labelledby')); + if (aria) return aria; + if (kind === 'group' && node.tagName === 'FIELDSET') { + const lg = node.querySelector(':scope > legend'); + if (lg) return clean(lg.textContent); + } + if (kind === 'row') { + const th = node.querySelector(':scope > th, :scope > [role="rowheader"]'); + return th ? clean(th.textContent) : ''; + } + const h = node.querySelector(':scope > h1, :scope > h2, :scope > h3, :scope > h4, :scope > h5, :scope > h6, :scope > header h1, :scope > header h2, :scope > header h3, :scope > header h4'); + return h ? clean(h.textContent) : ''; + }; + const chain = (el) => { + const out = []; + for (let n = el.parentElement; n && n !== document.body; n = n.parentElement) { + for (const [sel, kind] of KINDS) { + if (n.matches(sel)) { + out.unshift({handle: path(n), kind, name: containerName(n, kind), + text: clean(n.innerText).slice(0, 300)}); + break; + } + } + } + return out; + }; + const dialogs = []; + for (const d of document.querySelectorAll('[role="dialog"], [role="alertdialog"], dialog[open], [aria-modal="true"]')) { + if (!visible(d)) continue; + dialogs.push({handle: path(d), name: containerName(d, 'dialog'), + text: clean(d.innerText).slice(0, 2000), + modal: d.getAttribute('aria-modal') === 'true' || d.tagName === 'DIALOG' || d.getAttribute('role') === 'alertdialog'}); + } + const dialogOf = (el) => { + const d = el.closest('[role="dialog"], [role="alertdialog"], dialog[open], [aria-modal="true"]'); + return d && visible(d) ? path(d) : ''; + }; + const controls = []; + const seen = new Set(); + for (const el of document.querySelectorAll('input, select, textarea, button, a, [role], [contenteditable]')) { + const role = roleOf(el); + if (!role || seen.has(el) || !visible(el)) continue; + seen.add(el); + let value = ''; + let checked = null; + if (role === 'checkbox' || role === 'switch' || role === 'radio') { + checked = el.tagName === 'INPUT' ? !!el.checked : el.getAttribute('aria-checked') === 'true'; + value = el.tagName === 'INPUT' ? String(el.value || '') : ''; + } else if (el.tagName === 'SELECT') { + const o = el.selectedOptions && el.selectedOptions[0]; + value = o ? clean(o.textContent) : ''; + } else if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') { + if (role !== 'button') value = String(el.value || ''); + } else if (role === 'textbox' || role === 'cell') { + value = clean(el.textContent); + } + const errId = el.getAttribute('aria-errormessage') || ''; + controls.push({ + handle: path(el), role, name: nameOf(el, role), value, checked, + disabled: !!el.disabled || el.getAttribute('aria-disabled') === 'true', + readonly: !!el.readOnly || el.getAttribute('aria-readonly') === 'true', + required: !!el.required || el.getAttribute('aria-required') === 'true', + containers: chain(el), dialog: dialogOf(el), + target: role === 'link' ? (el.getAttribute('href') || '') : '', + error: el.getAttribute('aria-invalid') === 'true' ? byIds(errId) : '', + }); + } + const errors = []; + for (const a of document.querySelectorAll('[role="alert"]')) { + if (visible(a) && clean(a.textContent)) errors.push(clean(a.textContent)); + } + const text = String(document.body ? document.body.innerText : ''); + return {controls, dialogs, errors, title: document.title, + location: location.pathname + location.search, + text: text.slice(0, textCap), complete: text.length <= textCap}; +}""" + + +def screen_from_dom(raw: dict[str, Any]) -> Screen: + """Build a :class:`Screen` from what :data:`OBSERVE_JS` returned.""" + + controls = [] + for c in raw.get("controls") or (): + role = c.get("role") if c.get("role") in ROLES else "other" + controls.append( + Control( + handle=str(c["handle"]), + role=role, + name=str(c.get("name") or ""), + value=str(c.get("value") or ""), + checked=c.get("checked"), + disabled=bool(c.get("disabled")), + readonly=bool(c.get("readonly")), + required=bool(c.get("required")), + containers=tuple( + Container( + str(b["handle"]), + str(b.get("kind") or "group"), + str(b.get("name") or ""), + str(b.get("text") or ""), + ) + for b in c.get("containers") or () + ), + dialog=str(c.get("dialog") or ""), + target=str(c.get("target") or ""), + error=str(c.get("error") or ""), + ) + ) + return Screen( + controls=tuple(controls), + dialogs=tuple( + Dialog( + str(d["handle"]), + str(d.get("name") or ""), + str(d.get("text") or ""), + bool(d.get("modal")), + ) + for d in raw.get("dialogs") or () + ), + location=str(raw.get("location") or ""), + title=str(raw.get("title") or ""), + text=str(raw.get("text") or ""), + complete=bool(raw.get("complete")), + errors=tuple(str(e) for e in raw.get("errors") or ()), + ) + + +_READ_ONLY_METHODS = frozenset({"GET", "HEAD", "OPTIONS"}) + + +def _origin_of(url: str) -> str: + """Return normalized ``scheme://netloc`` for an HTTP(S) URL, or empty string.""" + from urllib.parse import urlsplit + + parts = urlsplit(url) + if parts.scheme not in ("http", "https") or not parts.netloc: + return "" + return f"{parts.scheme.lower()}://{parts.netloc.lower()}" + + +#: The prefix of a redirect outcome: ``"redirect "``. +REDIRECT = "redirect " + +#: What an id the server mints is replaced by in a redirect key. +ID_PLACEHOLDER = "{id}" + +_UUID = re.compile( + r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}" +) +_LONG_HEX = re.compile(r"[0-9a-fA-F]{16,}") +_DIGITS = re.compile(r"[0-9]+") + + +def _minted(value: str, *, digits: bool) -> bool: + """Whether a whole, decoded path segment or query value is an id.""" + if _UUID.fullmatch(value) or _LONG_HEX.fullmatch(value): + return True + return digits and _DIGITS.fullmatch(value) is not None + + +def _part(value: str, *, digits: bool) -> str: + from urllib.parse import quote + + return ID_PLACEHOLDER if _minted(value, digits=digits) else quote(value, safe="") + + +def location_key(request_url: str, target: str) -> str: + """A redirect target as the demo and a replay compare it. + + The path, without a trailing slash, each segment decoded and re-quoted, + and an id segment (all digits, a UUID, 16+ hex) replaced by ``{id}``; + then ``?`` and the sorted ``key=value`` query pairs, decoded and + re-quoted, with a UUID or 16+ hex value replaced by ``{id}``. The + fragment is dropped. A target on another origin than the request's is + prefixed with that origin.""" + from urllib.parse import parse_qsl, quote, unquote, urlsplit + + parts = urlsplit(target) + segments = [ + _part(unquote(seg), digits=True) if seg else "" + for seg in parts.path.rstrip("/").split("/") + ] + path = "/".join(segments) or "/" + pairs = sorted( + (quote(k, safe=""), _part(v, digits=False)) + for k, v in parse_qsl(parts.query, keep_blank_values=True) + ) + query = "&".join(f"{k}={v}" for k, v in pairs) + key = f"{path}?{query}" if query else path + origin = _origin_of(target) + return key if origin == _origin_of(request_url) else f"{origin}{key}" + + +class PageActuator: + """An :class:`~openadapt_flow.gui.model.Actuator` over a Playwright page. + + ``write_get_paths`` are regular expressions, from the pack, for GET + requests that change state on this app (a commit drawn as a plain link). + ``allowed_origins`` are extra origins (from the pack) whose write responses + count in addition to the page's own origin; third-party beacons to other + origins are ignored. + """ + + def __init__( + self, + page: Any, + *, + write_get_paths: Sequence[str] = (), + allowed_origins: Sequence[str] = (), + ) -> None: + self.page = page + self._writes = 0 + self._write_errors: list[str] = [] + self._outcomes: list[str] = [] + self._step_origin = "" + self._get_writes = tuple(re.compile(p) for p in write_get_paths) + self._allowed_origins = frozenset( + o for o in (_origin_of(raw) for raw in allowed_origins) if o + ) + page.on("response", self._on_response) + page.on("requestfailed", self._on_request_failed) + + def _is_counted_write_request(self, request: Any) -> bool: + req_url = str(request.url) + req_origin = _origin_of(req_url) + page_origin = self._step_origin or self._page_origin() + if not req_origin: + return False + if req_origin != page_origin and req_origin not in self._allowed_origins: + return False + method = str(request.method).upper() + if method not in _READ_ONLY_METHODS: + return True + if self._get_writes: + from urllib.parse import urlsplit + + path = urlsplit(req_url).path + if any(p.search(path) for p in self._get_writes): + return True + return False + + def _page_origin(self) -> str: + return _origin_of(str(getattr(self.page, "url", "") or "")) + + def _start_action(self) -> None: + # The page's origin when the action starts: a response that arrives + # mid-navigation must not make the new page's origin "own". + self._step_origin = self._page_origin() + + def _on_response(self, response: Any) -> None: + from urllib.parse import urljoin, urlsplit + + request = response.request + if not self._is_counted_write_request(request): + return + status = int(response.status) + method = str(request.method).upper() + req_url = str(request.url) + path = urlsplit(req_url).path or "/" + if 200 <= status < 300: + self._writes += 1 + self._outcomes.append("2xx") + elif 300 <= status < 400: + headers = getattr(response, "headers", None) or {} + location = next( + (str(v) for k, v in headers.items() if str(k).lower() == "location"), + "", + ).strip() + target = urljoin(req_url, location) if location else "" + if not _origin_of(target): + self._write_errors.append( + f"{method} {path} returned HTTP {status} with no usable Location" + ) + return + self._writes += 1 + self._outcomes.append(REDIRECT + location_key(req_url, target)) + elif status >= 400: + self._write_errors.append(f"{method} {path} returned HTTP {status}") + + def _on_request_failed(self, request: Any) -> None: + if not self._is_counted_write_request(request): + return + from urllib.parse import urlsplit + + method = str(request.method).upper() + path = urlsplit(str(request.url)).path or "/" + failure = getattr(request, "failure", None) or "request failed" + self._write_errors.append(f"{method} {path} failed: {failure}") + + def write_outcomes(self) -> tuple[str, ...]: + """What each counted write returned, in arrival order: ``"2xx"`` or + ``"redirect "`` (see :func:`location_key`).""" + return tuple(self._outcomes) + + def write_errors(self) -> tuple[str, ...]: + """Refuting HTTP 4xx/5xx or failed write-request errors observed so far.""" + return tuple(self._write_errors) + + def _settle(self) -> None: + self.page.wait_for_load_state("load") + self.page.wait_for_load_state("networkidle") + + def observe(self) -> Screen: + """Read the page once it settles. A read cut off by a navigation is + retried on the new page; after three tries the error is raised.""" + + from playwright.sync_api import Error as PlaywrightError + + for attempt in range(3): + self._settle() + try: + screen = screen_from_dom(self.page.evaluate(OBSERVE_JS, TEXT_CAP)) + except PlaywrightError as exc: + if attempt == 2 or "context was destroyed" not in str(exc): + raise + self.page.wait_for_timeout(100) + continue + # The action's page is read; a response from here on is judged + # against the page as it is then, not the origin the action + # started on. + self._step_origin = "" + return screen + raise AssertionError("unreachable") + + def click(self, handle: str) -> None: + self._start_action() + self.page.locator(handle).click() + # A click may start a navigation or a request a moment later; give + # it time to start before waiting for the page to settle. + self.page.wait_for_timeout(150) + self._settle() + + def set_text(self, handle: str, value: str) -> None: + self._start_action() + self.page.locator(handle).fill(value) + self.page.locator(handle).dispatch_event("change") + self._settle() + + def set_checked(self, handle: str, checked: bool) -> None: + self._start_action() + self.page.locator(handle).set_checked(checked) + self._settle() + + def write_count(self) -> Optional[int]: + return self._writes diff --git a/packages/flow/openadapt_flow/gui/model.py b/packages/flow/openadapt_flow/gui/model.py new file mode 100644 index 0000000000..6e688f9326 --- /dev/null +++ b/packages/flow/openadapt_flow/gui/model.py @@ -0,0 +1,396 @@ +"""A neutral view of one screen, and how a pack names a control on it. + +Every backend reads a screen differently: a browser has a DOM, a desktop app +an accessibility tree, a spreadsheet a grid of cells. The mechanisms in this +package read only what they all share: + +- :class:`Control`: one thing a person can act on or read, with a normalised + ``role`` (:data:`ROLES`), its accessible ``name``, its value or checked + state, and the chain of :class:`Container` objects it sits in (a fieldset, + a card, a table row, a dialog), outermost first. +- :class:`Dialog`: an open dialog, and the controls inside it. +- :class:`Screen`: the controls, dialogs and containers seen at one moment. + ``complete`` is False when the backend capped or could not finish the read; + a partial screen can refute a check, never hold one. + +A :class:`ControlSpec` is pack data that names exactly one control by role, +name, containers and (for a link) target. :func:`match_one` resolves it; zero +or several matches are different failures, and neither picks a control. + +:class:`DemoStep` is one action of a demonstration with the screen before and +after it and the number of writes the backend counted in between. +:class:`Actuator` is what a mechanism needs from a live backend. + +Nothing here names an application or holds a word list. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Callable, Literal, Optional, Protocol, runtime_checkable + +__all__ = [ + "ACTIVATABLE", + "EDITABLE", + "ROLES", + "Actuator", + "AmbiguousControl", + "Container", + "Control", + "ControlSpec", + "DemoStep", + "Dialog", + "MissingControl", + "Recorder", + "Screen", + "match_all", + "match_one", + "norm", + "screen_signature", + "spec_for", + "write_outcomes_of", +] + +#: The roles a backend maps its controls to. Anything else is ``other``. +ROLES = frozenset( + { + "textbox", + "checkbox", + "switch", + "radio", + "combobox", + "listbox", + "button", + "link", + "tab", + "menuitem", + "cell", + "text", + "other", + } +) +#: Roles a person activates to move on, open something or commit. +ACTIVATABLE = frozenset({"button", "link", "tab", "menuitem"}) +#: Roles that hold a value a person enters. +EDITABLE = frozenset( + {"textbox", "checkbox", "switch", "radio", "combobox", "listbox", "cell"} +) + + +def norm(text: object) -> str: + """Whitespace collapsed and case folded: how names are compared.""" + + return " ".join(str(text or "").split()).casefold() + + +@dataclass(frozen=True) +class Container: + """A labelled or structural region around controls. + + ``handle`` is the backend's opaque id for it, stable within one screen + read and across reads of the same element. ``kind`` is what it is + structurally (``group``, ``row``, ``dialog``, ``region``, ``item``, + ``form``); ``name`` its own label or heading, possibly empty; ``text`` its + visible text, capped by the backend.""" + + handle: str + kind: str = "group" + name: str = "" + text: str = "" + + +@dataclass(frozen=True) +class Control: + """One control. ``handle`` is opaque to every mechanism: only the backend + that made it acts on it.""" + + handle: str + role: str + name: str = "" + value: str = "" + checked: Optional[bool] = None + disabled: bool = False + readonly: bool = False + required: bool = False + #: Containers, outermost first. Dialogs appear here too. + containers: tuple[Container, ...] = () + #: Handle of the open dialog that holds the control, or "". + dialog: str = "" + #: Where a link goes, as the backend reports it (opaque), or "". + target: str = "" + #: The control's own error message, if the backend shows one. + error: str = "" + + def __post_init__(self) -> None: + if self.role not in ROLES: + raise ValueError(f"unknown role {self.role!r}") + + @property + def editable(self) -> bool: + return self.role in EDITABLE and not self.disabled and not self.readonly + + @property + def activatable(self) -> bool: + return self.role in ACTIVATABLE and not self.disabled + + def container_names(self) -> tuple[str, ...]: + return tuple(norm(c.name) for c in self.containers if c.name) + + +@dataclass(frozen=True) +class Dialog: + handle: str + name: str = "" + text: str = "" + #: ``modal`` when the backend says the dialog blocks the rest of the screen. + modal: bool = True + + +@dataclass(frozen=True) +class Screen: + controls: tuple[Control, ...] = () + dialogs: tuple[Dialog, ...] = () + #: Where the screen is (a URL path, a window title, a sheet name): opaque. + location: str = "" + title: str = "" + text: str = "" + #: False when the backend capped the read or could not finish it. + complete: bool = True + #: Banner or summary errors the backend shows outside any one control. + errors: tuple[str, ...] = () + + def control(self, handle: str) -> Optional[Control]: + for ctrl in self.controls: + if ctrl.handle == handle: + return ctrl + return None + + def containers(self) -> dict[str, Container]: + out: dict[str, Container] = {} + for ctrl in self.controls: + for box in ctrl.containers: + out.setdefault(box.handle, box) + return out + + def in_dialog(self, dialog: str) -> tuple[Control, ...]: + return tuple(c for c in self.controls if c.dialog == dialog) + + +def screen_signature(screen: Screen) -> tuple[object, ...]: + """What has to change for a step to count as having moved the screen: + the location, the title, the open dialogs and the editable controls (by + role, name and handle). A value typed into a field does not change it.""" + + return ( + screen.location, + screen.title, + tuple(sorted(d.handle for d in screen.dialogs)), + tuple((c.role, norm(c.name), c.handle) for c in screen.controls if c.editable), + ) + + +# -- naming a control ------------------------------------------------------------- + + +class MissingControl(LookupError): + """No control on the screen matches the spec.""" + + +class AmbiguousControl(LookupError): + """More than one control matches the spec.""" + + +@dataclass(frozen=True) +class ControlSpec: + """Pack data naming one control. + + ``role`` is one of :data:`ROLES`, or ``"activatable"`` for any of + :data:`ACTIVATABLE` (a step that one version of an app draws as a button + and another as a link). ``name`` is compared whole after :func:`norm`, never + as a substring. ``containers`` must appear in the control's container names + in this order (other containers may sit between them). ``target``, when + set, must equal the link's target exactly. ``dialog`` says whether the + control must be inside an open dialog (True), outside every dialog + (False) or either (None).""" + + role: str + name: str + containers: tuple[str, ...] = () + target: Optional[str] = None + dialog: Optional[bool] = None + + def __post_init__(self) -> None: + if self.role != "activatable" and self.role not in ROLES: + raise ValueError(f"unknown role {self.role!r}") + if not norm(self.name): + raise ValueError("a control spec needs a name") + + def matches(self, ctrl: Control) -> bool: + if self.role == "activatable": + if ctrl.role not in ACTIVATABLE: + return False + elif ctrl.role != self.role: + return False + if norm(ctrl.name) != norm(self.name): + return False + if self.target is not None and ctrl.target != self.target: + return False + if self.dialog is not None and bool(ctrl.dialog) != self.dialog: + return False + return _in_order( + tuple(norm(c) for c in self.containers), ctrl.container_names() + ) + + +def _in_order(wanted: tuple[str, ...], have: tuple[str, ...]) -> bool: + at = 0 + for name in have: + if at < len(wanted) and name == wanted[at]: + at += 1 + return at == len(wanted) + + +def match_all(spec: ControlSpec, screen: Screen) -> tuple[Control, ...]: + return tuple(c for c in screen.controls if spec.matches(c)) + + +def match_one(spec: ControlSpec, screen: Screen) -> Control: + """The one control ``spec`` names. Raises :class:`MissingControl` or + :class:`AmbiguousControl`; it never picks the first of several.""" + + found = match_all(spec, screen) + if not found: + raise MissingControl(f"no {spec.role} named {spec.name!r}") + if len(found) > 1: + raise AmbiguousControl(f"{len(found)} controls match {spec.role} {spec.name!r}") + return found[0] + + +def spec_for( + ctrl: Control, + screen: Screen, + *, + role: Optional[str] = None, +) -> Optional[ControlSpec]: + """The narrowest spec that names ``ctrl`` alone on ``screen``: its role and + name, then its labelled containers and its link target as needed. None + when even all of them still match another control (two identical rows + with no label between them): the pack author has to say which.""" + + base = ControlSpec( + role=role or ctrl.role, + name=ctrl.name, + dialog=bool(ctrl.dialog), + ) + names = tuple(c.name for c in ctrl.containers if c.name) + tries = [base] + for n in range(1, len(names) + 1): + tries.append(ControlSpec(base.role, base.name, names[-n:], dialog=base.dialog)) + if ctrl.target: + tries += [ + ControlSpec(t.role, t.name, t.containers, ctrl.target, t.dialog) + for t in tries + ] + for spec in tries: + if match_all(spec, screen) == (ctrl,): + return spec + return None + + +# -- demonstrations and live backends --------------------------------------------- + +ActionKind = Literal["click", "type", "check", "uncheck", "select"] + + +@dataclass(frozen=True) +class DemoStep: + """One action of a demonstration. + + ``target`` is the control as seen in ``before``. ``writes`` is how many + writes the backend counted between ``before`` and ``after`` (requests that + change state, a file save, a cell committed), or None when it could not + count them. ``write_outcomes`` is what each of those writes returned + (``"2xx"``, ``"redirect /done"``), or None when the backend does not say.""" + + action: ActionKind + target: Control + before: Screen + after: Screen + writes: Optional[int] + value: str = "" + write_outcomes: Optional[tuple[str, ...]] = None + + +@runtime_checkable +class Actuator(Protocol): + """What a mechanism needs from a live backend. Every action waits for the + screen to settle before it returns.""" + + def observe(self) -> Screen: ... + + def click(self, handle: str) -> None: ... + + def set_text(self, handle: str, value: str) -> None: ... + + def set_checked(self, handle: str, checked: bool) -> None: ... + + def write_count(self) -> Optional[int]: + """Writes counted since the backend started, or None if it cannot + count them. A backend that cannot count can never show a commit.""" + ... + + +def write_outcomes_of(actuator: object) -> Optional[tuple[str, ...]]: + """What each write so far returned, from a backend's optional + ``write_outcomes()``, or None when it does not report them.""" + fn = getattr(actuator, "write_outcomes", None) + got = fn() if callable(fn) else None + return tuple(got) if isinstance(got, (tuple, list)) else None + + +@dataclass +class Recorder: + """Wrap an :class:`Actuator` and keep every action as a :class:`DemoStep`. + + Used to record a demonstration through the same backend a run uses.""" + + actuator: Actuator + steps: list[DemoStep] = field(default_factory=list) + + def _do( + self, + action: ActionKind, + handle: str, + run: Callable[[], None], + value: str = "", + ) -> None: + before = self.actuator.observe() + target = before.control(handle) + if target is None: + raise MissingControl(handle) + o0 = write_outcomes_of(self.actuator) + w0 = self.actuator.write_count() + run() + after = self.actuator.observe() + # Read after the screen settles, as a run does, so a late write is + # counted in the demo too. + w1 = self.actuator.write_count() + writes = None if w0 is None or w1 is None else w1 - w0 + o1 = write_outcomes_of(self.actuator) + outcomes = None if o0 is None or o1 is None else o1[len(o0) :] + self.steps.append( + DemoStep(action, target, before, after, writes, value, outcomes) + ) + + def click(self, handle: str) -> None: + self._do("click", handle, lambda: self.actuator.click(handle)) + + def set_text(self, handle: str, value: str) -> None: + self._do("type", handle, lambda: self.actuator.set_text(handle, value), value) + + def set_checked(self, handle: str, checked: bool) -> None: + self._do( + "check" if checked else "uncheck", + handle, + lambda: self.actuator.set_checked(handle, checked), + ) diff --git a/packages/flow/openadapt_flow/gui/steps.py b/packages/flow/openadapt_flow/gui/steps.py new file mode 100644 index 0000000000..097fee5356 --- /dev/null +++ b/packages/flow/openadapt_flow/gui/steps.py @@ -0,0 +1,426 @@ +"""Steps that move a form on, whatever control draws them, and the commit point. + +A form moves on when a person activates something: a "Next" button, a +"Continue" link, a step tab, a menu item. Packs used to list only buttons as +next controls, so a form whose next control was a link stopped with "next +button missing". Here any activatable control (:data:`~openadapt_flow.gui.model.ACTIVATABLE`) +can be a step, and what a step *does* comes from the demonstration, never +from its words: + +- :func:`learn_steps` reads each click of a demonstration and records what the + backend saw it do (:class:`StepRole`): ``commit`` when it counted writes, + ``navigate`` when the screen changed and nothing was written, ``in_place`` + when neither, ``unknown`` when the backend could not count writes. +- The commit points are the steps the demonstration showed writing + (:func:`commit_points`), with the number of writes each made. A link that + commits is a commit point because it wrote, not because it says "Submit". +- :func:`take_step` resolves a learned step on the live screen, clicks it + and asks :func:`judge_step` whether it did what the demonstration showed. + +:func:`judge_step` is a verdict site. A commit step holds only when the +backend counted exactly the writes the demonstration made, and each returned +what the demonstrated one did: the same status class and, for a redirect, +the same ``Location`` key (path and query, with minted ids replaced; see +:func:`~openadapt_flow.gui.dom.location_key`). A save bounced to a sign-in +page is a 302 like a save that went to its confirmation page; only the +``Location`` tells them apart. A commit spec with no recorded outcomes, or +with an outcome in the old path-only ``"3xx "`` form (an older pack), +is never clicked. A +backend that cannot count writes never shows a commit, so a commit through a +plain link that sends nothing the backend counts stays unproven, as it +should: the run has no evidence the record was saved. A navigation step that wrote, or that +left the screen as it was, is refuted. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +from typing import Optional, Sequence + +from openadapt_flow.gui.model import ( + Actuator, + AmbiguousControl, + Control, + ControlSpec, + DemoStep, + MissingControl, + Screen, + match_one, + screen_signature, + spec_for, + write_outcomes_of, +) +from openadapt_flow.verdict import Observed, Result, Status, Subject +from openadapt_flow.verdict_sites import verdict_site + +__all__ = [ + "LearnedStep", + "StepEvidence", + "StepOutcome", + "StepRole", + "StepSpec", + "commit_points", + "judge_step", + "learn_steps", + "take_step", +] + + +class StepRole(str, Enum): + COMMIT = "commit" + NAVIGATE = "navigate" + IN_PLACE = "in_place" + UNKNOWN = "unknown" + + +@dataclass(frozen=True) +class StepSpec: + """Pack data for one step: which control, and what it did in the demo. + + ``writes`` is the number of writes the demonstration counted for it: at + least 1 for a commit, 0 otherwise. ``outcomes`` is what each of a + commit's writes returned in the demo, sorted (``"2xx"``, + ``"redirect /done"``); None on a spec learned before outcomes were + recorded. Such a commit is not taken, and nor is one with an outcome in + the old ``"3xx "`` form.""" + + step_id: str + control: ControlSpec + role: StepRole + writes: int = 0 + outcomes: Optional[tuple[str, ...]] = None + + def __post_init__(self) -> None: + if not isinstance(self.role, StepRole): + raise ValueError(f"unknown step role {self.role!r}") + if self.role is StepRole.COMMIT and self.writes < 1: + raise ValueError("a commit step wrote at least once in the demo") + if self.role is not StepRole.COMMIT and self.writes != 0: + raise ValueError("only a commit step writes") + if self.outcomes is not None and ( + self.role is not StepRole.COMMIT or len(self.outcomes) != self.writes + ): + raise ValueError("a commit records one outcome per demonstrated write") + + +@dataclass(frozen=True) +class LearnedStep: + """What :func:`learn_steps` found for one demonstrated click. ``spec`` is + None when no spec names the control alone (``reason`` says why); the + pack author has to name it.""" + + index: int + control: Control + role: StepRole + writes: Optional[int] + spec: Optional[StepSpec] + reason: str = "" + + +def _role_of(step: DemoStep) -> StepRole: + if step.writes is None or step.writes < 0: + return StepRole.UNKNOWN + if step.writes > 0: + return StepRole.COMMIT + if screen_signature(step.after) != screen_signature(step.before): + return StepRole.NAVIGATE + return StepRole.IN_PLACE + + +def learn_steps(demo: Sequence[DemoStep]) -> tuple[LearnedStep, ...]: + """One :class:`LearnedStep` per click on an activatable control. + + A step's role comes from what the backend counted and saw, so the same + word ("Continue") can be a navigation in one app and a commit in + another, and a link and a button are treated alike.""" + + out = [] + for index, step in enumerate(demo): + if step.action != "click" or not step.target.activatable: + continue + role = _role_of(step) + spec = spec_for(step.target, step.before) + if role is StepRole.UNKNOWN: + out.append( + LearnedStep( + index, + step.target, + role, + step.writes, + None, + "the backend could not count writes for this click", + ) + ) + continue + if spec is None: + out.append( + LearnedStep( + index, + step.target, + role, + step.writes, + None, + "another control on the screen has the same role, name and containers", + ) + ) + continue + writes = int(step.writes or 0) if role is StepRole.COMMIT else 0 + outcomes = None + if role is StepRole.COMMIT: + outcomes = _outcomes(step.write_outcomes) + if outcomes is None or len(outcomes) != writes or _legacy(outcomes): + out.append( + LearnedStep( + index, + step.target, + role, + step.writes, + None, + "the backend did not report what this commit's writes returned", + ) + ) + continue + out.append( + LearnedStep( + index, + step.target, + role, + step.writes, + StepSpec(f"step-{index}", spec, role, writes, outcomes), + ) + ) + return tuple(out) + + +def commit_points(steps: Sequence[LearnedStep]) -> tuple[LearnedStep, ...]: + """The steps the demonstration showed writing, in order.""" + + return tuple(s for s in steps if s.role is StepRole.COMMIT) + + +# -- the verdict ------------------------------------------------------------------ + + +@dataclass(frozen=True) +class StepEvidence: + """What one live step did. ``moved`` is whether the screen signature + changed (None when the after read failed).""" + + step_id: str + role: object + expected_writes: object + writes_before: object + writes_after: object + moved: object + after_complete: object + after_errors: tuple[str, ...] = () + run_id: str = "" + #: What the demo's writes returned, and what this step's writes did. + expected_outcomes: object = None + outcomes: object = None + + +def _count(value: object) -> Optional[int]: + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + return None + return value + + +#: The prefix of a redirect outcome learned before the query and minted ids +#: were part of the key. Such an outcome is never compared: its path-only +#: key could match a replay that went somewhere else. +LEGACY_REDIRECT = "3xx " + + +def _legacy(outcomes: object) -> bool: + """Whether any outcome is in the old path-only redirect form.""" + return isinstance(outcomes, (tuple, list)) and any( + isinstance(o, str) and o.startswith(LEGACY_REDIRECT) for o in outcomes + ) + + +def _outcomes(value: object) -> Optional[tuple[str, ...]]: + """``value`` as a sorted tuple of non-empty strings, else None.""" + if not isinstance(value, (tuple, list)): + return None + if not all(isinstance(v, str) and v for v in value): + return None + return tuple(sorted(value)) + + +@verdict_site("gui.steps.judge_step", classes="C3 C5") +def judge_step(ev: StepEvidence) -> Result: + """Did the step do what the demonstration showed? + + - ``commit``: exactly ``expected_writes`` new writes, on a complete read + with no error shown, each returning what the demo's did (status class, + and the ``Location`` key of a redirect). No write, a different + number, or a different outcome is refuted; outcomes missing on either + side, or in the old path-only ``"3xx "`` form, are not checked. + - ``navigate``: the screen changed and nothing was written. + - ``in_place``: nothing was written and the screen did not move. + - ``unknown`` or any role nobody listed: not checked. + + A write count that is missing, negative or not a whole number is not + checked; so is a partial read with nothing to refute.""" + + subject = Subject(run_id=ev.run_id, surface="gui", key=ev.step_id, field="step") + obs = Observed(ev, complete=ev.after_complete is True) + try: + role = StepRole(ev.role) if not isinstance(ev.role, StepRole) else ev.role + except ValueError: + return Result.not_checked(subject, f"unlisted step role {ev.role!r}") + if role is StepRole.UNKNOWN: + return Result.not_checked( + subject, "the demo could not count this step's writes" + ) + before, after = _count(ev.writes_before), _count(ev.writes_after) + if before is None or after is None or after < before: + return Result.not_checked(subject, "the backend could not count writes") + delta = after - before + if ev.after_errors: + return Result.refuted( + subject, obs, f"the screen shows an error: {ev.after_errors[0]}" + ) + if role is StepRole.COMMIT: + want = _count(ev.expected_writes) + if not want: + return Result.not_checked(subject, "no expected write count for a commit") + if delta == 0: + return Result.refuted(subject, obs, "the commit step wrote nothing") + if delta != want: + return Result.refuted( + subject, + obs, + f"the commit step wrote {delta} times; the demo wrote {want}", + ) + want_out, got_out = _outcomes(ev.expected_outcomes), _outcomes(ev.outcomes) + if want_out is None or len(want_out) != want: + return Result.not_checked( + subject, "the demo did not record what its writes returned" + ) + if _legacy(want_out) or _legacy(got_out): + return Result.not_checked( + subject, + "an outcome is in the old path-only redirect form; relearn the step", + ) + if got_out is None or len(got_out) != delta: + return Result.not_checked( + subject, "the backend did not report what the writes returned" + ) + if got_out != want_out: + return Result.refuted( + subject, + obs, + f"the commit's writes returned {', '.join(got_out)}; " + f"the demo's returned {', '.join(want_out)}", + ) + elif delta: + return Result.refuted(subject, obs, f"a {role.value} step wrote {delta} times") + elif role is StepRole.NAVIGATE: + if ev.moved is False: + return Result.refuted(subject, obs, "the screen did not change") + if ev.moved is not True: + return Result.not_checked(subject, "the screen after the step was not read") + elif role is StepRole.IN_PLACE: + if ev.moved is True: + return Result.refuted(subject, obs, "an in-place step moved the screen") + if ev.moved is not False: + return Result.not_checked(subject, "the screen after the step was not read") + if ev.after_complete is not True: + return Result.not_checked(subject, "the screen after the step was read in part") + return Result.held(subject, obs, f"{role.value} as demonstrated") + + +# -- running a step --------------------------------------------------------------- + + +@dataclass(frozen=True) +class StepOutcome: + result: Result + clicked: bool + control: Optional[Control] = None + after: Optional[Screen] = None + + @property + def held(self) -> bool: + return self.result.status is Status.HELD + + +def take_step( + actuator: Actuator, + spec: StepSpec, + *, + run_id: str = "", + screen: Optional[Screen] = None, +) -> StepOutcome: + """Resolve ``spec`` on the live screen, click it, and judge it. + + Nothing is clicked when the control is missing or ambiguous, when the + backend cannot count writes (no step could be judged there, so none is + attempted), or for a commit when the spec or the backend has no record of + what the writes returned, or the spec has it only in the old path-only + redirect form.""" + + subject = Subject(run_id=run_id, surface="gui", key=spec.step_id, field="step") + before_screen = screen if screen is not None else actuator.observe() + try: + ctrl = match_one(spec.control, before_screen) + except (MissingControl, AmbiguousControl) as exc: + return StepOutcome(Result.not_checked(subject, str(exc)), clicked=False) + if not ctrl.activatable: + return StepOutcome( + Result.not_checked(subject, "the control is disabled"), False, ctrl + ) + w0 = actuator.write_count() + if w0 is None: + # Without a write count no step can be judged (a navigation must be + # shown not to write), so none is taken. + return StepOutcome( + Result.not_checked( + subject, "this backend cannot count writes; no step is taken" + ), + False, + ctrl, + ) + o0 = write_outcomes_of(actuator) + if spec.role is StepRole.COMMIT and ( + spec.outcomes is None or o0 is None or _legacy(spec.outcomes) + ): + # Without the demo's outcomes in the current form, or a backend that + # reports them, a commit bounced to a sign-in page looks like one + # that saved. + return StepOutcome( + Result.not_checked( + subject, + "the spec or the backend has no record of what the commit's " + "writes returned; the commit is not taken", + ), + False, + ctrl, + ) + err_fn = getattr(actuator, "write_errors", None) + err0 = len(err_fn()) if callable(err_fn) else 0 + actuator.click(ctrl.handle) + after = actuator.observe() + w1 = actuator.write_count() + write_errors = tuple(err_fn()[err0:]) if callable(err_fn) else () + o1 = write_outcomes_of(actuator) + outcomes = None if o0 is None or o1 is None else o1[len(o0) :] + ev = StepEvidence( + step_id=spec.step_id, + role=spec.role, + expected_writes=spec.writes if spec.role is StepRole.COMMIT else 0, + writes_before=w0, + writes_after=w1, + moved=screen_signature(after) != screen_signature(before_screen), + after_complete=after.complete, + after_errors=tuple(after.errors) + + tuple(c.error for c in after.controls if c.error) + + write_errors, + run_id=run_id, + expected_outcomes=spec.outcomes if spec.role is StepRole.COMMIT else None, + outcomes=outcomes, + ) + return StepOutcome(judge_step(ev), True, ctrl, after) diff --git a/packages/flow/tests/failopen/sites/gui_steps.py b/packages/flow/tests/failopen/sites/gui_steps.py new file mode 100644 index 0000000000..cdf01ca27c --- /dev/null +++ b/packages/flow/tests/failopen/sites/gui_steps.py @@ -0,0 +1,180 @@ +"""gui.steps.judge_step (C3 C5): did a step (a link, a tab, a button) do what +the demonstration showed? + +A commit holds only on exactly the demonstrated number of writes, each +returning what the demonstrated one did (a 302 to a sign-in page is not the +302 to the confirmation page the demo saw, and an outcome in the old +path-only ``"3xx "`` form is not checked); a +navigation only when the screen moved and nothing was written. Write counts +that are not whole numbers, and roles nobody listed, are not checked. + +No M8: the evidence is gathered in-process by ``take_step`` from the live +backend in the same call, not read back from a store another run could have +written, so there is no stored binding to swap. +""" + +from __future__ import annotations + +from typing import Any + +from openadapt_flow.gui.steps import StepEvidence, judge_step +from openadapt_flow.verdict import Status +from tests.failopen.harness import CodeCase, Lens, Seed, SiteSpec, register + +#: The fields each role's verdict depends on. +RELEVANT = { + "commit": ( + "role", + "expected_writes", + "writes_before", + "writes_after", + "after_complete", + "expected_outcomes", + "outcomes", + ), + "navigate": ("role", "writes_before", "writes_after", "moved", "after_complete"), + "in_place": ("role", "writes_before", "writes_after", "moved", "after_complete"), +} + + +def _ev(role: str, **over: Any) -> dict[str, Any]: + base = { + "step_id": "s1", + "role": role, + "expected_writes": 1 if role == "commit" else 0, + "writes_before": 3, + "writes_after": 4 if role == "commit" else 3, + "moved": role == "navigate", + "after_complete": True, + "after_errors": (), + "expected_outcomes": ("2xx",) if role == "commit" else None, + "outcomes": ("2xx",) if role == "commit" else None, + } + return {**base, **over} + + +def _relevant(ev: dict[str, Any]) -> tuple[str, ...]: + return RELEVANT.get(str(ev.get("role")), ("role",)) + + +def _fields() -> Lens: + def get(ev: dict[str, Any]) -> dict[str, Any]: + return {k: ev[k] for k in _relevant(ev) if k in ev} + + def put(ev: dict[str, Any], value: dict[str, Any]) -> None: + for k in _relevant(ev): + ev.pop(k, None) + ev.update(value) + + return Lens(get, put) + + +def _value(name: str) -> Lens: + def get(ev: dict[str, Any]) -> Any: + if name not in _relevant(ev): + raise KeyError(name) + return ev[name] + + def put(ev: dict[str, Any], value: Any) -> None: + from tests.failopen.harness import ABSENT + + if value is ABSENT: + ev.pop(name, None) + else: + ev[name] = value + + return Lens(get, put) + + +register( + SiteSpec( + id="gui.steps.judge_step", + classes="C3 C5", + target="openadapt_flow.gui.steps:judge_step", + run=lambda ev: judge_step(StepEvidence(**ev)), + is_pass=lambda out: out.status is Status.HELD, + level=lambda out: out.status, + seeds=lambda: [ + Seed(_ev("commit"), True, "one write, as demonstrated"), + Seed(_ev("navigate"), True, "moved, nothing written"), + Seed(_ev("in_place"), True, "nothing written"), + Seed(_ev("commit", writes_after=3), False, "a commit that wrote nothing"), + Seed(_ev("commit", writes_after=5), False, "two writes for one"), + Seed( + _ev("commit", outcomes=("redirect /login",)), + False, + "a redirect to sign-in where the demo saved", + ), + Seed( + _ev( + "commit", + expected_outcomes=("redirect /done",), + outcomes=("redirect /login",), + ), + False, + "a redirect elsewhere than the demo's", + ), + Seed( + _ev( + "commit", + expected_outcomes=("redirect /register?status=saved",), + outcomes=("redirect /register?status=session-expired",), + ), + False, + "a redirect to the same path with another query", + ), + Seed( + _ev( + "commit", + expected_outcomes=("redirect /records/{id}",), + outcomes=("redirect /records/{id}",), + ), + True, + "a redirect to the record just created", + ), + Seed( + _ev( + "commit", + expected_outcomes=("3xx /done",), + outcomes=("3xx /done",), + ), + False, + "an outcome learned in the old path-only form", + ), + Seed( + _ev("commit", expected_outcomes=None), + False, + "a spec with no recorded outcomes", + ), + Seed(_ev("navigate", writes_after=4), False, "a navigation that wrote"), + Seed(_ev("navigate", moved=False), False, "did not move"), + Seed(_ev("commit", after_errors=("Card declined",)), False, "error shown"), + Seed(_ev("unknown"), False, "the demo could not count writes"), + Seed(_ev("in_place", moved=True), False, "an in-place step moved"), + ], + fields=_fields(), + values=tuple( + _value(n) + for n in ( + "role", + "expected_writes", + "writes_before", + "writes_after", + "moved", + "after_complete", + "expected_outcomes", + "outcomes", + ) + ), + partial=lambda ev: [("after_complete", {**ev, "after_complete": False})], + codes=lambda: [ + CodeCase( + evidence={**_ev("commit"), "role": "submitted"}, + may_have_changed=True, + forbidden=lambda out: False, + label="a step role nobody listed", + unknown=True, + ) + ], + ) +) diff --git a/packages/flow/tests/gui/__init__.py b/packages/flow/tests/gui/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/flow/tests/gui/_apps.py b/packages/flow/tests/gui/_apps.py new file mode 100644 index 0000000000..4159ef98b5 --- /dev/null +++ b/packages/flow/tests/gui/_apps.py @@ -0,0 +1,299 @@ +"""Synthetic apps for the GUI mechanism tests, served through Playwright routes. + +Each app is a small in-memory server on a ``.test`` host: requests never +leave the browser process. The apps are of different kinds on purpose (a web +form, an EMR-like chart, a SaaS settings page), and none of them copies a +benchmark portal. Every record is synthetic. +""" + +from __future__ import annotations + +import contextlib +import http.server +import json +import threading +from dataclasses import dataclass, field +from typing import Any, Callable, Iterator, Optional +from urllib.parse import parse_qs, urlsplit + +Handler = Callable[["App", str, str, dict[str, list[str]]], tuple[int, str]] + +PAGE = """{title} +{body}""" + + +@dataclass +class App: + host: str + routes: dict[tuple[str, str], Handler] + state: dict[str, Any] = field(default_factory=dict) + log: list[tuple[str, str]] = field(default_factory=list) + _origin: str = "" + + @property + def origin(self) -> str: + return self._origin or f"http://{self.host}" + + def dispatch(self, method: str, target: str, body: str = "") -> tuple[int, str]: + parts = urlsplit(target) + verb = method.upper() + form = parse_qs(body) if body and not body.startswith("{") else {} + if body.startswith("{"): + form = {k: [str(v)] for k, v in json.loads(body).items()} + form.update(parse_qs(parts.query)) + self.log.append((verb, parts.path)) + fn = self.routes.get((verb, parts.path)) or self.routes.get((verb, "*")) + if fn is None: + return 404, "not found" + return fn(self, parts.path, verb, form) + + def handle(self, route: Any) -> None: + req = route.request + status, html = self.dispatch(req.method, req.url, req.post_data or "") + if status in (302, 303): + route.fulfill(status=status, headers={"Location": html}, body="") + return + route.fulfill(status=status, body=html, content_type="text/html") + + +@contextlib.contextmanager +def serve(page: Any, app: App) -> Iterator[App]: + class _Handler(http.server.BaseHTTPRequestHandler): + def _run(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length).decode("utf-8") if length else "" + status, payload = app.dispatch(self.command, self.path, body) + if status in (302, 303): + self.send_response(status) + self.send_header("Location", payload) + self.send_header("Content-Length", "0") + self.end_headers() + return + encoded = payload.encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + do_GET = _run + do_POST = _run + + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 + return + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + port = server.server_address[1] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + prev_origin = app._origin + app._origin = f"http://127.0.0.1:{port}" + try: + yield app + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2.0) + app._origin = prev_origin + + +def page(title: str, body: str) -> str: + return PAGE.format(title=title, body=body) + + +# -- a web form: an event registration wizard whose next control is a link -------- + + +def registration_app( + *, + next_writes: bool = False, + commit_posts: int = 1, + error_after: bool = False, + fetch_writes: bool = False, + redirect: str = "", + saves: Optional[bool] = None, + first_id: int = 101, +) -> App: + """Contact details, then a ticket, then Register. "Continue" is a link that + keeps the values in session storage. ``next_writes`` makes the link also + post a draft (an app that changed); ``commit_posts`` is how many requests + Register sends; ``error_after`` shows an alert after the commit. + + The extra writes are synchronous XHR, which finish before the page + navigates; ``fetch_writes`` sends them with ``fetch()`` instead, which the + navigation aborts. ``redirect="/done"`` saves and answers 302 to the + confirmation page; ``redirect="/login"`` saves nothing and answers 302 to + a plain sign-in page (an expired session), with no alert. ``saves`` says + whether Register saves (by default, unless the redirect is ``/login``). + ``{id}`` in ``redirect`` is the new record's id, counted from + ``first_id`` (a post-redirect-get to the record just created).""" + + keeps = redirect != "/login" if saves is None else saves + + def _post(path: str, body: str) -> str: + if fetch_writes: + return f"fetch('{path}',{{method:'POST',body:{body}}});" + return ( + "(function(){var x=new XMLHttpRequest();" + f"x.open('POST','{path}',false);x.send({body});}})();" + ) + + draft = _post("/draft", "'{}'") if next_writes else "" + + def contact(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + return 200, page( + "Your details", + f"""

Your details

+
Contact + +
+ +
""", + ) + + def ticket(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + sends = "".join( + _post("/register", "JSON.stringify(data())") + for _ in range(commit_posts - 1) + ) + return 200, page( + "Ticket", + f"""

Ticket

+ + +Back
+
""", + ) + + def register(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + if not keeps: + return 302, redirect or "/login" + records = app.state.setdefault("records", []) + records.append({k: v[0] for k, v in form.items() if v}) + if redirect: + return 302, redirect.replace("{id}", str(first_id + len(records) - 1)) + return done(app, path, method, form) + + def login(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + return 200, page( + "Sign in", + """

Sign in

Your session expired.

+ +
""", + ) + + def done(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + alert = '

Payment could not be taken

' if error_after else "" + return 200, page("Done", f"

Registration received

{alert}
") + + def landing(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + # Any other page a redirect lands on: a record, or a status page. + status = form.get("status", [""])[0] + return 200, page("Result", f"

{path}

{status}

") + + def draft_ok(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + return 200, "{}" + + return App( + "reg.test", + { + ("GET", "/contact"): contact, + ("GET", "/ticket"): ticket, + ("POST", "/register"): register, + ("GET", "/done"): done, + ("GET", "/login"): login, + ("POST", "/draft"): draft_ok, + ("GET", "*"): landing, + }, + ) + + +# -- an EMR-like chart whose commit is a plain link --------------------------------- + + +def chart_app() -> App: + """A patient chart. "Save draft" posts in place; "Sign note" is a link + whose GET signs the note on the server.""" + + def chart(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + note = app.state.get("draft", "") + return 200, page( + "Chart", + f"""

Chart: Test Patient A

+

Progress note

+ + +Sign note
+
""", + ) + + def save_draft(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + app.state["draft"] = form.get("note", [""])[0] + return 200, "{}" + + def sign(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + app.state["signed"] = app.state.get("draft", "") + return 200, page("Signed", "

Note signed

") + + def patients(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + return 200, page("Patients", "

Patients

") + + return App( + "chart.test", + { + ("GET", "/patient/7"): chart, + ("POST", "/notes/7/draft"): save_draft, + ("GET", "/notes/7/sign"): sign, + ("GET", "/patients"): patients, + }, + ) + + +# -- a SaaS settings page with tabs and a link that publishes ------------------------ + + +def settings_app() -> App: + def settings(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + return 200, page( + "Settings", + """

Workspace settings

+
+
+
+ +Publish changes +

+
""", + ) + + def api(app: App, path: str, method: str, form: dict) -> tuple[int, str]: + app.state["settings"] = {k: v[0] for k, v in form.items()} + return 200, "{}" + + return App( + "app.test", + {("GET", "/settings"): settings, ("POST", "/api/settings"): api}, + ) + + +def wait_idle(page_: Any, ms: int = 50) -> None: + page_.wait_for_timeout(ms) + + +def first(seq: Any, pred: Callable[[Any], bool]) -> Optional[Any]: + for x in seq: + if pred(x): + return x + return None diff --git a/packages/flow/tests/gui/_grid.py b/packages/flow/tests/gui/_grid.py new file mode 100644 index 0000000000..89fba85bea --- /dev/null +++ b/packages/flow/tests/gui/_grid.py @@ -0,0 +1,149 @@ +"""A spreadsheet-like grid surface with no browser. + +It exposes its screen as an accessibility tree (sheet tabs, a grid of rows +and cells, a toolbar, an optional dialog) and reads it through +:func:`openadapt_flow.gui.adapters.screen_from_tree`, the path a desktop +backend would use. Writes are counted when the workbook is saved, so the +grid can show a commit, and each save reports the outcome ``"saved"``; +``count_writes=False`` makes a backend that cannot. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Optional + +from openadapt_flow.gui.adapters import screen_from_tree +from openadapt_flow.gui.model import Screen + + +@dataclass +class Sheet: + name: str + columns: tuple[str, ...] + rows: list[list[str]] = field(default_factory=list) + + +@dataclass +class GridApp: + sheets: list[Sheet] + count_writes: bool = True + active: int = 0 + saved: list[dict[str, list[list[str]]]] = field(default_factory=list) + #: Extra toolbar items: (handle, role, name, action key). + extra_tools: list[tuple[str, str, str, str]] = field(default_factory=list) + dialog: Optional[dict[str, Any]] = None + checks: dict[str, bool] = field(default_factory=dict) + _writes: int = 0 + _outcomes: list[str] = field(default_factory=list) + + # -- the tree --------------------------------------------------------------- + + def tree(self) -> dict[str, Any]: + sheet = self.sheets[self.active] + rows = [] + for r, row in enumerate(sheet.rows): + cells = [ + { + "role": "cell", + "name": col, + "value": row[c], + "handle": f"cell:{sheet.name}:{r}:{c}", + } + for c, col in enumerate(sheet.columns) + ] + rows.append( + { + "role": "row", + "name": f"Row {r + 1}", + "handle": f"row:{sheet.name}:{r}", + "text": " ".join(row), + "children": cells, + } + ) + tools = [ + {"role": "menu item", "name": "Save", "handle": "tool:save"}, + {"role": "push button", "name": "Insert row", "handle": "tool:insert"}, + ] + [ + {"role": role, "name": name, "handle": handle} + for handle, role, name, _ in self.extra_tools + ] + children: list[dict[str, Any]] = [ + { + "role": "group", + "name": "Sheets", + "handle": "tabs", + "children": [ + {"role": "tab item", "name": s.name, "handle": f"tab:{i}"} + for i, s in enumerate(self.sheets) + ], + }, + { + "role": "group", + "name": "Toolbar", + "handle": "toolbar", + "children": tools, + }, + { + "role": "grid", + "name": sheet.name, + "handle": f"grid:{sheet.name}", + "children": rows, + }, + ] + if self.dialog is not None: + children.append(self.dialog) + return { + "role": "window", + "name": f"Workbook - {sheet.name}", + "children": children, + } + + # -- the actuator ------------------------------------------------------------- + + def observe(self) -> Screen: + return screen_from_tree( + self.tree(), location=f"sheet:{self.sheets[self.active].name}" + ) + + def click(self, handle: str) -> None: + if handle.startswith("tab:"): + self.active = int(handle.split(":")[1]) + elif handle == "tool:save": + self.saved.append({s.name: [list(r) for r in s.rows] for s in self.sheets}) + self._writes += 1 + self._outcomes.append("saved") + elif handle == "tool:insert": + sheet = self.sheets[self.active] + sheet.rows.append([""] * len(sheet.columns)) + else: + for h, _, _, action in self.extra_tools: + if h == handle: + self.on_tool(action) + return + if self.dialog is not None: + self.on_dialog_click(handle) + return + raise KeyError(handle) + + def on_tool(self, action: str) -> None: # overridden by tests + raise KeyError(action) + + def on_dialog_click(self, handle: str) -> None: # overridden by tests + raise KeyError(handle) + + def set_text(self, handle: str, value: str) -> None: + kind, sheet_name, r, c = handle.split(":") + if kind != "cell": + raise KeyError(handle) + sheet = next(s for s in self.sheets if s.name == sheet_name) + sheet.rows[int(r)][int(c)] = value + + def set_checked(self, handle: str, checked: bool) -> None: + self.checks[handle] = checked + + def write_count(self) -> Optional[int]: + return self._writes if self.count_writes else None + + def write_outcomes(self) -> Optional[tuple[str, ...]]: + return tuple(self._outcomes) if self.count_writes else None diff --git a/packages/flow/tests/gui/conftest.py b/packages/flow/tests/gui/conftest.py new file mode 100644 index 0000000000..17104e290a --- /dev/null +++ b/packages/flow/tests/gui/conftest.py @@ -0,0 +1,27 @@ +"""A headless browser page for the GUI mechanism tests.""" + +from __future__ import annotations + +from typing import Any, Iterator + +import pytest + + +@pytest.fixture(scope="module") +def _browser() -> Iterator[Any]: + sync_api = pytest.importorskip("playwright.sync_api") + with sync_api.sync_playwright() as pw: + browser = pw.chromium.launch(headless=True) + try: + yield browser + finally: + browser.close() + + +@pytest.fixture +def page(_browser: Any) -> Iterator[Any]: + context = _browser.new_context() + try: + yield context.new_page() + finally: + context.close() diff --git a/packages/flow/tests/gui/test_gui_steps.py b/packages/flow/tests/gui/test_gui_steps.py new file mode 100644 index 0000000000..720ab4b3c0 --- /dev/null +++ b/packages/flow/tests/gui/test_gui_steps.py @@ -0,0 +1,702 @@ +"""Links, tabs and menu items as steps, and the commit point, on four kinds of app. + +- a web form whose next control is a link (registration wizard); +- an EMR-like chart whose commit is a plain link (a GET that signs the note); +- a SaaS settings page with tabs and a link that publishes by POST; +- a spreadsheet-like grid with no browser (sheet tabs, a Save menu item). + +Each app is recorded once through the same backend a run uses, the steps are +learned from that demonstration, and a second run with other values replays +them. The negative cases change the app after the demonstration. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +import openadapt_flow +from openadapt_flow.gui.adapters import screen_from_form_snapshot +from openadapt_flow.gui.dom import PageActuator, location_key +from openadapt_flow.gui.model import ControlSpec, Recorder, match_one +from openadapt_flow.gui.steps import ( + StepEvidence, + StepRole, + StepSpec, + commit_points, + judge_step, + learn_steps, + take_step, +) +from openadapt_flow.verdict import Status +from tests.gui import _apps +from tests.gui._grid import GridApp, Sheet + + +def test_code_under_test_is_this_checkout() -> None: + flow = Path(__file__).resolve().parents[2] + assert Path(openadapt_flow.__file__).resolve().is_relative_to(flow) + + +def _handle(screen, role: str, name: str) -> str: + return match_one(ControlSpec(role, name), screen).handle + + +def _record_registration(page, app) -> list: + act = PageActuator(page) + page.goto(f"{app.origin}/contact") + rec = Recorder(act) + s = act.observe() + rec.set_text(_handle(s, "textbox", "Full name"), "Ada Example") + rec.set_text(_handle(s, "textbox", "Email"), "ada@example.test") + rec.click(_handle(s, "link", "Continue")) + s = act.observe() + page.select_option(_handle(s, "combobox", "Ticket type"), "std") + rec.click(_handle(act.observe(), "button", "Register")) + return rec.steps + + +# -- web form: the next control is a link ------------------------------------------ + + +def test_web_form_link_is_a_navigation_step_and_the_button_commits(page) -> None: + with _apps.serve(page, _apps.registration_app()) as app: + learned = learn_steps(_record_registration(page, app)) + roles = [(s.control.role, s.control.name, s.role) for s in learned] + assert roles == [ + ("link", "Continue", StepRole.NAVIGATE), + ("button", "Register", StepRole.COMMIT), + ] + nxt = learned[0].spec + assert nxt is not None and nxt.control.role == "link" + assert nxt.control.target == "/ticket" or nxt.control.target is None + (commit,) = commit_points(learned) + assert commit.spec is not None and commit.spec.writes == 1 + + +def test_web_form_replays_learned_link_and_commit_with_new_values(page) -> None: + with _apps.serve(page, _apps.registration_app()) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + app2 = _apps.registration_app() + with _apps.serve(page, app2): + act = PageActuator(page) + page.goto(f"{app2.origin}/contact") + s = act.observe() + act.set_text(_handle(s, "textbox", "Full name"), "Bo Sample") + act.set_text(_handle(s, "textbox", "Email"), "bo@example.test") + out = take_step(act, steps[0], run_id="r1") + assert out.held, out.result.reason + page.select_option(_handle(act.observe(), "combobox", "Ticket type"), "vip") + out = take_step(act, steps[1], run_id="r1") + assert out.held, out.result.reason + assert app2.state["records"] == [ + {"name": "Bo Sample", "email": "bo@example.test", "ticket": "vip"} + ] + + +def test_a_link_that_starts_writing_is_refuted(page) -> None: + with _apps.serve(page, _apps.registration_app()) as app: + nxt = learn_steps(_record_registration(page, app))[0].spec + changed = _apps.registration_app(next_writes=True) + with _apps.serve(page, changed): + act = PageActuator(page) + page.goto(f"{changed.origin}/contact") + out = take_step(act, nxt) + assert out.clicked and out.result.status is Status.REFUTED + assert "navigate step wrote" in out.result.reason + + +@pytest.mark.parametrize( + ("variant", "reason"), + [ + ({"commit_posts": 2}, "wrote 2 times; the demo wrote 1"), + ({"error_after": True}, "shows an error"), + ], +) +def test_a_commit_that_differs_from_the_demo_is_refuted(page, variant, reason) -> None: + with _apps.serve(page, _apps.registration_app()) as app: + commit = learn_steps(_record_registration(page, app))[1].spec + changed = _apps.registration_app(**variant) + with _apps.serve(page, changed): + act = PageActuator(page) + page.goto(f"{changed.origin}/ticket") + out = take_step(act, commit) + assert out.result.status is Status.REFUTED + assert reason in out.result.reason + + +def test_fetch_then_navigate_is_refuted_as_aborted(page) -> None: + """Pins a known limit: a link that fires ``fetch()`` and then navigates + aborts its own request, so the step is refuted for ERR_ABORTED (failing + closed) rather than for the write it started.""" + with _apps.serve(page, _apps.registration_app()) as app: + nxt = learn_steps(_record_registration(page, app))[0].spec + changed = _apps.registration_app(next_writes=True, fetch_writes=True) + with _apps.serve(page, changed): + act = PageActuator(page) + page.goto(f"{changed.origin}/contact") + out = take_step(act, nxt) + assert out.clicked and out.result.status is Status.REFUTED + assert "ERR_ABORTED" in out.result.reason + + +def _replay_commit(page, steps, app, run_id: str): + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/contact") + s = act.observe() + act.set_text(_handle(s, "textbox", "Full name"), "Bo Sample") + act.set_text(_handle(s, "textbox", "Email"), "bo@example.test") + assert take_step(act, steps[0], run_id=run_id).held + page.select_option(_handle(act.observe(), "combobox", "Ticket type"), "vip") + return take_step(act, steps[1], run_id=run_id) + + +def test_a_commit_bounced_to_sign_in_is_not_held(page) -> None: + """Demo POST answers 200; replay answers 302 to a plain sign-in page with + no alert and saves nothing. The redirect is not the demo's outcome.""" + with _apps.serve(page, _apps.registration_app()) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + assert steps[1].outcomes == ("2xx",) + app2 = _apps.registration_app(redirect="/login") + out = _replay_commit(page, steps, app2, "r302") + assert out.clicked and out.result.status is not Status.HELD + assert out.result.status is Status.REFUTED, out.result.reason + assert "redirect /login" in out.result.reason + assert not app2.state.get("records") + + +def test_a_redirect_to_another_path_than_the_demo_is_not_held(page) -> None: + """Demo POST answers 302 to /done; replay answers 302 to /login.""" + with _apps.serve(page, _apps.registration_app(redirect="/done")) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + assert steps[1].outcomes == ("redirect /done",) + app2 = _apps.registration_app(redirect="/login") + out = _replay_commit(page, steps, app2, "r302b") + assert out.clicked and out.result.status is Status.REFUTED, out.result.reason + assert not app2.state.get("records") + app3 = _apps.registration_app(redirect="/done") + out = _replay_commit(page, steps, app3, "r302c") + assert out.held, out.result.reason + assert app3.state["records"] == [ + {"name": "Bo Sample", "email": "bo@example.test", "ticket": "vip"} + ] + + +def test_a_commit_spec_without_recorded_outcomes_is_never_clicked(page) -> None: + with _apps.serve(page, _apps.registration_app()) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + old = StepSpec(steps[1].step_id, steps[1].control, StepRole.COMMIT, 1) + app2 = _apps.registration_app() + out = _replay_commit(page, [steps[0], old], app2, "rold") + assert not out.clicked and out.result.status is Status.NOT_CHECKED + assert not app2.state.get("records") + + +def test_a_same_path_redirect_with_another_query_is_refuted(page) -> None: + """Demo POST saves and answers 302 to ``/register?status=saved``; the + replay saves nothing and answers 302 to the same path with + ``?status=session-expired``. Only the query tells them apart.""" + demo = _apps.registration_app(redirect="/register?status=saved") + with _apps.serve(page, demo) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + assert steps[1].outcomes == ("redirect /register?status=saved",) + app2 = _apps.registration_app( + redirect="/register?status=session-expired", saves=False + ) + out = _replay_commit(page, steps, app2, "rq1") + assert out.clicked and out.result.status is Status.REFUTED, out.result.reason + assert "status=session-expired" in out.result.reason + assert not app2.state.get("records") + app3 = _apps.registration_app(redirect="/register?status=saved") + out = _replay_commit(page, steps, app3, "rq2") + assert out.held, out.result.reason + assert len(app3.state["records"]) == 1 + + +def test_a_redirect_to_the_record_just_created_is_held(page) -> None: + """Post-redirect-get to the new record: ``/records/101`` in the demo, + ``/records/102`` on replay. The minted id is not part of the outcome.""" + demo = _apps.registration_app(redirect="/records/{id}", first_id=101) + with _apps.serve(page, demo) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + assert steps[1].outcomes == ("redirect /records/{id}",) + app2 = _apps.registration_app(redirect="/records/{id}", first_id=102) + out = _replay_commit(page, steps, app2, "rprg") + assert out.held, out.result.reason + assert app2.state["records"] == [ + {"name": "Bo Sample", "email": "bo@example.test", "ticket": "vip"} + ] + assert page.url.endswith("/records/102") + + +def test_a_redirect_to_sign_in_where_the_demo_went_to_a_record_is_refuted( + page, +) -> None: + demo = _apps.registration_app(redirect="/records/{id}") + with _apps.serve(page, demo) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + app2 = _apps.registration_app(redirect="/login") + out = _replay_commit(page, steps, app2, "rprg2") + assert out.clicked and out.result.status is Status.REFUTED, out.result.reason + assert "redirect /login" in out.result.reason + assert not app2.state.get("records") + + +def test_a_commit_spec_with_an_old_path_only_redirect_is_never_clicked(page) -> None: + """A spec learned when the key was the path alone (``"3xx /done"``) + could match a replay that went to the same path with another query, so + it is not taken, even where the replay would have matched.""" + with _apps.serve(page, _apps.registration_app(redirect="/done")) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + old = StepSpec( + steps[1].step_id, steps[1].control, StepRole.COMMIT, 1, ("3xx /done",) + ) + app2 = _apps.registration_app(redirect="/done") + out = _replay_commit(page, [steps[0], old], app2, "rlegacy") + assert not out.clicked and out.result.status is Status.NOT_CHECKED + assert not app2.state.get("records") + + +def test_a_missing_renamed_or_doubled_link_is_never_clicked(page) -> None: + spec = StepSpec("next", ControlSpec("link", "Continue"), StepRole.NAVIGATE) + app = _apps.registration_app() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/contact") + page.evaluate("document.getElementById('next').textContent = 'Next'") + out = take_step(act, spec) + assert not out.clicked and out.result.status is Status.NOT_CHECKED + page.evaluate( + "document.getElementById('next').textContent = 'Continue';" + "document.querySelector('nav').insertAdjacentHTML('beforeend'," + "'Continue')" + ) + out = take_step(act, spec) + assert not out.clicked and "2 controls match" in out.result.reason + pinned = StepSpec( + "next", ControlSpec("link", "Continue", target="/ticket"), StepRole.NAVIGATE + ) + page.evaluate("document.getElementById('next').setAttribute('href','/other')") + out = take_step(act, pinned) + assert not out.clicked + assert ("GET", "/elsewhere") not in app.log and ("GET", "/other") not in app.log + + +# -- EMR-like chart: the commit is a GET link ---------------------------------------- + + +def _record_chart(page, app, *, write_get_paths=()) -> list: + act = PageActuator(page, write_get_paths=write_get_paths) + page.goto(f"{app.origin}/patient/7") + rec = Recorder(act) + s = act.observe() + rec.set_text(_handle(s, "textbox", "Note"), "Seen today; stable.") + rec.click(_handle(s, "button", "Save draft")) + rec.click(_handle(act.observe(), "link", "Sign note")) + return rec.steps + + +def test_emr_sign_link_is_a_commit_only_when_its_request_is_declared(page) -> None: + with _apps.serve(page, _apps.chart_app()) as app: + declared = learn_steps( + _record_chart(page, app, write_get_paths=[r"^/notes/\d+/sign$"]) + ) + assert [(s.control.name, s.role) for s in declared] == [ + ("Save draft", StepRole.COMMIT), + ("Sign note", StepRole.COMMIT), + ] + assert [s.control.name for s in commit_points(declared)] == [ + "Save draft", + "Sign note", + ] + with _apps.serve(page, _apps.chart_app()) as app: + undeclared = learn_steps(_record_chart(page, app)) + # A GET the backend does not count is not evidence of a commit: the link + # is learned as a navigation, and the program has one commit point fewer. + assert [(s.control.name, s.role) for s in undeclared][1] == ( + "Sign note", + StepRole.NAVIGATE, + ) + + +def test_emr_learned_sign_link_replays_and_signs(page) -> None: + paths = [r"^/notes/\d+/sign$"] + with _apps.serve(page, _apps.chart_app()) as app: + steps = [ + s.spec for s in learn_steps(_record_chart(page, app, write_get_paths=paths)) + ] + app2 = _apps.chart_app() + with _apps.serve(page, app2): + act = PageActuator(page, write_get_paths=paths) + page.goto(f"{app2.origin}/patient/7") + act.set_text(_handle(act.observe(), "textbox", "Note"), "Follow up in 2 weeks.") + assert take_step(act, steps[0]).held + out = take_step(act, steps[1]) + assert out.held, out.result.reason + assert app2.state["signed"] == "Follow up in 2 weeks." + + +# -- SaaS settings: tabs move between panels, a link publishes ------------------------ + + +def test_saas_tabs_navigate_and_a_publish_link_commits(page) -> None: + app = _apps.settings_app() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/settings") + rec = Recorder(act) + s = act.observe() + rec.set_text(_handle(s, "textbox", "Workspace name"), "North team") + rec.click(_handle(s, "tab", "Billing")) + s = act.observe() + rec.set_text(_handle(s, "textbox", "Billing email"), "ap@example.test") + rec.click(_handle(s, "link", "Publish changes")) + learned = learn_steps(rec.steps) + assert [(s.control.role, s.role) for s in learned] == [ + ("tab", StepRole.NAVIGATE), + ("link", StepRole.COMMIT), + ] + assert app.state["settings"] == {"ws": "North team", "be": "ap@example.test"} + + +# -- spreadsheet-like grid: no browser ------------------------------------------------- + + +def _grid() -> GridApp: + return GridApp( + [ + Sheet("Q1", ("Item", "Amount"), [["Rent", "1200"]]), + Sheet("Q2", ("Item", "Amount"), [["Rent", ""]]), + ] + ) + + +def test_grid_sheet_tab_navigates_and_save_menu_item_commits() -> None: + grid = _grid() + rec = Recorder(grid) + rec.click("tab:1") + rec.set_text("cell:Q2:0:1", "1250") + rec.click("tool:save") + learned = learn_steps(rec.steps) + assert [(s.control.role, s.control.name, s.role) for s in learned] == [ + ("tab", "Q2", StepRole.NAVIGATE), + ("menuitem", "Save", StepRole.COMMIT), + ] + replay = _grid() + for step in learned: + assert take_step(replay, step.spec).held + assert replay.saved[-1]["Q2"] == [["Rent", ""]] + + +def test_a_backend_that_cannot_count_writes_never_takes_a_step() -> None: + grid = _grid() + rec = Recorder(grid) + rec.click("tab:1") + rec.click("tool:save") + tab, save = learn_steps(rec.steps) + blind = _grid() + blind.count_writes = False + for step in (save, tab): + out = take_step(blind, step.spec) + assert not out.clicked and out.result.status is Status.NOT_CHECKED + assert blind.saved == [] and blind.active == 0 + rec2 = Recorder(blind) + rec2.click("tool:save") + (unknown,) = learn_steps(rec2.steps) + assert unknown.role is StepRole.UNKNOWN and unknown.spec is None + + +# -- the verdict and the form_tx adapter ------------------------------------------------ + + +def test_an_in_place_step_that_moves_the_screen_is_refuted() -> None: + ev = StepEvidence("s", StepRole.IN_PLACE, 0, 2, 2, True, True) + assert judge_step(ev).status is Status.REFUTED + held = StepEvidence("s", StepRole.IN_PLACE, 0, 2, 2, False, True) + assert judge_step(held).status is Status.HELD + + +def test_judge_step_needs_exact_whole_counts() -> None: + base = dict( + step_id="s", + role=StepRole.COMMIT, + expected_writes=1, + writes_before=3, + writes_after=4, + moved=True, + after_complete=True, + expected_outcomes=("2xx",), + outcomes=("2xx",), + ) + assert judge_step(StepEvidence(**base)).status is Status.HELD + for change in ( + {"outcomes": ("redirect /login",)}, + {"outcomes": ("redirect /register?status=session-expired",)}, + { + "expected_outcomes": ("redirect /register?status=saved",), + "outcomes": ("redirect /register?status=session-expired",), + }, + {"expected_outcomes": ("3xx /done",), "outcomes": ("3xx /done",)}, + {"expected_outcomes": ("3xx /done",), "outcomes": ("redirect /done",)}, + {"outcomes": None}, + {"outcomes": "2xx"}, + {"outcomes": ("2xx", "2xx")}, + {"expected_outcomes": None}, + {"expected_outcomes": ()}, + {"writes_after": "4"}, + {"writes_after": True}, + {"writes_before": None}, + {"writes_after": 2}, + {"role": "submit"}, + {"expected_writes": 0}, + {"after_complete": False}, + ): + got = judge_step(StepEvidence(**{**base, **change})) + assert got.status is not Status.HELD, change + + +def test_judge_step_does_not_check_an_old_path_only_redirect() -> None: + ev = StepEvidence( + "s", + StepRole.COMMIT, + 1, + 3, + 4, + True, + True, + expected_outcomes=("3xx /done",), + outcomes=("3xx /done",), + ) + got = judge_step(ev) + assert got.status is Status.NOT_CHECKED and "old path-only" in got.reason + + +REQ = "http://app.test/records" + + +@pytest.mark.parametrize( + ("a", "b"), + [ + ("/records/101", "/records/102"), + ("/records/7/", "/records/8"), + ( + "/r/3f2b8c1e-0a4d-4e5f-9b6a-7c8d9e0f1a2b", + "/r/00000000-0000-4000-8000-000000000000", + ), + ("/r/0123456789abcdef", "/r/fedcba9876543210ABCD"), + ("/view?id=0123456789abcdef0123", "/view?id=ffffffffffffffff"), + ("/done?b=2&a=1", "/done?a=1&b=2"), + ("/done?msg=two%20words", "/done?msg=two+words"), + ("/done?error=", "/done?error="), + ("/done#top", "/done"), + ("/done/", "http://app.test/done"), + ], +) +def test_location_keys_that_match(a: str, b: str) -> None: + assert location_key(REQ, a) == location_key(REQ, b) + + +@pytest.mark.parametrize( + ("a", "b"), + [ + ("/register?status=saved", "/register?status=session-expired"), + ("/index.php?page=done", "/index.php?page=login"), + ("/records/101", "/login"), + ("/records/101", "/records/new"), + ("/done?saved=1", "/done?saved=0"), + ("/view?id=101", "/view?id=102"), + ("/r/deadbeef", "/r/cafebabe"), + ("/r/{id}", "/r/101"), + ("/done?error=", "/done"), + ("/done?a=1&a=2", "/done?a=1"), + ("/done?a=1%262", "/done?a=1&2="), + ("/done", "http://other.test/done"), + ], +) +def test_location_keys_that_differ(a: str, b: str) -> None: + assert location_key(REQ, a) != location_key(REQ, b) + + +def test_location_key_format() -> None: + assert location_key(REQ, "/records/101/?b=x&a=0123456789abcdef#f") == ( + "/records/{id}?a={id}&b=x" + ) + assert location_key(REQ, "https://Sso.Example.test/login?next=%2Fa") == ( + "https://sso.example.test/login?next=%2Fa" + ) + + +class _FakeRequest: + def __init__(self, method: str, url: str) -> None: + self.method, self.url = method, url + + +class _FakeResponse: + def __init__(self, method: str, url: str, status: int = 200) -> None: + self.request, self.status, self.headers = _FakeRequest(method, url), status, {} + + +class _FakePage: + def __init__(self, url: str) -> None: + self.url = url + self.handlers: dict = {} + + def on(self, event: str, fn) -> None: + self.handlers[event] = fn + + def wait_for_load_state(self, state: str) -> None: + pass + + def wait_for_timeout(self, ms: int) -> None: + pass + + def evaluate(self, js: str, arg) -> dict: + return {"controls": [], "complete": True} + + def locator(self, handle: str): + page = self + + class _Loc: + def click(self) -> None: + page.handlers["response"](_FakeResponse("POST", "http://a.test/save")) + + return _Loc() + + +def test_the_step_origin_is_cleared_once_the_page_is_read() -> None: + """After an action's page is read, a response is judged against the page + the caller is on now, not the origin the action started on.""" + fake = _FakePage("http://a.test/form") + act = PageActuator(fake) + act.click("#save") + assert act.write_count() == 1 + act.observe() + fake.url = "http://b.test/other" + fake.handlers["response"](_FakeResponse("POST", "http://a.test/late")) + assert act.write_count() == 1 + fake.handlers["response"](_FakeResponse("POST", "http://b.test/save")) + assert act.write_count() == 2 + assert act.write_outcomes() == ("2xx", "2xx") + + +def test_form_snapshot_links_become_link_controls() -> None: + from openadapt_flow.form_tx.types import FormSnapshot, ObservedControl + + snap = FormSnapshot( + url_origin_and_path="/hub", + controls=( + ObservedControl( + control_id="a1", dom_selector="#a1", tag="a", label_text="Continue" + ), + ObservedControl( + control_id="b1", dom_selector="#b1", tag="button", label_text="Back" + ), + ), + ) + screen = screen_from_form_snapshot(snap) + assert [(c.role, c.name) for c in screen.controls] == [ + ("link", "Continue"), + ("button", "Back"), + ] + spec = ControlSpec("activatable", "Continue") + assert match_one(spec, screen).handle == "#a1" + + +def test_commit_server_500_without_alert_is_refuted(page) -> None: + """A 500 response on a commit POST must refute even with no role=alert.""" + with _apps.serve(page, _apps.registration_app()) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + app2 = _apps.registration_app() + with _apps.serve(page, app2): + act = PageActuator(page) + page.goto(f"{app2.origin}/contact") + s = act.observe() + act.set_text(_handle(s, "textbox", "Full name"), "Bo Sample") + act.set_text(_handle(s, "textbox", "Email"), "bo@example.test") + assert take_step(act, steps[0], run_id="r500").held + page.select_option(_handle(act.observe(), "combobox", "Ticket type"), "vip") + page.route( + f"{app2.origin}/register", + lambda route: route.fulfill( + status=500, + content_type="text/html", + body="

Internal Server Error

", + ), + ) + try: + out = take_step(act, steps[1], run_id="r500") + finally: + page.unroute(f"{app2.origin}/register") + assert out.clicked and out.result.status is Status.REFUTED + assert "HTTP 500" in out.result.reason + assert act.write_count() == 0 + assert not app2.state.get("records") + + +def test_commit_third_party_beacon_does_not_count_as_write_or_commit(page) -> None: + """A third-party beacon POST must neither satisfy a commit nor teach one.""" + with _apps.serve(page, _apps.registration_app()) as app: + steps = [s.spec for s in learn_steps(_record_registration(page, app))] + + beacon_hits: list[str] = [] + page.route( + "http://analytics.test/collect", + lambda route: ( + beacon_hits.append(route.request.method), + route.fulfill( + status=200, + headers={"Access-Control-Allow-Origin": "*"}, + body="ok", + ), + ), + ) + try: + app2 = _apps.registration_app() + with _apps.serve(page, app2): + act = PageActuator(page) + page.goto(f"{app2.origin}/contact") + s = act.observe() + act.set_text(_handle(s, "textbox", "Full name"), "Bo Sample") + act.set_text(_handle(s, "textbox", "Email"), "bo@example.test") + assert take_step(act, steps[0], run_id="rbeacon").held + page.select_option(_handle(act.observe(), "combobox", "Ticket type"), "vip") + # Replace submit with a third-party beacon that prevents the real POST. + page.evaluate( + """() => { + const form = document.querySelector('form'); + form.addEventListener('submit', (ev) => { + ev.preventDefault(); + fetch('http://analytics.test/collect', {method: 'POST', body: 'ping'}); + }); + }""" + ) + out = take_step(act, steps[1], run_id="rbeacon") + assert beacon_hits == ["POST"] + assert out.clicked and out.result.status is Status.REFUTED + assert act.write_count() == 0 + assert not app2.state.get("records") + + # Also verify learn_steps does not learn a third-party-only beacon as COMMIT. + app3 = _apps.registration_app() + with _apps.serve(page, app3): + act3 = PageActuator(page) + page.goto(f"{app3.origin}/ticket") + page.evaluate( + """() => { + const form = document.querySelector('form'); + form.addEventListener('submit', (ev) => { + ev.preventDefault(); + fetch('http://analytics.test/collect', {method: 'POST', body: 'demo'}); + }); + }""" + ) + rec = Recorder(act3) + rec.click(_handle(act3.observe(), "button", "Register")) + learned = learn_steps(rec.steps) + assert len(learned) == 1 + assert learned[0].role is not StepRole.COMMIT + assert act3.write_count() == 0 + finally: + page.unroute("http://analytics.test/collect")