From b205dba2a6640d6b75b102226d9d82f8fa1bb314 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:16:48 -0500 Subject: [PATCH 01/11] feat: exception queue for any agent (closed kinds, raise_exception MCP tool, detectors, local registry, Desktop cards) --- CAPABILITIES.md | 2 + llms-full.txt | 2 + openadapt/cli_tasks.py | 1 + packages/desktop/CHANGELOG.md | 12 + .../desktop/openadapt_desktop/__init__.py | 2 +- .../desktop/openadapt_desktop/dispatch.py | 71 +- .../openadapt_desktop/exception_queue.py | 296 +++++++ .../openadapt_desktop/portal/shell/stops.js | 10 +- .../desktop/openadapt_desktop/stop_queue.py | 197 ++++- packages/desktop/package-lock.json | 4 +- packages/desktop/package.json | 2 +- packages/desktop/pyproject.toml | 2 +- packages/desktop/src-tauri/Cargo.lock | 2 +- packages/desktop/src-tauri/Cargo.toml | 2 +- packages/desktop/src-tauri/tauri.conf.json | 2 +- packages/desktop/tests/conftest.py | 3 + .../test_engine/test_stop_queue_exceptions.py | 378 +++++++++ packages/desktop/uv.lock | 2 +- packages/flow/docs/EXCEPTION_QUEUE.md | 156 ++++ .../commands/03-run-and-answer/exceptions.md | 1 + packages/flow/openadapt_flow/__main__.py | 1 + packages/flow/openadapt_flow/cli_tasks.py | 1 + .../openadapt_flow/exceptions/__init__.py | 11 + .../flow/openadapt_flow/exceptions/cli.py | 214 +++++ .../openadapt_flow/exceptions/detectors.py | 498 ++++++++++++ .../openadapt_flow/exceptions/mcp_server.py | 213 +++++ .../openadapt_flow/exceptions/registry.py | 751 ++++++++++++++++++ .../flow/tests/e2e/test_exception_mcp_e2e.py | 371 +++++++++ .../exception_card_second_factor.json | 1 + .../flow/tests/test_exception_detectors.py | 203 +++++ .../flow/tests/test_exception_registry.py | 530 ++++++++++++ .../types/openadapt_types/exception_card.py | 227 ++++++ packages/types/tests/test_exception_card.py | 165 ++++ 33 files changed, 4318 insertions(+), 15 deletions(-) create mode 100644 packages/desktop/openadapt_desktop/exception_queue.py create mode 100644 packages/desktop/tests/test_engine/test_stop_queue_exceptions.py create mode 100644 packages/flow/docs/EXCEPTION_QUEUE.md create mode 100644 packages/flow/docs/commands/03-run-and-answer/exceptions.md create mode 100644 packages/flow/openadapt_flow/exceptions/__init__.py create mode 100644 packages/flow/openadapt_flow/exceptions/cli.py create mode 100644 packages/flow/openadapt_flow/exceptions/detectors.py create mode 100644 packages/flow/openadapt_flow/exceptions/mcp_server.py create mode 100644 packages/flow/openadapt_flow/exceptions/registry.py create mode 100644 packages/flow/tests/e2e/test_exception_mcp_e2e.py create mode 100644 packages/flow/tests/fixtures/exception_card_second_factor.json create mode 100644 packages/flow/tests/test_exception_detectors.py create mode 100644 packages/flow/tests/test_exception_registry.py create mode 100644 packages/types/openadapt_types/exception_card.py create mode 100644 packages/types/tests/test_exception_card.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index cad88c6b1c..780add2b24 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -212,6 +212,7 @@ improvising or retrying when something is off. | Admit once, then stop only on problems | Released ([#1212](https://github.com/OpenAdaptAI/OpenAdapt/pull/1212)), behind a readiness gate | Synthetic | [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md) | | Show the field values a save writes on the phone | Released ([#1257](https://github.com/OpenAdaptAI/OpenAdapt/pull/1257)) | Unit tests | `console/save_approvals.py` | | Show why an agent asked for a save: who asked, its own reason (as a quote), the screen text it saw, and any of that text that reads like an instruction to an agent | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359)) | Unit tests, synthetic | `ApprovalProvenance` in `approval_mode/item_approval.py`; the phone card in openadapt-desktop `portal/shell` | +| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, cards from any run in Desktop's stop queue and on a paired phone, and detectors that say when to ask. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The tool can't make an agent that ignores it stop. The share of cases that need a person is unmeasured | On main | Unit tests and a synthetic end-to-end test (a scripted agent on a one-time-code page over real MCP stdio: one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state) | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md), openadapt-desktop `exception_queue.py` | ## Branching work, not one linear path @@ -414,6 +415,7 @@ A test fails when a command has no file or this list is out of date. - `business-decisions` - `console` - `deferred` +- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md). - `explain` - `item-approval` - `replay` diff --git a/llms-full.txt b/llms-full.txt index d67812cb9a..4a2cc78cd3 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -646,6 +646,7 @@ improvising or retrying when something is off. | Admit once, then stop only on problems | Released ([#1212](https://github.com/OpenAdaptAI/OpenAdapt/pull/1212)), behind a readiness gate | Synthetic | [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md) | | Show the field values a save writes on the phone | Released ([#1257](https://github.com/OpenAdaptAI/OpenAdapt/pull/1257)) | Unit tests | `console/save_approvals.py` | | Show why an agent asked for a save: who asked, its own reason (as a quote), the screen text it saw, and any of that text that reads like an instruction to an agent | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359)) | Unit tests, synthetic | `ApprovalProvenance` in `approval_mode/item_approval.py`; the phone card in openadapt-desktop `portal/shell` | +| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, cards from any run in Desktop's stop queue and on a paired phone, and detectors that say when to ask. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The tool can't make an agent that ignores it stop. The share of cases that need a person is unmeasured | On main | Unit tests and a synthetic end-to-end test (a scripted agent on a one-time-code page over real MCP stdio: one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state) | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EXCEPTION_QUEUE.md), openadapt-desktop `exception_queue.py` | ## Branching work, not one linear path @@ -848,6 +849,7 @@ A test fails when a command has no file or this list is out of date. - `business-decisions` - `console` - `deferred` +- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EXCEPTION_QUEUE.md). - `explain` - `item-approval` - `replay` diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index 61bb8854d7..cb954733e9 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -61,6 +61,7 @@ "disambiguate": "compile --disambiguate", "emit-mcp": "workflow emit-mcp", "emit-skill": "workflow emit-skill", + "exceptions": "approve exceptions", "explain": "inspect explain", "fleet": "services fleet", "for-each": "run --for-each", diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index 9916a41b8d..381e2caf13 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,6 +1,18 @@ # CHANGELOG +## v0.31.0 (2026-11-21) + +### Features + +- **desktop**: The stop queue now lists exception cards from any run on this + computer that asked a person (a one-time code prompt, an unexpected dialog, + a sign-in partway through, a stall, a possible duplicate, an ambiguous + record, a task it can't finish), not only Desktop's own runs. Each card is + answered on its own, here or on a paired phone, and the answer is signed + with the same approver key as other stop answers. + + ## v0.30.6 (2026-11-19) ### Bug Fixes diff --git a/packages/desktop/openadapt_desktop/__init__.py b/packages/desktop/openadapt_desktop/__init__.py index c5dd5310f4..f30ef439c1 100644 --- a/packages/desktop/openadapt_desktop/__init__.py +++ b/packages/desktop/openadapt_desktop/__init__.py @@ -21,4 +21,4 @@ +-- backends/ Storage backend plugins """ -__version__ = "0.30.6" +__version__ = "0.31.0" diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index 59d0fa0d28..0397448aa9 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -81,7 +81,7 @@ #: Stop cards a paired phone may answer through Desktop. A waiting save is #: answered through the portal's own save approval; turning "only ask about #: problems" back on is answered on the computer. -PHONE_ANSWERABLE_KINDS = frozenset({"same_record", "confirm_save", "halted"}) +PHONE_ANSWERABLE_KINDS = frozenset({"same_record", "confirm_save", "halted", "exception"}) _TEACH_CORRECTION_SCHEMA = "openadapt.desktop-teach-correction/v1" _TEACH_CORRECTION_META_KEY = "teach_correction" @@ -4519,6 +4519,14 @@ def _stop_cards(self) -> list[dict]: card = stop_queue.card_for_rearm(switch) if card is not None: cards.append(card) + # Any run on this computer that asked a person (CLI guard, wrap, + # flight, hooks), not only Desktop's own runs. + from openadapt_desktop import exception_queue + + for raw in exception_queue.open_cards(): + card = stop_queue.card_for_exception(raw) + if card is not None: + cards.append(card) return stop_queue.sort_cards(cards) def _rearm_offer(self, workflow_id: str) -> dict | None: @@ -4841,6 +4849,8 @@ def _answer_stop_cards( } if choice_id == "leave": return {"ok": True, "results": [], "changed": 0} + if any(card["kind"] == stop_queue.EXCEPTION_KIND for card in cards): + return self._answer_exception(cards, choice_id, sign=sign, device=device) if any(card["kind"] == "rearm_problems_only" for card in cards): if len(cards) != 1 or device is not None: return { @@ -4911,6 +4921,65 @@ def _answer_stop_cards( ), } + def _answer_exception( + self, + cards: list[dict], + choice_id: str, + *, + sign: Callable[..., dict], + device: dict[str, str] | None, + ) -> dict: + """Answer one exception card: sign it and write the run's answer file.""" + + from openadapt_desktop import exception_queue, stop_queue + from openadapt_desktop.approver_keychain import ApproverKeychainError + + if len(cards) != 1: + return { + "ok": False, + "code": "answer_one_by_one", + "error": "Each of these stops is answered on its own. Nothing changed.", + } + card = cards[0] + try: + outcome = exception_queue.answer( + card["source"], + choice_id, + sign=sign, + route="desktop" if device is None else "portal", + ) + except ApproverKeychainError as exc: + return {"ok": False, "code": exc.code, "error": str(exc)} + if not outcome.get("ok"): + return { + "ok": False, + "code": outcome.get("code"), + "error": f"{outcome.get('error')} Nothing changed.", + } + self._record_stop_decision( + { + "schema": stop_queue.DECISION_SCHEMA, + "card_ids": [card["card_id"]], + "kinds": [stop_queue.EXCEPTION_KIND], + "choice": choice_id, + "decided_at": outcome["decided_at"], + "opened_at": outcome["opened_at"], + "public_key": outcome["public_key"], + "signature": outcome["signature"], + "key": outcome.get("key"), + "results": [{"card_id": card["card_id"], "ok": True}], + **({"device": device} if device is not None else {}), + } + ) + self.services.audit.log( + "exception_answered", kind=card.get("exception_kind"), choice=choice_id + ) + return { + "ok": True, + "results": [{"card_id": card["card_id"], "ok": True, "error": None}], + "changed": 1, + } + def _answer_rearm(self, card: dict, *, shown_ms: Any) -> dict: """Turn a task's switch back on with one Touch ID. diff --git a/packages/desktop/openadapt_desktop/exception_queue.py b/packages/desktop/openadapt_desktop/exception_queue.py new file mode 100644 index 0000000000..3273952b7f --- /dev/null +++ b/packages/desktop/openadapt_desktop/exception_queue.py @@ -0,0 +1,296 @@ +"""Exception cards from any agent's run, in the stop queue. + +Flow's exception registry (``openadapt-flow exceptions``) keeps one folder per +run under ``$OPENADAPT_HOME/exceptions`` (``~/.openadapt/exceptions`` by +default). A run that hits a second-factor prompt, an unexpected dialog, a +sign-in page mid-task, a stall, a possible duplicate, a record it can't tell +apart, or a task it can't finish writes a ``card-.json`` and waits for an +``answer-.json``. Cards come from any run on this computer: a CLI guard, +``openadapt wrap``, a flight recorder, a hook, a Desktop-launched run. + +Desktop pins an exact Flow release, so this module reads the files as plain +JSON and checks them itself: the schema id, the closed kind and answer sets, +the card id (the digest of the card), a regular 0600-style file under the +size cap. A card that fails any check isn't shown. + +An answer is the closed answer signed with the approver key Desktop already +uses for the stop queue (Touch ID on a Mac, the portal's key for a phone). +The waiting run checks the signature against its pinned approver roster, so +an answer Desktop writes counts only when that key is on the roster. The +answer file records ``opened_at`` and ``decided_at``: how long a person held +the run. + +Nothing here is sent anywhere. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import stat +import uuid +from collections.abc import Callable +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +CARD_SCHEMA = "openadapt.exception-card/v1" +ANSWER_SCHEMA = "openadapt.exception-answer/v1" +#: The bytes an approver key signs before the canonical answer. Flow's +#: ``openadapt_types.exception_card.EXCEPTION_ANSWER_DOMAIN``. +ANSWER_DOMAIN = b"openadapt.exception-answer/v1\x00" +KINDS = frozenset( + { + "second_factor", + "unexpected_dialog", + "session_expired", + "timeout_or_stall", + "possible_duplicate", + "ambiguous_record", + "cannot_complete", + } +) +ANSWERS = frozenset({"continue", "skip", "decline", "done_by_person", "abort"}) +#: How many cards one scan reads at most. +MAX_CARDS = 200 +_MAX_BYTES = 256 * 1024 +_RUN_REF = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$") +_CARD_FILE = re.compile(r"^card-([0-9a-f]{64})\.json$") +_SUMMARY_MAX = 200 + + +def _canonical(value: Any) -> bytes: + return json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +def registry_root() -> Path: + home = os.environ.get("OPENADAPT_HOME") + return (Path(home) if home else Path.home() / ".openadapt") / "exceptions" + + +def _read(path: Path) -> bytes | None: + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) + try: + fd = os.open(path, flags) + except OSError: + return None + try: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_size > _MAX_BYTES: + return None + if hasattr(os, "getuid") and info.st_uid != os.getuid(): + return None + return os.read(fd, _MAX_BYTES + 1)[:_MAX_BYTES] + finally: + os.close(fd) + + +def _time(value: Any) -> bool: + try: + parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00")) + except ValueError: + return False + return parsed.tzinfo is not None + + +def valid_card(raw: Any, *, run_ref: str, file_hex: str) -> dict[str, Any] | None: + """The card when every field checks out, else ``None``.""" + + if not isinstance(raw, dict) or raw.get("schema") != CARD_SCHEMA: + return None + if raw.get("kind") not in KINDS or raw.get("run_ref") != run_ref: + return None + body = {k: v for k, v in raw.items() if k != "card_id"} + digest = "sha256:" + hashlib.sha256(_canonical(body)).hexdigest() + if raw.get("card_id") != digest or digest != f"sha256:{file_hex}": + return None + if not (_time(raw.get("opened_at")) and _time(raw.get("deadline_at"))): + return None + summary = raw.get("summary") + if not isinstance(summary, str) or not summary or len(summary) > _SUMMARY_MAX: + return None + choices = raw.get("choices") + if not isinstance(choices, list) or not choices: + return None + ids = [c.get("id") if isinstance(c, dict) else None for c in choices] + if any(i not in ANSWERS for i in ids) or len(set(ids)) != len(ids): + return None + task_id = raw.get("task_id") + if task_id is not None and (not isinstance(task_id, str) or len(task_id) > 128): + return None + return raw + + +def open_cards(root: Path | None = None) -> list[dict[str, Any]]: + """Every valid card with no answer yet, oldest first.""" + + base = root if root is not None else registry_root() + try: + folders = sorted(p for p in base.iterdir() if _RUN_REF.fullmatch(p.name)) + except OSError: + return [] + cards: list[dict[str, Any]] = [] + for folder in folders: + try: + if stat.S_ISLNK(os.lstat(folder).st_mode) or not folder.is_dir(): + continue + names = sorted(os.listdir(folder)) + except OSError: + continue + for name in names: + match = _CARD_FILE.fullmatch(name) + if match is None: + continue + if (folder / f"answer-{match.group(1)}.json").exists(): + continue + data = _read(folder / name) + if data is None: + continue + try: + raw = json.loads(data) + except ValueError: + continue + card = valid_card(raw, run_ref=folder.name, file_hex=match.group(1)) + if card is not None: + cards.append(card) + if len(cards) >= MAX_CARDS: + break + return sorted(cards, key=lambda c: str(c.get("opened_at"))) + + +def find_card(card_id: str, run_ref: str, root: Path | None = None) -> dict[str, Any] | None: + """The card, still unanswered and unchanged, or ``None``.""" + + return next( + ( + c + for c in open_cards(root) + if c.get("card_id") == card_id and c.get("run_ref") == run_ref + ), + None, + ) + + +def unsigned_answer(card: dict[str, Any], answer: str, *, route: str, decided_at: str) -> dict: + """The answer the approver key signs (Flow's ``ExceptionAnswerV1`` fields).""" + + if answer not in ANSWERS or route not in {"desktop", "portal"}: + raise ValueError("not an answer") + return { + "schema": ANSWER_SCHEMA, + "card_id": card["card_id"], + "kind": card["kind"], + "opened_at": card["opened_at"], + "decided_at": decided_at, + "answer": answer, + "approver_kind": "person", + "route": route, + "reason": None, + } + + +def message(unsigned: dict[str, Any]) -> bytes: + """The exact bytes the approver key signs.""" + + return ANSWER_DOMAIN + _canonical(unsigned) + + +def _write_exclusive(path: Path, payload: bytes) -> None: + tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(tmp, flags, 0o600) + try: + view = memoryview(payload) + while view: + view = view[os.write(fd, view) :] + os.fsync(fd) + finally: + os.close(fd) + try: + os.link(tmp, path) + finally: + try: + os.unlink(tmp) + except OSError: + pass + + +def answer( + source: dict[str, Any], + choice: str, + *, + sign: Callable[..., dict], + route: str, + root: Path | None = None, + now: Callable[[], datetime] = lambda: datetime.now(timezone.utc), +) -> dict[str, Any]: + """Sign and write one card's answer. Returns ``{"ok", ...}``. + + ``source`` is the queue card's ``source`` (the Flow card id and run). + The Flow card is read again before signing and again before writing: one + answered, changed or gone in between changes nothing. Raises the + signer's own error (``ApproverKeychainError``) for the caller to report. + """ + + base = root if root is not None else registry_root() + card_id, run_ref = str(source.get("id") or ""), str(source.get("run_ref") or "") + card = find_card(card_id, run_ref, base) + if card is None: + return {"ok": False, "code": "card_changed", "error": "The stop was answered or is gone."} + if choice not in {c.get("id") for c in card["choices"]}: + return {"ok": False, "code": "choice_not_offered", "error": "That choice isn't on this stop."} + decided = now().astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + if _after(decided, card["deadline_at"]): + return {"ok": False, "code": "card_expired", "error": "The stop expired."} + unsigned = unsigned_answer(card, choice, route=route, decided_at=decided) + signature = sign(message(unsigned), count=1) + if find_card(card_id, run_ref, base) is None: + return {"ok": False, "code": "card_changed", "error": "The stop was answered or is gone."} + record = { + **unsigned, + "public_key": signature["public_key"], + "signature": signature["signature"], + } + path = base / run_ref / f"answer-{card_id.removeprefix('sha256:')}.json" + try: + _write_exclusive(path, (json.dumps(record, sort_keys=True, indent=2) + "\n").encode()) + except FileExistsError: + return {"ok": False, "code": "card_changed", "error": "The stop was answered first."} + except OSError: + return {"ok": False, "code": "registry_unwritable", "error": "Desktop couldn't save the answer."} + return { + "ok": True, + "answer": choice, + "decided_at": decided, + "opened_at": card["opened_at"], + "key": signature.get("key"), + "public_key": signature["public_key"], + "signature": signature["signature"], + } + + +def _after(a: str, b: str) -> bool: + try: + return datetime.fromisoformat(a.replace("Z", "+00:00")) > datetime.fromisoformat( + str(b).replace("Z", "+00:00") + ) + except ValueError: + return True + + +__all__ = [ + "ANSWERS", + "ANSWER_DOMAIN", + "ANSWER_SCHEMA", + "CARD_SCHEMA", + "KINDS", + "answer", + "find_card", + "message", + "open_cards", + "registry_root", + "unsigned_answer", + "valid_card", +] diff --git a/packages/desktop/openadapt_desktop/portal/shell/stops.js b/packages/desktop/openadapt_desktop/portal/shell/stops.js index a916569954..725e4d2ed6 100644 --- a/packages/desktop/openadapt_desktop/portal/shell/stops.js +++ b/packages/desktop/openadapt_desktop/portal/shell/stops.js @@ -8,6 +8,12 @@ // choice the stop doesn't offer, changes nothing, and this page shows the // refusal as it came. // +// An exception card is any agent's run asking a person (a one-time code +// prompt, a dialog in the way, a sign-in partway through, a stall, a +// possible duplicate, an ambiguous record, a task it can't finish). It shows +// the run's scrubbed summary and its closed choices, and is answered on its +// own. A one-time code is typed in the live browser, never here. +// // Answers are signed on the computer with the decision portal's approver // key. Two kinds of stop are view-only here: a waiting save is answered on // the Decisions page (the portal's own save approval), and turning "only ask @@ -19,7 +25,7 @@ const POLL_MS = 10000; const MAX_BATCH = 25; -const PHONE_KINDS = new Set(["same_record", "confirm_save", "halted"]); +const PHONE_KINDS = new Set(["same_record", "confirm_save", "halted", "exception"]); const store = window.sessionStorage; const state = { @@ -437,7 +443,7 @@ function render() { className: "stops-warn", text: "Answers from this phone need the decision portal's approver key. Set it up on the computer. Until then, nothing here changes.", }), - evidence(card), + card.kind === "exception" ? null : evidence(card), choices(card), batchBlock(card), ]), diff --git a/packages/desktop/openadapt_desktop/stop_queue.py b/packages/desktop/openadapt_desktop/stop_queue.py index f51438331f..5606f05bbb 100644 --- a/packages/desktop/openadapt_desktop/stop_queue.py +++ b/packages/desktop/openadapt_desktop/stop_queue.py @@ -24,6 +24,12 @@ first, so every answer names a registered approver. * ``rearm_problems_only``: a task whose "only ask about problems" switch went off, when a signed re-arm is available. +* ``exception``: a card any agent's run opened in Flow's exception registry + (a one-time code prompt, an unexpected dialog, a sign-in mid-task, a stall, + a possible duplicate, an ambiguous record, a task it can't finish). The + answer is the closed answer, signed with the approver key and written as + the card's answer file (:mod:`openadapt_desktop.exception_queue`); the + waiting run checks the signature itself. Similar cards share a ``batch_key``. A batch is answered with one choice and one signature, and each card in it is still checked on its own. @@ -489,6 +495,179 @@ def card_for_rearm(switch: dict) -> dict[str, Any] | None: return _seal(card) +# -- exception cards ------------------------------------------------------------- + +#: Per kind: the question, and the closed answers with what each one does. +#: Desktop shows its own words for each answer, and only answers the run's +#: own card offers. +_EXCEPTION_QUESTIONS = { + "second_factor": "The app wants a one-time code", + "unexpected_dialog": "A dialog is in the way", + "session_expired": "The app signed out partway through", + "timeout_or_stall": "The run has stalled", + "possible_duplicate": "Is this record already in the app?", + "ambiguous_record": "Which record is it?", + "cannot_complete": "The run can't finish this item", +} + +_EXCEPTION_SKIP = Choice( + "skip", "Skip this item", "Nothing is saved. The run moves to the next item.", "exception:skip" +) +_EXCEPTION_ABORT = Choice( + "abort", "Stop the run", "Nothing more is saved. The whole run stops.", "exception:abort" +) + +_EXCEPTION_CHOICES: dict[str, tuple[Choice, ...]] = { + "second_factor": ( + Choice( + "done_by_person", + "I entered the code in the browser", + "You type the code in the live browser yourself, then the run goes on. " + "OpenAdapt never sees the code.", + "exception:done_by_person", + ), + _EXCEPTION_SKIP, + _EXCEPTION_ABORT, + ), + "unexpected_dialog": ( + Choice( + "done_by_person", + "I dealt with the dialog", + "You close or answer it yourself, then the run goes on.", + "exception:done_by_person", + ), + Choice( + "continue", + "It's harmless, go on", + "The run goes on with the dialog as it is. Every check still runs.", + "exception:continue", + ), + _EXCEPTION_SKIP, + _EXCEPTION_ABORT, + ), + "session_expired": ( + Choice( + "done_by_person", + "I signed in again", + "You sign in yourself in the live browser, then the run goes on. " + "OpenAdapt never sees the password.", + "exception:done_by_person", + ), + _EXCEPTION_SKIP, + _EXCEPTION_ABORT, + ), + "timeout_or_stall": ( + Choice( + "continue", + "Keep waiting", + "The run tries the step again, with every check.", + "exception:continue", + ), + _EXCEPTION_SKIP, + _EXCEPTION_ABORT, + ), + "possible_duplicate": ( + Choice( + "skip", + "Same record: don't add it", + "Nothing is saved. The item closes as skipped.", + "exception:skip", + ), + Choice( + "continue", + "Different record: go on", + "The run goes on to fill the form. The save still needs every check.", + "exception:continue", + ), + Choice( + "done_by_person", + "I'll do this one by hand", + "OpenAdapt saves nothing. The item closes as done by a person.", + "exception:done_by_person", + ), + _EXCEPTION_ABORT, + ), + "ambiguous_record": ( + Choice( + "done_by_person", + "I opened the right record", + "You open the right record yourself, then the run goes on from there.", + "exception:done_by_person", + ), + _EXCEPTION_SKIP, + Choice( + "decline", + "This item shouldn't be done", + "Nothing is saved. The item closes as declined.", + "exception:decline", + ), + ), + "cannot_complete": ( + Choice( + "done_by_person", + "I did it by hand", + "OpenAdapt saves nothing. The item closes as done by a person.", + "exception:done_by_person", + ), + _EXCEPTION_SKIP, + _EXCEPTION_ABORT, + ), +} + +#: Card kinds that are exception cards (one card kind, many exception kinds). +EXCEPTION_KIND = "exception" + + +def card_for_exception(raw: dict) -> dict[str, Any] | None: + """A card from Flow's exception registry as a queue card, or None. + + ``raw`` is a card :func:`openadapt_desktop.exception_queue.open_cards` + already checked. Its summary was scrubbed by the run before it was + written. Each exception is answered on its own: no batch. + """ + + kind = raw.get("kind") if isinstance(raw, dict) else None + table = _EXCEPTION_CHOICES.get(str(kind)) + if table is None: + return None + offered = {c.get("id") for c in raw.get("choices") or [] if isinstance(c, dict)} + choices = [c for c in table if c.id in offered] + if not choices: + return None + card = { + "schema": CARD_SCHEMA, + "kind": EXCEPTION_KIND, + "exception_kind": kind, + "source": { + "type": "exception", + "id": raw["card_id"], + "run_ref": raw["run_ref"], + }, + "workflow_id": "", + "task_name": str(raw.get("task_id") or raw["run_ref"]), + "label": "", + "question": _EXCEPTION_QUESTIONS[str(kind)], + "summary": str(raw.get("summary") or ""), + "evidence": { + "source": [], + "record": [], + "differences": [], + "candidates": [], + "reason": "", + "step": "", + "expected": "", + "observed": "", + "screenshot": None, + }, + "choices": [c.public() for c in [*choices, _LEAVE]], + "expires_at": raw.get("deadline_at"), + "created_at": raw.get("opened_at"), + "batch_key": None, + "status": "waiting", + } + return _seal(card) + + def choice_for(card: dict, choice_id: str) -> Choice | None: """The full choice behind a card's button, or None if it doesn't offer it.""" @@ -500,6 +679,9 @@ def choice_for(card: dict, choice_id: str) -> Choice | None: return next((c for c in _APPROVAL_CHOICES if c.id == choice_id), None) if card["kind"] == "rearm_problems_only": return Choice("rearm", "", "", "rearm") if choice_id == "rearm" else None + if card["kind"] == EXCEPTION_KIND: + table = _EXCEPTION_CHOICES.get(str(card.get("exception_kind")), ()) + return next((c for c in table if c.id == choice_id), None) table = _ITEM_CHOICES.get(card["kind"], {}) return next((c for c in table.values() if c.id == choice_id), None) @@ -531,9 +713,16 @@ def decision_message(card_ids: Iterable[str], choice_id: str, *, decided_at: str def sort_cards(cards: list[dict]) -> list[dict]: - """Waiting saves first (they expire), then the oldest stop first.""" - - order = {"approve_save": 0, "confirm_save": 1, "same_record": 2, "halted": 3} + """Waiting saves and exceptions first (they expire), then the oldest stop.""" + + # A run holding on an exception waits with a deadline, like a save. + order = { + "approve_save": 0, + EXCEPTION_KIND: 0, + "confirm_save": 1, + "same_record": 2, + "halted": 3, + } return sorted( cards, key=lambda c: (order.get(c["kind"], 4), str(c.get("created_at") or "")), @@ -544,10 +733,12 @@ def sort_cards(cards: list[dict]) -> list[dict]: "CARD_SCHEMA", "DECISION_DOMAIN", "DECISION_SCHEMA", + "EXCEPTION_KIND", "MAX_BATCH", "RECORD_CHECK_ACTIONS", "Choice", "card_for_approval", + "card_for_exception", "card_for_item", "card_for_rearm", "choice_for", diff --git a/packages/desktop/package-lock.json b/packages/desktop/package-lock.json index 3fa77186e8..88c85f2015 100644 --- a/packages/desktop/package-lock.json +++ b/packages/desktop/package-lock.json @@ -1,12 +1,12 @@ { "name": "openadapt-desktop", - "version": "0.30.6", + "version": "0.31.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openadapt-desktop", - "version": "0.30.6", + "version": "0.31.0", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-notification": "^2", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 2922cf9315..1b92b8568c 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "openadapt-desktop", - "version": "0.30.6", + "version": "0.31.0", "description": "Installed companion for OpenAdapt authoring, teaching, and local pairing", "private": true, "type": "module", diff --git a/packages/desktop/pyproject.toml b/packages/desktop/pyproject.toml index bd1d994ee7..84d122859c 100644 --- a/packages/desktop/pyproject.toml +++ b/packages/desktop/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "openadapt-desktop" -version = "0.30.6" +version = "0.31.0" description = "The OpenAdapt desktop app and local engine: record a data-entry task, run it on a list, and check each saved record" readme = "README.md" requires-python = ">=3.11" diff --git a/packages/desktop/src-tauri/Cargo.lock b/packages/desktop/src-tauri/Cargo.lock index 111ec12503..98cf6ea65f 100644 --- a/packages/desktop/src-tauri/Cargo.lock +++ b/packages/desktop/src-tauri/Cargo.lock @@ -2513,7 +2513,7 @@ dependencies = [ [[package]] name = "openadapt-desktop" -version = "0.30.6" +version = "0.31.0" dependencies = [ "hex", "reqwest", diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml index 80279fdaab..e8c03f006a 100644 --- a/packages/desktop/src-tauri/Cargo.toml +++ b/packages/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "openadapt-desktop" -version = "0.30.6" +version = "0.31.0" description = "Installed companion for OpenAdapt authoring, teaching, and local pairing" authors = ["OpenAdapt AI"] license = "MIT" diff --git a/packages/desktop/src-tauri/tauri.conf.json b/packages/desktop/src-tauri/tauri.conf.json index ede2e28594..aa17f4b35d 100644 --- a/packages/desktop/src-tauri/tauri.conf.json +++ b/packages/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://raw.githubusercontent.com/nicoverbruggen/tauri-v2-schema/main/schema.json", "productName": "OpenAdapt Desktop", - "version": "0.30.6", + "version": "0.31.0", "identifier": "ai.openadapt.desktop", "build": { "frontendDist": "../dist", diff --git a/packages/desktop/tests/conftest.py b/packages/desktop/tests/conftest.py index cdfb7ce65c..e8a4208cd3 100644 --- a/packages/desktop/tests/conftest.py +++ b/packages/desktop/tests/conftest.py @@ -151,6 +151,9 @@ def _isolated_flow_at_rest(tmp_path_factory, monkeypatch): monkeypatch.setenv("OPENADAPT_FLOW_AT_REST_HOME", str(tmp_path_factory.mktemp("at-rest-home"))) monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "test suite: synthetic data") monkeypatch.delenv("OPENADAPT_FLOW_AT_REST", raising=False) + # The stop queue also lists Flow's exception registry under + # OPENADAPT_HOME; keep a developer's real cards out of every test. + monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path_factory.mktemp("openadapt-home"))) @pytest.fixture(autouse=True) diff --git a/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py b/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py new file mode 100644 index 0000000000..debcf3a868 --- /dev/null +++ b/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py @@ -0,0 +1,378 @@ +"""Exception cards from any agent's run, in the stop queue and on the phone. + +The cards are files in a temporary OPENADAPT_HOME, written as Flow's +exception registry writes them (the committed Flow fixture is the contract). +Answers are signed with the fake Secure Enclave's approver key, or the +portal's key for the phone. Synthetic data only. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import stat +import threading +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + +from openadapt_desktop import exception_queue, stop_queue +from openadapt_desktop.portal.stops import DispatcherStopQueue +from tests.test_engine.test_stop_queue import ( # noqa: F401 (fixtures) + enclave, + queue, +) +from tests.test_engine.test_stop_queue_portal import ( # noqa: F401 (fixtures) + _app, + _paired, + portal_key, +) + +FLOW_FIXTURE = ( + Path(__file__).resolve().parents[3] + / "flow" + / "tests" + / "fixtures" + / "exception_card_second_factor.json" +) +CHOICES = { + "second_factor": ["done_by_person", "skip", "abort"], + "unexpected_dialog": ["done_by_person", "continue", "skip", "abort"], + "session_expired": ["done_by_person", "skip", "abort"], + "timeout_or_stall": ["continue", "skip", "abort"], + "possible_duplicate": ["skip", "continue", "done_by_person", "abort"], + "ambiguous_record": ["done_by_person", "skip", "decline"], + "cannot_complete": ["done_by_person", "skip", "abort"], +} + + +def _canonical(value) -> bytes: + return json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + + +def _iso(value: datetime) -> str: + return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +def _write_card( + kind: str = "second_factor", + *, + run_ref: str = "guard-run", + minutes: int = 15, + summary: str = "The app is asking for a one-time code.", +) -> dict: + opened = datetime.now(timezone.utc) + body = { + "schema": "openadapt.exception-card/v1", + "run_ref": run_ref, + "task_id": "intake", + "kind": kind, + "opened_at": _iso(opened), + "deadline_at": _iso(opened + timedelta(minutes=minutes)), + "screenshot_ref": None, + "summary": summary, + "choices": [ + {"id": answer, "label": answer.replace("_", " "), "consequence": "As the run says."} + for answer in CHOICES[kind] + ], + } + card = {**body, "card_id": "sha256:" + hashlib.sha256(_canonical(body)).hexdigest()} + folder = exception_queue.registry_root() / run_ref + folder.mkdir(parents=True, exist_ok=True) + path = folder / f"card-{card['card_id'][7:]}.json" + path.write_text(json.dumps(card, indent=2)) + path.chmod(0o600) + return card + + +def _cards(disp) -> list[dict]: + listed = disp.dispatch("list_stop_cards", {}) + assert listed["ok"] is True + return [c for c in listed["cards"] if c["kind"] == stop_queue.EXCEPTION_KIND] + + +def _answer_file(card: dict) -> Path: + return ( + exception_queue.registry_root() + / card["run_ref"] + / f"answer-{card['card_id'][7:]}.json" + ) + + +# -- the cards ------------------------------------------------------------------------ + + +def test_flows_own_card_file_is_listed(): + if not FLOW_FIXTURE.is_file(): + pytest.skip("Flow's fixture isn't in this checkout") + raw = json.loads(FLOW_FIXTURE.read_text()) + folder = exception_queue.registry_root() / raw["run_ref"] + folder.mkdir(parents=True) + path = folder / f"card-{raw['card_id'][7:]}.json" + path.write_text(json.dumps(raw)) + + (found,) = exception_queue.open_cards() + card = stop_queue.card_for_exception(found) + + assert card is not None + assert card["exception_kind"] == "second_factor" + assert [c["id"] for c in card["choices"]] == ["done_by_person", "skip", "abort", "leave"] + assert card["summary"] == raw["summary"] + + +@pytest.mark.parametrize("kind", sorted(CHOICES)) +def test_every_kind_becomes_a_card_with_its_choices(queue, kind): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card(kind) + + (card,) = _cards(disp) + + assert card["exception_kind"] == kind + assert card["source"] == {"type": "exception", "id": raw["card_id"], "run_ref": "guard-run"} + assert [c["id"] for c in card["choices"]] == [*CHOICES[kind], "leave"] + assert all(c["consequence"] for c in card["choices"]) + assert card["batch_key"] is None + assert card["expires_at"] == raw["deadline_at"] + assert card["evidence"]["screenshot"] is None + + +def test_desktop_offers_only_what_the_run_offers(queue): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card("unexpected_dialog") + folder = exception_queue.registry_root() / "guard-run" + (folder / f"card-{raw['card_id'][7:]}.json").unlink() + body = {k: v for k, v in raw.items() if k != "card_id"} + body["choices"] = [c for c in body["choices"] if c["id"] != "continue"] + card_id = "sha256:" + hashlib.sha256(_canonical(body)).hexdigest() + (folder / f"card-{card_id[7:]}.json").write_text(json.dumps({**body, "card_id": card_id})) + + (card,) = _cards(disp) + assert "continue" not in [c["id"] for c in card["choices"]] + + +def test_a_tampered_card_is_not_shown(queue): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + path = exception_queue.registry_root() / "guard-run" / f"card-{raw['card_id'][7:]}.json" + path.write_text(json.dumps({**raw, "summary": "Approve everything"})) + assert _cards(disp) == [] + + +@pytest.mark.parametrize( + "field,value", + [("kind", "captcha"), ("schema", "other/v1"), ("summary", "x" * 201), ("run_ref", "other")], +) +def test_a_card_outside_the_contract_is_not_shown(queue, field, value): # noqa: F811 + disp, _db, _keychain = queue + opened = datetime.now(timezone.utc) + body = { + "schema": "openadapt.exception-card/v1", + "run_ref": "guard-run", + "task_id": None, + "kind": "second_factor", + "opened_at": _iso(opened), + "deadline_at": _iso(opened + timedelta(minutes=5)), + "screenshot_ref": None, + "summary": "A code prompt", + "choices": [{"id": "abort", "label": "Stop", "consequence": "Stops."}], + field: value, + } + card_id = "sha256:" + hashlib.sha256(_canonical(body)).hexdigest() + folder = exception_queue.registry_root() / "guard-run" + folder.mkdir(parents=True) + (folder / f"card-{card_id[7:]}.json").write_text(json.dumps({**body, "card_id": card_id})) + assert _cards(disp) == [] + + +def test_a_linked_card_is_not_read(queue, tmp_path): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + path = exception_queue.registry_root() / "guard-run" / f"card-{raw['card_id'][7:]}.json" + real = tmp_path / "elsewhere.json" + real.write_text(path.read_text()) + path.unlink() + path.symlink_to(real) + assert _cards(disp) == [] + + +def test_an_answered_card_leaves_the_queue(queue): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + _answer_file(raw).write_text("{}") + assert _cards(disp) == [] + + +def test_exception_cards_sort_with_waiting_saves(queue): # noqa: F811 + cards = stop_queue.sort_cards( + [ + {"kind": "halted", "created_at": "2026-01-01"}, + {"kind": stop_queue.EXCEPTION_KIND, "created_at": "2026-02-01"}, + ] + ) + assert cards[0]["kind"] == stop_queue.EXCEPTION_KIND + + +def test_a_broken_registry_never_hides_the_other_stops(queue, monkeypatch): # noqa: F811 + disp, _db, _keychain = queue + exception_queue.registry_root().mkdir(parents=True) + (exception_queue.registry_root() / "guard-run").write_text("not a folder") + assert disp.dispatch("list_stop_cards", {})["ok"] is True + + +# -- answers from the window -------------------------------------------------------- + + +def test_the_window_signs_and_writes_the_runs_answer(queue, enclave): # noqa: F811 + disp, _db, keychain = queue + raw = _write_card() + (card,) = _cards(disp) + + result = disp.dispatch( + "answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "done_by_person"} + ) + + assert result["ok"] is True and result["changed"] == 1 + assert len(enclave.prompts) == 1 + path = _answer_file(raw) + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + answer = json.loads(path.read_text()) + assert answer["answer"] == "done_by_person" + assert answer["approver_kind"] == "person" and answer["route"] == "desktop" + assert answer["opened_at"] == raw["opened_at"] and answer["decided_at"] + assert answer["public_key"] == keychain.stored().public_key + unsigned = {k: v for k, v in answer.items() if k not in {"signature", "public_key"}} + Ed25519PublicKey.from_public_bytes(bytes.fromhex(answer["public_key"])).verify( + bytes.fromhex(answer["signature"].removeprefix("ed25519:")), + exception_queue.ANSWER_DOMAIN + _canonical(unsigned), + ) + assert _cards(disp) == [] + (receipt,) = [ + json.loads(line) + for line in (disp.config.data_dir / "stop_decisions.jsonl").read_text().splitlines() + ] + assert receipt["kinds"] == ["exception"] + assert receipt["opened_at"] == raw["opened_at"] and receipt["decided_at"] + + +def test_the_answer_file_matches_flows_answer_contract(queue, enclave): # noqa: F811 + """Flow's ExceptionAnswerV1 accepts what Desktop writes, when it's importable.""" + + types = pytest.importorskip("openadapt_types.exception_card") + disp, _db, _keychain = queue + raw = _write_card() + (card,) = _cards(disp) + disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "skip"}) + answer = types.ExceptionAnswerV1.model_validate(json.loads(_answer_file(raw).read_text())) + assert types.answer_message(answer.wire()) == exception_queue.message( + {k: v for k, v in answer.wire().items() if k not in {"signature", "public_key"}} + ) + + +def test_a_choice_the_card_doesnt_offer_changes_nothing(queue): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card("second_factor") + (card,) = _cards(disp) + result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "continue"}) + assert result["ok"] is False and result["code"] == "choice_not_offered" + assert not _answer_file(raw).exists() + + +def test_leave_changes_nothing(queue, enclave): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + (card,) = _cards(disp) + result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "leave"}) + assert result["ok"] is True and result["changed"] == 0 + assert not _answer_file(raw).exists() and enclave.prompts == [] + + +def test_an_expired_card_changes_nothing(queue): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card(minutes=-1) + (card,) = _cards(disp) + result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "abort"}) + assert result["ok"] is False + assert not _answer_file(raw).exists() + + +def test_a_cancelled_prompt_writes_nothing(queue, enclave): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + (card,) = _cards(disp) + enclave.answer = "cancel" + result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "abort"}) + assert result["ok"] is False and result["code"] == "approver_presence_refused" + assert not _answer_file(raw).exists() + + +def test_a_card_answered_elsewhere_during_the_prompt_is_not_overwritten(queue, enclave, monkeypatch): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + (card,) = _cards(disp) + original = disp._sign_stop_decision + + def sign_while_the_cli_answers(message, *, count): + _answer_file(raw).write_text('{"answered": "elsewhere"}') + return original(message, count=count) + + monkeypatch.setattr(disp, "_sign_stop_decision", sign_while_the_cli_answers) + result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "abort"}) + assert result["ok"] is False and result["code"] == "card_changed" + assert json.loads(_answer_file(raw).read_text()) == {"answered": "elsewhere"} + + +def test_two_exception_cards_are_never_one_batch(queue): # noqa: F811 + disp, _db, _keychain = queue + _write_card(run_ref="run-a") + _write_card(run_ref="run-b") + ids = [c["card_id"] for c in _cards(disp)] + result = disp.dispatch("answer_stop_cards", {"card_ids": ids, "choice": "abort"}) + assert result["ok"] is False + assert not list(exception_queue.registry_root().rglob("answer-*.json")) + + +# -- answers from the paired phone --------------------------------------------------- + + +def test_the_phone_answers_with_the_portal_key(queue, portal_key, enclave): # noqa: F811 + disp, _db, _keychain = queue + disp.serial_lock = threading.RLock() + raw = _write_card("possible_duplicate") + app, pairings = _app(DispatcherStopQueue(disp)) + headers = _paired(pairings) + + status, _h, body = app.handle("GET", "/api/portal/stops", headers, b"") + (card,) = [c for c in json.loads(body)["cards"] if c["kind"] == "exception"] + status, _h, body = app.handle( + "POST", + f"/api/portal/stops/{card['card_id'].removeprefix('sha256:')}/answer", + headers, + json.dumps({"choice": "skip", "shown_ms": 900}).encode(), + ) + + assert status == 200 and json.loads(body)["ok"] is True + assert enclave.prompts == [] + answer = json.loads(_answer_file(raw).read_text()) + assert answer["route"] == "portal" and answer["answer"] == "skip" + assert answer["public_key"] == portal_key.public_key + + +def test_the_phone_page_knows_the_exception_cards(): + script = ( + Path(__file__).resolve().parents[2] + / "openadapt_desktop" + / "portal" + / "shell" + / "stops.js" + ).read_text() + assert '"exception"' in script + assert "const MAX_BATCH = 25;" in script + assert stop_queue.MAX_BATCH == 25 + + +def test_no_registry_folder_is_an_empty_list(tmp_path): + assert exception_queue.open_cards(tmp_path / "missing") == [] + assert os.environ["OPENADAPT_HOME"] diff --git a/packages/desktop/uv.lock b/packages/desktop/uv.lock index 2f82f650e6..97ac5c27f7 100644 --- a/packages/desktop/uv.lock +++ b/packages/desktop/uv.lock @@ -1172,7 +1172,7 @@ wheels = [ [[package]] name = "openadapt-desktop" -version = "0.30.6" +version = "0.31.0" source = { editable = "." } dependencies = [ { name = "cryptography" }, diff --git a/packages/flow/docs/EXCEPTION_QUEUE.md b/packages/flow/docs/EXCEPTION_QUEUE.md new file mode 100644 index 0000000000..0aa92775be --- /dev/null +++ b/packages/flow/docs/EXCEPTION_QUEUE.md @@ -0,0 +1,156 @@ +# The exception queue + +Any agent can stop and ask a person, and wait for one closed answer. The agent +can be a compiled program, Claude computer use, an OpenAI CUA harness, +Browser-Use, or a person's own script. A person answers from the terminal, from +Desktop's stop queue, or from a paired phone. A run that gets no answer, or an +answer it can't verify, stops before any write. + +The share of cases that need a person has not been measured. Any figure, such +as "about 10%", is an estimate until a deployment measures it. + +## The kinds + +`kind` is a closed set. Nothing else validates. + +| Kind | When | Usual answer | +| --- | --- | --- | +| `second_factor` | The app asks for a one-time code. | `done_by_person`: the person types the code in the live browser. | +| `unexpected_dialog` | A modal the run didn't expect covers the target. | `done_by_person` or `continue` | +| `session_expired` | A sign-in page appears after the run reached a screen where it could save. | `done_by_person`: the person signs in again. | +| `timeout_or_stall` | No action and no screen change for N seconds. | `continue` | +| `possible_duplicate` | A row already in the app matches the record on `record.duplicate_key`. | `skip` or `continue` | +| `ambiguous_record` | The agent can't tell which record is the right one. | `done_by_person` | +| `cannot_complete` | The agent can't finish the item. | `done_by_person` | + +`answer` is also closed: `continue`, `skip`, `decline`, `done_by_person` and +`abort`. Each kind offers only some of them (`openadapt_flow/exceptions/registry.py`, +`CHOICES`). Only `continue` and `done_by_person` let a run go on. + +The one-time code is never relayed through OpenAdapt. The card asks the person +to type it into the live browser, and the agent goes on from the same screen. + +## For an agent: the MCP tool + +```bash +openadapt-flow exceptions serve --run-ref intake-0412 --task-id intake +``` + +This starts a stdio MCP server with one tool: + +```text +raise_exception(kind, summary, screenshot_path?) +``` + +The tool opens a card and blocks until a person answers or the card expires +(15 minutes by default, `--deadline-s` to change it). It returns: + +```json +{"card_id": "sha256:...", "kind": "second_factor", "answer": "done_by_person", + "proceed": true, "reason": null, "opened_at": "...", "decided_at": "...", + "instruction": "A person answered done_by_person. Go on from the current screen."} +``` + +Go on only when `proceed` is `true`. Otherwise stop and write nothing. + +The tool can tell an agent to stop. It can't make an agent that ignores the +result stop. To hold an agent at the boundary whatever it does, run it under a +guard (`openadapt-flow guard`) or `openadapt wrap`. + +## For a person: answering + +```bash +openadapt-flow exceptions list +openadapt-flow exceptions answer sha256:... done_by_person +``` + +`answer` signs with an approver key on the pinned approver roster +(`openadapt-flow jit approver init|add`). By default it reads the key file +Desktop keeps, `~/.openadapt/approver/desktop-approver.pem`, with +`OPENADAPT_JIT_KEY_PASSPHRASE`. Pass `--key` for another key. The roster's +root comes from `--approver-root` or `OPENADAPT_APPROVER_ROOT`, and its folder +from `--key-dir` (default `~/.openadapt/jit`). `answer` refuses to write an +answer the waiting run wouldn't accept. + +Desktop lists every open card from every run on the computer in its stop +queue, beside the saves and stops of its own runs, and shows each one on a +paired phone. An answer from Desktop is signed with the same approver key as +its other stop answers (Touch ID on a Mac). An answer from the phone is signed +with the decision portal's key. Exception cards are answered one at a time, +never in a batch. + +## The files + +Each run has one folder, `$OPENADAPT_HOME/exceptions//` +(`~/.openadapt/exceptions` by default): + +| File | Written by | +| --- | --- | +| `card-.json` | The run, when it asks (`openadapt.exception-card/v1`) | +| `screenshot-.png` | The run, as a scrubbed copy, only when a scrubber could redact it | +| `answer-.json` | A person's signed answer, or the registry when the card expires (`openadapt.exception-answer/v1`) | +| `consumed-.json` | The run, when it acts on the answer | + +Every file is created once (a temporary file, then a hard link), owner read and +write only, and never replaced. The schemas are in +`openadapt_types.exception_card`. `card_id` is the SHA-256 of the card's other +fields, so an answer names exactly the card a person saw. + +An answer records `opened_at` and `decided_at`: how long a person held the run. +An expiry record has `answer` `decline`, `decided_at` `null`, +`approver_kind` `expiry` and `reason` `expired`. + +## What the run checks + +The waiting run checks every answer itself. It goes on only when all of these +hold: + +- the answer names this card's id, kind and open time; +- it is one of the card's choices; +- it was decided after the card opened and before its deadline; +- it is signed by a key on the approver roster the run pins; +- it hasn't been used before (`consumed-.json` is created exclusively). + +Anything else (`decline`, `skip`, `abort`, an expiry, a file that can't be +read, an unregistered key, a bad signature, a late answer, a reused answer) +means stop before any write. When the registry's expiry and a person's answer +land at the same moment, whichever file is created first is the answer, and +the run checks it like any other. + +## Privacy + +The summary can reach a paired phone, so it follows Flow's outbound rule. With +a working scrubber (the `privacy` extra), the agent's text is scrubbed, digit +runs, dates and email addresses are masked, and the result is cut to 200 +characters. Without one, the card shows only the kind's own sentence and drops +the agent's text. A screenshot is kept only as a redacted copy, and only when a +scrubber can redact images. The path an agent passes is read only as a regular +PNG file under 8 MB, never through a link. Nothing in the registry is sent +anywhere. + +## Detectors + +`openadapt_flow.exceptions.detectors` is a library of pure functions over the +screen's text, an accessibility snapshot, a DOM snapshot when there is one, and +timing. Each returns a kind or `None`. They use general signals only: + +- an input with `autocomplete=one-time-code`, or a short numeric input near a + word like *code* or *verification*, is `second_factor`; +- a password field after the first save-eligible screen is `session_expired`; +- a modal on top of the target is `unexpected_dialog`; +- no action and no screen change for N seconds is `timeout_or_stall`; +- a row matching the proposed record on every field of verify.yaml's + `record.duplicate_key` is `possible_duplicate`. + +A detector that can't tell (a dialog with no geometry, a failed read, a clock +with no last event) returns its kind: uncertain means ask. The detectors read +nothing and name no app. A caller passes in what it already saw. + +## Not in this release + +- Relaying a second-factor code through OpenAdapt. A follow-up can seal and + type the code through the existing second-factor handoff, so the agent never + sees it. +- `raise_exception` on the `openadapt wrap -- COMMAND` MCP surface. +- Calling the detectors from the flight gate and the guard's observe path. +- A Cloud intake for exception cards and web push. diff --git a/packages/flow/docs/commands/03-run-and-answer/exceptions.md b/packages/flow/docs/commands/03-run-and-answer/exceptions.md new file mode 100644 index 0000000000..9e8714809f --- /dev/null +++ b/packages/flow/docs/commands/03-run-and-answer/exceptions.md @@ -0,0 +1 @@ +Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md). diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 931f0ee13a..d87a7a79eb 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -9353,6 +9353,7 @@ def build_parser() -> argparse.ArgumentParser: sub = parser.add_subparsers( dest="command", required=True, parser_class=argparse.ArgumentParser ) + __import__("openadapt_flow.exceptions.cli", fromlist=["register"]).register(sub) p = sub.add_parser( "demo", diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index 8d18591838..b83d799139 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -60,6 +60,7 @@ "disambiguate": "compile --disambiguate", "emit-mcp": "workflow emit-mcp", "emit-skill": "workflow emit-skill", + "exceptions": "approve exceptions", "explain": "inspect explain", "fleet": "services fleet", "for-each": "run --for-each", diff --git a/packages/flow/openadapt_flow/exceptions/__init__.py b/packages/flow/openadapt_flow/exceptions/__init__.py new file mode 100644 index 0000000000..3417b5770c --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/__init__.py @@ -0,0 +1,11 @@ +"""The exception queue: any agent stops, a person answers, the run goes on +or stops before any write. + +- :mod:`.registry`: the local file protocol (cards, answers, expiry, consume). +- :mod:`.detectors`: pure checks that say when to ask (no app names). +- :mod:`.mcp_server`: the ``raise_exception`` MCP tool. +- :mod:`.cli`: ``openadapt-flow exceptions serve|list|answer``. + +The schemas live in :mod:`openadapt_types.exception_card`. See +``docs/EXCEPTION_QUEUE.md``. +""" diff --git a/packages/flow/openadapt_flow/exceptions/cli.py b/packages/flow/openadapt_flow/exceptions/cli.py new file mode 100644 index 0000000000..88e68a0c62 --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/cli.py @@ -0,0 +1,214 @@ +"""CLI: ``openadapt-flow exceptions serve|list|answer``. See +``docs/EXCEPTION_QUEUE.md``. + + openadapt-flow exceptions serve --run-ref intake-0412 + openadapt-flow exceptions list + openadapt-flow exceptions answer sha256:… done_by_person + +``answer`` signs with an approver key on the pinned roster (by default the +key file Desktop keeps, ``~/.openadapt/approver/desktop-approver.pem``, opened +with ``OPENADAPT_JIT_KEY_PASSPHRASE``; read only). It refuses to write an +answer the waiting run wouldn't accept. Exit 0 on success, 2 when refused. +""" + +from __future__ import annotations + +import argparse +import json +import sys +import uuid +from pathlib import Path +from typing import Optional + +KEY_DEFAULT = Path.home() / ".openadapt" / "approver" / "desktop-approver.pem" + + +def _common(p: argparse.ArgumentParser) -> None: + p.add_argument( + "--registry", + help="the exceptions folder (default: $OPENADAPT_HOME/exceptions)", + ) + + +def _roster(p: argparse.ArgumentParser) -> None: + p.add_argument("--key-dir", help="the approver roster's folder (default: ~/.openadapt/jit)") + p.add_argument( + "--approver-root", + help="the roster's root public key (default: OPENADAPT_APPROVER_ROOT)", + ) + + +def register(sub: argparse._SubParsersAction) -> None: + p = sub.add_parser( + "exceptions", + allow_abbrev=False, + help="Let any agent stop and ask a person (2FA, a dialog, a sign-in, a " + "stall, a possible duplicate), and answer from here, Desktop or a phone", + ) + ops = p.add_subparsers(dest="exceptions_command", required=True) + + s = ops.add_parser( + "serve", + allow_abbrev=False, + help="Serve the raise_exception MCP tool over stdio", + ) + s.add_argument("--run-ref", help="this run's folder name (default: a new one)") + s.add_argument("--task-id", help="the task the cards belong to") + s.add_argument( + "--deadline-s", + type=float, + default=None, + help="how long a card waits for a person (default 900)", + ) + _roster(s) + _common(s) + s.set_defaults(func=cmd_serve) + + ls = ops.add_parser("list", allow_abbrev=False, help="Show cards waiting for a person") + ls.add_argument("--run-ref", help="only this run's cards") + ls.add_argument("--json", action="store_true", help="print JSON") + _common(ls) + ls.set_defaults(func=cmd_list) + + a = ops.add_parser( + "answer", + allow_abbrev=False, + help="Answer a card, signed with your approver key", + ) + a.add_argument("card_id", metavar="CARD_ID") + a.add_argument( + "choice", + metavar="CHOICE", + choices=["continue", "skip", "decline", "done_by_person", "abort"], + ) + a.add_argument("--key", help=f"the encrypted approver key (default: {KEY_DEFAULT})") + a.add_argument("--json", action="store_true", help="print JSON") + _roster(a) + _common(a) + a.set_defaults(func=cmd_answer) + + +def _registry(args: argparse.Namespace): + from openadapt_flow.exceptions.registry import ExceptionRegistry + + return ExceptionRegistry(args.registry) + + +def _pin(args: argparse.Namespace) -> tuple[Path, Optional[str]]: + from openadapt_flow.approval_mode.approver_roster import RosterError, pinned_root + from openadapt_flow.jit.lifecycle import default_key_dir + + try: + root = pinned_root(args.approver_root) + except RosterError as exc: + raise SystemExit(f"REFUSED ({exc.code}): {exc}. Nothing changed.") from None + return (Path(args.key_dir) if args.key_dir else default_key_dir()), root + + +def cmd_serve(args: argparse.Namespace) -> int: + from openadapt_flow.exceptions.mcp_server import RaiseException, serve + from openadapt_flow.exceptions.registry import DEFAULT_DEADLINE_S, roster_verifier + + key_dir, root = _pin(args) + run_ref = args.run_ref or f"mcp-{uuid.uuid4().hex[:16]}" + registry = _registry(args) + registry.run_dir(run_ref) # refuse a bad name before serving + print( + f"exceptions: serving raise_exception for run {run_ref}; " + f"cards in {registry.root / run_ref}", + file=sys.stderr, + ) + serve( + RaiseException( + registry, + run_ref=run_ref, + verify=roster_verifier(key_dir, root), + task_id=args.task_id, + deadline_s=args.deadline_s or DEFAULT_DEADLINE_S, + ) + ) + return 0 + + +def cmd_list(args: argparse.Namespace) -> int: + from openadapt_flow.exceptions.registry import ExceptionRegistryError + + try: + cards = _registry(args).open_cards(args.run_ref) + except ExceptionRegistryError as exc: + print(f"REFUSED ({exc.code}): {exc}", file=sys.stderr) + return 2 + if args.json: + print(json.dumps({"cards": [c.wire() for c in cards]}, indent=2)) + return 0 + if not cards: + print("Nothing is waiting for a person.") + return 0 + for card in cards: + print(f"{card.card_id} {card.kind} run {card.run_ref} until {card.deadline_at}") + print(f" {card.summary}") + for choice in card.choices: + print(f" - {choice.id}: {choice.label}. {choice.consequence}") + return 0 + + +def cmd_answer(args: argparse.Namespace) -> int: + from openadapt_types.exception_card import ExceptionAnswerV1, answer_message + + from openadapt_flow.execute.keys import sign_bytes + from openadapt_flow.exceptions.registry import ( + ExceptionRegistryError, + parse_time, + roster_verifier, + ) + from openadapt_flow.jit.authority import AuthorityError, load_encrypted_key, public_hex + + def refuse(code: str, message: str) -> int: + if args.json: + print(json.dumps({"ok": False, "code": code, "error": message})) + else: + print(f"REFUSED ({code}): {message} Nothing changed.", file=sys.stderr) + return 2 + + registry = _registry(args) + card_id = args.card_id if args.card_id.startswith("sha256:") else f"sha256:{args.card_id}" + try: + found = registry.card(card_id) + except ExceptionRegistryError as exc: + return refuse(exc.code, str(exc)) + if found is None: + return refuse("card_not_found", "No card has that id.") + _run_ref, card = found + try: + unsigned = registry.unsigned_answer(card, args.choice, route="cli") + except ExceptionRegistryError as exc: + return refuse(exc.code, str(exc)) + if parse_time(unsigned["decided_at"]) > parse_time(card.deadline_at): + return refuse("card_expired", "The card expired.") + key_dir, root = _pin(args) + try: + key = load_encrypted_key(args.key or KEY_DEFAULT) + except (AuthorityError, OSError, ValueError) as exc: + return refuse("approver_key_unusable", str(exc)) + signed = { + **unsigned, + "public_key": public_hex(key), + "signature": sign_bytes(key, answer_message(unsigned)), + } + del key + answer = ExceptionAnswerV1.model_validate(signed) + refusal = roster_verifier(key_dir, root)(answer) + if refusal is not None: + return refuse(refusal, "The waiting run wouldn't accept this key's answer.") + try: + registry.write_answer(card, answer.wire()) + except ExceptionRegistryError as exc: + return refuse(exc.code, str(exc)) + if args.json: + print(json.dumps({"ok": True, "answer": answer.wire()})) + else: + print(f"Answered {card.card_id}: {args.choice}.") + return 0 + + +__all__ = ["register"] diff --git a/packages/flow/openadapt_flow/exceptions/detectors.py b/packages/flow/openadapt_flow/exceptions/detectors.py new file mode 100644 index 0000000000..0e7c868285 --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/detectors.py @@ -0,0 +1,498 @@ +"""Detectors: should this run stop and ask a person? + +Pure functions over what an agent can already see: the screen's text, an +accessibility snapshot, a DOM snapshot when there is one, and timing. Each +detector returns an exception kind (``openadapt_types.exception_card``) or +``None``. Nothing here reads an app, names an app, or drives anything; a +caller (a guard, a harness, the agent itself through ``raise_exception``) +decides what to do with the kind. + +The signals are general: + +* ``second_factor``: an input marked ``autocomplete=one-time-code``, or a + short numeric input labelled with a word like *code* or *verification*. +* ``session_expired``: a password field after the run has reached a screen + where it could save (the caller says when that happened). +* ``unexpected_dialog``: a modal on top of the page, covering the target. +* ``timeout_or_stall``: no action and no screen change for N seconds. +* ``possible_duplicate``: a row already read from the app matches the + proposed record on every field of ``record.duplicate_key`` (verify.yaml). + +Uncertain means ask, not go on. A detector that can't tell (a modal with no +geometry, a duplicate read that failed, a stall clock with no last event) +returns its kind. + +Elements are plain dicts, so any snapshot can be mapped to them: +``tag``, ``type``, ``role``, ``name``, ``id``, ``label``, ``placeholder``, +``autocomplete``, ``inputmode``, ``pattern``, ``maxlength``, ``context`` +(text just before the element), ``visible`` (default true), ``modal``, +``bbox`` (``[x, y, width, height]``) and ``z``. :func:`elements_from_html` +and :func:`elements_from_accessibility` build them. +""" + +from __future__ import annotations + +import re +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from html.parser import HTMLParser +from typing import Any, Optional + +Element = Mapping[str, Any] + +#: Words that make a short input a second-factor code (any language a deployer +#: adds goes in ``code_words``; these are the defaults). +CODE_WORDS = ( + "code", + "verification", + "verify", + "passcode", + "one-time", + "one time", + "otp", + "2fa", + "two-factor", + "two factor", + "authenticator", + "security key", +) +#: Screen text that says a code was sent, whatever the field looks like. +CODE_PHRASES = ( + "verification code", + "one-time code", + "one-time password", + "enter the code", + "two-factor", + "authentication code", + "security code", +) +SESSION_PHRASES = ( + "session expired", + "session has expired", + "signed out", + "sign in again", + "log in again", + "please log in", + "please sign in", +) +DIALOG_ROLES = frozenset({"dialog", "alertdialog"}) +_TEXT_INPUT_TYPES = frozenset({"", "text", "tel", "number", "search"}) +_VOID = frozenset( + {"input", "br", "img", "meta", "link", "hr", "area", "base", "col", "embed", "source", "wbr"} +) +DEFAULT_STALL_S = 120.0 + + +def _s(value: Any) -> str: + return " ".join(str(value or "").split()).casefold() + + +def _visible(element: Element) -> bool: + return element.get("visible", True) is not False + + +def _words(element: Element) -> str: + return " ".join( + _s(element.get(key)) + for key in ("label", "name", "id", "placeholder", "context", "aria_label") + ) + + +def _is_input(element: Element) -> bool: + tag = _s(element.get("tag")) + role = _s(element.get("role")) + return tag in {"input", "textarea"} or role in {"textbox", "spinbutton"} + + +def _is_password(element: Element) -> bool: + role = _s(element.get("role")) + return ( + (_s(element.get("tag")) == "input" and _s(element.get("type")) == "password") + or role in {"password", "securetextfield", "axsecuretextfield", "password text"} + or element.get("protected") is True + ) + + +def _short_numeric(element: Element) -> bool: + if _s(element.get("type")) not in _TEXT_INPUT_TYPES: + return False + inputmode = _s(element.get("inputmode")) + pattern = str(element.get("pattern") or "") + try: + maxlength = int(element.get("maxlength") or 0) + except (TypeError, ValueError): + maxlength = 0 + numeric = ( + inputmode == "numeric" + or _s(element.get("type")) in {"number", "tel"} + or bool(re.search(r"\\d|\[0-9\]", pattern)) + ) + short = 3 <= maxlength <= 10 + return numeric or short + + +# -- detectors ----------------------------------------------------------------- + + +def second_factor( + elements: Sequence[Element] = (), + screen_text: str = "", + *, + code_words: Iterable[str] = CODE_WORDS, +) -> Optional[str]: + """``second_factor`` when the screen asks for a one-time code.""" + + words = tuple(_s(w) for w in code_words) + inputs = [e for e in elements if _visible(e) and _is_input(e)] + for element in inputs: + if _s(element.get("autocomplete")) == "one-time-code": + return "second_factor" + if _short_numeric(element) and any(w in _words(element) for w in words): + return "second_factor" + text = _s(screen_text) + if any(phrase in text for phrase in CODE_PHRASES): + # The screen says a code is wanted. A visible text input, or no + # structure to look at, is enough: uncertain means ask. + if not elements or any(not _is_password(e) for e in inputs): + return "second_factor" + return None + + +def session_expired( + elements: Sequence[Element] = (), + screen_text: str = "", + *, + save_eligible_seen: bool, +) -> Optional[str]: + """``session_expired`` when a sign-in appears after a save-eligible screen. + + Before the run reached a screen where it could save, a password field is + the ordinary start of a task, not an exception. + """ + + if not save_eligible_seen: + return None + if any(_visible(e) and _is_password(e) for e in elements): + return "session_expired" + text = _s(screen_text) + if any(phrase in text for phrase in SESSION_PHRASES): + return "session_expired" + return None + + +def _covers(outer: Sequence[float], inner: Sequence[float]) -> bool: + ox, oy, ow, oh = (float(v) for v in outer) + ix, iy, iw, ih = (float(v) for v in inner) + cx, cy = ix + iw / 2, iy + ih / 2 + return ox <= cx <= ox + ow and oy <= cy <= oy + oh + + +def _bbox(element: Element) -> Optional[Sequence[float]]: + box = element.get("bbox") + if isinstance(box, (list, tuple)) and len(box) == 4: + try: + values = [float(v) for v in box] + except (TypeError, ValueError): + return None + if values[2] > 0 and values[3] > 0: + return values + return None + + +def unexpected_dialog( + elements: Sequence[Element] = (), + *, + target: Optional[Element] = None, + expected_dialog: bool = False, +) -> Optional[str]: + """``unexpected_dialog`` when a modal sits on top of the target. + + A modal (``aria-modal``, an open ````, a ``dialog`` or + ``alertdialog`` role) blocks the page. With geometry for both, a modal + that doesn't cover the target's centre is not in the way. Without + geometry the detector can't tell, so it asks. ``expected_dialog`` is the + caller saying this step opens one (a confirm box it means to answer). + """ + + if expected_dialog: + return None + dialogs = [ + e + for e in elements + if _visible(e) + and ( + e.get("modal") is True + or _s(e.get("role")) in DIALOG_ROLES + or (_s(e.get("tag")) == "dialog" and e.get("open") is True) + ) + ] + if not dialogs: + return None + target_box = _bbox(target) if target is not None else None + target_z = float((target or {}).get("z") or 0) + for dialog in dialogs: + if dialog.get("modal") is True: + return "unexpected_dialog" # a modal blocks everything under it + box = _bbox(dialog) + if box is None or target_box is None: + return "unexpected_dialog" + if _covers(box, target_box) and float(dialog.get("z") or 0) >= target_z: + return "unexpected_dialog" + return None + + +def timeout_or_stall( + *, + now: float, + last_action_at: Optional[float], + last_change_at: Optional[float], + stall_s: float = DEFAULT_STALL_S, +) -> Optional[str]: + """``timeout_or_stall`` when neither an action nor a screen change happened + for ``stall_s`` seconds. A clock with no last event can't show progress.""" + + events = [t for t in (last_action_at, last_change_at) if t is not None] + if not events: + return "timeout_or_stall" + if now - max(events) >= stall_s: + return "timeout_or_stall" + return None + + +def _key_fields(duplicate_key: Any) -> Optional[list[str]]: + if duplicate_key is None: + return None + if isinstance(duplicate_key, str): + return [duplicate_key] if duplicate_key.strip() else [] + if isinstance(duplicate_key, (list, tuple)): + return [str(name) for name in duplicate_key] + return [] # a key spec of another shape can't be checked + + +def duplicate_key_from_config(config: Mapping[str, Any]) -> Any: + """``record.duplicate_key`` from a loaded verify.yaml, or ``None``.""" + + record = config.get("record") if isinstance(config, Mapping) else None + return record.get("duplicate_key") if isinstance(record, Mapping) else None + + +def possible_duplicate( + duplicate_key: Any, + proposed: Mapping[str, Any], + existing: Optional[Sequence[Mapping[str, Any]]], +) -> Optional[str]: + """``possible_duplicate`` when a row already in the app has the same key. + + ``duplicate_key`` is ``record.duplicate_key`` (one field or a list). + ``existing`` is what the caller already read (``None`` when the read + failed). This function reads nothing. A key with no fields, a proposed + record without a key value, a failed read, or a row missing a key field + can't rule a duplicate out, so it asks. + """ + + fields = _key_fields(duplicate_key) + if fields is None: + return None + if not fields or existing is None: + return "possible_duplicate" + wanted = {} + for name in fields: + value = _s(proposed.get(name)) + if not value: + return "possible_duplicate" + wanted[name] = value + for row in existing: + if not isinstance(row, Mapping): + return "possible_duplicate" + if any(name not in row for name in fields): + return "possible_duplicate" + if all(_s(row.get(name)) == wanted[name] for name in fields): + return "possible_duplicate" + return None + + +# -- all of them ----------------------------------------------------------------- + + +@dataclass(frozen=True) +class Observation: + """One look at the run: what's on screen, and when things last happened.""" + + screen_text: str = "" + elements: Sequence[Element] = () + target: Optional[Element] = None + save_eligible_seen: bool = False + expected_dialog: bool = False + #: Seconds on one clock. ``now`` None means "don't check for a stall". + now: Optional[float] = None + last_action_at: Optional[float] = None + last_change_at: Optional[float] = None + stall_s: float = DEFAULT_STALL_S + #: The duplicate check, when the caller has one: key spec, the proposed + #: record, and the rows it read (None when the read failed). + duplicate_key: Any = None + proposed: Mapping[str, Any] = field(default_factory=dict) + existing: Optional[Sequence[Mapping[str, Any]]] = () + + +def detect_all(observation: Observation) -> list[str]: + """Every kind the observation shows, most urgent first.""" + + found: list[str] = [] + o = observation + for kind in ( + second_factor(o.elements, o.screen_text), + session_expired(o.elements, o.screen_text, save_eligible_seen=o.save_eligible_seen), + unexpected_dialog(o.elements, target=o.target, expected_dialog=o.expected_dialog), + None + if o.now is None + else timeout_or_stall( + now=o.now, + last_action_at=o.last_action_at, + last_change_at=o.last_change_at, + stall_s=o.stall_s, + ), + possible_duplicate(o.duplicate_key, o.proposed, o.existing) + if o.duplicate_key is not None + else None, + ): + if kind is not None and kind not in found: + found.append(kind) + return found + + +def detect(observation: Observation) -> Optional[str]: + """The most urgent kind, or ``None`` when nothing calls for a person.""" + + found = detect_all(observation) + return found[0] if found else None + + +# -- snapshots --------------------------------------------------------------------- + + +class _Snapshot(HTMLParser): + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.elements: list[dict[str, Any]] = [] + self.labels: dict[str, str] = {} + self._label_for: Optional[str] = None + self._label_text: list[str] = [] + self._hidden: list[bool] = [] + self._text: list[str] = [] + + def _hidden_now(self) -> bool: + return any(self._hidden) + + def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None: + a = {k.lower(): (v if v is not None else "") for k, v in attrs} + style = _s(a.get("style")).replace(" ", "") + hidden = ( + "hidden" in a + or a.get("aria-hidden") == "true" + or "display:none" in style + or "visibility:hidden" in style + ) + visible = not (hidden or self._hidden_now()) + if tag == "label": + self._label_for = a.get("for") or "" + self._label_text = [] + role = a.get("role", "") + if tag in {"input", "textarea", "select", "button", "dialog"} or role: + context = " ".join(self._text)[-160:] + element = { + "tag": tag, + "type": a.get("type", "text" if tag == "input" else ""), + "role": role, + "id": a.get("id", ""), + "name": a.get("name", ""), + "placeholder": a.get("placeholder", ""), + "autocomplete": a.get("autocomplete", ""), + "inputmode": a.get("inputmode", ""), + "pattern": a.get("pattern", ""), + "maxlength": a.get("maxlength", ""), + "aria_label": a.get("aria-label", ""), + "context": context, + "visible": visible and a.get("type") != "hidden", + "modal": a.get("aria-modal") == "true", + "open": "open" in a, + } + self.elements.append(element) + if tag not in _VOID: + self._hidden.append(hidden) + + def handle_endtag(self, tag: str) -> None: + if tag == "label" and self._label_for is not None: + if self._label_for: + self.labels[self._label_for] = " ".join(self._label_text) + self._label_for = None + if tag not in _VOID and self._hidden: + self._hidden.pop() + + def handle_data(self, data: str) -> None: + text = " ".join(data.split()) + if not text: + return + if self._label_for is not None: + self._label_text.append(text) + if not self._hidden_now(): + self._text.append(text) + + +def elements_from_html(html: str) -> tuple[list[dict[str, Any]], str]: + """A DOM snapshot's elements and its visible text, from HTML. + + No geometry: an HTML string has none, so a non-modal dialog found this + way counts as covering the target (uncertain means ask). + """ + + parser = _Snapshot() + parser.feed(html) + parser.close() + for element in parser.elements: + element["label"] = parser.labels.get(str(element.get("id") or ""), "") + return parser.elements, " ".join(parser._text) + + +def elements_from_accessibility(nodes: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]: + """Accessibility nodes (``role``, ``name``, optional ``bbox``, ``modal``, + ``protected``, ``autocomplete``) as detector elements.""" + + out = [] + for node in nodes: + role = _s(node.get("role")) + out.append( + { + "tag": "input" if role in {"textbox", "textfield", "axtextfield"} else "", + "type": "password" if node.get("protected") is True else "text", + "role": "textbox" if role in {"textfield", "axtextfield"} else role, + "name": node.get("name", ""), + "label": node.get("name", ""), + "autocomplete": node.get("autocomplete", ""), + "maxlength": node.get("maxlength", ""), + "inputmode": node.get("inputmode", ""), + "visible": node.get("visible", True), + "modal": node.get("modal") is True, + "bbox": node.get("bbox"), + "z": node.get("z", 0), + "protected": node.get("protected") is True, + } + ) + return out + + +__all__ = [ + "CODE_WORDS", + "DEFAULT_STALL_S", + "Observation", + "detect", + "detect_all", + "duplicate_key_from_config", + "elements_from_accessibility", + "elements_from_html", + "possible_duplicate", + "second_factor", + "session_expired", + "timeout_or_stall", + "unexpected_dialog", +] diff --git a/packages/flow/openadapt_flow/exceptions/mcp_server.py b/packages/flow/openadapt_flow/exceptions/mcp_server.py new file mode 100644 index 0000000000..a94f512447 --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/mcp_server.py @@ -0,0 +1,213 @@ +"""``openadapt-flow exceptions serve``: one MCP tool any agent can call. + +``raise_exception(kind, summary, screenshot_path?)`` opens a card in the +local registry (:mod:`openadapt_flow.exceptions.registry`), blocks until a +person answers it or it expires, and returns the closed answer: + + {"card_id": "sha256:…", "kind": "second_factor", "answer": "done_by_person", + "proceed": true, "reason": null, "opened_at": "…", "decided_at": "…", + "instruction": "A person answered done_by_person. Go on from the current screen."} + +``proceed`` is true only for a signed ``continue`` or ``done_by_person``. +Anything else tells the agent to stop before any write. The tool can tell an +agent to stop; it can't make a foreign agent stop. Wrap the agent with a +guard for that. + +The server speaks MCP over stdio. Heartbeats go to stderr, never stdout. +""" + +from __future__ import annotations + +import functools +import json +from importlib import import_module +from typing import Any, Optional + +from openadapt_types.exception_card import EXCEPTION_KINDS + +from openadapt_flow.exceptions.registry import ( + DEFAULT_DEADLINE_S, + AnswerVerifier, + ExceptionRegistry, + ExceptionRegistryError, +) + +TOOL_NAME = "raise_exception" + +INPUT_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "kind": {"type": "string", "enum": list(EXCEPTION_KINDS)}, + "summary": { + "type": "string", + "minLength": 1, + "maxLength": 2000, + "description": ( + "What you see, in a sentence. It is scrubbed and cut to 200 " + "characters before a person sees it; never put a code, a " + "password or a record's values here." + ), + }, + "screenshot_path": { + "type": "string", + "maxLength": 4096, + "description": "A local PNG of the screen. Kept only as a scrubbed copy.", + }, + }, + "required": ["kind", "summary"], + "additionalProperties": False, +} + +DESCRIPTION = ( + "Ask a person, then wait for the answer. Call it when you hit a one-time " + "code prompt (second_factor), a dialog you didn't expect (unexpected_dialog), " + "a sign-in page partway through (session_expired), no progress " + "(timeout_or_stall), a record that may already exist (possible_duplicate), " + "two records you can't tell apart (ambiguous_record), or a task you can't " + "finish (cannot_complete). Never type a code or password yourself. Go on " + "only when the result says proceed=true; otherwise stop and write nothing." +) + + +class RaiseException: + """The tool's work, without the protocol (used by tests and the server).""" + + def __init__( + self, + registry: ExceptionRegistry, + *, + run_ref: str, + verify: AnswerVerifier, + task_id: Optional[str] = None, + deadline_s: float = DEFAULT_DEADLINE_S, + poll_s: float = 0.5, + ) -> None: + self.registry = registry + self.run_ref = run_ref + self.verify = verify + self.task_id = task_id + self.deadline_s = deadline_s + self.poll_s = poll_s + + def __call__( + self, kind: str, summary: str, screenshot_path: Optional[str] = None + ) -> dict[str, Any]: + card = self.registry.open( + self.run_ref, + kind, + summary, + task_id=self.task_id, + screenshot_path=screenshot_path, + deadline_s=self.deadline_s, + ) + return self.registry.wait(card, verify=self.verify, poll_s=self.poll_s).wire() + + +def _error(types: Any, error_field: str, code: str) -> Any: + body = {"error": code, "proceed": False, "instruction": "Stop now. Make no further writes for this task."} + return types.CallToolResult( + content=[types.TextContent(type="text", text=json.dumps(body))], + **{error_field: True}, + ) + + +def build_server(tool: RaiseException) -> Any: + """The MCP server (MCP 1 decorator API or MCP 2 callbacks).""" + + import anyio + from jsonschema import ValidationError, validate + from mcp.server.lowlevel import Server + + types: Any + try: + types = import_module("mcp.types") + except ModuleNotFoundError as error: + if error.name != "mcp.types": + raise + types = import_module("mcp_types") + modern = types.__name__ == "mcp_types" + input_schema_field = "input_schema" if modern else "inputSchema" + error_field = "is_error" if modern else "isError" + structured_field = "structured_content" if modern else "structuredContent" + + async def list_tools() -> list[Any]: + return [ + types.Tool( + name=TOOL_NAME, + description=DESCRIPTION, + **{input_schema_field: INPUT_SCHEMA}, + ) + ] + + async def call_tool(name: str, arguments: Optional[dict[str, Any]]) -> Any: + if name != TOOL_NAME: + return _error(types, error_field, "unknown_tool") + try: + validate(arguments, INPUT_SCHEMA) + except ValidationError: + return _error(types, error_field, "invalid_arguments") + assert arguments is not None + try: + result = await anyio.to_thread.run_sync( + functools.partial( + tool, + arguments["kind"], + arguments["summary"], + arguments.get("screenshot_path"), + ), + abandon_on_cancel=False, + ) + except ExceptionRegistryError as exc: + return _error(types, error_field, exc.code) + except Exception: # noqa: BLE001 - no raw exception text on the wire + return _error(types, error_field, "registry_unavailable") + return types.CallToolResult( + content=[types.TextContent(type="text", text=json.dumps(result))], + **{structured_field: result}, + ) + + instructions = ( + "One tool, raise_exception, asks a person and waits. Go on only when its " + "result has proceed=true. Never relay a code or a password through it." + ) + if hasattr(Server, "list_tools"): + server = Server("openadapt-exceptions", version="1", instructions=instructions) + server.list_tools()(list_tools) + server.call_tool(validate_input=False)(call_tool) + return server + + async def list_v2(context: Any, params: Any) -> Any: + return types.ListToolsResult(tools=await list_tools()) + + async def call_v2(context: Any, params: Any) -> Any: + return await call_tool(params.name, params.arguments) + + callback_server: Any = Server + return callback_server( + "openadapt-exceptions", + version="1", + instructions=instructions, + on_list_tools=list_v2, + on_call_tool=call_v2, + ) + + +def serve(tool: RaiseException) -> None: + """Serve over stdio, keeping every log line off the protocol.""" + + import anyio + from mcp.server.stdio import stdio_server + + from openadapt_flow.agent.mcp import _protected_stdout + + async def run() -> None: + server = build_server(tool) + with _protected_stdout() as wire: + kwargs = {"stdout": wire} if wire is not None else {} + async with stdio_server(**kwargs) as (reader, writer): + await server.run(reader, writer, server.create_initialization_options()) + + anyio.run(run) + + +__all__ = ["DESCRIPTION", "INPUT_SCHEMA", "TOOL_NAME", "RaiseException", "build_server", "serve"] diff --git a/packages/flow/openadapt_flow/exceptions/registry.py b/packages/flow/openadapt_flow/exceptions/registry.py new file mode 100644 index 0000000000..1ef21f9ad9 --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/registry.py @@ -0,0 +1,751 @@ +"""The local exception registry: one folder of small files per run. + +``$OPENADAPT_HOME/exceptions//`` (``~/.openadapt`` by default) +holds, for each card: + +- ``card-.json``: the :class:`~openadapt_types.exception_card.ExceptionCardV1` + the run opened, written by :meth:`ExceptionRegistry.open`; +- ``screenshot-.png``: the scrubbed copy the card names, when a + scrubber could redact it; +- ``answer-.json``: the one answer, written by a person's signed answer + (``openadapt-flow exceptions answer``, Desktop, the paired phone) or by the + registry itself when the card expires; +- ``consumed-.json``: written once by the waiting run when it acts on + the answer. An answer is never used twice. + +Files are created exclusively (a temporary file, then a hard link), owner +read and write only (0600), and never replaced. It mirrors the item-approval +folder (``approval_mode/item_approval.py``) without sharing its code. + +The run re-checks every answer itself (:meth:`ExceptionRegistry.wait`). +``continue`` and ``done_by_person`` let it go on only when the answer is +signed by a key on the pinned approver roster, names this exact card, is one +of the card's choices and was decided before the deadline. Everything else +(decline, skip, abort, expiry, an answer that can't be read, verified or +matched) means stop before any write. + +Nothing here is sent anywhere. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import stat +import sys +import time +import uuid +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any, Optional + +from openadapt_types.exception_card import ( + EXCEPTION_KINDS, + RUN_REF_PATTERN, + SUMMARY_MAX, + ExceptionAnswerV1, + ExceptionCardV1, + ExceptionChoice, + answer_message, + card_digest, +) + +#: How long a card waits for a person by default, and at most. +DEFAULT_DEADLINE_S = 15 * 60 +MAX_DEADLINE_S = 24 * 60 * 60 +HEARTBEAT_S = 30.0 +_MAX_FILE_BYTES = 256 * 1024 +_MAX_SCREENSHOT_BYTES = 8 * 1024 * 1024 +_PNG = b"\x89PNG\r\n\x1a\n" +_RUN_REF = re.compile(RUN_REF_PATTERN) +_HEX_ID = re.compile(r"^[0-9a-f]{64}$") + + +def _c(answer: str, label: str, consequence: str) -> ExceptionChoice: + return ExceptionChoice(id=answer, label=label, consequence=consequence) # type: ignore[arg-type] + + +_SKIP = _c("skip", "Skip this item", "Nothing is saved. The run moves to the next item.") +_ABORT = _c("abort", "Stop the run", "Nothing more is saved. The whole run stops.") + +#: Each kind's choices, in the order a card shows them. The first is the +#: usual answer; no card offers a choice that writes on its own. +CHOICES: dict[str, tuple[ExceptionChoice, ...]] = { + "second_factor": ( + _c( + "done_by_person", + "I entered the code in the browser", + "You type the code in the live browser yourself. The run then goes on " + "from the same screen. OpenAdapt never sees the code.", + ), + _SKIP, + _ABORT, + ), + "unexpected_dialog": ( + _c( + "done_by_person", + "I dealt with the dialog", + "You close or answer the dialog yourself. The run then goes on.", + ), + _c( + "continue", + "It's harmless, go on", + "The run goes on with the dialog as it is, and every check still runs.", + ), + _SKIP, + _ABORT, + ), + "session_expired": ( + _c( + "done_by_person", + "I signed in again", + "You sign in yourself in the live browser. The run then goes on. " + "OpenAdapt never sees the password.", + ), + _SKIP, + _ABORT, + ), + "timeout_or_stall": ( + _c( + "continue", + "Keep waiting", + "The run tries the step again, with every check.", + ), + _SKIP, + _ABORT, + ), + "possible_duplicate": ( + _c( + "skip", + "Same record: don't add it", + "Nothing is saved. The item closes as skipped.", + ), + _c( + "continue", + "Different record: go on", + "The run goes on to fill the form. The save still needs every check.", + ), + _c( + "done_by_person", + "I'll do this one by hand", + "Nothing is saved by OpenAdapt. The item closes as done by a person.", + ), + _ABORT, + ), + "ambiguous_record": ( + _c( + "done_by_person", + "I opened the right record", + "You open the right record yourself. The run then goes on from there.", + ), + _SKIP, + _c( + "decline", + "This item shouldn't be done", + "Nothing is saved. The item closes as declined.", + ), + ), + "cannot_complete": ( + _c( + "done_by_person", + "I did it by hand", + "Nothing is saved by OpenAdapt. The item closes as done by a person.", + ), + _SKIP, + _ABORT, + ), +} + +#: What a card says when the agent's own words can't be scrubbed first. +GENERIC_SUMMARIES: dict[str, str] = { + "second_factor": "The app is asking for a one-time code. Enter it in the browser.", + "unexpected_dialog": "A dialog the run didn't expect is covering the page.", + "session_expired": "The app is asking to sign in again partway through the task.", + "timeout_or_stall": "The run has made no progress for a while.", + "possible_duplicate": "The app may already have this record.", + "ambiguous_record": "The run can't tell which record is the right one.", + "cannot_complete": "The run can't finish this item on its own.", +} + +assert set(CHOICES) == set(EXCEPTION_KINDS) == set(GENERIC_SUMMARIES) + + +class ExceptionRegistryError(ValueError): + def __init__(self, code: str, message: str) -> None: + super().__init__(message) + self.code = code + + +# -- time and text --------------------------------------------------------------- + + +def _now() -> datetime: + return datetime.now(timezone.utc) + + +def iso(value: datetime) -> str: + return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +def parse_time(value: str) -> datetime: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + if parsed.tzinfo is None: + raise ValueError("no time zone") + return parsed.astimezone(timezone.utc) + + +_EMAIL = re.compile(r"[\w.+-]+@[\w-]+(\.[\w-]+)+") +_DATE = re.compile(r"\b\d{1,4}[-/.]\d{1,2}[-/.]\d{1,4}\b") +#: Any token holding four or more digits: record numbers, phone numbers, +#: account numbers, codes. +_DIGITS = re.compile(r"\S*(?:\d\S*){4,}") + + +def _pattern_scrub(text: str) -> str: + text = _EMAIL.sub("[email]", text) + text = _DATE.sub("[date]", text) + return _DIGITS.sub("[number]", text) + + +def scrub_summary(kind: str, text: Optional[str]) -> tuple[str, str]: + """``(summary, source)``: the agent's words scrubbed, or the kind's own. + + The summary can reach a paired phone, so this follows the outbound rule + (``openadapt_flow.privacy``): without a working scrubber the agent's text + is dropped and the card says the kind's generic sentence + (``source="generic"``). Digit runs, dates and email addresses are masked + on top of the scrubber either way. + """ + + from openadapt_flow import privacy + + generic = GENERIC_SUMMARIES[kind] + raw = " ".join(str(text or "").split()) + if not raw: + return generic, "generic" + scrubber = privacy.get_scrubber() + if scrubber is None: + return generic, "generic" + try: + scrubbed = scrubber.scrub_text(raw) + except Exception: # noqa: BLE001 - a broken provider scrubs nothing + return generic, "generic" + cleaned = " ".join(_pattern_scrub(str(scrubbed or "")).split()) + if not cleaned: + return generic, "generic" + if len(cleaned) > SUMMARY_MAX: + cleaned = cleaned[: SUMMARY_MAX - 1].rstrip() + "…" + return cleaned, "scrubbed" + + +# -- files ----------------------------------------------------------------------- + + +def _flags(base: int) -> int: + for name in ("O_NOFOLLOW", "O_CLOEXEC"): + base |= getattr(os, name, 0) + return base + + +def _read_regular(path: Path, *, limit: int = _MAX_FILE_BYTES) -> Optional[bytes]: + """The file's bytes, ``None`` when it doesn't exist. Raises ``OSError`` + for a link, a non-regular file or one over ``limit``.""" + + try: + fd = os.open(path, _flags(os.O_RDONLY)) + except FileNotFoundError: + return None + try: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + raise OSError("not a small regular file") + data = b"" + while len(data) <= limit: + chunk = os.read(fd, 65536) + if not chunk: + break + data += chunk + if len(data) > limit: + raise OSError("file too large") + return data + finally: + os.close(fd) + + +def _write_exclusive(path: Path, payload: bytes) -> None: + """Create ``path`` once, 0600. Raises ``FileExistsError`` if it's there.""" + + tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") + fd = os.open(tmp, _flags(os.O_WRONLY | os.O_CREAT | os.O_EXCL), 0o600) + try: + view = memoryview(payload) + while view: + view = view[os.write(fd, view) :] + os.fsync(fd) + finally: + os.close(fd) + try: + os.link(tmp, path) + finally: + try: + os.unlink(tmp) + except OSError: + pass + try: + dfd = os.open(path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + except OSError: + return + try: + os.fsync(dfd) + except OSError: + pass + finally: + os.close(dfd) + + +def _json(value: Mapping[str, Any]) -> bytes: + return (json.dumps(value, sort_keys=True, indent=2) + "\n").encode("utf-8") + + +def default_root() -> Path: + home = os.environ.get("OPENADAPT_HOME") + return (Path(home) if home else Path.home() / ".openadapt") / "exceptions" + + +def _hex(card_id: str) -> str: + value = card_id.removeprefix("sha256:") + if not _HEX_ID.fullmatch(value): + raise ExceptionRegistryError("card_id_invalid", "that isn't a card id") + return value + + +# -- outcome --------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Outcome: + """What the waiting run does now.""" + + card_id: str + kind: str + answer: str + #: True only for a verified ``continue`` or ``done_by_person``. + proceed: bool + #: Why the run stops when the answer alone doesn't say: ``expired``, or + #: a closed refusal code for an answer that couldn't be used. + reason: Optional[str] + opened_at: str + decided_at: Optional[str] + + def wire(self) -> dict[str, Any]: + return { + "card_id": self.card_id, + "kind": self.kind, + "answer": self.answer, + "proceed": self.proceed, + "reason": self.reason, + "opened_at": self.opened_at, + "decided_at": self.decided_at, + "instruction": ( + f"A person answered {self.answer}. Go on from the current screen." + if self.proceed + else "Stop now. Make no further writes for this task." + ), + } + + +#: ``verify(answer)`` returns ``None`` for a valid signature by a key on the +#: pinned approver roster, or a closed refusal code. +AnswerVerifier = Callable[[ExceptionAnswerV1], Optional[str]] + + +def roster_verifier(key_dir: Optional[Path], root: Optional[str]) -> AnswerVerifier: + """Check answers against Flow's signed approver roster (``jit approver``). + + Without a key directory or a pinned root no person's answer counts. + """ + + def verify(answer: ExceptionAnswerV1) -> Optional[str]: + from openadapt_flow.approval_mode.human_attestation import ( + AttestationRefused, + approvers, + ) + from openadapt_flow.execute.keys import verify_signature + from openadapt_flow.jit.authority import _public + + if key_dir is None: + return "human_answer_unverifiable" + try: + known = approvers(key_dir, root) + except AttestationRefused as exc: + return exc.code + if not answer.public_key or answer.public_key not in set(known.values()): + return "human_approver_unregistered" + try: + public = _public(answer.public_key) + except ValueError: + return "human_answer_signature_invalid" + if not verify_signature( + public, answer_message(answer.wire()), str(answer.signature or "") + ): + return "human_answer_signature_invalid" + return None + + return verify + + +def _stop(card: ExceptionCardV1, reason: str, answer: str = "decline") -> Outcome: + return Outcome(card.card_id, card.kind, answer, False, reason, card.opened_at, None) + + +# -- the registry ---------------------------------------------------------------- + + +class ExceptionRegistry: + """The exceptions folder: open cards, list them, answer them, wait.""" + + def __init__(self, root: Optional[Path | str] = None) -> None: + self.root = Path(root) if root is not None else default_root() + + def run_dir(self, run_ref: str) -> Path: + if not _RUN_REF.fullmatch(run_ref or ""): + raise ExceptionRegistryError( + "run_ref_invalid", "a run reference is letters, digits, '.', '_' or '-'" + ) + return self.root / run_ref + + def _ensure(self, path: Path) -> None: + for directory in (self.root, path): + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + info = os.lstat(directory) + if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode): + raise ExceptionRegistryError( + "registry_unsafe", f"{directory} isn't a plain folder" + ) + if hasattr(os, "getuid") and info.st_uid != os.getuid(): + raise ExceptionRegistryError( + "registry_unsafe", f"{directory} belongs to another user" + ) + + # -- opening ----------------------------------------------------------- + + def _copy_screenshot(self, folder: Path, source: Optional[str]) -> Optional[str]: + """A scrubbed copy of the agent's screenshot, or ``None``. + + The path is the agent's: only a regular PNG file under the size cap + is read, never through a link. Without a scrubber that can redact + it, no image is kept. + """ + + if not source: + return None + from openadapt_flow import privacy + + try: + data = _read_regular(Path(source), limit=_MAX_SCREENSHOT_BYTES) + except OSError: + return None + if not data or not data.startswith(_PNG): + return None + if privacy.get_scrubber() is None: + return None + try: + redacted = privacy.scrub_image_bytes(data, force=True) + except Exception: # noqa: BLE001 - no redaction, no image + return None + if not redacted.startswith(_PNG): + return None + name = f"screenshot-{hashlib.sha256(redacted).hexdigest()[:32]}.png" + try: + _write_exclusive(folder / name, redacted) + except FileExistsError: + pass + return name + + def open( + self, + run_ref: str, + kind: str, + summary: Optional[str], + *, + task_id: Optional[str] = None, + screenshot_path: Optional[str] = None, + deadline_s: float = DEFAULT_DEADLINE_S, + now: Optional[datetime] = None, + ) -> ExceptionCardV1: + """Write a new card and return it. Raises ``ExceptionRegistryError``.""" + + if kind not in CHOICES: + raise ExceptionRegistryError( + "kind_unknown", "kind is one of " + ", ".join(EXCEPTION_KINDS) + ) + folder = self.run_dir(run_ref) + self._ensure(folder) + opened = now or _now() + seconds = max(1.0, min(float(deadline_s), MAX_DEADLINE_S)) + text, _source = scrub_summary(kind, summary) + if task_id is not None: + task_id = _pattern_scrub(" ".join(str(task_id).split()))[:128] or None + body = { + "schema": "openadapt.exception-card/v1", + "run_ref": run_ref, + "task_id": task_id, + "kind": kind, + "opened_at": iso(opened), + "deadline_at": iso(opened + timedelta(seconds=seconds)), + "screenshot_ref": self._copy_screenshot(folder, screenshot_path), + "summary": text, + "choices": [c.model_dump(mode="json") for c in CHOICES[kind]], + } + for _attempt in range(3): + card = ExceptionCardV1.model_validate({**body, "card_id": card_digest(body)}) + try: + _write_exclusive(folder / f"card-{_hex(card.card_id)}.json", _json(card.wire())) + return card + except FileExistsError: + opened = opened + timedelta(microseconds=1) + body["opened_at"] = iso(opened) + body["deadline_at"] = iso(opened + timedelta(seconds=seconds)) + raise ExceptionRegistryError("card_exists", "could not open a new card") + + # -- reading ----------------------------------------------------------- + + def _load(self, path: Path, model: type) -> Any: + data = _read_regular(path) + if data is None: + return None + return model.model_validate(json.loads(data)) + + def card(self, card_id: str) -> Optional[tuple[str, ExceptionCardV1]]: + """``(run_ref, card)`` for an id, searching every run's folder.""" + + name = f"card-{_hex(card_id)}.json" + if not self.root.is_dir(): + return None + for folder in sorted(self.root.iterdir()): + if not _RUN_REF.fullmatch(folder.name) or not (folder / name).exists(): + continue + try: + card = self._load(folder / name, ExceptionCardV1) + except (OSError, ValueError): + return None + if card is not None and card.run_ref == folder.name: + return folder.name, card + return None + + def read_answer(self, card: ExceptionCardV1) -> Optional[ExceptionAnswerV1]: + """The card's answer, ``None`` if there isn't one. Raises on a bad file.""" + + return self._load( + self.run_dir(card.run_ref) / f"answer-{_hex(card.card_id)}.json", + ExceptionAnswerV1, + ) + + def open_cards(self, run_ref: Optional[str] = None) -> list[ExceptionCardV1]: + """Cards with no answer yet, oldest first. Unreadable files are skipped.""" + + if not self.root.is_dir(): + return [] + folders = [self.run_dir(run_ref)] if run_ref else sorted(self.root.iterdir()) + cards = [] + for folder in folders: + if not folder.is_dir() or not _RUN_REF.fullmatch(folder.name): + continue + for path in sorted(folder.glob("card-*.json")): + try: + card = self._load(path, ExceptionCardV1) + except (OSError, ValueError): + continue + if card is None or card.run_ref != folder.name: + continue + if path.name != f"card-{_hex(card.card_id)}.json": + continue + if (folder / f"answer-{_hex(card.card_id)}.json").exists(): + continue + cards.append(card) + return sorted(cards, key=lambda c: c.opened_at) + + # -- answering --------------------------------------------------------- + + def unsigned_answer( + self, card: ExceptionCardV1, answer: str, *, route: str, now: Optional[datetime] = None + ) -> dict[str, Any]: + """The answer a person's key signs (no key or signature yet).""" + + if not card.offers(answer): + raise ExceptionRegistryError( + "choice_not_offered", "that answer isn't one of the card's choices" + ) + return { + "schema": "openadapt.exception-answer/v1", + "card_id": card.card_id, + "kind": card.kind, + "opened_at": card.opened_at, + "decided_at": iso(now or _now()), + "answer": answer, + "approver_kind": "person", + "route": route, + "reason": None, + } + + def write_answer(self, card: ExceptionCardV1, answer: Mapping[str, Any]) -> ExceptionAnswerV1: + """Write the card's one answer. Raises ``ExceptionRegistryError``.""" + + model = ExceptionAnswerV1.model_validate(dict(answer)) + if model.card_id != card.card_id or model.kind != card.kind: + raise ExceptionRegistryError("answer_mismatch", "the answer names another card") + folder = self.run_dir(card.run_ref) + self._ensure(folder) + try: + _write_exclusive(folder / f"answer-{_hex(card.card_id)}.json", _json(model.wire())) + except FileExistsError: + raise ExceptionRegistryError( + "already_answered", "this card already has an answer" + ) from None + return model + + def _expire(self, card: ExceptionCardV1) -> None: + record = ExceptionAnswerV1.model_validate( + { + "schema": "openadapt.exception-answer/v1", + "card_id": card.card_id, + "kind": card.kind, + "opened_at": card.opened_at, + "decided_at": None, + "answer": "decline", + "approver_kind": "expiry", + "route": "registry", + "reason": "expired", + } + ) + _write_exclusive( + self.run_dir(card.run_ref) / f"answer-{_hex(card.card_id)}.json", + _json(record.wire()), + ) + + def _settle( + self, card: ExceptionCardV1, answer: ExceptionAnswerV1, verify: AnswerVerifier + ) -> Outcome: + if answer.card_id != card.card_id or answer.kind != card.kind: + return _stop(card, "answer_mismatch") + if answer.opened_at != card.opened_at: + return _stop(card, "answer_mismatch") + if answer.approver_kind == "expiry": + outcome = _stop(card, "expired") + else: + if not card.offers(answer.answer): + return _stop(card, "choice_not_offered") + try: + decided = parse_time(str(answer.decided_at)) + except ValueError: + return _stop(card, "answer_time_invalid") + if decided < parse_time(card.opened_at): + return _stop(card, "answer_time_invalid") + if decided > parse_time(card.deadline_at): + return _stop(card, "answer_late") + refusal = verify(answer) + if refusal is not None: + return _stop(card, refusal) + outcome = Outcome( + card.card_id, + card.kind, + answer.answer, + answer.proceeds, + None, + card.opened_at, + answer.decided_at, + ) + consumed = { + "card_id": card.card_id, + "answer": outcome.answer, + "proceed": outcome.proceed, + "reason": outcome.reason, + "consumed_at": iso(_now()), + } + try: + _write_exclusive( + self.run_dir(card.run_ref) / f"consumed-{_hex(card.card_id)}.json", + _json(consumed), + ) + except FileExistsError: + return _stop(card, "answer_already_used", outcome.answer) + return outcome + + def wait( + self, + card: ExceptionCardV1, + *, + verify: AnswerVerifier, + deadline: Optional[datetime] = None, + poll_s: float = 0.5, + heartbeat_s: float = HEARTBEAT_S, + heartbeat: Optional[Callable[[str, float], None]] = None, + clock: Callable[[], datetime] = _now, + sleep: Callable[[float], None] = time.sleep, + ) -> Outcome: + """Block until the card is answered or expires; return what to do. + + ``deadline`` (default the card's ``deadline_at``) can only shorten the + wait. On expiry the registry writes an ``answer=decline``, + ``decided_at=null``, ``reason=expired`` record, unless a person's + answer got there first, which is then checked like any other. + ``heartbeat(card_id, seconds_left)`` is called every ``heartbeat_s`` + (default: a line on stderr, never stdout). + """ + + end = parse_time(card.deadline_at) + if deadline is not None: + end = min(end, deadline.astimezone(timezone.utc)) + beat = heartbeat or _stderr_heartbeat + next_beat = 0.0 + started = time.monotonic() + while True: + try: + answer = self.read_answer(card) + except (OSError, ValueError): + return _stop(card, "answer_unreadable") + if answer is not None: + return self._settle(card, answer, verify) + now = clock() + if now >= end: + try: + self._expire(card) + except FileExistsError: + continue # a person's answer won the race: read it + except OSError: + return _stop(card, "expired") + continue + elapsed = time.monotonic() - started + if elapsed >= next_beat: + beat(card.card_id, (end - now).total_seconds()) + next_beat = elapsed + heartbeat_s + sleep(poll_s) + + +def _stderr_heartbeat(card_id: str, seconds_left: float) -> None: + print( + f"exceptions: waiting for a person on {card_id[:19]}… " + f"({int(seconds_left)} s left)", + file=sys.stderr, + flush=True, + ) + + +__all__ = [ + "CHOICES", + "DEFAULT_DEADLINE_S", + "GENERIC_SUMMARIES", + "AnswerVerifier", + "ExceptionRegistry", + "ExceptionRegistryError", + "Outcome", + "default_root", + "iso", + "parse_time", + "roster_verifier", + "scrub_summary", +] diff --git a/packages/flow/tests/e2e/test_exception_mcp_e2e.py b/packages/flow/tests/e2e/test_exception_mcp_e2e.py new file mode 100644 index 0000000000..737dcbc912 --- /dev/null +++ b/packages/flow/tests/e2e/test_exception_mcp_e2e.py @@ -0,0 +1,371 @@ +"""End to end: a scripted agent hits a code prompt, asks through MCP, a +person answers, and the agent goes on or stops. + +The app is a synthetic two-step site on 127.0.0.1: a one-time-code page +until the session is verified, then a form whose saves the app keeps in +memory (read back from ``/api/records``). The "agent" is a script that reads +each page as HTML, runs the exception detectors on it, and talks to +``openadapt-flow exceptions serve`` over real MCP stdio in a subprocess. The +"person" types the code into the app directly (as in the live browser), +then answers with ``openadapt-flow exceptions answer`` in another +subprocess, signed with a synthetic approver key on a fresh roster. When the +monorepo's Desktop package is on disk, Desktop's stop queue is checked to +show the same card. + +Asserted: the agent writes once after ``done_by_person`` and zero times +after a decline or an expiry (read from the app's own state), both answer +timestamps are present, and no planted identifier is in the registry, the +MCP result or Desktop's card. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import threading +import time +import urllib.parse +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any, Callable + +import pytest + +pytest.importorskip("mcp") +import anyio # noqa: E402 +from cryptography.hazmat.primitives import serialization # noqa: E402 +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402 +from mcp import ClientSession, StdioServerParameters # noqa: E402 +from mcp.client.stdio import stdio_client # noqa: E402 + +from openadapt_flow.approval_mode.approver_roster import ( # noqa: E402 + ROOT_ENV, + file_key_signer, + init_root, +) +from openadapt_flow.exceptions.detectors import Observation, detect, elements_from_html # noqa: E402 +from openadapt_flow.jit.authority import public_hex # noqa: E402 + +PLANTED = ("Maribel Quintanilla", "1961-04-09", "88812345") +SUMMARY = "The sign-in for Maribel Quintanilla (1961-04-09, MRN 88812345) wants a code" +CODE = "482913" # synthetic; the person types it into the app, never through OpenAdapt +PASSPHRASE = "synthetic-e2e-passphrase" +REPO = Path(__file__).resolve().parents[4] +DESKTOP = REPO / "packages" / "desktop" + +CODE_PAGE = """

Check your phone

+
+ +
""" +FORM_PAGE = """

New note

+
+
""" + + +class SyntheticApp: + """A code gate, then a form. State lives here, read back by the test.""" + + def __init__(self) -> None: + self.verified = False + self.records: list[dict[str, str]] = [] + self.lock = threading.Lock() + + def handler(self) -> type[BaseHTTPRequestHandler]: + app = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_args: object) -> None: + return None + + def _send(self, status: int, body: str, kind: str = "text/html") -> None: + data = body.encode() + self.send_response(status) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def _form(self) -> dict[str, str]: + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length).decode() + return {k: v[0] for k, v in urllib.parse.parse_qs(raw).items()} + + def do_GET(self) -> None: # noqa: N802 + if self.path == "/api/records": + with app.lock: + self._send(200, json.dumps(app.records), "application/json") + return + self._send(200, FORM_PAGE if app.verified else CODE_PAGE) + + def do_POST(self) -> None: # noqa: N802 + form = self._form() + if self.path == "/verify": + app.verified = form.get("otc") == CODE + self._send(200, FORM_PAGE if app.verified else CODE_PAGE) + return + if self.path == "/save" and app.verified: + with app.lock: + app.records.append({"note": form.get("note", "")}) + self._send(200, "

Saved

") + return + self._send(403, "

Not signed in

") + + return Handler + + +@pytest.fixture +def app(): + state = SyntheticApp() + server = ThreadingHTTPServer(("127.0.0.1", 0), state.handler()) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_address[1]}", state + server.shutdown() + server.server_close() + + +@pytest.fixture +def env(tmp_path: Path) -> dict[str, str]: + """A fresh OPENADAPT_HOME, roster and encrypted approver key.""" + + key_dir = tmp_path / "keys" + key = Ed25519PrivateKey.generate() + init_root(key_dir, principal="front-desk", public_key=public_hex(key), sign=file_key_signer(key)) + pem = tmp_path / "approver.pem" + pem.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.BestAvailableEncryption(PASSPHRASE.encode()), + ) + ) + pem.chmod(0o600) + home = tmp_path / "home" + home.mkdir() + out = { + k: v + for k, v in os.environ.items() + if k not in {ROOT_ENV, "OPENADAPT_JIT_KEY_DIR", "OPENADAPT_HOME"} + } + out.update( + { + "OPENADAPT_HOME": str(home), + "OPENADAPT_JIT_KEY_DIR": str(key_dir), + ROOT_ENV: public_hex(key), + "OPENADAPT_JIT_KEY_PASSPHRASE": PASSPHRASE, + "OPENADAPT_TEST_KEY_PEM": str(pem), + "HOME": str(tmp_path), + } + ) + return out + + +def _get(url: str) -> str: + with urllib.request.urlopen(url, timeout=10) as response: # noqa: S310 - 127.0.0.1 + return response.read().decode() + + +def _post(url: str, data: dict[str, str]) -> str: + body = urllib.parse.urlencode(data).encode() + with urllib.request.urlopen(url, data=body, timeout=10) as response: # noqa: S310 + return response.read().decode() + + +def _registry(env: dict[str, str]) -> Path: + return Path(env["OPENADAPT_HOME"]) / "exceptions" + + +def _wait_for_card(env: dict[str, str], timeout: float = 60) -> dict[str, Any]: + end = time.monotonic() + timeout + while time.monotonic() < end: + for path in _registry(env).rglob("card-*.json"): + answer = path.with_name(path.name.replace("card-", "answer-")) + if not answer.exists(): + return json.loads(path.read_text()) + time.sleep(0.2) + raise AssertionError("no card appeared") + + +def _desktop_cards(env: dict[str, str]) -> list[dict[str, Any]] | None: + """Desktop's stop queue for the registry, when Desktop's source is here.""" + + if not (DESKTOP / "openadapt_desktop" / "exception_queue.py").is_file(): + return None + if str(DESKTOP) not in sys.path: + sys.path.insert(0, str(DESKTOP)) + from openadapt_desktop import exception_queue, stop_queue + + cards = [stop_queue.card_for_exception(raw) for raw in exception_queue.open_cards(_registry(env))] + return [c for c in cards if c is not None] + + +def _answer(env: dict[str, str], card_id: str, choice: str) -> subprocess.CompletedProcess: + return subprocess.run( + [ + sys.executable, "-m", "openadapt_flow", "exceptions", "answer", card_id, choice, + "--key", env["OPENADAPT_TEST_KEY_PEM"], "--json", + ], + env=env, + capture_output=True, + text=True, + timeout=120, + ) + + +async def _agent(base: str, env: dict[str, str], deadline_s: float) -> dict[str, Any]: + """The scripted agent: look, ask when a detector fires, write only if told.""" + + params = StdioServerParameters( + command=sys.executable, + args=[ + "-m", "openadapt_flow", "exceptions", "serve", + "--run-ref", "e2e-run", "--task-id", "note-intake", + "--deadline-s", str(deadline_s), + ], + env=env, + ) + log: dict[str, Any] = {"asked": [], "wrote": False} + async with stdio_client(params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + tools = await session.list_tools() + assert [t.name for t in tools.tools] == ["raise_exception"] + for _step in range(4): + page = await anyio.to_thread.run_sync(_get, base + "/") + elements, text = elements_from_html(page) + kind = detect(Observation(screen_text=text, elements=elements)) + if kind is not None: + result = await session.call_tool( + "raise_exception", {"kind": kind, "summary": SUMMARY} + ) + body = json.loads(result.content[0].text) + log["asked"].append(body) + if not body.get("proceed"): + return log # stop before any write + continue + if "Save" in page: + await anyio.to_thread.run_sync(_post, base + "/save", {"note": "synthetic note"}) + log["wrote"] = True + return log + return log + + +def _run_agent(base: str, env: dict[str, str], deadline_s: float, person: Callable[[], None]): + result: dict[str, Any] = {} + + def agent() -> None: + result.update(anyio.run(_agent, base, env, deadline_s)) + + thread = threading.Thread(target=agent) + thread.start() + person() + thread.join(timeout=180) + assert not thread.is_alive(), "the agent never finished" + return result + + +def _no_planted(*blobs: bytes) -> None: + for blob in blobs: + for planted in PLANTED: + assert planted.encode() not in blob + + +def _registry_bytes(env: dict[str, str]) -> bytes: + return b"".join(p.read_bytes() for p in _registry(env).rglob("*") if p.is_file()) + + +def test_done_by_person_after_a_code_prompt_lets_the_agent_save_once(app, env): + base, state = app + seen: dict[str, Any] = {} + + def person() -> None: + card = _wait_for_card(env) + seen["card"] = card + seen["desktop"] = _desktop_cards(env) + _post(base + "/verify", {"otc": CODE}) # typed in the live app by the person + done = _answer(env, card["card_id"], "done_by_person") + assert done.returncode == 0, done.stderr + + log = _run_agent(base, env, 120, person) + + assert seen["card"]["kind"] == "second_factor" + if seen["desktop"] is not None: + (desktop_card,) = seen["desktop"] + assert desktop_card["exception_kind"] == "second_factor" + assert desktop_card["source"]["id"] == seen["card"]["card_id"] + assert [c["id"] for c in desktop_card["choices"]] == ["done_by_person", "skip", "abort", "leave"] + _no_planted(json.dumps(desktop_card).encode()) + (asked,) = log["asked"] + assert asked["answer"] == "done_by_person" and asked["proceed"] is True + assert asked["opened_at"] and asked["decided_at"] + assert log["wrote"] is True + assert json.loads(_get(base + "/api/records")) == [{"note": "synthetic note"}] + answer = json.loads(next(_registry(env).rglob("answer-*.json")).read_text()) + assert answer["opened_at"] and answer["decided_at"] + _no_planted(_registry_bytes(env), json.dumps(log).encode()) + assert CODE.encode() not in _registry_bytes(env) + + +@pytest.mark.parametrize("choice", ["abort", "skip"]) +def test_a_stop_answer_means_no_write(app, env, choice): + base, state = app + + def person() -> None: + card = _wait_for_card(env) + done = _answer(env, card["card_id"], choice) + assert done.returncode == 0, done.stderr + + log = _run_agent(base, env, 120, person) + + (asked,) = log["asked"] + assert asked["proceed"] is False and asked["answer"] == choice + assert asked["opened_at"] and asked["decided_at"] + assert log["wrote"] is False + assert json.loads(_get(base + "/api/records")) == [] + _no_planted(_registry_bytes(env), json.dumps(log).encode()) + + +def test_an_expired_card_is_a_decline_and_no_write(app, env): + base, state = app + + def person() -> None: + _wait_for_card(env) # nobody answers + + log = _run_agent(base, env, 2, person) + + (asked,) = log["asked"] + assert asked["proceed"] is False + assert asked["answer"] == "decline" and asked["reason"] == "expired" + assert asked["opened_at"] and asked["decided_at"] is None + assert log["wrote"] is False + assert json.loads(_get(base + "/api/records")) == [] + record = json.loads(next(_registry(env).rglob("answer-*.json")).read_text()) + assert record["approver_kind"] == "expiry" and record["decided_at"] is None + + +def test_an_answer_from_a_key_off_the_roster_is_refused_and_nothing_is_written(app, env, tmp_path): + base, state = app + stranger = tmp_path / "stranger.pem" + stranger.write_bytes( + Ed25519PrivateKey.generate().private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.BestAvailableEncryption(PASSPHRASE.encode()), + ) + ) + + def person() -> None: + card = _wait_for_card(env) + forged = _answer({**env, "OPENADAPT_TEST_KEY_PEM": str(stranger)}, card["card_id"], "done_by_person") + assert forged.returncode == 2 + assert "human_approver_unregistered" in forged.stdout + # nobody else answers: the card expires + + log = _run_agent(base, env, 3, person) + (asked,) = log["asked"] + assert asked["proceed"] is False + assert json.loads(_get(base + "/api/records")) == [] + diff --git a/packages/flow/tests/fixtures/exception_card_second_factor.json b/packages/flow/tests/fixtures/exception_card_second_factor.json new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/packages/flow/tests/fixtures/exception_card_second_factor.json @@ -0,0 +1 @@ +{} diff --git a/packages/flow/tests/test_exception_detectors.py b/packages/flow/tests/test_exception_detectors.py new file mode 100644 index 0000000000..88b24f8fec --- /dev/null +++ b/packages/flow/tests/test_exception_detectors.py @@ -0,0 +1,203 @@ +"""Exception detectors on synthetic pages: a code prompt, a mid-task sign-in, +a modal, a stall and a duplicate, plus the weak signal for each (it must +still ask) and ordinary pages (they must not).""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from openadapt_flow.exceptions import detectors as d +from openadapt_flow.exceptions.detectors import Observation, detect, elements_from_html + +FORM = """

New entry

+ + +
""" + +OTP_MARKED = """

Check your phone

+ + +
""" + +OTP_WEAK = """

We sent you a message.

+ +
""" + +OTP_TEXT_ONLY = "

Enter the code we sent to your phone.

" + +SIGN_IN = """

Sign in

+ + +
""" + +MODAL = """""" + FORM + """ +

Your changes may be lost.

+""" + +HIDDEN_MODAL = """""" + FORM + """ +""" + + +def _obs(html: str, **fields) -> Observation: + elements, text = elements_from_html(html) + return Observation(screen_text=text, elements=elements, **fields) + + +# -- second factor ------------------------------------------------------------------ + + +@pytest.mark.parametrize("page", [OTP_MARKED, OTP_WEAK, OTP_TEXT_ONLY]) +def test_a_code_prompt_is_a_second_factor(page): + assert detect(_obs(page)) == "second_factor" + + +def test_screen_text_alone_still_asks(): + assert d.second_factor((), "Two-factor authentication: enter the code") == "second_factor" + + +def test_an_ordinary_form_is_not_a_second_factor(): + assert d.second_factor(*elements_from_html(FORM)) is None + assert detect(_obs(FORM)) is None + + +def test_a_hidden_code_field_is_not_on_screen(): + page = "
" + assert d.second_factor(*elements_from_html(page)) is None + + +# -- session expired ---------------------------------------------------------------- + + +def test_a_sign_in_page_before_any_save_screen_is_the_tasks_start(): + assert detect(_obs(SIGN_IN, save_eligible_seen=False)) is None + + +def test_a_sign_in_page_after_a_save_screen_is_a_session_expiry(): + assert detect(_obs(SIGN_IN, save_eligible_seen=True)) == "session_expired" + + +def test_words_alone_after_a_save_screen_still_ask(): + page = "

Your session has expired.

" + assert detect(_obs(page, save_eligible_seen=True)) == "session_expired" + + +def test_accessibility_secure_field_counts_as_a_password(): + nodes = [{"role": "AXSecureTextField", "name": "Password"}] + elements = d.elements_from_accessibility(nodes) + assert d.session_expired(elements, save_eligible_seen=True) == "session_expired" + + +# -- dialogs ------------------------------------------------------------------------ + + +def test_a_modal_over_the_form_is_an_unexpected_dialog(): + assert detect(_obs(MODAL)) == "unexpected_dialog" + + +def test_a_hidden_modal_is_not_in_the_way(): + assert detect(_obs(HIDDEN_MODAL)) is None + + +def test_a_dialog_the_step_expects_is_not_an_exception(): + assert detect(_obs(MODAL, expected_dialog=True)) is None + + +def test_a_non_modal_dialog_away_from_the_target_is_not_in_the_way(): + dialog = {"role": "dialog", "bbox": [900, 0, 200, 100], "z": 5} + target = {"tag": "button", "bbox": [10, 500, 80, 30], "z": 0} + assert d.unexpected_dialog([dialog], target=target) is None + + +def test_a_non_modal_dialog_covering_the_target_is_in_the_way(): + dialog = {"role": "dialog", "bbox": [0, 400, 400, 300], "z": 5} + target = {"tag": "button", "bbox": [10, 500, 80, 30], "z": 0} + assert d.unexpected_dialog([dialog], target=target) == "unexpected_dialog" + + +def test_a_dialog_with_no_geometry_asks(): + assert d.unexpected_dialog([{"role": "alertdialog"}], target={"bbox": [1, 1, 1, 1]}) == ( + "unexpected_dialog" + ) + + +# -- stalls ------------------------------------------------------------------------- + + +def test_no_action_and_no_change_for_too_long_is_a_stall(): + assert detect(Observation(now=1000.0, last_action_at=700.0, last_change_at=800.0, stall_s=120)) == ( + "timeout_or_stall" + ) + + +def test_a_recent_change_is_not_a_stall(): + assert d.timeout_or_stall(now=1000.0, last_action_at=700.0, last_change_at=950.0, stall_s=120) is None + + +def test_a_clock_with_no_last_event_asks(): + assert d.timeout_or_stall(now=5.0, last_action_at=None, last_change_at=None) == "timeout_or_stall" + + +def test_no_clock_means_no_stall_check(): + assert detect(Observation()) is None + + +# -- duplicates --------------------------------------------------------------------- + +ROWS = [{"last_name": "Okafor", "dob": "1950-01-01"}, {"last_name": "Vance", "dob": "1972-03-04"}] + + +def test_a_row_with_the_same_key_is_a_possible_duplicate(): + observation = Observation( + duplicate_key=["last_name", "dob"], + proposed={"last_name": " vance ", "dob": "1972-03-04", "note": "x"}, + existing=ROWS, + ) + assert detect(observation) == "possible_duplicate" + + +def test_no_matching_row_is_not_a_duplicate(): + assert d.possible_duplicate("last_name", {"last_name": "Nobody"}, ROWS) is None + + +@pytest.mark.parametrize( + "key,proposed,rows", + [ + (["last_name", "dob"], {"last_name": "Vance"}, ROWS), # no key value + ("last_name", {"last_name": "Vance"}, None), # the read failed + ("last_name", {"last_name": "Nobody"}, [{"dob": "1950-01-01"}]), # row lacks key + ([], {"last_name": "Vance"}, ROWS), # a key with no fields + ({"weird": 1}, {"last_name": "Vance"}, ROWS), # a key shape we can't check + ], +) +def test_a_duplicate_check_that_cant_rule_it_out_asks(key, proposed, rows): + assert d.possible_duplicate(key, proposed, rows) == "possible_duplicate" + + +def test_no_duplicate_key_configured_means_no_duplicate_check(): + assert d.possible_duplicate(None, {"a": "b"}, ROWS) is None + + +def test_the_key_comes_from_verify_yaml_record_duplicate_key(): + config = {"record": {"duplicate_key": ["last_name", "dob"]}, "verifier": {}} + assert d.duplicate_key_from_config(config) == ["last_name", "dob"] + assert d.duplicate_key_from_config({"verifier": {}}) is None + + +# -- general mechanisms only -------------------------------------------------------- + + +def test_the_detectors_name_no_app(): + source = Path(d.__file__).read_text(encoding="utf-8").casefold() + for name in ("openemr", "mockmed", "epic", "cerner", "salesforce", "okta", "google", "microsoft"): + assert name not in source + + +def test_every_detector_returns_a_closed_kind_or_none(): + from openadapt_types.exception_card import EXCEPTION_KINDS + + pages = [FORM, OTP_MARKED, OTP_WEAK, SIGN_IN, MODAL] + for page in pages: + for kind in d.detect_all(_obs(page, save_eligible_seen=True)): + assert kind in EXCEPTION_KINDS diff --git a/packages/flow/tests/test_exception_registry.py b/packages/flow/tests/test_exception_registry.py new file mode 100644 index 0000000000..d5f7a4101a --- /dev/null +++ b/packages/flow/tests/test_exception_registry.py @@ -0,0 +1,530 @@ +"""The exception registry: cards, signed answers, expiry, and what never proceeds. + +Synthetic data only. The approver roster is a fresh one in a temporary +folder, with a root key made here; nothing reads the real ~/.openadapt. +""" + +from __future__ import annotations + +import json +import os +import stat +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from openadapt_types.exception_card import ( + EXCEPTION_KINDS, + ExceptionAnswerV1, + ExceptionCardV1, + answer_message, +) + +from openadapt_flow import privacy +from openadapt_flow.approval_mode.approver_roster import ( + ROOT_ENV, + file_key_signer, + init_root, +) +from openadapt_flow.exceptions import cli as exceptions_cli +from openadapt_flow.exceptions.registry import ( + CHOICES, + GENERIC_SUMMARIES, + ExceptionRegistry, + ExceptionRegistryError, + iso, + roster_verifier, +) +from openadapt_flow.execute.keys import sign_bytes +from openadapt_flow.jit.authority import public_hex + +#: Made-up identifiers planted in what an agent says; none may reach a card. +PLANTED = ("Maribel Quintanilla", "1961-04-09", "MRN 88812345", "maribel@example.test") +SUMMARY = ( + "Code prompt for Maribel Quintanilla, born 1961-04-09, MRN 88812345, " + "mail maribel@example.test" +) + +PNG = ( + b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02" + b"\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00" + b"\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82" +) + + +class FakeScrubber: + """Replaces the planted name; the registry masks digits and dates itself.""" + + def scrub_text(self, text: str) -> str: + return text.replace("Maribel Quintanilla", "") + + def scrub_image(self, image, fill_color=None): # noqa: ARG002 + return image + + +@pytest.fixture(autouse=True) +def _scrubber(): + privacy.set_text_scrubber(FakeScrubber()) + yield + privacy.reset_scrubbers() + + +@pytest.fixture +def registry(tmp_path: Path) -> ExceptionRegistry: + return ExceptionRegistry(tmp_path / "exceptions") + + +@pytest.fixture +def roster(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + key_dir = tmp_path / "keys" + key = Ed25519PrivateKey.generate() + init_root(key_dir, principal="front-desk", public_key=public_hex(key), sign=file_key_signer(key)) + monkeypatch.setenv(ROOT_ENV, public_hex(key)) + return key_dir, key + + +def _signed(registry, card, answer: str, key, *, now=None) -> dict: + unsigned = registry.unsigned_answer(card, answer, route="cli", now=now) + return { + **unsigned, + "public_key": public_hex(key), + "signature": sign_bytes(key, answer_message(unsigned)), + } + + +def _verify(roster): + key_dir, key = roster + return roster_verifier(key_dir, public_hex(key)) + + +def _no_sleep(_s: float) -> None: + return None + + +# -- cards ----------------------------------------------------------------------- + + +def test_a_card_is_sealed_private_and_names_closed_choices(registry): + card = registry.open("run-1", "second_factor", "A code prompt appeared") + + path = registry.root / "run-1" / f"card-{card.card_id[7:]}.json" + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + on_disk = ExceptionCardV1.model_validate(json.loads(path.read_text())) + assert on_disk == card + assert [c.id for c in card.choices] == ["done_by_person", "skip", "abort"] + assert card.kind == "second_factor" + assert registry.open_cards() == [card] + + +def test_every_kind_has_choices_and_no_card_offers_a_write_on_its_own(): + assert set(CHOICES) == set(EXCEPTION_KINDS) + for kind, choices in CHOICES.items(): + assert choices, kind + assert len(choices) <= 5 + + +@pytest.mark.parametrize("kind", ["unknown", "SECOND_FACTOR", ""]) +def test_an_unknown_kind_is_refused(registry, kind): + with pytest.raises(ExceptionRegistryError) as err: + registry.open("run-1", kind, "x") + assert err.value.code == "kind_unknown" + + +@pytest.mark.parametrize("run_ref", ["../escape", "a/b", "", ".hidden", "x" * 200]) +def test_a_run_reference_never_becomes_a_path_outside_the_registry(registry, run_ref): + with pytest.raises(ExceptionRegistryError) as err: + registry.open(run_ref, "cannot_complete", "x") + assert err.value.code == "run_ref_invalid" + + +def test_a_tampered_card_is_not_listed(registry): + card = registry.open("run-1", "cannot_complete", "Stuck") + path = registry.root / "run-1" / f"card-{card.card_id[7:]}.json" + data = json.loads(path.read_text()) + data["summary"] = "Something else" + os.chmod(path, 0o600) + path.unlink() + path.write_text(json.dumps(data)) + assert registry.open_cards() == [] + + +# -- scrubbing -------------------------------------------------------------------- + + +def _bytes_under(root: Path) -> bytes: + return b"".join(p.read_bytes() for p in root.rglob("*") if p.is_file()) + + +def test_the_summary_is_scrubbed_and_cut(registry): + card = registry.open("run-1", "second_factor", SUMMARY + " " + "x" * 400, task_id="T-12345678") + + assert len(card.summary) <= 200 + blob = _bytes_under(registry.root) + for planted in PLANTED: + assert planted.encode() not in blob + assert b"" in blob + assert card.task_id == "T-[number]" + + +def test_without_a_scrubber_the_card_says_only_the_kinds_own_words(registry): + privacy.set_text_scrubber(None) + card = registry.open("run-1", "session_expired", SUMMARY) + + assert card.summary == GENERIC_SUMMARIES["session_expired"] + blob = _bytes_under(registry.root) + for planted in PLANTED: + assert planted.encode() not in blob + + +def test_a_broken_scrubber_is_no_scrubber(registry): + class Broken: + def scrub_text(self, text): + raise RuntimeError("model missing") + + privacy.set_text_scrubber(Broken()) + card = registry.open("run-1", "cannot_complete", SUMMARY) + assert card.summary == GENERIC_SUMMARIES["cannot_complete"] + + +def test_a_screenshot_is_kept_only_as_a_scrubbed_private_copy(registry, tmp_path): + shot = tmp_path / "screen.png" + shot.write_bytes(PNG) + card = registry.open("run-1", "unexpected_dialog", "A dialog", screenshot_path=str(shot)) + + assert card.screenshot_ref is not None + copy = registry.root / "run-1" / card.screenshot_ref + assert copy.read_bytes().startswith(b"\x89PNG") + assert stat.S_IMODE(copy.stat().st_mode) == 0o600 + + +def test_no_screenshot_without_a_scrubber_a_png_or_a_plain_file(registry, tmp_path): + shot = tmp_path / "screen.png" + shot.write_bytes(PNG) + link = tmp_path / "link.png" + link.symlink_to(shot) + text = tmp_path / "notes.png" + text.write_text("not an image") + + assert registry.open("r", "cannot_complete", "x", screenshot_path=str(link)).screenshot_ref is None + assert registry.open("r", "cannot_complete", "y", screenshot_path=str(text)).screenshot_ref is None + assert registry.open("r", "cannot_complete", "z", screenshot_path=str(tmp_path)).screenshot_ref is None + privacy.set_text_scrubber(None) + assert registry.open("r", "cannot_complete", "w", screenshot_path=str(shot)).screenshot_ref is None + + +# -- answers ----------------------------------------------------------------------- + + +def test_a_signed_done_by_person_lets_the_run_go_on(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + registry.write_answer(card, _signed(registry, card, "done_by_person", key)) + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + + assert outcome.proceed is True + assert outcome.answer == "done_by_person" + assert outcome.opened_at == card.opened_at + assert outcome.decided_at is not None + assert (registry.root / "run-1" / f"consumed-{card.card_id[7:]}.json").exists() + assert registry.open_cards() == [] + + +@pytest.mark.parametrize("answer", ["skip", "abort"]) +def test_a_signed_stop_answer_stops_the_run(registry, roster, answer): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + registry.write_answer(card, _signed(registry, card, answer, key)) + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.answer == answer + + +def test_an_answer_from_a_key_off_the_roster_never_proceeds(registry, roster): + card = registry.open("run-1", "second_factor", "A code prompt") + stranger = Ed25519PrivateKey.generate() + registry.write_answer(card, _signed(registry, card, "done_by_person", stranger)) + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.reason == "human_approver_unregistered" + + +def test_a_forged_signature_never_proceeds(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "timeout_or_stall", "Nothing moves") + answer = _signed(registry, card, "skip", key) + answer["answer"] = "continue" # the signature covered "skip" + registry.write_answer(card, answer) + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.reason == "human_answer_signature_invalid" + + +def test_without_a_pinned_root_no_answer_counts(registry, roster): + key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + registry.write_answer(card, _signed(registry, card, "done_by_person", key)) + + outcome = registry.wait(card, verify=roster_verifier(key_dir, None), sleep=_no_sleep) + assert outcome.proceed is False + + +def test_a_choice_the_card_doesnt_offer_never_proceeds(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + with pytest.raises(ExceptionRegistryError): + registry.unsigned_answer(card, "continue", route="cli") + unsigned = { + "schema": "openadapt.exception-answer/v1", + "card_id": card.card_id, + "kind": card.kind, + "opened_at": card.opened_at, + "decided_at": iso(datetime.now(timezone.utc)), + "answer": "continue", + "approver_kind": "person", + "route": "cli", + "reason": None, + } + registry.write_answer( + card, + {**unsigned, "public_key": public_hex(key), "signature": sign_bytes(key, answer_message(unsigned))}, + ) + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.reason == "choice_not_offered" + + +def test_an_answer_decided_after_the_deadline_never_proceeds(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt", deadline_s=5) + late = datetime.now(timezone.utc) + timedelta(seconds=60) + registry.write_answer(card, _signed(registry, card, "done_by_person", key, now=late)) + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.reason == "answer_late" + + +def test_an_answer_is_used_once(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + registry.write_answer(card, _signed(registry, card, "done_by_person", key)) + assert registry.wait(card, verify=_verify(roster), sleep=_no_sleep).proceed is True + + again = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert again.proceed is False + assert again.reason == "answer_already_used" + + +def test_a_card_has_one_answer(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + registry.write_answer(card, _signed(registry, card, "abort", key)) + with pytest.raises(ExceptionRegistryError) as err: + registry.write_answer(card, _signed(registry, card, "done_by_person", key)) + assert err.value.code == "already_answered" + + +def test_an_unreadable_answer_stops_the_run(registry, roster): + card = registry.open("run-1", "second_factor", "A code prompt") + (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").write_text("{not json") + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.reason == "answer_unreadable" + + +def test_an_unsigned_answer_that_claims_to_be_a_persons_is_unreadable(registry, roster): + card = registry.open("run-1", "second_factor", "A code prompt") + answer = { + "schema": "openadapt.exception-answer/v1", + "card_id": card.card_id, + "kind": card.kind, + "opened_at": card.opened_at, + "decided_at": iso(datetime.now(timezone.utc)), + "answer": "done_by_person", + "approver_kind": "person", + "route": "cli", + } + (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").write_text(json.dumps(answer)) + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + + +# -- expiry ------------------------------------------------------------------------ + + +def test_expiry_writes_a_decline_with_no_decision_time(registry, roster): + card = registry.open("run-1", "second_factor", "A code prompt", deadline_s=60) + after = datetime.now(timezone.utc) + timedelta(seconds=61) + beats: list[float] = [] + + outcome = registry.wait( + card, + verify=_verify(roster), + clock=lambda: after, + sleep=_no_sleep, + heartbeat=lambda _id, left: beats.append(left), + ) + + assert outcome.proceed is False + assert outcome.answer == "decline" + assert outcome.reason == "expired" + assert outcome.decided_at is None + record = ExceptionAnswerV1.model_validate( + json.loads((registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").read_text()) + ) + assert record.approver_kind == "expiry" + assert record.decided_at is None + assert record.reason == "expired" + assert record.opened_at == card.opened_at + + +def test_the_wait_beats_and_then_expires(registry, roster): + card = registry.open("run-1", "timeout_or_stall", "Stalled", deadline_s=60) + times = iter( + [datetime.now(timezone.utc)] * 3 + [datetime.now(timezone.utc) + timedelta(seconds=120)] * 5 + ) + beats: list[float] = [] + outcome = registry.wait( + card, + verify=_verify(roster), + clock=lambda: next(times), + sleep=_no_sleep, + heartbeat_s=0, + heartbeat=lambda _id, left: beats.append(left), + ) + assert outcome.reason == "expired" + assert beats and all(b > 0 for b in beats) + + +def test_a_person_who_answers_at_the_deadline_wins_the_race(registry, roster, monkeypatch): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt", deadline_s=60) + answer = _signed(registry, card, "done_by_person", key) + original = registry._expire + + def expire_after_the_person(c): + registry.write_answer(c, answer) # lands first + original(c) # then the registry's expiry link fails + + monkeypatch.setattr(registry, "_expire", expire_after_the_person) + after = datetime.now(timezone.utc) + timedelta(seconds=61) + outcome = registry.wait(card, verify=_verify(roster), clock=lambda: after, sleep=_no_sleep) + assert outcome.proceed is True + + +def test_the_heartbeat_goes_to_stderr_never_stdout(registry, roster, capsys): + card = registry.open("run-1", "timeout_or_stall", "Stalled", deadline_s=60) + times = iter([datetime.now(timezone.utc), datetime.now(timezone.utc) + timedelta(seconds=99)] * 3) + registry.wait(card, verify=_verify(roster), clock=lambda: next(times), sleep=_no_sleep) + out, err = capsys.readouterr() + assert out == "" + assert "waiting for a person" in err + + +# -- CLI --------------------------------------------------------------------------- + + +def _encrypted(tmp_path: Path, key: Ed25519PrivateKey, passphrase: str) -> Path: + path = tmp_path / "approver.pem" + path.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.BestAvailableEncryption(passphrase.encode()), + ) + ) + path.chmod(0o600) + return path + + +def _parse(argv: list[str]): + import argparse + + parser = argparse.ArgumentParser() + sub = parser.add_subparsers(dest="command", required=True) + exceptions_cli.register(sub) + return parser.parse_args(argv) + + +def test_the_cli_answers_with_a_key_on_the_roster(registry, roster, tmp_path, monkeypatch, capsys): + key_dir, key = roster + monkeypatch.setenv("OPENADAPT_JIT_KEY_PASSPHRASE", "synthetic-passphrase") + pem = _encrypted(tmp_path, key, "synthetic-passphrase") + card = registry.open("run-1", "second_factor", "A code prompt") + + args = _parse(["exceptions", "list", "--registry", str(registry.root), "--json"]) + assert args.func(args) == 0 + listed = json.loads(capsys.readouterr().out) + assert [c["card_id"] for c in listed["cards"]] == [card.card_id] + + args = _parse( + [ + "exceptions", "answer", card.card_id, "done_by_person", + "--registry", str(registry.root), "--key", str(pem), "--key-dir", str(key_dir), + ] + ) + assert args.func(args) == 0 + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is True + + +def test_the_cli_refuses_a_key_off_the_roster(registry, roster, tmp_path, monkeypatch, capsys): + key_dir, _key = roster + monkeypatch.setenv("OPENADAPT_JIT_KEY_PASSPHRASE", "synthetic-passphrase") + pem = _encrypted(tmp_path, Ed25519PrivateKey.generate(), "synthetic-passphrase") + card = registry.open("run-1", "second_factor", "A code prompt") + + args = _parse( + [ + "exceptions", "answer", card.card_id, "done_by_person", + "--registry", str(registry.root), "--key", str(pem), "--key-dir", str(key_dir), + ] + ) + assert args.func(args) == 2 + assert "human_approver_unregistered" in capsys.readouterr().err + assert not (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").exists() + + +def test_the_cli_refuses_a_choice_the_card_doesnt_offer(registry, roster, tmp_path, monkeypatch): + key_dir, key = roster + monkeypatch.setenv("OPENADAPT_JIT_KEY_PASSPHRASE", "synthetic-passphrase") + pem = _encrypted(tmp_path, key, "synthetic-passphrase") + card = registry.open("run-1", "second_factor", "A code prompt") + args = _parse( + [ + "exceptions", "answer", card.card_id, "continue", + "--registry", str(registry.root), "--key", str(pem), "--key-dir", str(key_dir), + ] + ) + assert args.func(args) == 2 + + +# -- the file Desktop reads --------------------------------------------------------- + +FIXTURE = Path(__file__).parent / "fixtures" / "exception_card_second_factor.json" + + +def test_the_desktop_fixture_is_what_flow_writes(registry): + """Desktop's suite reads this file; Flow must still write exactly it.""" + + opened = datetime(2026, 11, 21, 12, 0, 0, tzinfo=timezone.utc) + card = registry.open( + "fixture-run", + "second_factor", + "The sign-in page asks for a six-digit code", + task_id="intake", + now=opened, + ) + written = json.loads( + (registry.root / "fixture-run" / f"card-{card.card_id[7:]}.json").read_text() + ) + if os.environ.get("OPENADAPT_REGENERATE_FIXTURES") == "1": + FIXTURE.write_text(json.dumps(written, sort_keys=True, indent=2) + "\n") + assert written == json.loads(FIXTURE.read_text()) diff --git a/packages/types/openadapt_types/exception_card.py b/packages/types/openadapt_types/exception_card.py new file mode 100644 index 0000000000..398fdb252b --- /dev/null +++ b/packages/types/openadapt_types/exception_card.py @@ -0,0 +1,227 @@ +"""Exception cards: the closed question a run asks a person, and the answer. + +Any agent (a compiled program, Claude computer use, a CUA harness, a person's +own script) can stop at a moment it can't get past alone: a second-factor +prompt, a dialog it didn't expect, a sign-in page mid-task, a stall, a +possible duplicate, a record it can't tell apart from another, or a task it +can't finish. It opens one :class:`ExceptionCardV1`, and a person answers it +with one :class:`ExceptionAnswerV1`. + +Both sets are closed. ``kind`` is one of :data:`EXCEPTION_KINDS` and +``answer`` is one of :data:`EXCEPTION_ANSWERS`; nothing else validates. Only +``continue`` and ``done_by_person`` let a run go on +(:data:`PROCEED_ANSWERS`). Every other answer, an expired card and an answer +that can't be read or verified mean the run stops before any write. + +The card carries no raw values. ``summary`` is scrubbed text of at most +:data:`SUMMARY_MAX` characters, and ``screenshot_ref`` names a local, scrubbed +copy, never the original frame. ``card_id`` is the digest of everything else +on the card (:func:`card_digest`), so an answer names exactly the card a +person saw. + +``opened_at`` and ``decided_at`` on the answer are the intervention interval: +how long a person held the run. An expiry answer has ``decided_at`` ``None``, +``approver_kind`` ``expiry``, ``answer`` ``decline`` and ``reason`` +``expired``. + +This module is imported by its submodule path +(``openadapt_types.exception_card``); it is not re-exported from the package. +""" + +from __future__ import annotations + +import hashlib +import json +from typing import Any, Literal, Optional, get_args + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +EXCEPTION_CARD_SCHEMA = "openadapt.exception-card/v1" +EXCEPTION_ANSWER_SCHEMA = "openadapt.exception-answer/v1" +#: What an approver key signs for an answer: these bytes, then the canonical +#: JSON of :func:`answer_signing_payload`. +EXCEPTION_ANSWER_DOMAIN = b"openadapt.exception-answer/v1\x00" + +ExceptionKind = Literal[ + "second_factor", + "unexpected_dialog", + "session_expired", + "timeout_or_stall", + "possible_duplicate", + "ambiguous_record", + "cannot_complete", +] +EXCEPTION_KINDS: tuple[str, ...] = get_args(ExceptionKind) + +ExceptionAnswerValue = Literal["continue", "skip", "decline", "done_by_person", "abort"] +EXCEPTION_ANSWERS: tuple[str, ...] = get_args(ExceptionAnswerValue) +#: The only answers that let a run go on. Anything else stops before a write. +PROCEED_ANSWERS = frozenset({"continue", "done_by_person"}) + +ApproverKind = Literal["person", "expiry"] +#: Where a person's answer came from. +AnswerRoute = Literal["cli", "desktop", "portal", "registry"] + +SUMMARY_MAX = 200 +_DIGEST = r"^sha256:[0-9a-f]{64}$" +#: A run reference is opaque: it becomes a directory name. +RUN_REF_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" +_TIME = r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$" +_SIGNATURE = r"^ed25519:[0-9a-f]{128}$" +_PUBLIC_KEY = r"^[0-9a-f]{64}$" + + +def canonical(value: Any) -> bytes: + """The canonical JSON bytes every digest and signature here covers.""" + + return json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +class ExceptionChoice(BaseModel): + """One button: the closed answer, its label, and what it does.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + id: ExceptionAnswerValue + label: str = Field(min_length=1, max_length=80) + consequence: str = Field(min_length=1, max_length=200) + + +class ExceptionCardV1(BaseModel): + """The question one run asks a person.""" + + model_config = ConfigDict(extra="forbid", frozen=True, populate_by_name=True) + + schema_: Literal["openadapt.exception-card/v1"] = Field( + default=EXCEPTION_CARD_SCHEMA, alias="schema" + ) + card_id: str = Field(pattern=_DIGEST) + run_ref: str = Field(pattern=RUN_REF_PATTERN) + task_id: Optional[str] = Field(default=None, max_length=128) + kind: ExceptionKind + opened_at: str = Field(pattern=_TIME) + deadline_at: str = Field(pattern=_TIME) + #: A file name inside the card's own folder (a scrubbed copy), or None. + screenshot_ref: Optional[str] = Field( + default=None, pattern=r"^screenshot-[0-9a-f]{16,64}\.png$" + ) + summary: str = Field(min_length=1, max_length=SUMMARY_MAX) + choices: tuple[ExceptionChoice, ...] = Field(min_length=1, max_length=5) + + @field_validator("choices") + @classmethod + def _distinct(cls, value: tuple[ExceptionChoice, ...]) -> tuple[ExceptionChoice, ...]: + ids = [choice.id for choice in value] + if len(set(ids)) != len(ids): + raise ValueError("a card offers each answer once") + return value + + @model_validator(mode="after") + def _sealed(self) -> "ExceptionCardV1": + if card_digest(self.body()) != self.card_id: + raise ValueError("card_id is not the digest of the card") + return self + + def body(self) -> dict[str, Any]: + """Everything on the card except its id (what ``card_id`` digests).""" + + data = self.model_dump(mode="json", by_alias=True) + data.pop("card_id") + return data + + def wire(self) -> dict[str, Any]: + return self.model_dump(mode="json", by_alias=True) + + def offers(self, answer: str) -> bool: + return any(choice.id == answer for choice in self.choices) + + +class ExceptionAnswerV1(BaseModel): + """A person's answer to one card, or the registry's expiry record.""" + + model_config = ConfigDict(extra="forbid", frozen=True, populate_by_name=True) + + schema_: Literal["openadapt.exception-answer/v1"] = Field( + default=EXCEPTION_ANSWER_SCHEMA, alias="schema" + ) + card_id: str = Field(pattern=_DIGEST) + kind: ExceptionKind + opened_at: str = Field(pattern=_TIME) + decided_at: Optional[str] = Field(default=None, pattern=_TIME) + answer: ExceptionAnswerValue + approver_kind: ApproverKind + route: AnswerRoute + #: The closed reason for a registry-written answer. + reason: Optional[Literal["expired"]] = None + #: The approver key that signed (hex Ed25519), not part of what it signs. + public_key: Optional[str] = Field(default=None, pattern=_PUBLIC_KEY) + signature: Optional[str] = Field(default=None, pattern=_SIGNATURE) + + @model_validator(mode="after") + def _shape(self) -> "ExceptionAnswerV1": + if self.approver_kind == "expiry": + if ( + self.answer != "decline" + or self.decided_at is not None + or self.reason != "expired" + or self.signature is not None + or self.route != "registry" + ): + raise ValueError( + "an expiry record is answer=decline, decided_at=null, " + "reason=expired, unsigned, written by the registry" + ) + else: + if self.decided_at is None or self.signature is None or self.public_key is None: + raise ValueError("a person's answer is timed and signed") + if self.reason is not None or self.route == "registry": + raise ValueError("a person's answer carries no registry reason") + return self + + def wire(self) -> dict[str, Any]: + return self.model_dump(mode="json", by_alias=True) + + @property + def proceeds(self) -> bool: + return self.approver_kind == "person" and self.answer in PROCEED_ANSWERS + + +def card_digest(body: dict[str, Any]) -> str: + """``sha256:`` of the canonical card body (the card without ``card_id``).""" + + return "sha256:" + hashlib.sha256(canonical(body)).hexdigest() + + +def answer_signing_payload(answer: dict[str, Any]) -> dict[str, Any]: + """What an approver key signs: the answer without its key and signature.""" + + return {k: v for k, v in answer.items() if k not in {"signature", "public_key"}} + + +def answer_message(answer: dict[str, Any]) -> bytes: + """The exact bytes an approver key signs for ``answer``.""" + + return EXCEPTION_ANSWER_DOMAIN + canonical(answer_signing_payload(answer)) + + +__all__ = [ + "EXCEPTION_ANSWERS", + "EXCEPTION_ANSWER_DOMAIN", + "EXCEPTION_ANSWER_SCHEMA", + "EXCEPTION_CARD_SCHEMA", + "EXCEPTION_KINDS", + "PROCEED_ANSWERS", + "RUN_REF_PATTERN", + "SUMMARY_MAX", + "AnswerRoute", + "ApproverKind", + "ExceptionAnswerV1", + "ExceptionAnswerValue", + "ExceptionCardV1", + "ExceptionChoice", + "ExceptionKind", + "answer_message", + "answer_signing_payload", + "canonical", + "card_digest", +] diff --git a/packages/types/tests/test_exception_card.py b/packages/types/tests/test_exception_card.py new file mode 100644 index 0000000000..680681ab28 --- /dev/null +++ b/packages/types/tests/test_exception_card.py @@ -0,0 +1,165 @@ +"""The exception card and answer contracts: closed sets, sealed ids, expiry shape.""" + +from __future__ import annotations + +import pytest +from pydantic import ValidationError + +from openadapt_types import exception_card as ec + +OPENED = "2026-11-21T12:00:00Z" +DEADLINE = "2026-11-21T12:15:00Z" + + +def _body(**overrides): + body = { + "schema": ec.EXCEPTION_CARD_SCHEMA, + "run_ref": "run-1", + "task_id": None, + "kind": "second_factor", + "opened_at": OPENED, + "deadline_at": DEADLINE, + "screenshot_ref": None, + "summary": "The app is asking for a one-time code.", + "choices": [ + {"id": "done_by_person", "label": "I entered it", "consequence": "The run goes on."}, + {"id": "abort", "label": "Stop", "consequence": "Nothing more is saved."}, + ], + } + body.update(overrides) + return body + + +def _card(**overrides): + body = _body(**overrides) + return ec.ExceptionCardV1.model_validate({**body, "card_id": ec.card_digest(body)}) + + +def test_the_closed_sets(): + assert ec.EXCEPTION_KINDS == ( + "second_factor", + "unexpected_dialog", + "session_expired", + "timeout_or_stall", + "possible_duplicate", + "ambiguous_record", + "cannot_complete", + ) + assert ec.EXCEPTION_ANSWERS == ("continue", "skip", "decline", "done_by_person", "abort") + assert ec.PROCEED_ANSWERS == {"continue", "done_by_person"} + + +def test_a_card_round_trips_with_its_schema_name(): + card = _card() + wire = card.wire() + assert wire["schema"] == "openadapt.exception-card/v1" + assert ec.ExceptionCardV1.model_validate(wire) == card + assert card.offers("abort") and not card.offers("continue") + + +@pytest.mark.parametrize( + "overrides", + [ + {"kind": "captcha"}, + {"summary": "x" * 201}, + {"summary": ""}, + {"run_ref": "../up"}, + {"opened_at": "yesterday"}, + {"screenshot_ref": "/etc/passwd"}, + {"choices": [{"id": "approve", "label": "x", "consequence": "y"}]}, + {"choices": []}, + ], +) +def test_anything_outside_the_contract_is_refused(overrides): + with pytest.raises(ValidationError): + _card(**overrides) + + +def test_a_card_whose_id_isnt_its_digest_is_refused(): + body = _body() + with pytest.raises(ValidationError): + ec.ExceptionCardV1.model_validate({**body, "card_id": "sha256:" + "0" * 64}) + + +def test_a_card_offers_each_answer_once(): + twice = [{"id": "abort", "label": "a", "consequence": "b"}] * 2 + with pytest.raises(ValidationError): + _card(choices=twice) + + +def test_an_unknown_field_is_refused(): + body = _body() + body["raw_values"] = {"name": "x"} + with pytest.raises(ValidationError): + ec.ExceptionCardV1.model_validate({**body, "card_id": ec.card_digest(body)}) + + +def _answer(**overrides): + base = { + "schema": ec.EXCEPTION_ANSWER_SCHEMA, + "card_id": "sha256:" + "a" * 64, + "kind": "second_factor", + "opened_at": OPENED, + "decided_at": "2026-11-21T12:01:00Z", + "answer": "done_by_person", + "approver_kind": "person", + "route": "cli", + "reason": None, + "public_key": "b" * 64, + "signature": "ed25519:" + "c" * 128, + } + base.update(overrides) + return ec.ExceptionAnswerV1.model_validate(base) + + +def test_a_persons_answer_is_timed_and_signed(): + answer = _answer() + assert answer.proceeds + with pytest.raises(ValidationError): + _answer(signature=None) + with pytest.raises(ValidationError): + _answer(decided_at=None) + with pytest.raises(ValidationError): + _answer(reason="expired") + + +def test_an_expiry_is_an_unsigned_decline_with_no_decision_time(): + expiry = _answer( + decided_at=None, + answer="decline", + approver_kind="expiry", + route="registry", + reason="expired", + public_key=None, + signature=None, + ) + assert not expiry.proceeds + with pytest.raises(ValidationError): # an expiry can't say continue + _answer( + decided_at=None, + answer="continue", + approver_kind="expiry", + route="registry", + reason="expired", + public_key=None, + signature=None, + ) + + +@pytest.mark.parametrize("value", ["skip", "decline", "abort"]) +def test_only_continue_and_done_by_person_proceed(value): + assert not _answer(answer=value).proceeds + + +def test_the_signed_bytes_leave_out_the_key_and_signature(): + wire = _answer().wire() + message = ec.answer_message(wire) + assert message.startswith(ec.EXCEPTION_ANSWER_DOMAIN) + assert b"signature" not in message and b"public_key" not in message + assert b'"answer":"done_by_person"' in message + + +def test_not_exported_from_the_package_root(): + import openadapt_types + + assert not hasattr(openadapt_types, "ExceptionCardV1") From fe42cb9860f25416deb509d87fd762d423d25f93 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 18:41:46 -0500 Subject: [PATCH 02/11] test(flow): write the exception card fixture Desktop reads --- .../exception_card_second_factor.json | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/packages/flow/tests/fixtures/exception_card_second_factor.json b/packages/flow/tests/fixtures/exception_card_second_factor.json index 0967ef424b..2cd32341c9 100644 --- a/packages/flow/tests/fixtures/exception_card_second_factor.json +++ b/packages/flow/tests/fixtures/exception_card_second_factor.json @@ -1 +1,28 @@ -{} +{ + "card_id": "sha256:789e54fd7198a18087709380c8db637b843b28fb2d1d04f1247e5ac8026097ce", + "choices": [ + { + "consequence": "You type the code in the live browser yourself. The run then goes on from the same screen. OpenAdapt never sees the code.", + "id": "done_by_person", + "label": "I entered the code in the browser" + }, + { + "consequence": "Nothing is saved. The run moves to the next item.", + "id": "skip", + "label": "Skip this item" + }, + { + "consequence": "Nothing more is saved. The whole run stops.", + "id": "abort", + "label": "Stop the run" + } + ], + "deadline_at": "2026-11-21T12:15:00Z", + "kind": "second_factor", + "opened_at": "2026-11-21T12:00:00Z", + "run_ref": "fixture-run", + "schema": "openadapt.exception-card/v1", + "screenshot_ref": null, + "summary": "The sign-in page asks for a six-digit code", + "task_id": "intake" +} From 3a212c399fe4af5971d82cd3f8b985a947068d39 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:16:21 -0500 Subject: [PATCH 03/11] fix(desktop): exception tests use a valid PNG; wrap long lines --- .../openadapt_desktop/exception_queue.py | 12 ++++++++-- .../test_engine/test_stop_queue_exceptions.py | 10 ++++++-- .../flow/openadapt_flow/exceptions/cli.py | 8 +++++-- .../flow/tests/test_exception_registry.py | 23 ++++++++++++++----- 4 files changed, 41 insertions(+), 12 deletions(-) diff --git a/packages/desktop/openadapt_desktop/exception_queue.py b/packages/desktop/openadapt_desktop/exception_queue.py index 3273952b7f..020203307b 100644 --- a/packages/desktop/openadapt_desktop/exception_queue.py +++ b/packages/desktop/openadapt_desktop/exception_queue.py @@ -240,7 +240,11 @@ def answer( if card is None: return {"ok": False, "code": "card_changed", "error": "The stop was answered or is gone."} if choice not in {c.get("id") for c in card["choices"]}: - return {"ok": False, "code": "choice_not_offered", "error": "That choice isn't on this stop."} + return { + "ok": False, + "code": "choice_not_offered", + "error": "That choice isn't on this stop.", + } decided = now().astimezone(timezone.utc).isoformat().replace("+00:00", "Z") if _after(decided, card["deadline_at"]): return {"ok": False, "code": "card_expired", "error": "The stop expired."} @@ -259,7 +263,11 @@ def answer( except FileExistsError: return {"ok": False, "code": "card_changed", "error": "The stop was answered first."} except OSError: - return {"ok": False, "code": "registry_unwritable", "error": "Desktop couldn't save the answer."} + return { + "ok": False, + "code": "registry_unwritable", + "error": "Desktop couldn't save the answer.", + } return { "ok": True, "answer": choice, diff --git a/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py b/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py index debcf3a868..0049a812ca 100644 --- a/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py +++ b/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py @@ -275,7 +275,9 @@ def test_a_choice_the_card_doesnt_offer_changes_nothing(queue): # noqa: F811 disp, _db, _keychain = queue raw = _write_card("second_factor") (card,) = _cards(disp) - result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "continue"}) + result = disp.dispatch( + "answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "continue"} + ) assert result["ok"] is False and result["code"] == "choice_not_offered" assert not _answer_file(raw).exists() @@ -308,7 +310,11 @@ def test_a_cancelled_prompt_writes_nothing(queue, enclave): # noqa: F811 assert not _answer_file(raw).exists() -def test_a_card_answered_elsewhere_during_the_prompt_is_not_overwritten(queue, enclave, monkeypatch): # noqa: F811 +def test_a_card_answered_elsewhere_during_the_prompt_is_not_overwritten( + queue, # noqa: F811 + enclave, # noqa: F811 + monkeypatch, +): disp, _db, _keychain = queue raw = _write_card() (card,) = _cards(disp) diff --git a/packages/flow/openadapt_flow/exceptions/cli.py b/packages/flow/openadapt_flow/exceptions/cli.py index 88e68a0c62..c3760ea35e 100644 --- a/packages/flow/openadapt_flow/exceptions/cli.py +++ b/packages/flow/openadapt_flow/exceptions/cli.py @@ -155,13 +155,17 @@ def cmd_list(args: argparse.Namespace) -> int: def cmd_answer(args: argparse.Namespace) -> int: from openadapt_types.exception_card import ExceptionAnswerV1, answer_message - from openadapt_flow.execute.keys import sign_bytes from openadapt_flow.exceptions.registry import ( ExceptionRegistryError, parse_time, roster_verifier, ) - from openadapt_flow.jit.authority import AuthorityError, load_encrypted_key, public_hex + from openadapt_flow.execute.keys import sign_bytes + from openadapt_flow.jit.authority import ( + AuthorityError, + load_encrypted_key, + public_hex, + ) def refuse(code: str, message: str) -> int: if args.json: diff --git a/packages/flow/tests/test_exception_registry.py b/packages/flow/tests/test_exception_registry.py index d5f7a4101a..dca361cadc 100644 --- a/packages/flow/tests/test_exception_registry.py +++ b/packages/flow/tests/test_exception_registry.py @@ -9,6 +9,8 @@ import json import os import stat +import struct +import zlib from datetime import datetime, timedelta, timezone from pathlib import Path @@ -47,11 +49,19 @@ "mail maribel@example.test" ) -PNG = ( - b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02" - b"\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00" - b"\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82" -) +def _png_1x1() -> bytes: + """A valid one-pixel RGB PNG, built without an imaging library.""" + + def chunk(tag: bytes, data: bytes) -> bytes: + body = tag + data + return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) + + header = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0) + pixels = zlib.compress(b"\x00\xff\xff\xff") + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", pixels) + chunk(b"IEND", b"") + + +PNG = _png_1x1() class FakeScrubber: @@ -165,7 +175,8 @@ def test_the_summary_is_scrubbed_and_cut(registry): for planted in PLANTED: assert planted.encode() not in blob assert b"" in blob - assert card.task_id == "T-[number]" + # A token holding four or more digits is masked whole. + assert card.task_id == "[number]" def test_without_a_scrubber_the_card_says_only_the_kinds_own_words(registry): From c5198f0f6e2bae39dc915d9e0c814f8dfe3dafb8 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:07:59 -0500 Subject: [PATCH 04/11] chore(desktop): move the exception cards to #2492 Only #2492 bumps Desktop to 0.31.0, so the stop queue's exception cards, their tests and their changelog line now land there. This pull request touches no packages/desktop file. --- packages/desktop/CHANGELOG.md | 12 - .../desktop/openadapt_desktop/__init__.py | 2 +- .../desktop/openadapt_desktop/dispatch.py | 71 +--- .../openadapt_desktop/exception_queue.py | 304 -------------- .../openadapt_desktop/portal/shell/stops.js | 10 +- .../desktop/openadapt_desktop/stop_queue.py | 197 +-------- packages/desktop/package-lock.json | 4 +- packages/desktop/package.json | 2 +- packages/desktop/pyproject.toml | 2 +- packages/desktop/src-tauri/Cargo.lock | 2 +- packages/desktop/src-tauri/Cargo.toml | 2 +- packages/desktop/src-tauri/tauri.conf.json | 2 +- packages/desktop/tests/conftest.py | 3 - .../test_engine/test_stop_queue_exceptions.py | 384 ------------------ packages/desktop/uv.lock | 2 +- 15 files changed, 15 insertions(+), 984 deletions(-) delete mode 100644 packages/desktop/openadapt_desktop/exception_queue.py delete mode 100644 packages/desktop/tests/test_engine/test_stop_queue_exceptions.py diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index 381e2caf13..9916a41b8d 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,18 +1,6 @@ # CHANGELOG -## v0.31.0 (2026-11-21) - -### Features - -- **desktop**: The stop queue now lists exception cards from any run on this - computer that asked a person (a one-time code prompt, an unexpected dialog, - a sign-in partway through, a stall, a possible duplicate, an ambiguous - record, a task it can't finish), not only Desktop's own runs. Each card is - answered on its own, here or on a paired phone, and the answer is signed - with the same approver key as other stop answers. - - ## v0.30.6 (2026-11-19) ### Bug Fixes diff --git a/packages/desktop/openadapt_desktop/__init__.py b/packages/desktop/openadapt_desktop/__init__.py index f30ef439c1..c5dd5310f4 100644 --- a/packages/desktop/openadapt_desktop/__init__.py +++ b/packages/desktop/openadapt_desktop/__init__.py @@ -21,4 +21,4 @@ +-- backends/ Storage backend plugins """ -__version__ = "0.31.0" +__version__ = "0.30.6" diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index e11168d63c..2c72ea20d8 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -81,7 +81,7 @@ #: Stop cards a paired phone may answer through Desktop. A waiting save is #: answered through the portal's own save approval; turning "only ask about #: problems" back on is answered on the computer. -PHONE_ANSWERABLE_KINDS = frozenset({"same_record", "confirm_save", "halted", "exception"}) +PHONE_ANSWERABLE_KINDS = frozenset({"same_record", "confirm_save", "halted"}) _TEACH_CORRECTION_SCHEMA = "openadapt.desktop-teach-correction/v1" _TEACH_CORRECTION_META_KEY = "teach_correction" @@ -4519,14 +4519,6 @@ def _stop_cards(self) -> list[dict]: card = stop_queue.card_for_rearm(switch) if card is not None: cards.append(card) - # Any run on this computer that asked a person (CLI guard, wrap, - # flight, hooks), not only Desktop's own runs. - from openadapt_desktop import exception_queue - - for raw in exception_queue.open_cards(): - card = stop_queue.card_for_exception(raw) - if card is not None: - cards.append(card) return stop_queue.sort_cards(cards) def _rearm_offer(self, workflow_id: str) -> dict | None: @@ -4849,8 +4841,6 @@ def _answer_stop_cards( } if choice_id == "leave": return {"ok": True, "results": [], "changed": 0} - if any(card["kind"] == stop_queue.EXCEPTION_KIND for card in cards): - return self._answer_exception(cards, choice_id, sign=sign, device=device) if any(card["kind"] == "rearm_problems_only" for card in cards): if len(cards) != 1 or device is not None: return { @@ -4921,65 +4911,6 @@ def _answer_stop_cards( ), } - def _answer_exception( - self, - cards: list[dict], - choice_id: str, - *, - sign: Callable[..., dict], - device: dict[str, str] | None, - ) -> dict: - """Answer one exception card: sign it and write the run's answer file.""" - - from openadapt_desktop import exception_queue, stop_queue - from openadapt_desktop.approver_keychain import ApproverKeychainError - - if len(cards) != 1: - return { - "ok": False, - "code": "answer_one_by_one", - "error": "Each of these stops is answered on its own. Nothing changed.", - } - card = cards[0] - try: - outcome = exception_queue.answer( - card["source"], - choice_id, - sign=sign, - route="desktop" if device is None else "portal", - ) - except ApproverKeychainError as exc: - return {"ok": False, "code": exc.code, "error": str(exc)} - if not outcome.get("ok"): - return { - "ok": False, - "code": outcome.get("code"), - "error": f"{outcome.get('error')} Nothing changed.", - } - self._record_stop_decision( - { - "schema": stop_queue.DECISION_SCHEMA, - "card_ids": [card["card_id"]], - "kinds": [stop_queue.EXCEPTION_KIND], - "choice": choice_id, - "decided_at": outcome["decided_at"], - "opened_at": outcome["opened_at"], - "public_key": outcome["public_key"], - "signature": outcome["signature"], - "key": outcome.get("key"), - "results": [{"card_id": card["card_id"], "ok": True}], - **({"device": device} if device is not None else {}), - } - ) - self.services.audit.log( - "exception_answered", kind=card.get("exception_kind"), choice=choice_id - ) - return { - "ok": True, - "results": [{"card_id": card["card_id"], "ok": True, "error": None}], - "changed": 1, - } - def _answer_rearm(self, card: dict, *, shown_ms: Any) -> dict: """Turn a task's switch back on with one Touch ID. diff --git a/packages/desktop/openadapt_desktop/exception_queue.py b/packages/desktop/openadapt_desktop/exception_queue.py deleted file mode 100644 index 020203307b..0000000000 --- a/packages/desktop/openadapt_desktop/exception_queue.py +++ /dev/null @@ -1,304 +0,0 @@ -"""Exception cards from any agent's run, in the stop queue. - -Flow's exception registry (``openadapt-flow exceptions``) keeps one folder per -run under ``$OPENADAPT_HOME/exceptions`` (``~/.openadapt/exceptions`` by -default). A run that hits a second-factor prompt, an unexpected dialog, a -sign-in page mid-task, a stall, a possible duplicate, a record it can't tell -apart, or a task it can't finish writes a ``card-.json`` and waits for an -``answer-.json``. Cards come from any run on this computer: a CLI guard, -``openadapt wrap``, a flight recorder, a hook, a Desktop-launched run. - -Desktop pins an exact Flow release, so this module reads the files as plain -JSON and checks them itself: the schema id, the closed kind and answer sets, -the card id (the digest of the card), a regular 0600-style file under the -size cap. A card that fails any check isn't shown. - -An answer is the closed answer signed with the approver key Desktop already -uses for the stop queue (Touch ID on a Mac, the portal's key for a phone). -The waiting run checks the signature against its pinned approver roster, so -an answer Desktop writes counts only when that key is on the roster. The -answer file records ``opened_at`` and ``decided_at``: how long a person held -the run. - -Nothing here is sent anywhere. -""" - -from __future__ import annotations - -import hashlib -import json -import os -import re -import stat -import uuid -from collections.abc import Callable -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - -CARD_SCHEMA = "openadapt.exception-card/v1" -ANSWER_SCHEMA = "openadapt.exception-answer/v1" -#: The bytes an approver key signs before the canonical answer. Flow's -#: ``openadapt_types.exception_card.EXCEPTION_ANSWER_DOMAIN``. -ANSWER_DOMAIN = b"openadapt.exception-answer/v1\x00" -KINDS = frozenset( - { - "second_factor", - "unexpected_dialog", - "session_expired", - "timeout_or_stall", - "possible_duplicate", - "ambiguous_record", - "cannot_complete", - } -) -ANSWERS = frozenset({"continue", "skip", "decline", "done_by_person", "abort"}) -#: How many cards one scan reads at most. -MAX_CARDS = 200 -_MAX_BYTES = 256 * 1024 -_RUN_REF = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$") -_CARD_FILE = re.compile(r"^card-([0-9a-f]{64})\.json$") -_SUMMARY_MAX = 200 - - -def _canonical(value: Any) -> bytes: - return json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") - - -def registry_root() -> Path: - home = os.environ.get("OPENADAPT_HOME") - return (Path(home) if home else Path.home() / ".openadapt") / "exceptions" - - -def _read(path: Path) -> bytes | None: - flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) - try: - fd = os.open(path, flags) - except OSError: - return None - try: - info = os.fstat(fd) - if not stat.S_ISREG(info.st_mode) or info.st_size > _MAX_BYTES: - return None - if hasattr(os, "getuid") and info.st_uid != os.getuid(): - return None - return os.read(fd, _MAX_BYTES + 1)[:_MAX_BYTES] - finally: - os.close(fd) - - -def _time(value: Any) -> bool: - try: - parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00")) - except ValueError: - return False - return parsed.tzinfo is not None - - -def valid_card(raw: Any, *, run_ref: str, file_hex: str) -> dict[str, Any] | None: - """The card when every field checks out, else ``None``.""" - - if not isinstance(raw, dict) or raw.get("schema") != CARD_SCHEMA: - return None - if raw.get("kind") not in KINDS or raw.get("run_ref") != run_ref: - return None - body = {k: v for k, v in raw.items() if k != "card_id"} - digest = "sha256:" + hashlib.sha256(_canonical(body)).hexdigest() - if raw.get("card_id") != digest or digest != f"sha256:{file_hex}": - return None - if not (_time(raw.get("opened_at")) and _time(raw.get("deadline_at"))): - return None - summary = raw.get("summary") - if not isinstance(summary, str) or not summary or len(summary) > _SUMMARY_MAX: - return None - choices = raw.get("choices") - if not isinstance(choices, list) or not choices: - return None - ids = [c.get("id") if isinstance(c, dict) else None for c in choices] - if any(i not in ANSWERS for i in ids) or len(set(ids)) != len(ids): - return None - task_id = raw.get("task_id") - if task_id is not None and (not isinstance(task_id, str) or len(task_id) > 128): - return None - return raw - - -def open_cards(root: Path | None = None) -> list[dict[str, Any]]: - """Every valid card with no answer yet, oldest first.""" - - base = root if root is not None else registry_root() - try: - folders = sorted(p for p in base.iterdir() if _RUN_REF.fullmatch(p.name)) - except OSError: - return [] - cards: list[dict[str, Any]] = [] - for folder in folders: - try: - if stat.S_ISLNK(os.lstat(folder).st_mode) or not folder.is_dir(): - continue - names = sorted(os.listdir(folder)) - except OSError: - continue - for name in names: - match = _CARD_FILE.fullmatch(name) - if match is None: - continue - if (folder / f"answer-{match.group(1)}.json").exists(): - continue - data = _read(folder / name) - if data is None: - continue - try: - raw = json.loads(data) - except ValueError: - continue - card = valid_card(raw, run_ref=folder.name, file_hex=match.group(1)) - if card is not None: - cards.append(card) - if len(cards) >= MAX_CARDS: - break - return sorted(cards, key=lambda c: str(c.get("opened_at"))) - - -def find_card(card_id: str, run_ref: str, root: Path | None = None) -> dict[str, Any] | None: - """The card, still unanswered and unchanged, or ``None``.""" - - return next( - ( - c - for c in open_cards(root) - if c.get("card_id") == card_id and c.get("run_ref") == run_ref - ), - None, - ) - - -def unsigned_answer(card: dict[str, Any], answer: str, *, route: str, decided_at: str) -> dict: - """The answer the approver key signs (Flow's ``ExceptionAnswerV1`` fields).""" - - if answer not in ANSWERS or route not in {"desktop", "portal"}: - raise ValueError("not an answer") - return { - "schema": ANSWER_SCHEMA, - "card_id": card["card_id"], - "kind": card["kind"], - "opened_at": card["opened_at"], - "decided_at": decided_at, - "answer": answer, - "approver_kind": "person", - "route": route, - "reason": None, - } - - -def message(unsigned: dict[str, Any]) -> bytes: - """The exact bytes the approver key signs.""" - - return ANSWER_DOMAIN + _canonical(unsigned) - - -def _write_exclusive(path: Path, payload: bytes) -> None: - tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") - flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) - fd = os.open(tmp, flags, 0o600) - try: - view = memoryview(payload) - while view: - view = view[os.write(fd, view) :] - os.fsync(fd) - finally: - os.close(fd) - try: - os.link(tmp, path) - finally: - try: - os.unlink(tmp) - except OSError: - pass - - -def answer( - source: dict[str, Any], - choice: str, - *, - sign: Callable[..., dict], - route: str, - root: Path | None = None, - now: Callable[[], datetime] = lambda: datetime.now(timezone.utc), -) -> dict[str, Any]: - """Sign and write one card's answer. Returns ``{"ok", ...}``. - - ``source`` is the queue card's ``source`` (the Flow card id and run). - The Flow card is read again before signing and again before writing: one - answered, changed or gone in between changes nothing. Raises the - signer's own error (``ApproverKeychainError``) for the caller to report. - """ - - base = root if root is not None else registry_root() - card_id, run_ref = str(source.get("id") or ""), str(source.get("run_ref") or "") - card = find_card(card_id, run_ref, base) - if card is None: - return {"ok": False, "code": "card_changed", "error": "The stop was answered or is gone."} - if choice not in {c.get("id") for c in card["choices"]}: - return { - "ok": False, - "code": "choice_not_offered", - "error": "That choice isn't on this stop.", - } - decided = now().astimezone(timezone.utc).isoformat().replace("+00:00", "Z") - if _after(decided, card["deadline_at"]): - return {"ok": False, "code": "card_expired", "error": "The stop expired."} - unsigned = unsigned_answer(card, choice, route=route, decided_at=decided) - signature = sign(message(unsigned), count=1) - if find_card(card_id, run_ref, base) is None: - return {"ok": False, "code": "card_changed", "error": "The stop was answered or is gone."} - record = { - **unsigned, - "public_key": signature["public_key"], - "signature": signature["signature"], - } - path = base / run_ref / f"answer-{card_id.removeprefix('sha256:')}.json" - try: - _write_exclusive(path, (json.dumps(record, sort_keys=True, indent=2) + "\n").encode()) - except FileExistsError: - return {"ok": False, "code": "card_changed", "error": "The stop was answered first."} - except OSError: - return { - "ok": False, - "code": "registry_unwritable", - "error": "Desktop couldn't save the answer.", - } - return { - "ok": True, - "answer": choice, - "decided_at": decided, - "opened_at": card["opened_at"], - "key": signature.get("key"), - "public_key": signature["public_key"], - "signature": signature["signature"], - } - - -def _after(a: str, b: str) -> bool: - try: - return datetime.fromisoformat(a.replace("Z", "+00:00")) > datetime.fromisoformat( - str(b).replace("Z", "+00:00") - ) - except ValueError: - return True - - -__all__ = [ - "ANSWERS", - "ANSWER_DOMAIN", - "ANSWER_SCHEMA", - "CARD_SCHEMA", - "KINDS", - "answer", - "find_card", - "message", - "open_cards", - "registry_root", - "unsigned_answer", - "valid_card", -] diff --git a/packages/desktop/openadapt_desktop/portal/shell/stops.js b/packages/desktop/openadapt_desktop/portal/shell/stops.js index 725e4d2ed6..a916569954 100644 --- a/packages/desktop/openadapt_desktop/portal/shell/stops.js +++ b/packages/desktop/openadapt_desktop/portal/shell/stops.js @@ -8,12 +8,6 @@ // choice the stop doesn't offer, changes nothing, and this page shows the // refusal as it came. // -// An exception card is any agent's run asking a person (a one-time code -// prompt, a dialog in the way, a sign-in partway through, a stall, a -// possible duplicate, an ambiguous record, a task it can't finish). It shows -// the run's scrubbed summary and its closed choices, and is answered on its -// own. A one-time code is typed in the live browser, never here. -// // Answers are signed on the computer with the decision portal's approver // key. Two kinds of stop are view-only here: a waiting save is answered on // the Decisions page (the portal's own save approval), and turning "only ask @@ -25,7 +19,7 @@ const POLL_MS = 10000; const MAX_BATCH = 25; -const PHONE_KINDS = new Set(["same_record", "confirm_save", "halted", "exception"]); +const PHONE_KINDS = new Set(["same_record", "confirm_save", "halted"]); const store = window.sessionStorage; const state = { @@ -443,7 +437,7 @@ function render() { className: "stops-warn", text: "Answers from this phone need the decision portal's approver key. Set it up on the computer. Until then, nothing here changes.", }), - card.kind === "exception" ? null : evidence(card), + evidence(card), choices(card), batchBlock(card), ]), diff --git a/packages/desktop/openadapt_desktop/stop_queue.py b/packages/desktop/openadapt_desktop/stop_queue.py index 5606f05bbb..f51438331f 100644 --- a/packages/desktop/openadapt_desktop/stop_queue.py +++ b/packages/desktop/openadapt_desktop/stop_queue.py @@ -24,12 +24,6 @@ first, so every answer names a registered approver. * ``rearm_problems_only``: a task whose "only ask about problems" switch went off, when a signed re-arm is available. -* ``exception``: a card any agent's run opened in Flow's exception registry - (a one-time code prompt, an unexpected dialog, a sign-in mid-task, a stall, - a possible duplicate, an ambiguous record, a task it can't finish). The - answer is the closed answer, signed with the approver key and written as - the card's answer file (:mod:`openadapt_desktop.exception_queue`); the - waiting run checks the signature itself. Similar cards share a ``batch_key``. A batch is answered with one choice and one signature, and each card in it is still checked on its own. @@ -495,179 +489,6 @@ def card_for_rearm(switch: dict) -> dict[str, Any] | None: return _seal(card) -# -- exception cards ------------------------------------------------------------- - -#: Per kind: the question, and the closed answers with what each one does. -#: Desktop shows its own words for each answer, and only answers the run's -#: own card offers. -_EXCEPTION_QUESTIONS = { - "second_factor": "The app wants a one-time code", - "unexpected_dialog": "A dialog is in the way", - "session_expired": "The app signed out partway through", - "timeout_or_stall": "The run has stalled", - "possible_duplicate": "Is this record already in the app?", - "ambiguous_record": "Which record is it?", - "cannot_complete": "The run can't finish this item", -} - -_EXCEPTION_SKIP = Choice( - "skip", "Skip this item", "Nothing is saved. The run moves to the next item.", "exception:skip" -) -_EXCEPTION_ABORT = Choice( - "abort", "Stop the run", "Nothing more is saved. The whole run stops.", "exception:abort" -) - -_EXCEPTION_CHOICES: dict[str, tuple[Choice, ...]] = { - "second_factor": ( - Choice( - "done_by_person", - "I entered the code in the browser", - "You type the code in the live browser yourself, then the run goes on. " - "OpenAdapt never sees the code.", - "exception:done_by_person", - ), - _EXCEPTION_SKIP, - _EXCEPTION_ABORT, - ), - "unexpected_dialog": ( - Choice( - "done_by_person", - "I dealt with the dialog", - "You close or answer it yourself, then the run goes on.", - "exception:done_by_person", - ), - Choice( - "continue", - "It's harmless, go on", - "The run goes on with the dialog as it is. Every check still runs.", - "exception:continue", - ), - _EXCEPTION_SKIP, - _EXCEPTION_ABORT, - ), - "session_expired": ( - Choice( - "done_by_person", - "I signed in again", - "You sign in yourself in the live browser, then the run goes on. " - "OpenAdapt never sees the password.", - "exception:done_by_person", - ), - _EXCEPTION_SKIP, - _EXCEPTION_ABORT, - ), - "timeout_or_stall": ( - Choice( - "continue", - "Keep waiting", - "The run tries the step again, with every check.", - "exception:continue", - ), - _EXCEPTION_SKIP, - _EXCEPTION_ABORT, - ), - "possible_duplicate": ( - Choice( - "skip", - "Same record: don't add it", - "Nothing is saved. The item closes as skipped.", - "exception:skip", - ), - Choice( - "continue", - "Different record: go on", - "The run goes on to fill the form. The save still needs every check.", - "exception:continue", - ), - Choice( - "done_by_person", - "I'll do this one by hand", - "OpenAdapt saves nothing. The item closes as done by a person.", - "exception:done_by_person", - ), - _EXCEPTION_ABORT, - ), - "ambiguous_record": ( - Choice( - "done_by_person", - "I opened the right record", - "You open the right record yourself, then the run goes on from there.", - "exception:done_by_person", - ), - _EXCEPTION_SKIP, - Choice( - "decline", - "This item shouldn't be done", - "Nothing is saved. The item closes as declined.", - "exception:decline", - ), - ), - "cannot_complete": ( - Choice( - "done_by_person", - "I did it by hand", - "OpenAdapt saves nothing. The item closes as done by a person.", - "exception:done_by_person", - ), - _EXCEPTION_SKIP, - _EXCEPTION_ABORT, - ), -} - -#: Card kinds that are exception cards (one card kind, many exception kinds). -EXCEPTION_KIND = "exception" - - -def card_for_exception(raw: dict) -> dict[str, Any] | None: - """A card from Flow's exception registry as a queue card, or None. - - ``raw`` is a card :func:`openadapt_desktop.exception_queue.open_cards` - already checked. Its summary was scrubbed by the run before it was - written. Each exception is answered on its own: no batch. - """ - - kind = raw.get("kind") if isinstance(raw, dict) else None - table = _EXCEPTION_CHOICES.get(str(kind)) - if table is None: - return None - offered = {c.get("id") for c in raw.get("choices") or [] if isinstance(c, dict)} - choices = [c for c in table if c.id in offered] - if not choices: - return None - card = { - "schema": CARD_SCHEMA, - "kind": EXCEPTION_KIND, - "exception_kind": kind, - "source": { - "type": "exception", - "id": raw["card_id"], - "run_ref": raw["run_ref"], - }, - "workflow_id": "", - "task_name": str(raw.get("task_id") or raw["run_ref"]), - "label": "", - "question": _EXCEPTION_QUESTIONS[str(kind)], - "summary": str(raw.get("summary") or ""), - "evidence": { - "source": [], - "record": [], - "differences": [], - "candidates": [], - "reason": "", - "step": "", - "expected": "", - "observed": "", - "screenshot": None, - }, - "choices": [c.public() for c in [*choices, _LEAVE]], - "expires_at": raw.get("deadline_at"), - "created_at": raw.get("opened_at"), - "batch_key": None, - "status": "waiting", - } - return _seal(card) - - def choice_for(card: dict, choice_id: str) -> Choice | None: """The full choice behind a card's button, or None if it doesn't offer it.""" @@ -679,9 +500,6 @@ def choice_for(card: dict, choice_id: str) -> Choice | None: return next((c for c in _APPROVAL_CHOICES if c.id == choice_id), None) if card["kind"] == "rearm_problems_only": return Choice("rearm", "", "", "rearm") if choice_id == "rearm" else None - if card["kind"] == EXCEPTION_KIND: - table = _EXCEPTION_CHOICES.get(str(card.get("exception_kind")), ()) - return next((c for c in table if c.id == choice_id), None) table = _ITEM_CHOICES.get(card["kind"], {}) return next((c for c in table.values() if c.id == choice_id), None) @@ -713,16 +531,9 @@ def decision_message(card_ids: Iterable[str], choice_id: str, *, decided_at: str def sort_cards(cards: list[dict]) -> list[dict]: - """Waiting saves and exceptions first (they expire), then the oldest stop.""" - - # A run holding on an exception waits with a deadline, like a save. - order = { - "approve_save": 0, - EXCEPTION_KIND: 0, - "confirm_save": 1, - "same_record": 2, - "halted": 3, - } + """Waiting saves first (they expire), then the oldest stop first.""" + + order = {"approve_save": 0, "confirm_save": 1, "same_record": 2, "halted": 3} return sorted( cards, key=lambda c: (order.get(c["kind"], 4), str(c.get("created_at") or "")), @@ -733,12 +544,10 @@ def sort_cards(cards: list[dict]) -> list[dict]: "CARD_SCHEMA", "DECISION_DOMAIN", "DECISION_SCHEMA", - "EXCEPTION_KIND", "MAX_BATCH", "RECORD_CHECK_ACTIONS", "Choice", "card_for_approval", - "card_for_exception", "card_for_item", "card_for_rearm", "choice_for", diff --git a/packages/desktop/package-lock.json b/packages/desktop/package-lock.json index 88c85f2015..3fa77186e8 100644 --- a/packages/desktop/package-lock.json +++ b/packages/desktop/package-lock.json @@ -1,12 +1,12 @@ { "name": "openadapt-desktop", - "version": "0.31.0", + "version": "0.30.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openadapt-desktop", - "version": "0.31.0", + "version": "0.30.6", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-notification": "^2", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 1b92b8568c..2922cf9315 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "openadapt-desktop", - "version": "0.31.0", + "version": "0.30.6", "description": "Installed companion for OpenAdapt authoring, teaching, and local pairing", "private": true, "type": "module", diff --git a/packages/desktop/pyproject.toml b/packages/desktop/pyproject.toml index 84d122859c..bd1d994ee7 100644 --- a/packages/desktop/pyproject.toml +++ b/packages/desktop/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "openadapt-desktop" -version = "0.31.0" +version = "0.30.6" description = "The OpenAdapt desktop app and local engine: record a data-entry task, run it on a list, and check each saved record" readme = "README.md" requires-python = ">=3.11" diff --git a/packages/desktop/src-tauri/Cargo.lock b/packages/desktop/src-tauri/Cargo.lock index 98cf6ea65f..111ec12503 100644 --- a/packages/desktop/src-tauri/Cargo.lock +++ b/packages/desktop/src-tauri/Cargo.lock @@ -2513,7 +2513,7 @@ dependencies = [ [[package]] name = "openadapt-desktop" -version = "0.31.0" +version = "0.30.6" dependencies = [ "hex", "reqwest", diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml index e8c03f006a..80279fdaab 100644 --- a/packages/desktop/src-tauri/Cargo.toml +++ b/packages/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "openadapt-desktop" -version = "0.31.0" +version = "0.30.6" description = "Installed companion for OpenAdapt authoring, teaching, and local pairing" authors = ["OpenAdapt AI"] license = "MIT" diff --git a/packages/desktop/src-tauri/tauri.conf.json b/packages/desktop/src-tauri/tauri.conf.json index aa17f4b35d..ede2e28594 100644 --- a/packages/desktop/src-tauri/tauri.conf.json +++ b/packages/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://raw.githubusercontent.com/nicoverbruggen/tauri-v2-schema/main/schema.json", "productName": "OpenAdapt Desktop", - "version": "0.31.0", + "version": "0.30.6", "identifier": "ai.openadapt.desktop", "build": { "frontendDist": "../dist", diff --git a/packages/desktop/tests/conftest.py b/packages/desktop/tests/conftest.py index e8a4208cd3..cdfb7ce65c 100644 --- a/packages/desktop/tests/conftest.py +++ b/packages/desktop/tests/conftest.py @@ -151,9 +151,6 @@ def _isolated_flow_at_rest(tmp_path_factory, monkeypatch): monkeypatch.setenv("OPENADAPT_FLOW_AT_REST_HOME", str(tmp_path_factory.mktemp("at-rest-home"))) monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "test suite: synthetic data") monkeypatch.delenv("OPENADAPT_FLOW_AT_REST", raising=False) - # The stop queue also lists Flow's exception registry under - # OPENADAPT_HOME; keep a developer's real cards out of every test. - monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path_factory.mktemp("openadapt-home"))) @pytest.fixture(autouse=True) diff --git a/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py b/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py deleted file mode 100644 index 0049a812ca..0000000000 --- a/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py +++ /dev/null @@ -1,384 +0,0 @@ -"""Exception cards from any agent's run, in the stop queue and on the phone. - -The cards are files in a temporary OPENADAPT_HOME, written as Flow's -exception registry writes them (the committed Flow fixture is the contract). -Answers are signed with the fake Secure Enclave's approver key, or the -portal's key for the phone. Synthetic data only. -""" - -from __future__ import annotations - -import hashlib -import json -import os -import stat -import threading -from datetime import datetime, timedelta, timezone -from pathlib import Path - -import pytest -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey - -from openadapt_desktop import exception_queue, stop_queue -from openadapt_desktop.portal.stops import DispatcherStopQueue -from tests.test_engine.test_stop_queue import ( # noqa: F401 (fixtures) - enclave, - queue, -) -from tests.test_engine.test_stop_queue_portal import ( # noqa: F401 (fixtures) - _app, - _paired, - portal_key, -) - -FLOW_FIXTURE = ( - Path(__file__).resolve().parents[3] - / "flow" - / "tests" - / "fixtures" - / "exception_card_second_factor.json" -) -CHOICES = { - "second_factor": ["done_by_person", "skip", "abort"], - "unexpected_dialog": ["done_by_person", "continue", "skip", "abort"], - "session_expired": ["done_by_person", "skip", "abort"], - "timeout_or_stall": ["continue", "skip", "abort"], - "possible_duplicate": ["skip", "continue", "done_by_person", "abort"], - "ambiguous_record": ["done_by_person", "skip", "decline"], - "cannot_complete": ["done_by_person", "skip", "abort"], -} - - -def _canonical(value) -> bytes: - return json.dumps(value, sort_keys=True, separators=(",", ":")).encode() - - -def _iso(value: datetime) -> str: - return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") - - -def _write_card( - kind: str = "second_factor", - *, - run_ref: str = "guard-run", - minutes: int = 15, - summary: str = "The app is asking for a one-time code.", -) -> dict: - opened = datetime.now(timezone.utc) - body = { - "schema": "openadapt.exception-card/v1", - "run_ref": run_ref, - "task_id": "intake", - "kind": kind, - "opened_at": _iso(opened), - "deadline_at": _iso(opened + timedelta(minutes=minutes)), - "screenshot_ref": None, - "summary": summary, - "choices": [ - {"id": answer, "label": answer.replace("_", " "), "consequence": "As the run says."} - for answer in CHOICES[kind] - ], - } - card = {**body, "card_id": "sha256:" + hashlib.sha256(_canonical(body)).hexdigest()} - folder = exception_queue.registry_root() / run_ref - folder.mkdir(parents=True, exist_ok=True) - path = folder / f"card-{card['card_id'][7:]}.json" - path.write_text(json.dumps(card, indent=2)) - path.chmod(0o600) - return card - - -def _cards(disp) -> list[dict]: - listed = disp.dispatch("list_stop_cards", {}) - assert listed["ok"] is True - return [c for c in listed["cards"] if c["kind"] == stop_queue.EXCEPTION_KIND] - - -def _answer_file(card: dict) -> Path: - return ( - exception_queue.registry_root() - / card["run_ref"] - / f"answer-{card['card_id'][7:]}.json" - ) - - -# -- the cards ------------------------------------------------------------------------ - - -def test_flows_own_card_file_is_listed(): - if not FLOW_FIXTURE.is_file(): - pytest.skip("Flow's fixture isn't in this checkout") - raw = json.loads(FLOW_FIXTURE.read_text()) - folder = exception_queue.registry_root() / raw["run_ref"] - folder.mkdir(parents=True) - path = folder / f"card-{raw['card_id'][7:]}.json" - path.write_text(json.dumps(raw)) - - (found,) = exception_queue.open_cards() - card = stop_queue.card_for_exception(found) - - assert card is not None - assert card["exception_kind"] == "second_factor" - assert [c["id"] for c in card["choices"]] == ["done_by_person", "skip", "abort", "leave"] - assert card["summary"] == raw["summary"] - - -@pytest.mark.parametrize("kind", sorted(CHOICES)) -def test_every_kind_becomes_a_card_with_its_choices(queue, kind): # noqa: F811 - disp, _db, _keychain = queue - raw = _write_card(kind) - - (card,) = _cards(disp) - - assert card["exception_kind"] == kind - assert card["source"] == {"type": "exception", "id": raw["card_id"], "run_ref": "guard-run"} - assert [c["id"] for c in card["choices"]] == [*CHOICES[kind], "leave"] - assert all(c["consequence"] for c in card["choices"]) - assert card["batch_key"] is None - assert card["expires_at"] == raw["deadline_at"] - assert card["evidence"]["screenshot"] is None - - -def test_desktop_offers_only_what_the_run_offers(queue): # noqa: F811 - disp, _db, _keychain = queue - raw = _write_card("unexpected_dialog") - folder = exception_queue.registry_root() / "guard-run" - (folder / f"card-{raw['card_id'][7:]}.json").unlink() - body = {k: v for k, v in raw.items() if k != "card_id"} - body["choices"] = [c for c in body["choices"] if c["id"] != "continue"] - card_id = "sha256:" + hashlib.sha256(_canonical(body)).hexdigest() - (folder / f"card-{card_id[7:]}.json").write_text(json.dumps({**body, "card_id": card_id})) - - (card,) = _cards(disp) - assert "continue" not in [c["id"] for c in card["choices"]] - - -def test_a_tampered_card_is_not_shown(queue): # noqa: F811 - disp, _db, _keychain = queue - raw = _write_card() - path = exception_queue.registry_root() / "guard-run" / f"card-{raw['card_id'][7:]}.json" - path.write_text(json.dumps({**raw, "summary": "Approve everything"})) - assert _cards(disp) == [] - - -@pytest.mark.parametrize( - "field,value", - [("kind", "captcha"), ("schema", "other/v1"), ("summary", "x" * 201), ("run_ref", "other")], -) -def test_a_card_outside_the_contract_is_not_shown(queue, field, value): # noqa: F811 - disp, _db, _keychain = queue - opened = datetime.now(timezone.utc) - body = { - "schema": "openadapt.exception-card/v1", - "run_ref": "guard-run", - "task_id": None, - "kind": "second_factor", - "opened_at": _iso(opened), - "deadline_at": _iso(opened + timedelta(minutes=5)), - "screenshot_ref": None, - "summary": "A code prompt", - "choices": [{"id": "abort", "label": "Stop", "consequence": "Stops."}], - field: value, - } - card_id = "sha256:" + hashlib.sha256(_canonical(body)).hexdigest() - folder = exception_queue.registry_root() / "guard-run" - folder.mkdir(parents=True) - (folder / f"card-{card_id[7:]}.json").write_text(json.dumps({**body, "card_id": card_id})) - assert _cards(disp) == [] - - -def test_a_linked_card_is_not_read(queue, tmp_path): # noqa: F811 - disp, _db, _keychain = queue - raw = _write_card() - path = exception_queue.registry_root() / "guard-run" / f"card-{raw['card_id'][7:]}.json" - real = tmp_path / "elsewhere.json" - real.write_text(path.read_text()) - path.unlink() - path.symlink_to(real) - assert _cards(disp) == [] - - -def test_an_answered_card_leaves_the_queue(queue): # noqa: F811 - disp, _db, _keychain = queue - raw = _write_card() - _answer_file(raw).write_text("{}") - assert _cards(disp) == [] - - -def test_exception_cards_sort_with_waiting_saves(queue): # noqa: F811 - cards = stop_queue.sort_cards( - [ - {"kind": "halted", "created_at": "2026-01-01"}, - {"kind": stop_queue.EXCEPTION_KIND, "created_at": "2026-02-01"}, - ] - ) - assert cards[0]["kind"] == stop_queue.EXCEPTION_KIND - - -def test_a_broken_registry_never_hides_the_other_stops(queue, monkeypatch): # noqa: F811 - disp, _db, _keychain = queue - exception_queue.registry_root().mkdir(parents=True) - (exception_queue.registry_root() / "guard-run").write_text("not a folder") - assert disp.dispatch("list_stop_cards", {})["ok"] is True - - -# -- answers from the window -------------------------------------------------------- - - -def test_the_window_signs_and_writes_the_runs_answer(queue, enclave): # noqa: F811 - disp, _db, keychain = queue - raw = _write_card() - (card,) = _cards(disp) - - result = disp.dispatch( - "answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "done_by_person"} - ) - - assert result["ok"] is True and result["changed"] == 1 - assert len(enclave.prompts) == 1 - path = _answer_file(raw) - assert stat.S_IMODE(path.stat().st_mode) == 0o600 - answer = json.loads(path.read_text()) - assert answer["answer"] == "done_by_person" - assert answer["approver_kind"] == "person" and answer["route"] == "desktop" - assert answer["opened_at"] == raw["opened_at"] and answer["decided_at"] - assert answer["public_key"] == keychain.stored().public_key - unsigned = {k: v for k, v in answer.items() if k not in {"signature", "public_key"}} - Ed25519PublicKey.from_public_bytes(bytes.fromhex(answer["public_key"])).verify( - bytes.fromhex(answer["signature"].removeprefix("ed25519:")), - exception_queue.ANSWER_DOMAIN + _canonical(unsigned), - ) - assert _cards(disp) == [] - (receipt,) = [ - json.loads(line) - for line in (disp.config.data_dir / "stop_decisions.jsonl").read_text().splitlines() - ] - assert receipt["kinds"] == ["exception"] - assert receipt["opened_at"] == raw["opened_at"] and receipt["decided_at"] - - -def test_the_answer_file_matches_flows_answer_contract(queue, enclave): # noqa: F811 - """Flow's ExceptionAnswerV1 accepts what Desktop writes, when it's importable.""" - - types = pytest.importorskip("openadapt_types.exception_card") - disp, _db, _keychain = queue - raw = _write_card() - (card,) = _cards(disp) - disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "skip"}) - answer = types.ExceptionAnswerV1.model_validate(json.loads(_answer_file(raw).read_text())) - assert types.answer_message(answer.wire()) == exception_queue.message( - {k: v for k, v in answer.wire().items() if k not in {"signature", "public_key"}} - ) - - -def test_a_choice_the_card_doesnt_offer_changes_nothing(queue): # noqa: F811 - disp, _db, _keychain = queue - raw = _write_card("second_factor") - (card,) = _cards(disp) - result = disp.dispatch( - "answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "continue"} - ) - assert result["ok"] is False and result["code"] == "choice_not_offered" - assert not _answer_file(raw).exists() - - -def test_leave_changes_nothing(queue, enclave): # noqa: F811 - disp, _db, _keychain = queue - raw = _write_card() - (card,) = _cards(disp) - result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "leave"}) - assert result["ok"] is True and result["changed"] == 0 - assert not _answer_file(raw).exists() and enclave.prompts == [] - - -def test_an_expired_card_changes_nothing(queue): # noqa: F811 - disp, _db, _keychain = queue - raw = _write_card(minutes=-1) - (card,) = _cards(disp) - result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "abort"}) - assert result["ok"] is False - assert not _answer_file(raw).exists() - - -def test_a_cancelled_prompt_writes_nothing(queue, enclave): # noqa: F811 - disp, _db, _keychain = queue - raw = _write_card() - (card,) = _cards(disp) - enclave.answer = "cancel" - result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "abort"}) - assert result["ok"] is False and result["code"] == "approver_presence_refused" - assert not _answer_file(raw).exists() - - -def test_a_card_answered_elsewhere_during_the_prompt_is_not_overwritten( - queue, # noqa: F811 - enclave, # noqa: F811 - monkeypatch, -): - disp, _db, _keychain = queue - raw = _write_card() - (card,) = _cards(disp) - original = disp._sign_stop_decision - - def sign_while_the_cli_answers(message, *, count): - _answer_file(raw).write_text('{"answered": "elsewhere"}') - return original(message, count=count) - - monkeypatch.setattr(disp, "_sign_stop_decision", sign_while_the_cli_answers) - result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "abort"}) - assert result["ok"] is False and result["code"] == "card_changed" - assert json.loads(_answer_file(raw).read_text()) == {"answered": "elsewhere"} - - -def test_two_exception_cards_are_never_one_batch(queue): # noqa: F811 - disp, _db, _keychain = queue - _write_card(run_ref="run-a") - _write_card(run_ref="run-b") - ids = [c["card_id"] for c in _cards(disp)] - result = disp.dispatch("answer_stop_cards", {"card_ids": ids, "choice": "abort"}) - assert result["ok"] is False - assert not list(exception_queue.registry_root().rglob("answer-*.json")) - - -# -- answers from the paired phone --------------------------------------------------- - - -def test_the_phone_answers_with_the_portal_key(queue, portal_key, enclave): # noqa: F811 - disp, _db, _keychain = queue - disp.serial_lock = threading.RLock() - raw = _write_card("possible_duplicate") - app, pairings = _app(DispatcherStopQueue(disp)) - headers = _paired(pairings) - - status, _h, body = app.handle("GET", "/api/portal/stops", headers, b"") - (card,) = [c for c in json.loads(body)["cards"] if c["kind"] == "exception"] - status, _h, body = app.handle( - "POST", - f"/api/portal/stops/{card['card_id'].removeprefix('sha256:')}/answer", - headers, - json.dumps({"choice": "skip", "shown_ms": 900}).encode(), - ) - - assert status == 200 and json.loads(body)["ok"] is True - assert enclave.prompts == [] - answer = json.loads(_answer_file(raw).read_text()) - assert answer["route"] == "portal" and answer["answer"] == "skip" - assert answer["public_key"] == portal_key.public_key - - -def test_the_phone_page_knows_the_exception_cards(): - script = ( - Path(__file__).resolve().parents[2] - / "openadapt_desktop" - / "portal" - / "shell" - / "stops.js" - ).read_text() - assert '"exception"' in script - assert "const MAX_BATCH = 25;" in script - assert stop_queue.MAX_BATCH == 25 - - -def test_no_registry_folder_is_an_empty_list(tmp_path): - assert exception_queue.open_cards(tmp_path / "missing") == [] - assert os.environ["OPENADAPT_HOME"] diff --git a/packages/desktop/uv.lock b/packages/desktop/uv.lock index 97ac5c27f7..2f82f650e6 100644 --- a/packages/desktop/uv.lock +++ b/packages/desktop/uv.lock @@ -1172,7 +1172,7 @@ wheels = [ [[package]] name = "openadapt-desktop" -version = "0.31.0" +version = "0.30.6" source = { editable = "." } dependencies = [ { name = "cryptography" }, From 1f14cb60f0d215f67e76bcafd489dd4b0ffe26ab Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:30:22 -0500 Subject: [PATCH 05/11] test(flow): the off-roster answer test no longer races the card's expiry Under load the card's 3-second deadline passed before the answer command started, so the roster check never ran. The card now waits 600 seconds; the test checks the stranger's answer is refused with nothing written, then a rostered person answers abort to end the run. --- .../flow/tests/e2e/test_exception_mcp_e2e.py | 88 +++++++++++++++---- 1 file changed, 69 insertions(+), 19 deletions(-) diff --git a/packages/flow/tests/e2e/test_exception_mcp_e2e.py b/packages/flow/tests/e2e/test_exception_mcp_e2e.py index 737dcbc912..e6bb30e265 100644 --- a/packages/flow/tests/e2e/test_exception_mcp_e2e.py +++ b/packages/flow/tests/e2e/test_exception_mcp_e2e.py @@ -133,7 +133,12 @@ def env(tmp_path: Path) -> dict[str, str]: key_dir = tmp_path / "keys" key = Ed25519PrivateKey.generate() - init_root(key_dir, principal="front-desk", public_key=public_hex(key), sign=file_key_signer(key)) + init_root( + key_dir, + principal="front-desk", + public_key=public_hex(key), + sign=file_key_signer(key), + ) pem = tmp_path / "approver.pem" pem.write_bytes( key.private_bytes( @@ -198,15 +203,28 @@ def _desktop_cards(env: dict[str, str]) -> list[dict[str, Any]] | None: sys.path.insert(0, str(DESKTOP)) from openadapt_desktop import exception_queue, stop_queue - cards = [stop_queue.card_for_exception(raw) for raw in exception_queue.open_cards(_registry(env))] + cards = [ + stop_queue.card_for_exception(raw) + for raw in exception_queue.open_cards(_registry(env)) + ] return [c for c in cards if c is not None] -def _answer(env: dict[str, str], card_id: str, choice: str) -> subprocess.CompletedProcess: +def _answer( + env: dict[str, str], card_id: str, choice: str +) -> subprocess.CompletedProcess: return subprocess.run( [ - sys.executable, "-m", "openadapt_flow", "exceptions", "answer", card_id, choice, - "--key", env["OPENADAPT_TEST_KEY_PEM"], "--json", + sys.executable, + "-m", + "openadapt_flow", + "exceptions", + "answer", + card_id, + choice, + "--key", + env["OPENADAPT_TEST_KEY_PEM"], + "--json", ], env=env, capture_output=True, @@ -221,9 +239,16 @@ async def _agent(base: str, env: dict[str, str], deadline_s: float) -> dict[str, params = StdioServerParameters( command=sys.executable, args=[ - "-m", "openadapt_flow", "exceptions", "serve", - "--run-ref", "e2e-run", "--task-id", "note-intake", - "--deadline-s", str(deadline_s), + "-m", + "openadapt_flow", + "exceptions", + "serve", + "--run-ref", + "e2e-run", + "--task-id", + "note-intake", + "--deadline-s", + str(deadline_s), ], env=env, ) @@ -247,13 +272,17 @@ async def _agent(base: str, env: dict[str, str], deadline_s: float) -> dict[str, return log # stop before any write continue if "Save" in page: - await anyio.to_thread.run_sync(_post, base + "/save", {"note": "synthetic note"}) + await anyio.to_thread.run_sync( + _post, base + "/save", {"note": "synthetic note"} + ) log["wrote"] = True return log return log -def _run_agent(base: str, env: dict[str, str], deadline_s: float, person: Callable[[], None]): +def _run_agent( + base: str, env: dict[str, str], deadline_s: float, person: Callable[[], None] +): result: dict[str, Any] = {} def agent() -> None: @@ -296,7 +325,12 @@ def person() -> None: (desktop_card,) = seen["desktop"] assert desktop_card["exception_kind"] == "second_factor" assert desktop_card["source"]["id"] == seen["card"]["card_id"] - assert [c["id"] for c in desktop_card["choices"]] == ["done_by_person", "skip", "abort", "leave"] + assert [c["id"] for c in desktop_card["choices"]] == [ + "done_by_person", + "skip", + "abort", + "leave", + ] _no_planted(json.dumps(desktop_card).encode()) (asked,) = log["asked"] assert asked["answer"] == "done_by_person" and asked["proceed"] is True @@ -346,7 +380,9 @@ def person() -> None: assert record["approver_kind"] == "expiry" and record["decided_at"] is None -def test_an_answer_from_a_key_off_the_roster_is_refused_and_nothing_is_written(app, env, tmp_path): +def test_an_answer_from_a_key_off_the_roster_is_refused_and_nothing_is_written( + app, env, tmp_path +): base, state = app stranger = tmp_path / "stranger.pem" stranger.write_bytes( @@ -356,16 +392,30 @@ def test_an_answer_from_a_key_off_the_roster_is_refused_and_nothing_is_written(a serialization.BestAvailableEncryption(PASSPHRASE.encode()), ) ) + seen: dict[str, Any] = {} def person() -> None: card = _wait_for_card(env) - forged = _answer({**env, "OPENADAPT_TEST_KEY_PEM": str(stranger)}, card["card_id"], "done_by_person") - assert forged.returncode == 2 - assert "human_approver_unregistered" in forged.stdout - # nobody else answers: the card expires + forged = _answer( + {**env, "OPENADAPT_TEST_KEY_PEM": str(stranger)}, + card["card_id"], + "done_by_person", + ) + seen["forged"] = forged + # Refused before anything is written: the card is still open, so the + # run never saw an answer from the stranger. + seen["answers_after_forged"] = list(_registry(env).rglob("answer-*.json")) + # A rostered person then stops the run (not an expiry race: the card's + # deadline is long enough that a loaded machine can't expire it first). + done = _answer(env, card["card_id"], "abort") + assert done.returncode == 0, done.stderr - log = _run_agent(base, env, 3, person) + log = _run_agent(base, env, 600, person) + + assert seen["forged"].returncode == 2, seen["forged"].stderr + assert "human_approver_unregistered" in seen["forged"].stdout + assert seen["answers_after_forged"] == [] (asked,) = log["asked"] - assert asked["proceed"] is False + assert asked["proceed"] is False and asked["answer"] == "abort" + assert log["wrote"] is False assert json.loads(_get(base + "/api/records")) == [] - From aeffa2583f97fc40fa465275180c6d9068c4be3e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:30:23 -0500 Subject: [PATCH 06/11] feat(flow): exceptions watch raises cards without the agent raise_exception only works when the agent calls it. openadapt-flow exceptions watch attaches to the agent's Chromium over CDP (the endpoint the guard uses), reads the page with geometry every half second, runs the detectors and opens the card itself. While a card is open it blocks every save the page sends, using the guard's own classify() and the guard.yaml not_saves, so a person can still submit a code form listed there. A verified continue or done_by_person lifts the hold; any other outcome blocks every later save and the watch exits 3. Chromium hands a paused request to each DevTools session in turn, so the watch and the guard compose in either attach order. Covered: second_factor, unexpected_dialog, session_expired (after a save) and, with --stall-s, timeout_or_stall. Not covered: possible_duplicate, ambiguous_record, cannot_complete, non-browser agents, WebSocket saves, and a run with no watch. The registry gains poll(), one non-blocking look that wait() now loops on. The exception package's files are formatted to the CI ruff config. --- CAPABILITIES.md | 4 +- llms-full.txt | 4 +- packages/flow/docs/EXCEPTION_QUEUE.md | 62 ++- .../commands/03-run-and-answer/exceptions.md | 2 +- .../openadapt_flow/exceptions/__init__.py | 4 +- .../flow/openadapt_flow/exceptions/cli.py | 143 +++++- .../openadapt_flow/exceptions/detectors.py | 31 +- .../openadapt_flow/exceptions/mcp_server.py | 15 +- .../openadapt_flow/exceptions/registry.py | 86 +++- .../flow/openadapt_flow/exceptions/watch.py | 422 ++++++++++++++++++ .../tests/e2e/test_exception_watch_e2e.py | 268 +++++++++++ .../flow/tests/test_exception_detectors.py | 63 ++- .../flow/tests/test_exception_registry.py | 145 ++++-- packages/flow/tests/test_exception_watch.py | 253 +++++++++++ 14 files changed, 1417 insertions(+), 85 deletions(-) create mode 100644 packages/flow/openadapt_flow/exceptions/watch.py create mode 100644 packages/flow/tests/e2e/test_exception_watch_e2e.py create mode 100644 packages/flow/tests/test_exception_watch.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index c35c678f0f..b1fdc61bd8 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -213,7 +213,7 @@ improvising or retrying when something is off. | Admit once, then stop only on problems | Released ([#1212](https://github.com/OpenAdaptAI/OpenAdapt/pull/1212)), behind a readiness gate | Synthetic | [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md) | | Show the field values a save writes on the phone | Released ([#1257](https://github.com/OpenAdaptAI/OpenAdapt/pull/1257)) | Unit tests | `console/save_approvals.py` | | Show why an agent asked for a save: who asked, its own reason (as a quote), the screen text it saw, and any of that text that reads like an instruction to an agent | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359)) | Unit tests, synthetic | `ApprovalProvenance` in `approval_mode/item_approval.py`; the phone card in openadapt-desktop `portal/shell` | -| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, cards from any run in Desktop's stop queue and on a paired phone, and detectors that say when to ask. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The tool can't make an agent that ignores it stop. The share of cases that need a person is unmeasured | On main | Unit tests and a synthetic end-to-end test (a scripted agent on a one-time-code page over real MCP stdio: one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state) | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md), openadapt-desktop `exception_queue.py` | +| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, detectors that say when to ask, and `exceptions watch`, which reads a Chromium agent's page over CDP, raises `second_factor`, `unexpected_dialog`, `session_expired` and (opt-in) `timeout_or_stall` cards without the agent, and blocks the page's saves while a card is open. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The MCP tool can't make an agent that ignores it stop; the watch doesn't cover non-browser agents, WebSocket saves, `possible_duplicate`, or a run with no watch running. Cards in Desktop's stop queue and on a paired phone ship with openadapt-desktop 0.31.0 in [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492). The share of cases that need a person is unmeasured | In PR [#2494](https://github.com/OpenAdaptAI/OpenAdapt/pull/2494) | Unit tests and synthetic end-to-end tests: a scripted agent on a one-time-code page over real MCP stdio (one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state); and, in headless Chromium on MockMed with the guard attached, an agent that never calls the tool hits a synthetic code prompt, the watch raises the card and blocks its save, and after `done_by_person` one save lands and reads back VERIFIED | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md) | ## Branching work, not one linear path @@ -421,7 +421,7 @@ A test fails when a command has no file or this list is out of date. - `business-decisions` - `console` - `deferred` -- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md). +- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md). - `explain` - `item-approval` - `replay` diff --git a/llms-full.txt b/llms-full.txt index 9ea473a5f5..a298a1e3fa 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -653,7 +653,7 @@ improvising or retrying when something is off. | Admit once, then stop only on problems | Released ([#1212](https://github.com/OpenAdaptAI/OpenAdapt/pull/1212)), behind a readiness gate | Synthetic | [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md) | | Show the field values a save writes on the phone | Released ([#1257](https://github.com/OpenAdaptAI/OpenAdapt/pull/1257)) | Unit tests | `console/save_approvals.py` | | Show why an agent asked for a save: who asked, its own reason (as a quote), the screen text it saw, and any of that text that reads like an instruction to an agent | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359)) | Unit tests, synthetic | `ApprovalProvenance` in `approval_mode/item_approval.py`; the phone card in openadapt-desktop `portal/shell` | -| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, cards from any run in Desktop's stop queue and on a paired phone, and detectors that say when to ask. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The tool can't make an agent that ignores it stop. The share of cases that need a person is unmeasured | On main | Unit tests and a synthetic end-to-end test (a scripted agent on a one-time-code page over real MCP stdio: one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state) | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EXCEPTION_QUEUE.md), openadapt-desktop `exception_queue.py` | +| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, detectors that say when to ask, and `exceptions watch`, which reads a Chromium agent's page over CDP, raises `second_factor`, `unexpected_dialog`, `session_expired` and (opt-in) `timeout_or_stall` cards without the agent, and blocks the page's saves while a card is open. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The MCP tool can't make an agent that ignores it stop; the watch doesn't cover non-browser agents, WebSocket saves, `possible_duplicate`, or a run with no watch running. Cards in Desktop's stop queue and on a paired phone ship with openadapt-desktop 0.31.0 in [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492). The share of cases that need a person is unmeasured | In PR [#2494](https://github.com/OpenAdaptAI/OpenAdapt/pull/2494) | Unit tests and synthetic end-to-end tests: a scripted agent on a one-time-code page over real MCP stdio (one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state); and, in headless Chromium on MockMed with the guard attached, an agent that never calls the tool hits a synthetic code prompt, the watch raises the card and blocks its save, and after `done_by_person` one save lands and reads back VERIFIED | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EXCEPTION_QUEUE.md) | ## Branching work, not one linear path @@ -861,7 +861,7 @@ A test fails when a command has no file or this list is out of date. - `business-decisions` - `console` - `deferred` -- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EXCEPTION_QUEUE.md). +- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EXCEPTION_QUEUE.md). - `explain` - `item-approval` - `replay` diff --git a/packages/flow/docs/EXCEPTION_QUEUE.md b/packages/flow/docs/EXCEPTION_QUEUE.md index 0aa92775be..ffadabac27 100644 --- a/packages/flow/docs/EXCEPTION_QUEUE.md +++ b/packages/flow/docs/EXCEPTION_QUEUE.md @@ -54,8 +54,60 @@ The tool opens a card and blocks until a person answers or the card expires Go on only when `proceed` is `true`. Otherwise stop and write nothing. The tool can tell an agent to stop. It can't make an agent that ignores the -result stop. To hold an agent at the boundary whatever it does, run it under a -guard (`openadapt-flow guard`) or `openadapt wrap`. +result stop, and an agent that never calls it never asks anyone. For a browser +agent, run the watch below: it raises cards without the agent and holds its +saves. + +## Without the agent: the browser watch + +```bash +openadapt-flow exceptions watch --cdp http://127.0.0.1:9222 \ + --config guard.yaml --run-dir runs/intake-0412 +``` + +`watch` attaches to the agent's Chromium over CDP, the same endpoint +`openadapt-flow guard` attaches to, and reads the guard's `guard.yaml` for the +app's origin and its `not_saves`. Every half second (`--poll-s`) it reads the +page (its inputs, dialogs and text, with their positions) and runs the +detectors. When one fires, it opens a card itself, with the kind's own +sentence as the summary: nothing from the page goes on the card. + +While the card is open, the watch blocks every save the page sends, whatever +the agent does. The page gets a `409` with an `X-OpenAdapt-Exception` header, +and nothing reaches the app. A save is what the guard calls one: a write to +the app's origin that `not_saves` doesn't list, or a write to another origin. +Reads go through, and so does a write `not_saves` lists, so list the form a +person submits a code or a sign-in with, and they can do it in the live +browser. A verified `continue` or `done_by_person` lifts the hold. Any other +outcome (a stop answer, an expiry, an answer off the roster) blocks every +later save for the rest of the run, and the watch exits 3. + +The watch and the guard each pause requests in their own DevTools session. +Chromium hands a paused request to each session in turn, so a save the watch +blocks is never sent, whichever of the two attached first. + +The run's folder in the registry is `--run-ref`, or else the `--run-dir` +folder's name. `--run-dir` also gets `exceptions_watch.jsonl`: each card +opened, each answer and each blocked save, with no values. + +What the watch sees and raises: + +| Kind | Raised by the watch | +| --- | --- | +| `second_factor` | Yes | +| `unexpected_dialog` | Yes. The watch can't tell a dialog the task expects (a confirm box) from one it doesn't, so it asks about both | +| `session_expired` | Yes, once the watch has seen a save | +| `timeout_or_stall` | Only with `--stall-s N`: no request and no screen change for N seconds | +| `possible_duplicate` | No: it needs a read of the app's records | +| `ambiguous_record`, `cannot_complete` | No: only the agent knows | + +Not covered: agents that don't drive a Chromium, saves over a WebSocket (CDP +`Fetch` doesn't see them), and a run with no watch running. The watch is not a +sandbox: an agent with another way to reach the app, or that stops the watch, +gets past it. Tested in headless Chromium on MockMed with the guard attached: +an agent that never calls the tool hits a synthetic code prompt, its save is +blocked while the card is open, and after `done_by_person` its next save +lands once and reads back VERIFIED. ## For a person: answering @@ -74,7 +126,8 @@ answer the waiting run wouldn't accept. Desktop lists every open card from every run on the computer in its stop queue, beside the saves and stops of its own runs, and shows each one on a -paired phone. An answer from Desktop is signed with the same approver key as +paired phone. (Desktop's part ships with openadapt-desktop 0.31.0, in +[#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492).) An answer from Desktop is signed with the same approver key as its other stop answers (Touch ID on a Mac). An answer from the phone is signed with the decision portal's key. Exception cards are answered one at a time, never in a batch. @@ -152,5 +205,6 @@ nothing and name no app. A caller passes in what it already saw. type the code through the existing second-factor handoff, so the agent never sees it. - `raise_exception` on the `openadapt wrap -- COMMAND` MCP surface. -- Calling the detectors from the flight gate and the guard's observe path. +- Calling the detectors from the flight gate (`openadapt-flow flight`). The + browser watch covers a Chromium agent, with or without the guard. - A Cloud intake for exception cards and web push. diff --git a/packages/flow/docs/commands/03-run-and-answer/exceptions.md b/packages/flow/docs/commands/03-run-and-answer/exceptions.md index 9e8714809f..001a2e5dbb 100644 --- a/packages/flow/docs/commands/03-run-and-answer/exceptions.md +++ b/packages/flow/docs/commands/03-run-and-answer/exceptions.md @@ -1 +1 @@ -Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md). +Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md). diff --git a/packages/flow/openadapt_flow/exceptions/__init__.py b/packages/flow/openadapt_flow/exceptions/__init__.py index 3417b5770c..f8252d0f62 100644 --- a/packages/flow/openadapt_flow/exceptions/__init__.py +++ b/packages/flow/openadapt_flow/exceptions/__init__.py @@ -4,7 +4,9 @@ - :mod:`.registry`: the local file protocol (cards, answers, expiry, consume). - :mod:`.detectors`: pure checks that say when to ask (no app names). - :mod:`.mcp_server`: the ``raise_exception`` MCP tool. -- :mod:`.cli`: ``openadapt-flow exceptions serve|list|answer``. +- :mod:`.watch`: raise cards from a browser agent's page without the agent, + and block its saves while one is open. +- :mod:`.cli`: ``openadapt-flow exceptions serve|watch|list|answer``. The schemas live in :mod:`openadapt_types.exception_card`. See ``docs/EXCEPTION_QUEUE.md``. diff --git a/packages/flow/openadapt_flow/exceptions/cli.py b/packages/flow/openadapt_flow/exceptions/cli.py index c3760ea35e..804bd4f383 100644 --- a/packages/flow/openadapt_flow/exceptions/cli.py +++ b/packages/flow/openadapt_flow/exceptions/cli.py @@ -1,7 +1,8 @@ -"""CLI: ``openadapt-flow exceptions serve|list|answer``. See +"""CLI: ``openadapt-flow exceptions serve|watch|list|answer``. See ``docs/EXCEPTION_QUEUE.md``. openadapt-flow exceptions serve --run-ref intake-0412 + openadapt-flow exceptions watch --cdp http://127.0.0.1:9222 --config guard.yaml openadapt-flow exceptions list openadapt-flow exceptions answer sha256:… done_by_person @@ -31,7 +32,9 @@ def _common(p: argparse.ArgumentParser) -> None: def _roster(p: argparse.ArgumentParser) -> None: - p.add_argument("--key-dir", help="the approver roster's folder (default: ~/.openadapt/jit)") + p.add_argument( + "--key-dir", help="the approver roster's folder (default: ~/.openadapt/jit)" + ) p.add_argument( "--approver-root", help="the roster's root public key (default: OPENADAPT_APPROVER_ROOT)", @@ -64,7 +67,46 @@ def register(sub: argparse._SubParsersAction) -> None: _common(s) s.set_defaults(func=cmd_serve) - ls = ops.add_parser("list", allow_abbrev=False, help="Show cards waiting for a person") + w = ops.add_parser( + "watch", + allow_abbrev=False, + help="Watch the agent's Chromium, raise cards without the agent, and " + "block its saves while a card is open", + ) + w.add_argument("--cdp", required=True, help="the agent's DevTools endpoint") + w.add_argument( + "--config", + required=True, + help="the guard's guard.yaml: the app's origin and its not_saves", + ) + w.add_argument("--page-url", help="watch the tab whose URL starts with this") + w.add_argument( + "--run-dir", + help="write exceptions_watch.jsonl here (the guard's --out)", + ) + w.add_argument( + "--run-ref", + help="this run's folder name in the registry (default: --run-dir's " + "name, else a new one)", + ) + w.add_argument("--task-id", help="the task the cards belong to") + w.add_argument("--deadline-s", type=float, default=None, help="default 900") + w.add_argument( + "--stall-s", + type=float, + default=None, + help="raise timeout_or_stall after this long with no request and no " + "screen change (default: off)", + ) + w.add_argument("--poll-s", type=float, default=0.5, help="look every N seconds") + w.add_argument("--max-s", type=float, default=None, help="stop after N seconds") + _roster(w) + _common(w) + w.set_defaults(func=cmd_watch) + + ls = ops.add_parser( + "list", allow_abbrev=False, help="Show cards waiting for a person" + ) ls.add_argument("--run-ref", help="only this run's cards") ls.add_argument("--json", action="store_true", help="print JSON") _common(ls) @@ -130,6 +172,93 @@ def cmd_serve(args: argparse.Namespace) -> int: return 0 +def _watch_run_ref(args: argparse.Namespace) -> str: + import re + + from openadapt_flow.exceptions.registry import RUN_REF_PATTERN + + if args.run_ref: + return str(args.run_ref) + name = Path(args.run_dir).name if args.run_dir else "" + if name and re.fullmatch(RUN_REF_PATTERN, name): + return name + return f"watch-{uuid.uuid4().hex[:16]}" + + +def cmd_watch(args: argparse.Namespace) -> int: + from openadapt_flow.agent_guard.config import ConfigError, load_config + from openadapt_flow.exceptions.registry import ( + DEFAULT_DEADLINE_S, + ExceptionRegistryError, + roster_verifier, + ) + from openadapt_flow.exceptions.watch import ( + WATCH_EVENTS, + ExceptionWatch, + watch_browser, + ) + + key_dir, root = _pin(args) + try: + cfg = load_config(args.config) + except ConfigError as exc: + print(f"exceptions: {getattr(exc, 'message', exc)}", file=sys.stderr) + return 2 + run_ref = _watch_run_ref(args) + try: + watch = ExceptionWatch( + _registry(args), + run_ref=run_ref, + verify=roster_verifier(key_dir, root), + app_origin=cfg.app_origin, + not_saves=cfg.not_saves, + task_id=args.task_id, + deadline_s=args.deadline_s or DEFAULT_DEADLINE_S, + stall_s=args.stall_s, + events_path=Path(args.run_dir) / WATCH_EVENTS if args.run_dir else None, + ) + except ExceptionRegistryError as exc: + print(f"exceptions: REFUSED ({exc.code}): {exc}", file=sys.stderr) + return 2 + import signal + + stopping: list[int] = [] + + def _stop(signum: int, _frame: object) -> None: + stopping.append(signum) # the loop ends; paused saves are decided first + + for signum in (signal.SIGINT, signal.SIGTERM): + signal.signal(signum, _stop) + try: + code = watch_browser( + watch, + cdp_endpoint=args.cdp, + page_url=args.page_url, + poll_s=args.poll_s, + max_s=args.max_s, + stop=lambda: bool(stopping), + on_attached=lambda: print( + f"exceptions: watching for run {run_ref}; saves are blocked " + "while a card is open", + file=sys.stderr, + flush=True, + ), + ) + except RuntimeError as exc: + print(f"exceptions: {exc}", file=sys.stderr) + return 2 + print( + json.dumps( + { + "run_ref": run_ref, + "stopped": watch.stopped, + "outcomes": [o.wire() for o in watch.outcomes], + } + ) + ) + return code + + def cmd_list(args: argparse.Namespace) -> int: from openadapt_flow.exceptions.registry import ExceptionRegistryError @@ -145,7 +274,9 @@ def cmd_list(args: argparse.Namespace) -> int: print("Nothing is waiting for a person.") return 0 for card in cards: - print(f"{card.card_id} {card.kind} run {card.run_ref} until {card.deadline_at}") + print( + f"{card.card_id} {card.kind} run {card.run_ref} until {card.deadline_at}" + ) print(f" {card.summary}") for choice in card.choices: print(f" - {choice.id}: {choice.label}. {choice.consequence}") @@ -175,7 +306,9 @@ def refuse(code: str, message: str) -> int: return 2 registry = _registry(args) - card_id = args.card_id if args.card_id.startswith("sha256:") else f"sha256:{args.card_id}" + card_id = ( + args.card_id if args.card_id.startswith("sha256:") else f"sha256:{args.card_id}" + ) try: found = registry.card(card_id) except ExceptionRegistryError as exc: diff --git a/packages/flow/openadapt_flow/exceptions/detectors.py b/packages/flow/openadapt_flow/exceptions/detectors.py index 0e7c868285..49afb81c04 100644 --- a/packages/flow/openadapt_flow/exceptions/detectors.py +++ b/packages/flow/openadapt_flow/exceptions/detectors.py @@ -78,7 +78,20 @@ DIALOG_ROLES = frozenset({"dialog", "alertdialog"}) _TEXT_INPUT_TYPES = frozenset({"", "text", "tel", "number", "search"}) _VOID = frozenset( - {"input", "br", "img", "meta", "link", "hr", "area", "base", "col", "embed", "source", "wbr"} + { + "input", + "br", + "img", + "meta", + "link", + "hr", + "area", + "base", + "col", + "embed", + "source", + "wbr", + } ) DEFAULT_STALL_S = 120.0 @@ -342,8 +355,12 @@ def detect_all(observation: Observation) -> list[str]: o = observation for kind in ( second_factor(o.elements, o.screen_text), - session_expired(o.elements, o.screen_text, save_eligible_seen=o.save_eligible_seen), - unexpected_dialog(o.elements, target=o.target, expected_dialog=o.expected_dialog), + session_expired( + o.elements, o.screen_text, save_eligible_seen=o.save_eligible_seen + ), + unexpected_dialog( + o.elements, target=o.target, expected_dialog=o.expected_dialog + ), None if o.now is None else timeout_or_stall( @@ -454,7 +471,9 @@ def elements_from_html(html: str) -> tuple[list[dict[str, Any]], str]: return parser.elements, " ".join(parser._text) -def elements_from_accessibility(nodes: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]: +def elements_from_accessibility( + nodes: Iterable[Mapping[str, Any]], +) -> list[dict[str, Any]]: """Accessibility nodes (``role``, ``name``, optional ``bbox``, ``modal``, ``protected``, ``autocomplete``) as detector elements.""" @@ -463,7 +482,9 @@ def elements_from_accessibility(nodes: Iterable[Mapping[str, Any]]) -> list[dict role = _s(node.get("role")) out.append( { - "tag": "input" if role in {"textbox", "textfield", "axtextfield"} else "", + "tag": "input" + if role in {"textbox", "textfield", "axtextfield"} + else "", "type": "password" if node.get("protected") is True else "text", "role": "textbox" if role in {"textfield", "axtextfield"} else role, "name": node.get("name", ""), diff --git a/packages/flow/openadapt_flow/exceptions/mcp_server.py b/packages/flow/openadapt_flow/exceptions/mcp_server.py index a94f512447..cd2b7c7825 100644 --- a/packages/flow/openadapt_flow/exceptions/mcp_server.py +++ b/packages/flow/openadapt_flow/exceptions/mcp_server.py @@ -104,7 +104,11 @@ def __call__( def _error(types: Any, error_field: str, code: str) -> Any: - body = {"error": code, "proceed": False, "instruction": "Stop now. Make no further writes for this task."} + body = { + "error": code, + "proceed": False, + "instruction": "Stop now. Make no further writes for this task.", + } return types.CallToolResult( content=[types.TextContent(type="text", text=json.dumps(body))], **{error_field: True}, @@ -210,4 +214,11 @@ async def run() -> None: anyio.run(run) -__all__ = ["DESCRIPTION", "INPUT_SCHEMA", "TOOL_NAME", "RaiseException", "build_server", "serve"] +__all__ = [ + "DESCRIPTION", + "INPUT_SCHEMA", + "TOOL_NAME", + "RaiseException", + "build_server", + "serve", +] diff --git a/packages/flow/openadapt_flow/exceptions/registry.py b/packages/flow/openadapt_flow/exceptions/registry.py index 1ef21f9ad9..92aad562db 100644 --- a/packages/flow/openadapt_flow/exceptions/registry.py +++ b/packages/flow/openadapt_flow/exceptions/registry.py @@ -69,7 +69,9 @@ def _c(answer: str, label: str, consequence: str) -> ExceptionChoice: return ExceptionChoice(id=answer, label=label, consequence=consequence) # type: ignore[arg-type] -_SKIP = _c("skip", "Skip this item", "Nothing is saved. The run moves to the next item.") +_SKIP = _c( + "skip", "Skip this item", "Nothing is saved. The run moves to the next item." +) _ABORT = _c("abort", "Stop the run", "Nothing more is saved. The whole run stops.") #: Each kind's choices, in the order a card shows them. The first is the @@ -502,9 +504,13 @@ def open( "choices": [c.model_dump(mode="json") for c in CHOICES[kind]], } for _attempt in range(3): - card = ExceptionCardV1.model_validate({**body, "card_id": card_digest(body)}) + card = ExceptionCardV1.model_validate( + {**body, "card_id": card_digest(body)} + ) try: - _write_exclusive(folder / f"card-{_hex(card.card_id)}.json", _json(card.wire())) + _write_exclusive( + folder / f"card-{_hex(card.card_id)}.json", _json(card.wire()) + ) return card except FileExistsError: opened = opened + timedelta(microseconds=1) @@ -514,7 +520,7 @@ def open( # -- reading ----------------------------------------------------------- - def _load(self, path: Path, model: type) -> Any: + def _load(self, path: Path, model: Any) -> Any: data = _read_regular(path) if data is None: return None @@ -572,7 +578,12 @@ def open_cards(self, run_ref: Optional[str] = None) -> list[ExceptionCardV1]: # -- answering --------------------------------------------------------- def unsigned_answer( - self, card: ExceptionCardV1, answer: str, *, route: str, now: Optional[datetime] = None + self, + card: ExceptionCardV1, + answer: str, + *, + route: str, + now: Optional[datetime] = None, ) -> dict[str, Any]: """The answer a person's key signs (no key or signature yet).""" @@ -592,16 +603,22 @@ def unsigned_answer( "reason": None, } - def write_answer(self, card: ExceptionCardV1, answer: Mapping[str, Any]) -> ExceptionAnswerV1: + def write_answer( + self, card: ExceptionCardV1, answer: Mapping[str, Any] + ) -> ExceptionAnswerV1: """Write the card's one answer. Raises ``ExceptionRegistryError``.""" model = ExceptionAnswerV1.model_validate(dict(answer)) if model.card_id != card.card_id or model.kind != card.kind: - raise ExceptionRegistryError("answer_mismatch", "the answer names another card") + raise ExceptionRegistryError( + "answer_mismatch", "the answer names another card" + ) folder = self.run_dir(card.run_ref) self._ensure(folder) try: - _write_exclusive(folder / f"answer-{_hex(card.card_id)}.json", _json(model.wire())) + _write_exclusive( + folder / f"answer-{_hex(card.card_id)}.json", _json(model.wire()) + ) except FileExistsError: raise ExceptionRegistryError( "already_answered", "this card already has an answer" @@ -675,6 +692,39 @@ def _settle( return _stop(card, "answer_already_used", outcome.answer) return outcome + def poll( + self, + card: ExceptionCardV1, + *, + verify: AnswerVerifier, + deadline: Optional[datetime] = None, + clock: Callable[[], datetime] = _now, + now: Optional[datetime] = None, + ) -> Optional[Outcome]: + """One look at the card: what to do once it is answered or expired, + ``None`` while it is still open. Never blocks; :meth:`wait` loops on + it, and a caller with its own loop (the browser watch) calls it.""" + + end = parse_time(card.deadline_at) + if deadline is not None: + end = min(end, deadline.astimezone(timezone.utc)) + for _attempt in range(3): + try: + answer = self.read_answer(card) + except (OSError, ValueError): + return _stop(card, "answer_unreadable") + if answer is not None: + return self._settle(card, answer, verify) + if (now if now is not None else clock()) < end: + return None + try: + self._expire(card) + except FileExistsError: + continue # a person's answer won the race: read it + except OSError: + return _stop(card, "expired") + return _stop(card, "answer_unreadable") + def wait( self, card: ExceptionCardV1, @@ -705,20 +755,14 @@ def wait( started = time.monotonic() while True: try: - answer = self.read_answer(card) + answered = self.read_answer(card) is not None except (OSError, ValueError): - return _stop(card, "answer_unreadable") - if answer is not None: - return self._settle(card, answer, verify) - now = clock() - if now >= end: - try: - self._expire(card) - except FileExistsError: - continue # a person's answer won the race: read it - except OSError: - return _stop(card, "expired") - continue + answered = True # poll() reports the unreadable answer + now = None if answered else clock() + outcome = self.poll(card, verify=verify, deadline=deadline, now=now) + if outcome is not None: + return outcome + assert now is not None elapsed = time.monotonic() - started if elapsed >= next_beat: beat(card.card_id, (end - now).total_seconds()) diff --git a/packages/flow/openadapt_flow/exceptions/watch.py b/packages/flow/openadapt_flow/exceptions/watch.py new file mode 100644 index 0000000000..f96c3ea8de --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/watch.py @@ -0,0 +1,422 @@ +"""Raise exception cards from the agent's browser, without the agent. + +``raise_exception`` (:mod:`.mcp_server`) only works when the agent calls it. +An agent that never calls it never asks anyone. :class:`ExceptionWatch` asks +on its own: it attaches to the agent's Chromium over CDP (the same endpoint +``openadapt-flow guard`` attaches to), looks at the page every ``poll_s``, +runs the :mod:`.detectors`, and when one fires it opens a card in the +registry. While the card is open it holds the run at the browser: every save +the page sends is blocked (CDP ``Fetch``), whatever the agent does. A verified +``continue`` or ``done_by_person`` lifts the hold. Any other outcome (a stop +answer, an expiry, an answer off the roster) keeps every later save blocked +for the rest of the run. + + openadapt-flow exceptions watch --cdp http://127.0.0.1:9222 \\ + --config guard.yaml --run-dir runs/intake-0412 + +What is a save comes from the guard's own config and rules +(:func:`openadapt_flow.agent_guard.requests.classify`): a write to the app's +origin that ``not_saves`` doesn't list, and any write to another origin. A +write ``not_saves`` lists (a sign-in form, the code form a person submits +for a second factor) goes through, so a person can type the code in the live +browser. Reads always go through. + +The watch and the guard each pause requests in their own DevTools session. +Chromium hands a paused request to each session in turn, so a save the +watch blocks is never sent, whichever attached first. + +Covered, from what the page shows: ``second_factor``, ``unexpected_dialog``, +``session_expired`` (a password field after the watch has seen a save) and, +with ``stall_s``, ``timeout_or_stall`` (no request and no screen change). +Not covered: ``possible_duplicate`` (it needs a read of the app's records), +``ambiguous_record`` and ``cannot_complete`` (only the agent knows), +non-browser agents, saves over a WebSocket (``Fetch`` doesn't see them), and +a run with no watch running. The watch is not a sandbox: it can't stop an +agent that has its own way to the app, or one that kills the watch. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections.abc import Callable, Mapping, Sequence +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Optional + +from openadapt_flow.exceptions.detectors import DEFAULT_STALL_S, Observation, detect_all +from openadapt_flow.exceptions.registry import ( + DEFAULT_DEADLINE_S, + AnswerVerifier, + ExceptionRegistry, + Outcome, +) + +__all__ = [ + "BLOCK_HEADER", + "SNAPSHOT_JS", + "WATCH_EVENTS", + "ExceptionWatch", + "watch_browser", +] + +#: The watch's log in the run folder: what it raised and blocked, no values. +WATCH_EVENTS = "exceptions_watch.jsonl" +#: Set on every response the watch makes up for a blocked save. +BLOCK_HEADER = "X-OpenAdapt-Exception" +_PAUSED_TYPES = ("Document", "XHR", "Fetch", "Ping", "Other") + +#: The page, as detector elements (see :mod:`.detectors`), with geometry. +SNAPSHOT_JS = r""" +() => { + const sel = 'input, textarea, select, button, dialog, [role], [aria-modal]'; + const out = []; + const text = (el) => ((el && (el.innerText || el.textContent)) || '').replace(/\s+/g, ' ').trim(); + for (const el of Array.from(document.querySelectorAll(sel)).slice(0, 500)) { + if (el.closest('[data-openadapt-guard]')) continue; + const r = el.getBoundingClientRect(); + const st = getComputedStyle(el); + const visible = r.width > 0 && r.height > 0 && st.visibility !== 'hidden' + && st.display !== 'none' && el.type !== 'hidden'; + let label = ''; + if (el.labels && el.labels.length) label = text(el.labels[0]); + const prev = el.previousElementSibling; + const parent = el.parentElement; + out.push({ + tag: el.tagName.toLowerCase(), + type: (el.getAttribute('type') || (el.tagName === 'INPUT' ? 'text' : '')).toLowerCase(), + role: el.getAttribute('role') || '', + id: el.id || '', + name: el.getAttribute('name') || '', + label: label.slice(0, 160), + aria_label: el.getAttribute('aria-label') || '', + placeholder: el.getAttribute('placeholder') || '', + autocomplete: el.getAttribute('autocomplete') || '', + inputmode: el.getAttribute('inputmode') || '', + pattern: el.getAttribute('pattern') || '', + maxlength: el.getAttribute('maxlength') || '', + context: (prev ? text(prev) : text(parent)).slice(-160), + visible: visible, + modal: el.getAttribute('aria-modal') === 'true' + || (el.tagName === 'DIALOG' && el.matches(':modal')), + open: el.tagName === 'DIALOG' ? el.open : false, + bbox: [r.x, r.y, r.width, r.height], + z: parseInt(st.zIndex, 10) || 0, + }); + } + return {text: text(document.body).slice(0, 20000), elements: out}; +} +""" + + +def _iso(value: datetime) -> str: + return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +class ExceptionWatch: + """The watch's decisions, without a browser (the loop is :func:`watch_browser`). + + ``observe`` takes one page snapshot (``{"text", "elements"}``) and opens + a card when a detector fires and none is open. ``on_request`` says + whether a paused request goes on (``None``) or is blocked (a code). + ``poll`` settles an open card without blocking. + """ + + def __init__( + self, + registry: ExceptionRegistry, + *, + run_ref: str, + verify: AnswerVerifier, + app_origin: str, + not_saves: Sequence[Any] = (), + task_id: Optional[str] = None, + deadline_s: float = DEFAULT_DEADLINE_S, + stall_s: Optional[float] = None, + events_path: Optional[Path] = None, + clock: Callable[[], float] = time.monotonic, + ) -> None: + from openadapt_flow.agent_guard.requests import origin_of + + registry.run_dir(run_ref) # refuse a bad name before anything runs + self.registry = registry + self.run_ref = run_ref + self.verify = verify + self.app_origin = origin_of(app_origin) or app_origin + self.not_saves = tuple(not_saves) + self.task_id = task_id + self.deadline_s = deadline_s + self.stall_s = stall_s + self.events_path = events_path + self._clock = clock + self.card: Any = None + #: Why every later save is blocked (a stop outcome), or None. + self.stopped: Optional[str] = None + self.outcomes: list[Outcome] = [] + #: Kinds answered "go on" that the page still shows: not asked again + #: until the page stops showing them. + self._settled: set[str] = set() + self._save_seen = False + self._screen: Optional[str] = None + self._last_change: Optional[float] = None + self._last_request: Optional[float] = None + self._log("watch_started", run_ref=run_ref) + + # -- the log ------------------------------------------------------------- + + def _log(self, event: str, **fields: Any) -> None: + if self.events_path is None: + return + line = {"t": round(self._clock(), 3), "event": event, **fields} + try: + self.events_path.parent.mkdir(parents=True, exist_ok=True) + with self.events_path.open("a", encoding="utf-8") as fh: + fh.write(json.dumps(line, sort_keys=True) + "\n") + except OSError: + pass # the log is lost, never the hold + + # -- decisions ----------------------------------------------------------- + + @property + def holding(self) -> bool: + """Saves are blocked right now.""" + + return self.card is not None or self.stopped is not None + + def on_request(self, request: Any) -> Optional[str]: + """``None``: let the paused request go on; else the block's code.""" + + from openadapt_flow.agent_guard.requests import classify + + self._last_request = self._clock() + kind = classify(request, app_origin=self.app_origin, not_saves=self.not_saves) + if kind == "save": + self._save_seen = True + if kind not in ("save", "other_origin") or not self.holding: + return None + code = "exception_open" if self.card is not None else "exception_stopped" + self._log( + "request_blocked", + code=code, + kind=kind, + method=request.method, + resource_type=request.resource_type, + ) + return code + + def observe(self, snapshot: Mapping[str, Any]) -> Optional[str]: + """Look at one snapshot; open a card when it calls for a person. + + Returns the kind of the card opened, or None. + """ + + now = self._clock() + text = str(snapshot.get("text") or "") + raw = snapshot.get("elements") + elements = ( + [e for e in raw if isinstance(e, Mapping)] if isinstance(raw, list) else [] + ) + digest = hashlib.sha256( + (text + json.dumps(elements, sort_keys=True, default=str)).encode("utf-8") + ).hexdigest() + if digest != self._screen: + self._screen, self._last_change = digest, now + kinds = detect_all( + Observation( + screen_text=text, + elements=elements, + save_eligible_seen=self._save_seen, + now=now if self.stall_s else None, + last_action_at=self._last_request, + last_change_at=self._last_change, + stall_s=self.stall_s or DEFAULT_STALL_S, + ) + ) + self._settled &= set(kinds) # a kind the page stopped showing may ask again + if self.holding: + return None + fresh = [k for k in kinds if k not in self._settled] + if not fresh: + return None + kind = fresh[0] + self.card = self.registry.open( + self.run_ref, + kind, + None, # the kind's own sentence: nothing from the page is relayed + task_id=self.task_id, + deadline_s=self.deadline_s, + ) + self._log("card_opened", kind=kind, card_id=self.card.card_id) + return kind + + def poll(self) -> Optional[Outcome]: + """Settle the open card if it was answered or expired.""" + + if self.card is None: + return None + outcome = self.registry.poll(self.card, verify=self.verify) + if outcome is None: + return None + self.outcomes.append(outcome) + self._log( + "answer", + card_id=outcome.card_id, + answer=outcome.answer, + proceed=outcome.proceed, + reason=outcome.reason, + ) + if outcome.proceed: + self._settled.add(outcome.kind) + else: + self.stopped = outcome.reason or outcome.answer + self.card = None + return outcome + + def stop_code(self) -> int: + """The watch's exit code: 0, or 3 when an answer stopped the run.""" + + return 3 if self.stopped is not None else 0 + + +# -- the browser loop ------------------------------------------------------------ + + +def _blocked_body(code: str) -> str: + import base64 + + message = ( + "OpenAdapt is holding this run: a person is answering an exception card. " + "Nothing was sent. Wait, then save again." + if code == "exception_open" + else "A person stopped this run. Nothing was sent; write nothing more." + ) + payload = json.dumps({"error": code, "message": message}) + return base64.b64encode(payload.encode("utf-8")).decode("ascii") + + +def _decide(cdp: Any, watch: ExceptionWatch, params: Mapping[str, Any]) -> None: + from openadapt_flow.agent_guard.requests import HeldRequest + + request_id = str(params.get("requestId") or "") + try: + code = watch.on_request(HeldRequest.from_cdp(params)) + except Exception: # noqa: BLE001 - the watch can't tell: block while holding + code = "exception_open" if watch.holding else None + if code is None: + cdp.send("Fetch.continueRequest", {"requestId": request_id}) + return + cdp.send( + "Fetch.fulfillRequest", + { + "requestId": request_id, + "responseCode": 409, + "responseHeaders": [ + {"name": "Content-Type", "value": "application/json"}, + {"name": BLOCK_HEADER, "value": f"blocked; code={code}"}, + ], + "body": _blocked_body(code), + }, + ) + + +def _page(browser: Any, app_origin: str, page_url: Optional[str]) -> Any: + from openadapt_flow.agent_guard.requests import origin_of + + for context in browser.contexts: + for page in context.pages: + url = page.url or "" + if page_url and url.startswith(page_url): + return page + if not page_url and origin_of(url) == app_origin: + return page + return None + + +def watch_browser( + watch: ExceptionWatch, + *, + cdp_endpoint: str, + page_url: Optional[str] = None, + poll_s: float = 0.5, + attach_wait_s: float = 30.0, + max_s: Optional[float] = None, + on_attached: Optional[Callable[[], None]] = None, + stop: Optional[Callable[[], bool]] = None, +) -> int: + """Attach to the agent's Chromium and run the watch until the tab or the + browser closes, ``max_s`` passes or ``stop()`` says so. Returns the exit + code (:meth:`ExceptionWatch.stop_code`).""" + + from playwright.sync_api import sync_playwright + + pw = sync_playwright().start() + try: + deadline = time.monotonic() + attach_wait_s + browser = page = None + while page is None: + try: + browser = pw.chromium.connect_over_cdp(cdp_endpoint) + page = _page(browser, watch.app_origin, page_url) + except Exception: # noqa: BLE001 - not up yet + page = None + if page is None: + if browser is not None: + browser.close() + browser = None + if time.monotonic() >= deadline: + raise RuntimeError("no tab on the app's origin to watch") + time.sleep(0.25) + cdp = page.context.new_cdp_session(page) + paused: list[Mapping[str, Any]] = [] + cdp.on("Fetch.requestPaused", lambda params: paused.append(params)) + cdp.send( + "Fetch.enable", + { + "patterns": [ + {"urlPattern": "*", "resourceType": t, "requestStage": "Request"} + for t in _PAUSED_TYPES + ] + }, + ) + if on_attached is not None: + on_attached() + started = time.monotonic() + next_look = 0.0 + try: + while not page.is_closed(): + while paused: + _decide(cdp, watch, paused.pop(0)) + if time.monotonic() >= next_look: + try: + snapshot = page.evaluate(SNAPSHOT_JS) + except Exception: # noqa: BLE001 - navigating: look again + snapshot = None + if isinstance(snapshot, Mapping): + watch.observe(snapshot) + watch.poll() + next_look = time.monotonic() + poll_s + if stop is not None and stop(): + break + if max_s is not None and time.monotonic() - started >= max_s: + break + page.wait_for_timeout(50) # delivers CDP events + finally: + # Paused requests go on when the session detaches: decide them first. + while paused: + try: + _decide(cdp, watch, paused.pop(0)) + except Exception: # noqa: BLE001 - the tab is gone + break + try: + cdp.detach() + except Exception: # noqa: BLE001 - the tab is gone + pass + try: + if browser is not None: + browser.close() + except Exception: # noqa: BLE001 - already closed + pass + finally: + pw.stop() + return watch.stop_code() diff --git a/packages/flow/tests/e2e/test_exception_watch_e2e.py b/packages/flow/tests/e2e/test_exception_watch_e2e.py new file mode 100644 index 0000000000..4709ebafea --- /dev/null +++ b/packages/flow/tests/e2e/test_exception_watch_e2e.py @@ -0,0 +1,268 @@ +"""End to end: an agent that never asks is held at a code prompt anyway. + +Real headless Chromium. The scripted Playwright agent +(``benchmark/agent_guard/agent.py``) works in MockMed and never calls +``raise_exception``. ``openadapt-flow guard`` attaches to its browser over +CDP, and so does ``openadapt-flow exceptions watch``, each in its own +process. A synthetic one-time-code dialog appears on the agent's page. The +watch raises a ``second_factor`` card by itself and blocks the save the agent +tries while the card is open. A person clears the code prompt in the live +page and answers ``done_by_person`` with a registered test key; the agent's +next save goes through the guard and reads back VERIFIED. + +Asserted from the app's own store: no write while the card was open, exactly +one write after the answer. + +Synthetic MockMed in front of the ``effect_e2e`` record store; localhost only. +""" + +from __future__ import annotations + +import json +import os +import queue +import socket +import subprocess +import sys +import threading +import time +from pathlib import Path +from typing import Any + +import pytest + +pytest.importorskip("playwright") + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402 +from openadapt_types.exception_card import answer_message # noqa: E402 + +from benchmark.agent_guard import run as bench # noqa: E402 +from benchmark.agent_guard.agent import ScriptedAgent # noqa: E402 +from benchmark.agent_guard.app import serve # noqa: E402 +from openadapt_flow.approval_mode.approver_roster import ( # noqa: E402 + ROOT_ENV, + file_key_signer, + init_root, +) +from openadapt_flow.exceptions.registry import ExceptionRegistry # noqa: E402 +from openadapt_flow.execute.keys import sign_bytes # noqa: E402 +from openadapt_flow.jit.authority import public_hex # noqa: E402 + +pytestmark = pytest.mark.timeout(600) + +#: A synthetic code prompt laid over the page, as a sign-in service shows one. +CODE_PROMPT = """() => { + const box = document.createElement('div'); + box.id = 'synthetic-code-prompt'; + box.setAttribute('role', 'dialog'); + box.setAttribute('aria-modal', 'true'); + box.style.cssText = 'position:fixed;left:30%;top:30%;width:40%;height:20%;' + + 'background:#fff;border:1px solid #000;z-index:1000'; + box.innerHTML = '

Check your phone

' + + ''; + document.body.appendChild(box); +}""" +#: The agent's save while the prompt is up: MockMed's own write, sent from +#: its page. It ignores the prompt and never asks anyone. +AGENT_SAVE = """async (note) => { + const r = await fetch('/api/encounter?fault=ok', {method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({patient_id: 'p1', type: 'Triage', note: note})}); + return {status: r.status, header: r.headers.get('X-OpenAdapt-Exception')}; +}""" + + +def _port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + +def _chromium_or_skip() -> None: + from playwright.sync_api import sync_playwright + + try: + with sync_playwright() as pw: + pw.chromium.launch(headless=True).close() + except Exception as exc: # noqa: BLE001 + pytest.skip(f"chromium unavailable: {exc}") + + +class _Watch: + """``openadapt-flow exceptions watch`` in its own process.""" + + def __init__(self, args: list[str]) -> None: + self.proc = subprocess.Popen( + [sys.executable, "-m", "openadapt_flow", "exceptions", "watch", *args], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=os.environ.copy(), + ) + self.lines: "queue.Queue[str]" = queue.Queue() + self.stderr: list[str] = [] + threading.Thread(target=self._read, daemon=True).start() + + def _read(self) -> None: + assert self.proc.stderr is not None + for line in self.proc.stderr: + self.stderr.append(line) + self.lines.put(line) + + def wait_attached(self, timeout_s: float = 90.0) -> None: + end = time.monotonic() + timeout_s + while time.monotonic() < end: + try: + line = self.lines.get(timeout=0.2) + except queue.Empty: + if self.proc.poll() is not None: + break + continue + if "exceptions: watching" in line: + return + raise RuntimeError("the watch did not attach:\n" + "".join(self.stderr)) + + def finish(self) -> dict[str, Any]: + try: + out, _ = self.proc.communicate(timeout=120) + except subprocess.TimeoutExpired: + self.proc.kill() + out, _ = self.proc.communicate() + return { + "exit": self.proc.returncode, + **json.loads(out.strip().splitlines()[-1]), + } + + +def _until(check, timeout_s: float = 60.0, what: str = "") -> Any: + end = time.monotonic() + timeout_s + while time.monotonic() < end: + value = check() + if value: + return value + time.sleep(0.1) + raise AssertionError(f"timed out waiting for {what}") + + +def test_the_watch_holds_an_agent_that_never_asks( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _chromium_or_skip() + home = tmp_path / "home" + key_dir = tmp_path / "keys" + key = Ed25519PrivateKey.generate() + init_root( + key_dir, + principal="front-desk", + public_key=public_hex(key), + sign=file_key_signer(key), + ) + monkeypatch.setenv("OPENADAPT_HOME", str(home)) + monkeypatch.setenv("OPENADAPT_JIT_KEY_DIR", str(key_dir)) + monkeypatch.setenv(ROOT_ENV, public_hex(key)) + registry = ExceptionRegistry(home / "exceptions") + + app = serve(tmp_path / "app.sqlite") + port = _port() + work = tmp_path / "run" + agent = guard = watch = None + try: + bench._post( + app.base_url, "/api/reset", {"seed_concurrent": None, "fault": None} + ) + files = bench.write_setup(tmp_path / "setup", app.base_url, teach_dir=None) + agent = ScriptedAgent(port=port, think_s=0.2) + agent.open(f"{app.base_url}/?fault=ok&idempotency=demo#tasks") + guard = bench._GuardProcess( + [ + "--cdp", + f"http://127.0.0.1:{port}", + "--config", + str(files["guard"]), + "--task", + str(files["task"]), + "--out", + str(work), + "--timeout", + "120", + "--no-teach", + ] + ) + guard.wait_attached() + watch = _Watch( + [ + "--cdp", + f"http://127.0.0.1:{port}", + "--config", + str(files["guard"]), + "--run-dir", + str(work), + "--run-ref", + "watch-e2e", + "--task-id", + "triage-p1-0001", + "--poll-s", + "0.2", + "--max-s", + "240", + ] + ) + watch.wait_attached() + writes_before = app.writes + + # A code prompt appears. The agent doesn't ask anyone. + agent.page.evaluate(CODE_PROMPT) + card = _until( + lambda: next(iter(registry.open_cards("watch-e2e")), None), what="a card" + ) + assert card.kind == "second_factor" + # It saves anyway: the watch blocks it at the browser. + tried = agent.page.evaluate(AGENT_SAVE, bench.NOTE) + assert tried["status"] == 409, tried + assert tried["header"] == "blocked; code=exception_open" + assert app.writes == writes_before + + # A person clears the prompt in the live page, then answers. + agent.page.evaluate( + "() => document.getElementById('synthetic-code-prompt').remove()" + ) + unsigned = registry.unsigned_answer(card, "done_by_person", route="cli") + registry.write_answer( + card, + { + **unsigned, + "public_key": public_hex(key), + "signature": sign_bytes(key, answer_message(unsigned)), + }, + ) + log = work / "exceptions_watch.jsonl" + _until( + lambda: log.exists() and '"proceed": true' in log.read_text(), + what="the watch to settle the card", + ) + + # The agent saves the ordinary way: the guard checks it, it lands once. + acted = agent.add_triage_note(patient="p1", note=bench.NOTE) + result = guard.finish(wait_s=30) + assert result["run"]["verdict"] == "VERIFIED", (acted, result) + assert app.writes == writes_before + 1 + + watch.proc.terminate() + done = watch.finish() + assert done["run_ref"] == "watch-e2e" and done["stopped"] is None + [outcome] = done["outcomes"] + assert outcome["answer"] == "done_by_person" and outcome["proceed"] is True + events = [json.loads(line) for line in log.read_text().splitlines()] + kinds = [e["event"] for e in events] + assert kinds.count("card_opened") == 1 + assert {"event": "request_blocked", "code": "exception_open"}.items() <= next( + e for e in events if e["event"] == "request_blocked" + ).items() + assert bench.NOTE.encode() not in log.read_bytes() + finally: + for proc in (watch, guard): + if proc is not None and proc.proc.poll() is None: + proc.proc.kill() + if agent is not None: + agent.close() + app.stop() diff --git a/packages/flow/tests/test_exception_detectors.py b/packages/flow/tests/test_exception_detectors.py index 88b24f8fec..2f8a0edf5b 100644 --- a/packages/flow/tests/test_exception_detectors.py +++ b/packages/flow/tests/test_exception_detectors.py @@ -32,12 +32,20 @@ """ -MODAL = """""" + FORM + """ +MODAL = ( + """""" + + FORM + + """

Your changes may be lost.

""" +) -HIDDEN_MODAL = """""" + FORM + """ +HIDDEN_MODAL = ( + """""" + + FORM + + """ """ +) def _obs(html: str, **fields) -> Observation: @@ -54,7 +62,10 @@ def test_a_code_prompt_is_a_second_factor(page): def test_screen_text_alone_still_asks(): - assert d.second_factor((), "Two-factor authentication: enter the code") == "second_factor" + assert ( + d.second_factor((), "Two-factor authentication: enter the code") + == "second_factor" + ) def test_an_ordinary_form_is_not_a_second_factor(): @@ -117,26 +128,34 @@ def test_a_non_modal_dialog_covering_the_target_is_in_the_way(): def test_a_dialog_with_no_geometry_asks(): - assert d.unexpected_dialog([{"role": "alertdialog"}], target={"bbox": [1, 1, 1, 1]}) == ( - "unexpected_dialog" - ) + assert d.unexpected_dialog( + [{"role": "alertdialog"}], target={"bbox": [1, 1, 1, 1]} + ) == ("unexpected_dialog") # -- stalls ------------------------------------------------------------------------- def test_no_action_and_no_change_for_too_long_is_a_stall(): - assert detect(Observation(now=1000.0, last_action_at=700.0, last_change_at=800.0, stall_s=120)) == ( - "timeout_or_stall" - ) + assert detect( + Observation(now=1000.0, last_action_at=700.0, last_change_at=800.0, stall_s=120) + ) == ("timeout_or_stall") def test_a_recent_change_is_not_a_stall(): - assert d.timeout_or_stall(now=1000.0, last_action_at=700.0, last_change_at=950.0, stall_s=120) is None + assert ( + d.timeout_or_stall( + now=1000.0, last_action_at=700.0, last_change_at=950.0, stall_s=120 + ) + is None + ) def test_a_clock_with_no_last_event_asks(): - assert d.timeout_or_stall(now=5.0, last_action_at=None, last_change_at=None) == "timeout_or_stall" + assert ( + d.timeout_or_stall(now=5.0, last_action_at=None, last_change_at=None) + == "timeout_or_stall" + ) def test_no_clock_means_no_stall_check(): @@ -145,7 +164,10 @@ def test_no_clock_means_no_stall_check(): # -- duplicates --------------------------------------------------------------------- -ROWS = [{"last_name": "Okafor", "dob": "1950-01-01"}, {"last_name": "Vance", "dob": "1972-03-04"}] +ROWS = [ + {"last_name": "Okafor", "dob": "1950-01-01"}, + {"last_name": "Vance", "dob": "1972-03-04"}, +] def test_a_row_with_the_same_key_is_a_possible_duplicate(): @@ -166,7 +188,11 @@ def test_no_matching_row_is_not_a_duplicate(): [ (["last_name", "dob"], {"last_name": "Vance"}, ROWS), # no key value ("last_name", {"last_name": "Vance"}, None), # the read failed - ("last_name", {"last_name": "Nobody"}, [{"dob": "1950-01-01"}]), # row lacks key + ( + "last_name", + {"last_name": "Nobody"}, + [{"dob": "1950-01-01"}], + ), # row lacks key ([], {"last_name": "Vance"}, ROWS), # a key with no fields ({"weird": 1}, {"last_name": "Vance"}, ROWS), # a key shape we can't check ], @@ -190,7 +216,16 @@ def test_the_key_comes_from_verify_yaml_record_duplicate_key(): def test_the_detectors_name_no_app(): source = Path(d.__file__).read_text(encoding="utf-8").casefold() - for name in ("openemr", "mockmed", "epic", "cerner", "salesforce", "okta", "google", "microsoft"): + for name in ( + "openemr", + "mockmed", + "epic", + "cerner", + "salesforce", + "okta", + "google", + "microsoft", + ): assert name not in source diff --git a/packages/flow/tests/test_exception_registry.py b/packages/flow/tests/test_exception_registry.py index dca361cadc..67b484fe01 100644 --- a/packages/flow/tests/test_exception_registry.py +++ b/packages/flow/tests/test_exception_registry.py @@ -49,6 +49,7 @@ "mail maribel@example.test" ) + def _png_1x1() -> bytes: """A valid one-pixel RGB PNG, built without an imaging library.""" @@ -58,7 +59,12 @@ def chunk(tag: bytes, data: bytes) -> bytes: header = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0) pixels = zlib.compress(b"\x00\xff\xff\xff") - return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", pixels) + chunk(b"IEND", b"") + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + chunk(b"IDAT", pixels) + + chunk(b"IEND", b"") + ) PNG = _png_1x1() @@ -90,7 +96,12 @@ def registry(tmp_path: Path) -> ExceptionRegistry: def roster(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): key_dir = tmp_path / "keys" key = Ed25519PrivateKey.generate() - init_root(key_dir, principal="front-desk", public_key=public_hex(key), sign=file_key_signer(key)) + init_root( + key_dir, + principal="front-desk", + public_key=public_hex(key), + sign=file_key_signer(key), + ) monkeypatch.setenv(ROOT_ENV, public_hex(key)) return key_dir, key @@ -168,7 +179,9 @@ def _bytes_under(root: Path) -> bytes: def test_the_summary_is_scrubbed_and_cut(registry): - card = registry.open("run-1", "second_factor", SUMMARY + " " + "x" * 400, task_id="T-12345678") + card = registry.open( + "run-1", "second_factor", SUMMARY + " " + "x" * 400, task_id="T-12345678" + ) assert len(card.summary) <= 200 blob = _bytes_under(registry.root) @@ -202,7 +215,9 @@ def scrub_text(self, text): def test_a_screenshot_is_kept_only_as_a_scrubbed_private_copy(registry, tmp_path): shot = tmp_path / "screen.png" shot.write_bytes(PNG) - card = registry.open("run-1", "unexpected_dialog", "A dialog", screenshot_path=str(shot)) + card = registry.open( + "run-1", "unexpected_dialog", "A dialog", screenshot_path=str(shot) + ) assert card.screenshot_ref is not None copy = registry.root / "run-1" / card.screenshot_ref @@ -218,11 +233,31 @@ def test_no_screenshot_without_a_scrubber_a_png_or_a_plain_file(registry, tmp_pa text = tmp_path / "notes.png" text.write_text("not an image") - assert registry.open("r", "cannot_complete", "x", screenshot_path=str(link)).screenshot_ref is None - assert registry.open("r", "cannot_complete", "y", screenshot_path=str(text)).screenshot_ref is None - assert registry.open("r", "cannot_complete", "z", screenshot_path=str(tmp_path)).screenshot_ref is None + assert ( + registry.open( + "r", "cannot_complete", "x", screenshot_path=str(link) + ).screenshot_ref + is None + ) + assert ( + registry.open( + "r", "cannot_complete", "y", screenshot_path=str(text) + ).screenshot_ref + is None + ) + assert ( + registry.open( + "r", "cannot_complete", "z", screenshot_path=str(tmp_path) + ).screenshot_ref + is None + ) privacy.set_text_scrubber(None) - assert registry.open("r", "cannot_complete", "w", screenshot_path=str(shot)).screenshot_ref is None + assert ( + registry.open( + "r", "cannot_complete", "w", screenshot_path=str(shot) + ).screenshot_ref + is None + ) # -- answers ----------------------------------------------------------------------- @@ -281,7 +316,9 @@ def test_without_a_pinned_root_no_answer_counts(registry, roster): card = registry.open("run-1", "second_factor", "A code prompt") registry.write_answer(card, _signed(registry, card, "done_by_person", key)) - outcome = registry.wait(card, verify=roster_verifier(key_dir, None), sleep=_no_sleep) + outcome = registry.wait( + card, verify=roster_verifier(key_dir, None), sleep=_no_sleep + ) assert outcome.proceed is False @@ -303,7 +340,11 @@ def test_a_choice_the_card_doesnt_offer_never_proceeds(registry, roster): } registry.write_answer( card, - {**unsigned, "public_key": public_hex(key), "signature": sign_bytes(key, answer_message(unsigned))}, + { + **unsigned, + "public_key": public_hex(key), + "signature": sign_bytes(key, answer_message(unsigned)), + }, ) outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) assert outcome.proceed is False @@ -314,7 +355,9 @@ def test_an_answer_decided_after_the_deadline_never_proceeds(registry, roster): _key_dir, key = roster card = registry.open("run-1", "second_factor", "A code prompt", deadline_s=5) late = datetime.now(timezone.utc) + timedelta(seconds=60) - registry.write_answer(card, _signed(registry, card, "done_by_person", key, now=late)) + registry.write_answer( + card, _signed(registry, card, "done_by_person", key, now=late) + ) outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) assert outcome.proceed is False @@ -343,7 +386,9 @@ def test_a_card_has_one_answer(registry, roster): def test_an_unreadable_answer_stops_the_run(registry, roster): card = registry.open("run-1", "second_factor", "A code prompt") - (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").write_text("{not json") + (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").write_text( + "{not json" + ) outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) assert outcome.proceed is False @@ -362,7 +407,9 @@ def test_an_unsigned_answer_that_claims_to_be_a_persons_is_unreadable(registry, "approver_kind": "person", "route": "cli", } - (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").write_text(json.dumps(answer)) + (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").write_text( + json.dumps(answer) + ) outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) assert outcome.proceed is False @@ -388,7 +435,9 @@ def test_expiry_writes_a_decline_with_no_decision_time(registry, roster): assert outcome.reason == "expired" assert outcome.decided_at is None record = ExceptionAnswerV1.model_validate( - json.loads((registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").read_text()) + json.loads( + (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").read_text() + ) ) assert record.approver_kind == "expiry" assert record.decided_at is None @@ -399,7 +448,8 @@ def test_expiry_writes_a_decline_with_no_decision_time(registry, roster): def test_the_wait_beats_and_then_expires(registry, roster): card = registry.open("run-1", "timeout_or_stall", "Stalled", deadline_s=60) times = iter( - [datetime.now(timezone.utc)] * 3 + [datetime.now(timezone.utc) + timedelta(seconds=120)] * 5 + [datetime.now(timezone.utc)] * 3 + + [datetime.now(timezone.utc) + timedelta(seconds=120)] * 5 ) beats: list[float] = [] outcome = registry.wait( @@ -414,7 +464,9 @@ def test_the_wait_beats_and_then_expires(registry, roster): assert beats and all(b > 0 for b in beats) -def test_a_person_who_answers_at_the_deadline_wins_the_race(registry, roster, monkeypatch): +def test_a_person_who_answers_at_the_deadline_wins_the_race( + registry, roster, monkeypatch +): _key_dir, key = roster card = registry.open("run-1", "second_factor", "A code prompt", deadline_s=60) answer = _signed(registry, card, "done_by_person", key) @@ -426,14 +478,21 @@ def expire_after_the_person(c): monkeypatch.setattr(registry, "_expire", expire_after_the_person) after = datetime.now(timezone.utc) + timedelta(seconds=61) - outcome = registry.wait(card, verify=_verify(roster), clock=lambda: after, sleep=_no_sleep) + outcome = registry.wait( + card, verify=_verify(roster), clock=lambda: after, sleep=_no_sleep + ) assert outcome.proceed is True def test_the_heartbeat_goes_to_stderr_never_stdout(registry, roster, capsys): card = registry.open("run-1", "timeout_or_stall", "Stalled", deadline_s=60) - times = iter([datetime.now(timezone.utc), datetime.now(timezone.utc) + timedelta(seconds=99)] * 3) - registry.wait(card, verify=_verify(roster), clock=lambda: next(times), sleep=_no_sleep) + times = iter( + [datetime.now(timezone.utc), datetime.now(timezone.utc) + timedelta(seconds=99)] + * 3 + ) + registry.wait( + card, verify=_verify(roster), clock=lambda: next(times), sleep=_no_sleep + ) out, err = capsys.readouterr() assert out == "" assert "waiting for a person" in err @@ -464,7 +523,9 @@ def _parse(argv: list[str]): return parser.parse_args(argv) -def test_the_cli_answers_with_a_key_on_the_roster(registry, roster, tmp_path, monkeypatch, capsys): +def test_the_cli_answers_with_a_key_on_the_roster( + registry, roster, tmp_path, monkeypatch, capsys +): key_dir, key = roster monkeypatch.setenv("OPENADAPT_JIT_KEY_PASSPHRASE", "synthetic-passphrase") pem = _encrypted(tmp_path, key, "synthetic-passphrase") @@ -477,8 +538,16 @@ def test_the_cli_answers_with_a_key_on_the_roster(registry, roster, tmp_path, mo args = _parse( [ - "exceptions", "answer", card.card_id, "done_by_person", - "--registry", str(registry.root), "--key", str(pem), "--key-dir", str(key_dir), + "exceptions", + "answer", + card.card_id, + "done_by_person", + "--registry", + str(registry.root), + "--key", + str(pem), + "--key-dir", + str(key_dir), ] ) assert args.func(args) == 0 @@ -486,7 +555,9 @@ def test_the_cli_answers_with_a_key_on_the_roster(registry, roster, tmp_path, mo assert outcome.proceed is True -def test_the_cli_refuses_a_key_off_the_roster(registry, roster, tmp_path, monkeypatch, capsys): +def test_the_cli_refuses_a_key_off_the_roster( + registry, roster, tmp_path, monkeypatch, capsys +): key_dir, _key = roster monkeypatch.setenv("OPENADAPT_JIT_KEY_PASSPHRASE", "synthetic-passphrase") pem = _encrypted(tmp_path, Ed25519PrivateKey.generate(), "synthetic-passphrase") @@ -494,8 +565,16 @@ def test_the_cli_refuses_a_key_off_the_roster(registry, roster, tmp_path, monkey args = _parse( [ - "exceptions", "answer", card.card_id, "done_by_person", - "--registry", str(registry.root), "--key", str(pem), "--key-dir", str(key_dir), + "exceptions", + "answer", + card.card_id, + "done_by_person", + "--registry", + str(registry.root), + "--key", + str(pem), + "--key-dir", + str(key_dir), ] ) assert args.func(args) == 2 @@ -503,15 +582,25 @@ def test_the_cli_refuses_a_key_off_the_roster(registry, roster, tmp_path, monkey assert not (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").exists() -def test_the_cli_refuses_a_choice_the_card_doesnt_offer(registry, roster, tmp_path, monkeypatch): +def test_the_cli_refuses_a_choice_the_card_doesnt_offer( + registry, roster, tmp_path, monkeypatch +): key_dir, key = roster monkeypatch.setenv("OPENADAPT_JIT_KEY_PASSPHRASE", "synthetic-passphrase") pem = _encrypted(tmp_path, key, "synthetic-passphrase") card = registry.open("run-1", "second_factor", "A code prompt") args = _parse( [ - "exceptions", "answer", card.card_id, "continue", - "--registry", str(registry.root), "--key", str(pem), "--key-dir", str(key_dir), + "exceptions", + "answer", + card.card_id, + "continue", + "--registry", + str(registry.root), + "--key", + str(pem), + "--key-dir", + str(key_dir), ] ) assert args.func(args) == 2 diff --git a/packages/flow/tests/test_exception_watch.py b/packages/flow/tests/test_exception_watch.py new file mode 100644 index 0000000000..e2ce511694 --- /dev/null +++ b/packages/flow/tests/test_exception_watch.py @@ -0,0 +1,253 @@ +"""The exception watch raises cards and holds saves without the agent. + +No browser: page snapshots are the dicts :data:`SNAPSHOT_JS` returns, and +requests are :class:`HeldRequest` as the guard's CDP layer builds them. +Synthetic screens and keys only. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from openadapt_types.exception_card import answer_message + +from openadapt_flow.agent_guard.requests import HeldRequest, NotASave +from openadapt_flow.approval_mode.approver_roster import ( + ROOT_ENV, + file_key_signer, + init_root, +) +from openadapt_flow.exceptions.registry import ExceptionRegistry, roster_verifier +from openadapt_flow.exceptions.watch import WATCH_EVENTS, ExceptionWatch +from openadapt_flow.execute.keys import sign_bytes +from openadapt_flow.jit.authority import public_hex + +APP = "http://127.0.0.1:8123" +CODE_SCREEN = { + "text": "Check your phone. Verification code", + "elements": [ + { + "tag": "input", + "type": "text", + "id": "otc", + "label": "Verification code", + "autocomplete": "one-time-code", + "inputmode": "numeric", + "maxlength": "6", + "visible": True, + "bbox": [10, 10, 100, 20], + } + ], +} +FORM_SCREEN = { + "text": "New note", + "elements": [ + { + "tag": "input", + "type": "text", + "id": "note", + "label": "Note", + "visible": True, + }, + {"tag": "button", "type": "", "id": "save", "visible": True}, + ], +} +SIGN_IN_SCREEN = { + "text": "Sign in", + "elements": [{"tag": "input", "type": "password", "id": "pw", "visible": True}], +} + + +@pytest.fixture +def roster(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + key_dir = tmp_path / "keys" + key = Ed25519PrivateKey.generate() + init_root( + key_dir, + principal="front-desk", + public_key=public_hex(key), + sign=file_key_signer(key), + ) + monkeypatch.setenv(ROOT_ENV, public_hex(key)) + return key_dir, key + + +class _Clock: + def __init__(self) -> None: + self.t = 100.0 + + def __call__(self) -> float: + return self.t + + +def _watch(tmp_path: Path, roster, **kw) -> ExceptionWatch: + key_dir, key = roster + return ExceptionWatch( + ExceptionRegistry(tmp_path / "registry"), + run_ref="watch-run", + verify=roster_verifier(key_dir, public_hex(key)), + app_origin=APP, + events_path=tmp_path / "run" / WATCH_EVENTS, + **kw, + ) + + +def _save(path: str = "/api/encounter", method: str = "POST") -> HeldRequest: + return HeldRequest( + request_id="r1", + method=method, + url=APP + path, + resource_type="Fetch", + post_data=json.dumps({"note": "synthetic"}), + ) + + +def _answer(watch: ExceptionWatch, key, choice: str) -> None: + card = watch.card + unsigned = watch.registry.unsigned_answer(card, choice, route="cli") + watch.registry.write_answer( + card, + { + **unsigned, + "public_key": public_hex(key), + "signature": sign_bytes(key, answer_message(unsigned)), + }, + ) + + +def _events(tmp_path: Path) -> list[dict]: + return [ + json.loads(line) + for line in (tmp_path / "run" / WATCH_EVENTS).read_text().splitlines() + ] + + +def test_a_code_screen_opens_a_card_and_blocks_saves_until_a_person_answers( + tmp_path: Path, roster +) -> None: + watch = _watch(tmp_path, roster) + assert watch.on_request(_save()) is None # nothing open: the save goes on + assert watch.observe(CODE_SCREEN) == "second_factor" + assert watch.card is not None and watch.card.kind == "second_factor" + # The agent never asked; it saves anyway. Blocked, whatever it does. + assert watch.on_request(_save()) == "exception_open" + # Reads still go through, and so does a write the guard config lists + # as not a save (the code form a person submits in the live browser). + assert watch.on_request(_save(method="GET")) is None + assert watch.poll() is None # nobody has answered + _answer(watch, roster[1], "done_by_person") + outcome = watch.poll() + assert outcome is not None and outcome.proceed is True + assert watch.card is None and not watch.holding + assert watch.on_request(_save()) is None + # The page still shows the code screen: not asked again until it goes. + assert watch.observe(CODE_SCREEN) is None + assert watch.observe(FORM_SCREEN) is None + assert watch.observe(CODE_SCREEN) == "second_factor" + assert watch.stop_code() == 0 + events = [e["event"] for e in _events(tmp_path)] + assert events[:5] == [ + "watch_started", + "card_opened", + "request_blocked", + "answer", + "card_opened", + ] + + +def test_a_not_a_save_write_goes_through_while_a_card_is_open( + tmp_path: Path, roster +) -> None: + watch = _watch(tmp_path, roster, not_saves=(NotASave("POST", "/verify"),)) + watch.observe(CODE_SCREEN) + assert watch.on_request(_save("/verify")) is None + assert watch.on_request(_save("/api/encounter")) == "exception_open" + + +@pytest.mark.parametrize("choice", ["abort", "skip"]) +def test_a_stop_answer_blocks_every_later_save( + tmp_path: Path, roster, choice: str +) -> None: + watch = _watch(tmp_path, roster) + watch.observe(CODE_SCREEN) + _answer(watch, roster[1], choice) + outcome = watch.poll() + assert outcome is not None and outcome.proceed is False + assert watch.stopped == choice + assert watch.on_request(_save()) == "exception_stopped" + # No new card after a stop: the run is over. + assert watch.observe(SIGN_IN_SCREEN) is None + assert watch.stop_code() == 3 + + +def test_an_answer_off_the_roster_keeps_the_run_stopped(tmp_path: Path, roster) -> None: + watch = _watch(tmp_path, roster) + watch.observe(CODE_SCREEN) + _answer(watch, Ed25519PrivateKey.generate(), "done_by_person") + outcome = watch.poll() + assert outcome is not None and outcome.proceed is False + assert outcome.reason == "human_approver_unregistered" + assert watch.on_request(_save()) == "exception_stopped" + + +def test_an_expired_card_stops_the_run(tmp_path: Path, roster) -> None: + watch = _watch(tmp_path, roster, deadline_s=1) + watch.observe(CODE_SCREEN) + card = watch.card + from datetime import timedelta + + from openadapt_flow.exceptions.registry import parse_time + + later = parse_time(card.deadline_at) + timedelta(seconds=1) + outcome = watch.registry.poll(card, verify=watch.verify, now=later) + assert outcome is not None and outcome.reason == "expired" + # The watch reads the same record on its next look. + assert watch.poll() is not None + assert watch.on_request(_save()) == "exception_stopped" + + +def test_a_sign_in_counts_only_after_a_save(tmp_path: Path, roster) -> None: + watch = _watch(tmp_path, roster) + assert watch.observe(SIGN_IN_SCREEN) is None # the ordinary start of a task + watch.on_request(_save()) + assert watch.observe(SIGN_IN_SCREEN) == "session_expired" + + +def test_a_stall_is_raised_only_when_asked_for(tmp_path: Path, roster) -> None: + clock = _Clock() + off = _watch(tmp_path / "off", roster, clock=clock) + on = _watch(tmp_path / "on", roster, clock=clock, stall_s=30) + for watch in (off, on): + watch.observe(FORM_SCREEN) + clock.t += 31 + assert off.observe(FORM_SCREEN) is None + assert on.observe(FORM_SCREEN) == "timeout_or_stall" + + +def test_the_card_carries_nothing_from_the_page(tmp_path: Path, roster) -> None: + planted = dict( + CODE_SCREEN, text="Verification code for Maribel Quintanilla 88812345" + ) + watch = _watch(tmp_path, roster) + watch.observe(planted) + blob = b"".join( + p.read_bytes() for p in (tmp_path / "registry").rglob("*") if p.is_file() + ) + blob += (tmp_path / "run" / WATCH_EVENTS).read_bytes() + assert b"Maribel" not in blob and b"88812345" not in blob + + +def test_a_bad_run_ref_is_refused_before_anything_runs(tmp_path: Path, roster) -> None: + from openadapt_flow.exceptions.registry import ExceptionRegistryError + + key_dir, key = roster + with pytest.raises(ExceptionRegistryError): + ExceptionWatch( + ExceptionRegistry(tmp_path / "registry"), + run_ref="../elsewhere", + verify=roster_verifier(key_dir, public_hex(key)), + app_origin=APP, + ) From 2fb05fae1ffff90bc9465fdf151ff930aa3312a5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:41:17 -0500 Subject: [PATCH 07/11] docs(flow): start the exception watch after the guard Chromium hands a paused request to the DevTools session that attached last first, so the watch must attach after the guard to decide a save before the guard sees it. The earlier commit said the two compose in either order; in the other order a blocked save is still never sent, but the guard has already let it go and ends the run unconfirmed. Only the guard-first order is tested. Also lists two gaps: other tabs, and a save sent before the watch's next look at the page. --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/docs/EXCEPTION_QUEUE.md | 15 +++++++++++---- packages/flow/openadapt_flow/exceptions/cli.py | 7 ++++++- packages/flow/openadapt_flow/exceptions/watch.py | 11 +++++++---- 5 files changed, 26 insertions(+), 11 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index b1fdc61bd8..9ceeb344be 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -213,7 +213,7 @@ improvising or retrying when something is off. | Admit once, then stop only on problems | Released ([#1212](https://github.com/OpenAdaptAI/OpenAdapt/pull/1212)), behind a readiness gate | Synthetic | [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md) | | Show the field values a save writes on the phone | Released ([#1257](https://github.com/OpenAdaptAI/OpenAdapt/pull/1257)) | Unit tests | `console/save_approvals.py` | | Show why an agent asked for a save: who asked, its own reason (as a quote), the screen text it saw, and any of that text that reads like an instruction to an agent | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359)) | Unit tests, synthetic | `ApprovalProvenance` in `approval_mode/item_approval.py`; the phone card in openadapt-desktop `portal/shell` | -| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, detectors that say when to ask, and `exceptions watch`, which reads a Chromium agent's page over CDP, raises `second_factor`, `unexpected_dialog`, `session_expired` and (opt-in) `timeout_or_stall` cards without the agent, and blocks the page's saves while a card is open. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The MCP tool can't make an agent that ignores it stop; the watch doesn't cover non-browser agents, WebSocket saves, `possible_duplicate`, or a run with no watch running. Cards in Desktop's stop queue and on a paired phone ship with openadapt-desktop 0.31.0 in [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492). The share of cases that need a person is unmeasured | In PR [#2494](https://github.com/OpenAdaptAI/OpenAdapt/pull/2494) | Unit tests and synthetic end-to-end tests: a scripted agent on a one-time-code page over real MCP stdio (one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state); and, in headless Chromium on MockMed with the guard attached, an agent that never calls the tool hits a synthetic code prompt, the watch raises the card and blocks its save, and after `done_by_person` one save lands and reads back VERIFIED | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md) | +| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, detectors that say when to ask, and `exceptions watch`, which reads a Chromium agent's page over CDP, raises `second_factor`, `unexpected_dialog`, `session_expired` and (opt-in) `timeout_or_stall` cards without the agent, and blocks the page's saves while a card is open. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The MCP tool can't make an agent that ignores it stop; the watch must start after the guard attaches, and doesn't cover non-browser agents, WebSocket saves, other tabs, a save sent before its next look at the page, `possible_duplicate`, or a run with no watch running. Cards in Desktop's stop queue and on a paired phone ship with openadapt-desktop 0.31.0 in [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492). The share of cases that need a person is unmeasured | In PR [#2494](https://github.com/OpenAdaptAI/OpenAdapt/pull/2494) | Unit tests and synthetic end-to-end tests: a scripted agent on a one-time-code page over real MCP stdio (one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state); and, in headless Chromium on MockMed with the guard attached, an agent that never calls the tool hits a synthetic code prompt, the watch raises the card and blocks its save, and after `done_by_person` one save lands and reads back VERIFIED | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md) | ## Branching work, not one linear path diff --git a/llms-full.txt b/llms-full.txt index a298a1e3fa..8457ac9b5b 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -653,7 +653,7 @@ improvising or retrying when something is off. | Admit once, then stop only on problems | Released ([#1212](https://github.com/OpenAdaptAI/OpenAdapt/pull/1212)), behind a readiness gate | Synthetic | [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md) | | Show the field values a save writes on the phone | Released ([#1257](https://github.com/OpenAdaptAI/OpenAdapt/pull/1257)) | Unit tests | `console/save_approvals.py` | | Show why an agent asked for a save: who asked, its own reason (as a quote), the screen text it saw, and any of that text that reads like an instruction to an agent | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359)) | Unit tests, synthetic | `ApprovalProvenance` in `approval_mode/item_approval.py`; the phone card in openadapt-desktop `portal/shell` | -| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, detectors that say when to ask, and `exceptions watch`, which reads a Chromium agent's page over CDP, raises `second_factor`, `unexpected_dialog`, `session_expired` and (opt-in) `timeout_or_stall` cards without the agent, and blocks the page's saves while a card is open. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The MCP tool can't make an agent that ignores it stop; the watch doesn't cover non-browser agents, WebSocket saves, `possible_duplicate`, or a run with no watch running. Cards in Desktop's stop queue and on a paired phone ship with openadapt-desktop 0.31.0 in [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492). The share of cases that need a person is unmeasured | In PR [#2494](https://github.com/OpenAdaptAI/OpenAdapt/pull/2494) | Unit tests and synthetic end-to-end tests: a scripted agent on a one-time-code page over real MCP stdio (one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state); and, in headless Chromium on MockMed with the guard attached, an agent that never calls the tool hits a synthetic code prompt, the watch raises the card and blocks its save, and after `done_by_person` one save lands and reads back VERIFIED | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EXCEPTION_QUEUE.md) | +| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, detectors that say when to ask, and `exceptions watch`, which reads a Chromium agent's page over CDP, raises `second_factor`, `unexpected_dialog`, `session_expired` and (opt-in) `timeout_or_stall` cards without the agent, and blocks the page's saves while a card is open. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The MCP tool can't make an agent that ignores it stop; the watch must start after the guard attaches, and doesn't cover non-browser agents, WebSocket saves, other tabs, a save sent before its next look at the page, `possible_duplicate`, or a run with no watch running. Cards in Desktop's stop queue and on a paired phone ship with openadapt-desktop 0.31.0 in [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492). The share of cases that need a person is unmeasured | In PR [#2494](https://github.com/OpenAdaptAI/OpenAdapt/pull/2494) | Unit tests and synthetic end-to-end tests: a scripted agent on a one-time-code page over real MCP stdio (one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state); and, in headless Chromium on MockMed with the guard attached, an agent that never calls the tool hits a synthetic code prompt, the watch raises the card and blocks its save, and after `done_by_person` one save lands and reads back VERIFIED | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EXCEPTION_QUEUE.md) | ## Branching work, not one linear path diff --git a/packages/flow/docs/EXCEPTION_QUEUE.md b/packages/flow/docs/EXCEPTION_QUEUE.md index ffadabac27..f6e84ec637 100644 --- a/packages/flow/docs/EXCEPTION_QUEUE.md +++ b/packages/flow/docs/EXCEPTION_QUEUE.md @@ -82,9 +82,13 @@ browser. A verified `continue` or `done_by_person` lifts the hold. Any other outcome (a stop answer, an expiry, an answer off the roster) blocks every later save for the rest of the run, and the watch exits 3. -The watch and the guard each pause requests in their own DevTools session. -Chromium hands a paused request to each session in turn, so a save the watch -blocks is never sent, whichever of the two attached first. +The watch and the guard each pause requests in their own DevTools session, +and Chromium hands a paused request to the session that attached last first. +Start the watch after the guard has attached (`guard: attached` on its +stderr), so the watch decides a save before the guard sees it. In the other +order a save the watch blocks is still never sent, but the guard has already +let it go: it reads back no write, ends the run unconfirmed, and refuses the +agent's later save. Only the guard-first order is tested. The run's folder in the registry is `--run-ref`, or else the `--run-dir` folder's name. `--run-dir` also gets `exceptions_watch.jsonl`: each card @@ -102,7 +106,10 @@ What the watch sees and raises: | `ambiguous_record`, `cannot_complete` | No: only the agent knows | Not covered: agents that don't drive a Chromium, saves over a WebSocket (CDP -`Fetch` doesn't see them), and a run with no watch running. The watch is not a +`Fetch` doesn't see them), tabs other than the one the watch picked (the +first on the app's origin, or `--page-url`), a save sent in the moment +between a prompt appearing and the watch's next look at the page +(`--poll-s`), and a run with no watch running. The watch is not a sandbox: an agent with another way to reach the app, or that stops the watch, gets past it. Tested in headless Chromium on MockMed with the guard attached: an agent that never calls the tool hits a synthetic code prompt, its save is diff --git a/packages/flow/openadapt_flow/exceptions/cli.py b/packages/flow/openadapt_flow/exceptions/cli.py index 804bd4f383..5bf6355d4f 100644 --- a/packages/flow/openadapt_flow/exceptions/cli.py +++ b/packages/flow/openadapt_flow/exceptions/cli.py @@ -73,7 +73,12 @@ def register(sub: argparse._SubParsersAction) -> None: help="Watch the agent's Chromium, raise cards without the agent, and " "block its saves while a card is open", ) - w.add_argument("--cdp", required=True, help="the agent's DevTools endpoint") + w.add_argument( + "--cdp", + required=True, + help="the agent's DevTools endpoint (start the watch after the guard " + "has attached to it)", + ) w.add_argument( "--config", required=True, diff --git a/packages/flow/openadapt_flow/exceptions/watch.py b/packages/flow/openadapt_flow/exceptions/watch.py index f96c3ea8de..c4ad3f8cae 100644 --- a/packages/flow/openadapt_flow/exceptions/watch.py +++ b/packages/flow/openadapt_flow/exceptions/watch.py @@ -22,16 +22,19 @@ browser. Reads always go through. The watch and the guard each pause requests in their own DevTools session. -Chromium hands a paused request to each session in turn, so a save the -watch blocks is never sent, whichever attached first. +Chromium hands a paused request to the session that attached last first, so +start the watch after the guard: it then decides a save before the guard +sees it. (In the other order a blocked save is still never sent, but the +guard has already let it go and ends the run unconfirmed.) Covered, from what the page shows: ``second_factor``, ``unexpected_dialog``, ``session_expired`` (a password field after the watch has seen a save) and, with ``stall_s``, ``timeout_or_stall`` (no request and no screen change). Not covered: ``possible_duplicate`` (it needs a read of the app's records), ``ambiguous_record`` and ``cannot_complete`` (only the agent knows), -non-browser agents, saves over a WebSocket (``Fetch`` doesn't see them), and -a run with no watch running. The watch is not a sandbox: it can't stop an +non-browser agents, saves over a WebSocket (``Fetch`` doesn't see them), +tabs other than the one watched, a save sent before the next look at the page +(``poll_s``), and a run with no watch running. The watch is not a sandbox: it can't stop an agent that has its own way to the app, or one that kills the watch. """ From 85035585d3aa8e61194e5417f291ed02ee9b0abf Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 01:38:29 -0500 Subject: [PATCH 08/11] fix(flow): the exception watch survives a refused request, fails loudly when lost A CDP error from Fetch.continueRequest or Fetch.fulfillRequest (the page aborted a paused save, say) ended the watch loop, and nothing was blocked for the rest of the run. Each decision is now caught and logged as request_decision_failed, and the loop goes on. When the watch's own DevTools session stops answering while the tab is still open, it prints WATCH LOST on stderr, logs watch_lost, reports lost in its output and exits 4 if it was holding saves (a card open or a stop), else 5. The docs say a dead watch blocks nothing, so the guard is the backstop. Tested in headless Chromium: a save the page aborts while paused, then a save that is still blocked; and a dropped session with a card open. --- packages/flow/docs/EXCEPTION_QUEUE.md | 10 + .../flow/openadapt_flow/exceptions/cli.py | 1 + .../flow/openadapt_flow/exceptions/watch.py | 165 +++++++++---- .../e2e/test_exception_watch_faults_e2e.py | 221 ++++++++++++++++++ 4 files changed, 355 insertions(+), 42 deletions(-) create mode 100644 packages/flow/tests/e2e/test_exception_watch_faults_e2e.py diff --git a/packages/flow/docs/EXCEPTION_QUEUE.md b/packages/flow/docs/EXCEPTION_QUEUE.md index f6e84ec637..2b1b2082f6 100644 --- a/packages/flow/docs/EXCEPTION_QUEUE.md +++ b/packages/flow/docs/EXCEPTION_QUEUE.md @@ -82,6 +82,16 @@ browser. A verified `continue` or `done_by_person` lifts the hold. Any other outcome (a stop answer, an expiry, an answer off the roster) blocks every later save for the rest of the run, and the watch exits 3. +The watch holds saves only while it is attached. A request the page aborts +while it is paused, or a block the browser refuses, is logged +(`request_decision_failed`) and the watch goes on. If the watch loses its own +DevTools session while the tab is still open, it says so on stderr, writes +`watch_lost` to `exceptions_watch.jsonl`, reports `"lost"` in its output and +exits 4 when it was holding saves (a card open or a stop) or 5 otherwise. A +dead watch blocks nothing from then on, so run it beside the guard +(`openadapt-flow guard`): the guard still holds each save until the record on +screen is the right one, and reads it back. + The watch and the guard each pause requests in their own DevTools session, and Chromium hands a paused request to the session that attached last first. Start the watch after the guard has attached (`guard: attached` on its diff --git a/packages/flow/openadapt_flow/exceptions/cli.py b/packages/flow/openadapt_flow/exceptions/cli.py index 5bf6355d4f..e5f6aa2339 100644 --- a/packages/flow/openadapt_flow/exceptions/cli.py +++ b/packages/flow/openadapt_flow/exceptions/cli.py @@ -257,6 +257,7 @@ def _stop(signum: int, _frame: object) -> None: { "run_ref": run_ref, "stopped": watch.stopped, + "lost": watch.lost, "outcomes": [o.wire() for o in watch.outcomes], } ) diff --git a/packages/flow/openadapt_flow/exceptions/watch.py b/packages/flow/openadapt_flow/exceptions/watch.py index c4ad3f8cae..4e2453dcc8 100644 --- a/packages/flow/openadapt_flow/exceptions/watch.py +++ b/packages/flow/openadapt_flow/exceptions/watch.py @@ -35,7 +35,9 @@ non-browser agents, saves over a WebSocket (``Fetch`` doesn't see them), tabs other than the one watched, a save sent before the next look at the page (``poll_s``), and a run with no watch running. The watch is not a sandbox: it can't stop an -agent that has its own way to the app, or one that kills the watch. +agent that has its own way to the app, or one that kills the watch. A watch +that loses its DevTools session exits 4 (holding) or 5 and blocks nothing +from then on; the guard remains the backstop. """ from __future__ import annotations @@ -161,6 +163,8 @@ def __init__( #: until the page stops showing them. self._settled: set[str] = set() self._save_seen = False + #: Why the watch lost the tab (``session_lost``, ``browser_lost``). + self.lost: Optional[str] = None self._screen: Optional[str] = None self._last_change: Optional[float] = None self._last_request: Optional[float] = None @@ -276,9 +280,39 @@ def poll(self) -> Optional[Outcome]: self.card = None return outcome + def note_decision_failed(self, code: Optional[str], error: str) -> None: + """The browser refused a continue or a block (logged, not fatal).""" + + self._log("request_decision_failed", code=code, error=error[:64]) + + def mark_lost(self, reason: str) -> None: + """The watch can no longer see or hold the tab. From here it blocks + nothing: the guard (``openadapt-flow guard``) is the backstop.""" + + self.lost = reason + self._log( + "watch_lost", + reason=reason, + card_open=self.card is not None, + stopped=self.stopped, + ) + import sys + + print( + f"exceptions: WATCH LOST ({reason}): saves are no longer held by " + "the watch" + + ("; a card was open or the run was stopped" if self.holding else ""), + file=sys.stderr, + flush=True, + ) + def stop_code(self) -> int: - """The watch's exit code: 0, or 3 when an answer stopped the run.""" + """The watch's exit code: 0; 3 when an answer stopped the run; 4 when + the watch lost the tab's session while it was holding saves (a card + open or a stop); 5 when it lost the session otherwise.""" + if self.lost is not None: + return 4 if self.holding else 5 return 3 if self.stopped is not None else 0 @@ -298,7 +332,11 @@ def _blocked_body(code: str) -> str: return base64.b64encode(payload.encode("utf-8")).decode("ascii") -def _decide(cdp: Any, watch: ExceptionWatch, params: Mapping[str, Any]) -> None: +def _decide(cdp: Any, watch: ExceptionWatch, params: Mapping[str, Any]) -> bool: + """Continue or block one paused request. False when the browser refused + the decision (the page aborted the request, or the session is gone): the + caller checks the session. A request the page aborted was never sent.""" + from openadapt_flow.agent_guard.requests import HeldRequest request_id = str(params.get("requestId") or "") @@ -306,21 +344,85 @@ def _decide(cdp: Any, watch: ExceptionWatch, params: Mapping[str, Any]) -> None: code = watch.on_request(HeldRequest.from_cdp(params)) except Exception: # noqa: BLE001 - the watch can't tell: block while holding code = "exception_open" if watch.holding else None - if code is None: - cdp.send("Fetch.continueRequest", {"requestId": request_id}) - return - cdp.send( - "Fetch.fulfillRequest", - { - "requestId": request_id, - "responseCode": 409, - "responseHeaders": [ - {"name": "Content-Type", "value": "application/json"}, - {"name": BLOCK_HEADER, "value": f"blocked; code={code}"}, - ], - "body": _blocked_body(code), - }, - ) + try: + if code is None: + cdp.send("Fetch.continueRequest", {"requestId": request_id}) + else: + cdp.send( + "Fetch.fulfillRequest", + { + "requestId": request_id, + "responseCode": 409, + "responseHeaders": [ + {"name": "Content-Type", "value": "application/json"}, + {"name": BLOCK_HEADER, "value": f"blocked; code={code}"}, + ], + "body": _blocked_body(code), + }, + ) + except Exception as exc: # noqa: BLE001 - one request must not end the watch + watch.note_decision_failed(code, type(exc).__name__) + return False + return True + + +def _alive(cdp: Any) -> bool: + """The watch's own DevTools session still answers.""" + + try: + cdp.send("Runtime.evaluate", {"expression": "1", "returnByValue": True}) + return True + except Exception: # noqa: BLE001 - detached or the browser is gone + return False + + +def run_loop( + watch: ExceptionWatch, + page: Any, + cdp: Any, + paused: list[Mapping[str, Any]], + *, + poll_s: float = 0.5, + max_s: Optional[float] = None, + stop: Optional[Callable[[], bool]] = None, +) -> None: + """The watch's loop over an attached tab and its own Fetch session. + + Ends when the tab closes, ``stop()`` or ``max_s``, or when the session is + lost while the tab is still open (:meth:`ExceptionWatch.mark_lost`). + """ + + started = time.monotonic() + next_look = 0.0 + while not page.is_closed(): + while paused: + if not _decide(cdp, watch, paused.pop(0)) and not _alive(cdp): + watch.mark_lost("session_lost") + return + if time.monotonic() >= next_look: + if not _alive(cdp): + if page.is_closed(): + return + watch.mark_lost("session_lost") + return + try: + snapshot = page.evaluate(SNAPSHOT_JS) + except Exception: # noqa: BLE001 - navigating: look again + snapshot = None + if isinstance(snapshot, Mapping): + watch.observe(snapshot) + watch.poll() + next_look = time.monotonic() + poll_s + if stop is not None and stop(): + return + if max_s is not None and time.monotonic() - started >= max_s: + return + try: + page.wait_for_timeout(50) # delivers CDP events + except Exception: # noqa: BLE001 - the browser went away + if not page.is_closed(): + watch.mark_lost("browser_lost") + return def _page(browser: Any, app_origin: str, page_url: Optional[str]) -> Any: @@ -384,33 +486,12 @@ def watch_browser( ) if on_attached is not None: on_attached() - started = time.monotonic() - next_look = 0.0 try: - while not page.is_closed(): - while paused: - _decide(cdp, watch, paused.pop(0)) - if time.monotonic() >= next_look: - try: - snapshot = page.evaluate(SNAPSHOT_JS) - except Exception: # noqa: BLE001 - navigating: look again - snapshot = None - if isinstance(snapshot, Mapping): - watch.observe(snapshot) - watch.poll() - next_look = time.monotonic() + poll_s - if stop is not None and stop(): - break - if max_s is not None and time.monotonic() - started >= max_s: - break - page.wait_for_timeout(50) # delivers CDP events + run_loop(watch, page, cdp, paused, poll_s=poll_s, max_s=max_s, stop=stop) finally: # Paused requests go on when the session detaches: decide them first. - while paused: - try: - _decide(cdp, watch, paused.pop(0)) - except Exception: # noqa: BLE001 - the tab is gone - break + while paused and _decide(cdp, watch, paused.pop(0)): + pass try: cdp.detach() except Exception: # noqa: BLE001 - the tab is gone diff --git a/packages/flow/tests/e2e/test_exception_watch_faults_e2e.py b/packages/flow/tests/e2e/test_exception_watch_faults_e2e.py new file mode 100644 index 0000000000..11bb8be7a5 --- /dev/null +++ b/packages/flow/tests/e2e/test_exception_watch_faults_e2e.py @@ -0,0 +1,221 @@ +"""The exception watch under browser faults, in a real headless Chromium. + +* A save the page aborts while the watch holds it paused: the browser refuses + the watch's decision. The watch logs it and keeps going, and the next save + is still blocked while the card is open. +* The watch's own DevTools session is dropped while a card is open: the + watch says so, logs ``watch_lost`` and ends with exit code 4. + +Synthetic page on 127.0.0.1; nothing is sent anywhere else. +""" + +from __future__ import annotations + +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any + +import pytest + +pytest.importorskip("playwright") + +from cryptography.hazmat.primitives.asymmetric.ed25519 import ( # noqa: E402 + Ed25519PrivateKey, +) + +from openadapt_flow.approval_mode.approver_roster import ( # noqa: E402 + ROOT_ENV, + file_key_signer, + init_root, +) +from openadapt_flow.exceptions.registry import ( # noqa: E402 + ExceptionRegistry, + roster_verifier, +) +from openadapt_flow.exceptions.watch import ( # noqa: E402 + _PAUSED_TYPES, + WATCH_EVENTS, + ExceptionWatch, + run_loop, +) +from openadapt_flow.jit.authority import public_hex # noqa: E402 + +pytestmark = pytest.mark.timeout(300) + +PAGE = b"

New note

" +CODE_SCREEN = { + "text": "Verification code", + "elements": [ + { + "tag": "input", + "autocomplete": "one-time-code", + "visible": True, + "bbox": [1, 1, 50, 10], + } + ], +} +#: A save the page gives up on after ``ms``, recorded in window.saveResult. +SAVE = """(ms) => { + window.saveResult = null; + const c = new AbortController(); + fetch('/save', {method: 'POST', body: 'x', signal: c.signal}) + .then(r => { window.saveResult = r.status; }) + .catch(() => { window.saveResult = 'aborted'; }); + if (ms > 0) { setTimeout(() => c.abort(), ms); } +}""" + + +@pytest.fixture +def site(): + hits: list[str] = [] + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_a: Any) -> None: + return None + + def do_GET(self) -> None: # noqa: N802 + self.send_response(200) + self.send_header("Content-Type", "text/html") + self.send_header("Content-Length", str(len(PAGE))) + self.end_headers() + self.wfile.write(PAGE) + + def do_POST(self) -> None: # noqa: N802 + hits.append(self.path) + self.send_response(200) + self.send_header("Content-Length", "0") + self.end_headers() + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + yield f"http://127.0.0.1:{server.server_address[1]}", hits + server.shutdown() + server.server_close() + + +@pytest.fixture +def tab(site): + from playwright.sync_api import sync_playwright + + pw = sync_playwright().start() + try: + browser = pw.chromium.launch(headless=True) + except Exception as exc: # noqa: BLE001 + pw.stop() + pytest.skip(f"chromium unavailable: {exc}") + page = browser.new_page() + page.goto(site[0] + "/") + cdp = page.context.new_cdp_session(page) + paused: list[Any] = [] + cdp.on("Fetch.requestPaused", lambda params: paused.append(params)) + cdp.send( + "Fetch.enable", + { + "patterns": [ + {"urlPattern": "*", "resourceType": t, "requestStage": "Request"} + for t in _PAUSED_TYPES + ] + }, + ) + yield page, cdp, paused + browser.close() + pw.stop() + + +@pytest.fixture +def watch(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, site) -> ExceptionWatch: + key_dir = tmp_path / "keys" + key = Ed25519PrivateKey.generate() + init_root( + key_dir, + principal="front-desk", + public_key=public_hex(key), + sign=file_key_signer(key), + ) + monkeypatch.setenv(ROOT_ENV, public_hex(key)) + return ExceptionWatch( + ExceptionRegistry(tmp_path / "registry"), + run_ref="faults", + verify=roster_verifier(key_dir, public_hex(key)), + app_origin=site[0], + events_path=tmp_path / "run" / WATCH_EVENTS, + ) + + +def _events(tmp_path: Path) -> list[dict]: + path = tmp_path / "run" / WATCH_EVENTS + return [json.loads(line) for line in path.read_text().splitlines()] + + +def _until(page: Any, check: Any, what: str) -> None: + for _ in range(100): + if check(): + return + page.wait_for_timeout(50) + raise AssertionError(f"timed out waiting for {what}") + + +def _ticks(n: int) -> Any: + count = [0] + + def stop() -> bool: + count[0] += 1 + return count[0] >= n + + return stop + + +def test_an_aborted_paused_save_does_not_end_the_watch( + tmp_path: Path, site, tab, watch: ExceptionWatch +) -> None: + _base, hits = site + page, cdp, paused = tab + assert watch.observe(CODE_SCREEN) == "second_factor" + + # The page gives up on a save while the watch holds it paused. + page.evaluate(SAVE, 100) + _until(page, lambda: bool(paused), "the save to be paused") + _until( + page, + lambda: page.evaluate("() => window.saveResult") == "aborted", + "the page to abort", + ) + # The watch decides it late: the browser refuses, the loop goes on. + run_loop(watch, page, cdp, paused, poll_s=0.05, stop=_ticks(5)) + assert watch.lost is None + assert "request_decision_failed" in [e["event"] for e in _events(tmp_path)] + + # The next save is still blocked while the card is open. + page.evaluate(SAVE, 0) + _until(page, lambda: bool(paused), "the second save to be paused") + run_loop(watch, page, cdp, paused, poll_s=0.05, stop=_ticks(5)) + _until( + page, + lambda: page.evaluate("() => window.saveResult") == 409, + "the block", + ) + assert hits == [] + assert watch.stop_code() == 0 + + +def test_a_dropped_session_while_a_card_is_open_exits_loudly( + tmp_path: Path, tab, watch: ExceptionWatch, capsys: pytest.CaptureFixture +) -> None: + page, cdp, paused = tab + assert watch.observe(CODE_SCREEN) == "second_factor" + dropped = [False] + + def drop_then_go_on() -> bool: + if not dropped[0]: + cdp.detach() # the watch's own DevTools session goes away + dropped[0] = True + return False + + run_loop(watch, page, cdp, paused, poll_s=0.05, max_s=30, stop=drop_then_go_on) + assert watch.lost == "session_lost" + assert watch.stop_code() == 4 + [lost] = [e for e in _events(tmp_path) if e["event"] == "watch_lost"] + assert lost["card_open"] is True + assert "WATCH LOST" in capsys.readouterr().err From 695a44b6c8ccd67cd9a664affd952480ec0ceec9 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 02:01:51 -0500 Subject: [PATCH 09/11] fix(flow): the exception watch fails closed on its own errors If a detector, opening a card (a full disk, an unwritable registry) or reading an answer raised, the loop ended, the cleanup let the paused saves through, and the CLI ended on a traceback with exit 1. Now any such error marks the watch failed: every paused and later write is refused with a 409 until the process exits, watch_lost is logged with reason watch_failed, and the watch exits 4. cmd_watch turns any other failure into the same documented code. Also: a request the watch can't classify is refused, not let through; ending with a card still unanswered (--max-s, a signal) exits 6, not 0; EXCEPTION_QUEUE.md says a stop answer blocks later saves for as long as the watch runs. --- packages/flow/docs/EXCEPTION_QUEUE.md | 13 +- .../flow/openadapt_flow/exceptions/cli.py | 9 +- .../flow/openadapt_flow/exceptions/watch.py | 77 ++++++++-- .../e2e/test_exception_watch_faults_e2e.py | 3 +- packages/flow/tests/test_exception_watch.py | 142 +++++++++++++++++- 5 files changed, 222 insertions(+), 22 deletions(-) diff --git a/packages/flow/docs/EXCEPTION_QUEUE.md b/packages/flow/docs/EXCEPTION_QUEUE.md index 2b1b2082f6..dabc8cfaae 100644 --- a/packages/flow/docs/EXCEPTION_QUEUE.md +++ b/packages/flow/docs/EXCEPTION_QUEUE.md @@ -79,15 +79,22 @@ the app's origin that `not_saves` doesn't list, or a write to another origin. Reads go through, and so does a write `not_saves` lists, so list the form a person submits a code or a sign-in with, and they can do it in the live browser. A verified `continue` or `done_by_person` lifts the hold. Any other -outcome (a stop answer, an expiry, an answer off the roster) blocks every -later save for the rest of the run, and the watch exits 3. +outcome (a stop answer, an expiry, an answer off the roster) makes the watch +block every later save for as long as it runs, and it exits 3 when it ends. +A watch that ends (`--max-s` or a signal) with a card still unanswered exits +6. The watch holds saves only while it is attached. A request the page aborts while it is paused, or a block the browser refuses, is logged (`request_decision_failed`) and the watch goes on. If the watch loses its own DevTools session while the tab is still open, it says so on stderr, writes `watch_lost` to `exceptions_watch.jsonl`, reports `"lost"` in its output and -exits 4 when it was holding saves (a card open or a stop) or 5 otherwise. A +exits 4 when it was holding saves (a card open or a stop) or 5 otherwise. +If the watch's own code fails (a detector, opening a card on a full disk or +an unwritable registry, reading an answer), it refuses every paused and later +write with a `409` until it exits, logs `watch_lost` with reason +`watch_failed`, and exits 4. A request it can't classify is refused, not let +through. A dead watch blocks nothing from then on, so run it beside the guard (`openadapt-flow guard`): the guard still holds each save until the record on screen is the right one, and reads it back. diff --git a/packages/flow/openadapt_flow/exceptions/cli.py b/packages/flow/openadapt_flow/exceptions/cli.py index e5f6aa2339..19e31338ee 100644 --- a/packages/flow/openadapt_flow/exceptions/cli.py +++ b/packages/flow/openadapt_flow/exceptions/cli.py @@ -200,6 +200,7 @@ def cmd_watch(args: argparse.Namespace) -> int: from openadapt_flow.exceptions.watch import ( WATCH_EVENTS, ExceptionWatch, + WatchAttachError, watch_browser, ) @@ -249,15 +250,21 @@ def _stop(signum: int, _frame: object) -> None: flush=True, ), ) - except RuntimeError as exc: + except WatchAttachError as exc: print(f"exceptions: {exc}", file=sys.stderr) return 2 + except BaseException as exc: # noqa: BLE001 - any failure is loud, never 1 + if isinstance(exc, (SystemExit, KeyboardInterrupt)) and not watch.holding: + raise + watch.fail(exc if isinstance(exc, Exception) else RuntimeError(str(exc))) + code = watch.stop_code() print( json.dumps( { "run_ref": run_ref, "stopped": watch.stopped, "lost": watch.lost, + "failed": watch.failed, "outcomes": [o.wire() for o in watch.outcomes], } ) diff --git a/packages/flow/openadapt_flow/exceptions/watch.py b/packages/flow/openadapt_flow/exceptions/watch.py index 4e2453dcc8..14a8e4f9a9 100644 --- a/packages/flow/openadapt_flow/exceptions/watch.py +++ b/packages/flow/openadapt_flow/exceptions/watch.py @@ -63,6 +63,8 @@ "SNAPSHOT_JS", "WATCH_EVENTS", "ExceptionWatch", + "WatchAttachError", + "run_loop", "watch_browser", ] @@ -163,8 +165,12 @@ def __init__( #: until the page stops showing them. self._settled: set[str] = set() self._save_seen = False - #: Why the watch lost the tab (``session_lost``, ``browser_lost``). + #: Why the watch lost the tab (``session_lost``, ``browser_lost``, + #: ``watch_failed``). self.lost: Optional[str] = None + #: The watch's own error (detection, opening a card, polling): from + #: then on every write is refused until the process exits. + self.failed: Optional[str] = None self._screen: Optional[str] = None self._last_change: Optional[float] = None self._last_request: Optional[float] = None @@ -189,7 +195,9 @@ def _log(self, event: str, **fields: Any) -> None: def holding(self) -> bool: """Saves are blocked right now.""" - return self.card is not None or self.stopped is not None + return ( + self.card is not None or self.stopped is not None or self.failed is not None + ) def on_request(self, request: Any) -> Optional[str]: """``None``: let the paused request go on; else the block's code.""" @@ -200,9 +208,12 @@ def on_request(self, request: Any) -> Optional[str]: kind = classify(request, app_origin=self.app_origin, not_saves=self.not_saves) if kind == "save": self._save_seen = True - if kind not in ("save", "other_origin") or not self.holding: + if self.failed is not None and kind != "read": + code = "watch_failed" # the watch broke: no write goes on + elif kind not in ("save", "other_origin") or not self.holding: return None - code = "exception_open" if self.card is not None else "exception_stopped" + else: + code = "exception_open" if self.card is not None else "exception_stopped" self._log( "request_blocked", code=code, @@ -298,27 +309,50 @@ def mark_lost(self, reason: str) -> None: ) import sys + what = ( + "every write is refused until the watch exits; after that the " + "watch holds nothing" + if self.failed is not None + else "saves are no longer held by the watch" + ) print( - f"exceptions: WATCH LOST ({reason}): saves are no longer held by " - "the watch" + f"exceptions: WATCH LOST ({reason}): {what}" + ("; a card was open or the run was stopped" if self.holding else ""), file=sys.stderr, flush=True, ) + def fail(self, error: BaseException) -> None: + """The watch's own code failed: refuse every write from here on.""" + + self.failed = type(error).__name__ + self.mark_lost("watch_failed") + def stop_code(self) -> int: - """The watch's exit code: 0; 3 when an answer stopped the run; 4 when - the watch lost the tab's session while it was holding saves (a card - open or a stop); 5 when it lost the session otherwise.""" + """The watch's exit code: + + * 0: the tab closed or the watch was stopped with nothing open; + * 3: an answer stopped the run; + * 4: the watch failed or lost the tab's session while holding saves + (a card open, a stop, or its own error); + * 5: it lost the session with nothing held; + * 6: it ended (``max_s``, a signal) with a card still unanswered. + """ if self.lost is not None: return 4 if self.holding else 5 - return 3 if self.stopped is not None else 0 + if self.stopped is not None: + return 3 + return 6 if self.card is not None else 0 # -- the browser loop ------------------------------------------------------------ +class WatchAttachError(RuntimeError): + """The watch found no tab to watch (nothing was held).""" + + def _blocked_body(code: str) -> str: import base64 @@ -327,6 +361,9 @@ def _blocked_body(code: str) -> str: "Nothing was sent. Wait, then save again." if code == "exception_open" else "A person stopped this run. Nothing was sent; write nothing more." + if code == "exception_stopped" + else "OpenAdapt can't check this request. Nothing was sent; stop and " + "tell a person." ) payload = json.dumps({"error": code, "message": message}) return base64.b64encode(payload.encode("utf-8")).decode("ascii") @@ -342,8 +379,8 @@ def _decide(cdp: Any, watch: ExceptionWatch, params: Mapping[str, Any]) -> bool: request_id = str(params.get("requestId") or "") try: code = watch.on_request(HeldRequest.from_cdp(params)) - except Exception: # noqa: BLE001 - the watch can't tell: block while holding - code = "exception_open" if watch.holding else None + except Exception: # noqa: BLE001 - can't tell what it is: refuse it + code = "request_unclassified" try: if code is None: cdp.send("Fetch.continueRequest", {"requestId": request_id}) @@ -409,9 +446,15 @@ def run_loop( snapshot = page.evaluate(SNAPSHOT_JS) except Exception: # noqa: BLE001 - navigating: look again snapshot = None - if isinstance(snapshot, Mapping): - watch.observe(snapshot) - watch.poll() + try: + if isinstance(snapshot, Mapping): + watch.observe(snapshot) + watch.poll() + except Exception as exc: # noqa: BLE001 - fail closed + # Detection, the card, or its answer broke (a full disk, an + # unwritable registry): refuse every write until exit. + watch.fail(exc) + return next_look = time.monotonic() + poll_s if stop is not None and stop(): return @@ -470,7 +513,7 @@ def watch_browser( browser.close() browser = None if time.monotonic() >= deadline: - raise RuntimeError("no tab on the app's origin to watch") + raise WatchAttachError("no tab on the app's origin to watch") time.sleep(0.25) cdp = page.context.new_cdp_session(page) paused: list[Mapping[str, Any]] = [] @@ -488,6 +531,8 @@ def watch_browser( on_attached() try: run_loop(watch, page, cdp, paused, poll_s=poll_s, max_s=max_s, stop=stop) + except Exception as exc: # noqa: BLE001 - fail closed, then exit 4 + watch.fail(exc) finally: # Paused requests go on when the session detaches: decide them first. while paused and _decide(cdp, watch, paused.pop(0)): diff --git a/packages/flow/tests/e2e/test_exception_watch_faults_e2e.py b/packages/flow/tests/e2e/test_exception_watch_faults_e2e.py index 11bb8be7a5..05e89f6a63 100644 --- a/packages/flow/tests/e2e/test_exception_watch_faults_e2e.py +++ b/packages/flow/tests/e2e/test_exception_watch_faults_e2e.py @@ -197,7 +197,8 @@ def test_an_aborted_paused_save_does_not_end_the_watch( "the block", ) assert hits == [] - assert watch.stop_code() == 0 + assert watch.lost is None + assert watch.stop_code() == 6 # it would end with the card unanswered def test_a_dropped_session_while_a_card_is_open_exits_loudly( diff --git a/packages/flow/tests/test_exception_watch.py b/packages/flow/tests/test_exception_watch.py index e2ce511694..09759edba5 100644 --- a/packages/flow/tests/test_exception_watch.py +++ b/packages/flow/tests/test_exception_watch.py @@ -147,7 +147,8 @@ def test_a_code_screen_opens_a_card_and_blocks_saves_until_a_person_answers( assert watch.observe(CODE_SCREEN) is None assert watch.observe(FORM_SCREEN) is None assert watch.observe(CODE_SCREEN) == "second_factor" - assert watch.stop_code() == 0 + # Ending now would leave that new card unanswered: not a clean exit. + assert watch.stop_code() == 6 events = [e["event"] for e in _events(tmp_path)] assert events[:5] == [ "watch_started", @@ -251,3 +252,142 @@ def test_a_bad_run_ref_is_refused_before_anything_runs(tmp_path: Path, roster) - verify=roster_verifier(key_dir, public_hex(key)), app_origin=APP, ) + + +class _Page: + def __init__(self, snapshot: dict) -> None: + self.snapshot = snapshot + + def is_closed(self) -> bool: + return False + + def evaluate(self, _js: str) -> dict: + return self.snapshot + + def wait_for_timeout(self, _ms: int) -> None: + return None + + +class _Cdp: + def __init__(self) -> None: + self.sent: list[tuple[str, dict]] = [] + + def send(self, method: str, params: dict | None = None) -> dict: + self.sent.append((method, params or {})) + return {} + + +def _paused(path: str = "/api/encounter", rid: str = "1") -> dict: + return { + "requestId": rid, + "request": {"url": APP + path, "method": "POST", "headers": {}}, + "resourceType": "Fetch", + } + + +def _decisions(cdp: _Cdp) -> list[str]: + return [m for m, _ in cdp.sent if m.startswith("Fetch.")] + + +def test_a_registry_it_cannot_write_refuses_every_write_and_exits_4( + tmp_path: Path, roster +) -> None: + """The reviewer's probe: the card can't be written (an unwritable folder + stands in for a full disk). Nothing paused or later goes on.""" + + import os + + from openadapt_flow.exceptions.watch import _decide, run_loop + + key_dir, key = roster + root = tmp_path / "registry" + root.mkdir() + os.chmod(root, 0o500) + try: + watch = ExceptionWatch( + ExceptionRegistry(root), + run_ref="watch-run", + verify=roster_verifier(key_dir, public_hex(key)), + app_origin=APP, + events_path=tmp_path / "run" / WATCH_EVENTS, + ) + cdp = _Cdp() + run_loop(watch, _Page(CODE_SCREEN), cdp, [], poll_s=0.01, max_s=5) + assert watch.failed is not None and watch.lost == "watch_failed" + assert watch.stop_code() == 4 + # A save paused at that moment, and any later one, is refused. + for rid in ("2", "3"): + assert _decide(cdp, watch, _paused(rid=rid)) is True + assert _decisions(cdp) == ["Fetch.fulfillRequest", "Fetch.fulfillRequest"] + assert all( + p["responseCode"] == 409 for m, p in cdp.sent if m.startswith("Fetch.") + ) + lost = [e for e in _events(tmp_path) if e["event"] == "watch_lost"] + assert lost and lost[0]["reason"] == "watch_failed" + finally: + os.chmod(root, 0o700) + + +def test_a_request_it_cannot_classify_is_refused(tmp_path: Path, roster) -> None: + from openadapt_flow.exceptions.watch import _decide + + watch = _watch(tmp_path, roster) + cdp = _Cdp() + assert _decide(cdp, watch, {"requestId": "1", "request": "not a request"}) is True + [(method, params)] = cdp.sent + assert method == "Fetch.fulfillRequest" and params["responseCode"] == 409 + + +def test_ending_with_a_card_open_is_not_a_clean_exit(tmp_path: Path, roster) -> None: + from openadapt_flow.exceptions.watch import run_loop + + watch = _watch(tmp_path, roster) + run_loop(watch, _Page(CODE_SCREEN), _Cdp(), [], poll_s=0.01, max_s=0.2) + assert watch.card is not None and watch.lost is None + assert watch.stop_code() == 6 + + +def test_cmd_watch_turns_any_failure_into_a_documented_code( + tmp_path: Path, roster, monkeypatch: pytest.MonkeyPatch, capsys +) -> None: + import argparse + + from openadapt_flow.exceptions import cli, watch + + config = tmp_path / "guard.yaml" + (tmp_path / "verify.yaml").write_text( + "schema_version: openadapt.verify/v1\n" + "verifier: {kind: rest, base_url: 'http://127.0.0.1:8123'," + " records_path: /api/records}\n" + "effects: [{kind: record_written, match: {note: {param: note}}}]\n" + ) + config.write_text( + "schema_version: openadapt.agent-guard/v1\n" + f"app_url: {APP}/\n" + "verify: verify.yaml\n" + ) + + def broken(w: ExceptionWatch, **_kw: object) -> int: + w.observe(CODE_SCREEN) # a card is open ... + raise ValueError("something the loop didn't expect") # ... and it breaks + + monkeypatch.setattr(watch, "watch_browser", broken) + key_dir, key = roster + args = argparse.Namespace( + approver_root=public_hex(key), + key_dir=str(key_dir), + config=str(config), + run_ref="watch-run", + run_dir=str(tmp_path / "run"), + registry=str(tmp_path / "registry"), + task_id=None, + deadline_s=None, + stall_s=None, + cdp="http://127.0.0.1:9", + page_url=None, + poll_s=0.5, + max_s=None, + ) + assert cli.cmd_watch(args) == 4 + out = json.loads(capsys.readouterr().out.strip().splitlines()[-1]) + assert out["lost"] == "watch_failed" and out["failed"] == "ValueError" From c5309effb6e8a1e224244e77c2419ce7bf56908c Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 02:25:39 -0500 Subject: [PATCH 10/11] fix(flow): a failed exception watch keeps refusing writes until the run ends After the watch's own error, run_loop returned at once, so the agent's next save met no watch. The loop now stays in the failed state, refusing every write, until the tab closes, the session is lost, a signal arrives or max_s passes. Cleanup before detaching decides every paused request and skips one the browser refuses, instead of stopping at it and letting the rest through on detach. Also: the WATCH LOST line names a card or a stop only when there was one, and an interrupt with a card open exits 6. --- packages/flow/docs/EXCEPTION_QUEUE.md | 8 +- .../flow/openadapt_flow/exceptions/cli.py | 10 +- .../flow/openadapt_flow/exceptions/watch.py | 79 +++++++++---- packages/flow/tests/test_exception_watch.py | 108 +++++++++++++++++- 4 files changed, 173 insertions(+), 32 deletions(-) diff --git a/packages/flow/docs/EXCEPTION_QUEUE.md b/packages/flow/docs/EXCEPTION_QUEUE.md index dabc8cfaae..1860af3aa7 100644 --- a/packages/flow/docs/EXCEPTION_QUEUE.md +++ b/packages/flow/docs/EXCEPTION_QUEUE.md @@ -91,9 +91,11 @@ DevTools session while the tab is still open, it says so on stderr, writes `watch_lost` to `exceptions_watch.jsonl`, reports `"lost"` in its output and exits 4 when it was holding saves (a card open or a stop) or 5 otherwise. If the watch's own code fails (a detector, opening a card on a full disk or -an unwritable registry, reading an answer), it refuses every paused and later -write with a `409` until it exits, logs `watch_lost` with reason -`watch_failed`, and exits 4. A request it can't classify is refused, not let +an unwritable registry, reading an answer), it keeps running and refuses +every paused and later write with a `409` until the tab closes, its session +is lost, a signal arrives or `--max-s` passes. It logs `watch_lost` with +reason `watch_failed` and exits 4. Before it detaches, it decides every +paused request, even when the browser refuses one of those decisions. A request it can't classify is refused, not let through. A dead watch blocks nothing from then on, so run it beside the guard (`openadapt-flow guard`): the guard still holds each save until the record on diff --git a/packages/flow/openadapt_flow/exceptions/cli.py b/packages/flow/openadapt_flow/exceptions/cli.py index 19e31338ee..24d935a127 100644 --- a/packages/flow/openadapt_flow/exceptions/cli.py +++ b/packages/flow/openadapt_flow/exceptions/cli.py @@ -253,10 +253,12 @@ def _stop(signum: int, _frame: object) -> None: except WatchAttachError as exc: print(f"exceptions: {exc}", file=sys.stderr) return 2 - except BaseException as exc: # noqa: BLE001 - any failure is loud, never 1 - if isinstance(exc, (SystemExit, KeyboardInterrupt)) and not watch.holding: - raise - watch.fail(exc if isinstance(exc, Exception) else RuntimeError(str(exc))) + except KeyboardInterrupt: + # An interrupt ends the watch like a signal: paused saves were + # decided on the way out; 6 when a card is still unanswered. + code = watch.stop_code() + except Exception as exc: # noqa: BLE001 - any failure is loud, never 1 + watch.fail(exc) code = watch.stop_code() print( json.dumps( diff --git a/packages/flow/openadapt_flow/exceptions/watch.py b/packages/flow/openadapt_flow/exceptions/watch.py index 14a8e4f9a9..20cd2fb68d 100644 --- a/packages/flow/openadapt_flow/exceptions/watch.py +++ b/packages/flow/openadapt_flow/exceptions/watch.py @@ -64,6 +64,7 @@ "WATCH_EVENTS", "ExceptionWatch", "WatchAttachError", + "drain", "run_loop", "watch_browser", ] @@ -315,9 +316,15 @@ def mark_lost(self, reason: str) -> None: if self.failed is not None else "saves are no longer held by the watch" ) + held = ( + "; a card was open" + if self.card is not None + else "; the run was stopped" + if self.stopped is not None + else "" + ) print( - f"exceptions: WATCH LOST ({reason}): {what}" - + ("; a card was open or the run was stopped" if self.holding else ""), + f"exceptions: WATCH LOST ({reason}): {what}{held}", file=sys.stderr, flush=True, ) @@ -325,6 +332,8 @@ def mark_lost(self, reason: str) -> None: def fail(self, error: BaseException) -> None: """The watch's own code failed: refuse every write from here on.""" + if self.failed is not None: + return self.failed = type(error).__name__ self.mark_lost("watch_failed") @@ -403,6 +412,17 @@ def _decide(cdp: Any, watch: ExceptionWatch, params: Mapping[str, Any]) -> bool: return True +def drain(cdp: Any, watch: ExceptionWatch, paused: list[Mapping[str, Any]]) -> None: + """Decide every paused request before the session detaches. A decision + the browser refuses is skipped; the rest are still decided.""" + + while paused: + try: + _decide(cdp, watch, paused.pop(0)) + except Exception: # noqa: BLE001 - one request never stops the rest + continue + + def _alive(cdp: Any) -> bool: """The watch's own DevTools session still answers.""" @@ -442,19 +462,23 @@ def run_loop( return watch.mark_lost("session_lost") return - try: - snapshot = page.evaluate(SNAPSHOT_JS) - except Exception: # noqa: BLE001 - navigating: look again - snapshot = None - try: - if isinstance(snapshot, Mapping): - watch.observe(snapshot) - watch.poll() - except Exception as exc: # noqa: BLE001 - fail closed - # Detection, the card, or its answer broke (a full disk, an - # unwritable registry): refuse every write until exit. - watch.fail(exc) - return + snapshot = None + if watch.failed is None: + try: + snapshot = page.evaluate(SNAPSHOT_JS) + except Exception: # noqa: BLE001 - navigating: look again + snapshot = None + if watch.failed is None: + try: + if isinstance(snapshot, Mapping): + watch.observe(snapshot) + watch.poll() + except Exception as exc: # noqa: BLE001 - fail closed + # Detection, the card, or its answer broke (a full disk, + # an unwritable registry). The loop goes on, refusing + # every write, until the tab closes, the session is + # lost, a signal or max_s ends it. + watch.fail(exc) next_look = time.monotonic() + poll_s if stop is not None and stop(): return @@ -529,14 +553,29 @@ def watch_browser( ) if on_attached is not None: on_attached() + started = time.monotonic() try: - run_loop(watch, page, cdp, paused, poll_s=poll_s, max_s=max_s, stop=stop) - except Exception as exc: # noqa: BLE001 - fail closed, then exit 4 - watch.fail(exc) + try: + run_loop( + watch, page, cdp, paused, poll_s=poll_s, max_s=max_s, stop=stop + ) + except Exception as exc: # noqa: BLE001 - fail closed, then exit 4 + watch.fail(exc) + # Keep refusing writes in the failed state until the run ends. + left = ( + None + if max_s is None + else max(0.0, max_s - (time.monotonic() - started)) + ) + try: + run_loop( + watch, page, cdp, paused, poll_s=poll_s, max_s=left, stop=stop + ) + except Exception: # noqa: BLE001 - the tab or session is gone + pass finally: # Paused requests go on when the session detaches: decide them first. - while paused and _decide(cdp, watch, paused.pop(0)): - pass + drain(cdp, watch, paused) try: cdp.detach() except Exception: # noqa: BLE001 - the tab is gone diff --git a/packages/flow/tests/test_exception_watch.py b/packages/flow/tests/test_exception_watch.py index 09759edba5..eb1c7398d3 100644 --- a/packages/flow/tests/test_exception_watch.py +++ b/packages/flow/tests/test_exception_watch.py @@ -297,7 +297,7 @@ def test_a_registry_it_cannot_write_refuses_every_write_and_exits_4( import os - from openadapt_flow.exceptions.watch import _decide, run_loop + from openadapt_flow.exceptions.watch import run_loop key_dir, key = roster root = tmp_path / "registry" @@ -312,12 +312,26 @@ def test_a_registry_it_cannot_write_refuses_every_write_and_exits_4( events_path=tmp_path / "run" / WATCH_EVENTS, ) cdp = _Cdp() - run_loop(watch, _Page(CODE_SCREEN), cdp, [], poll_s=0.01, max_s=5) + paused: list[dict] = [] + ticks = [0] + + class _Arrives(_Page): + """Saves the agent sends after the failure, as CDP delivers them.""" + + def wait_for_timeout(self, _ms: int) -> None: + ticks[0] += 1 + if watch.failed is not None and ticks[0] in (3, 6): + paused.append(_paused(rid=str(ticks[0]))) + + def stop() -> bool: + return ticks[0] >= 10 + + # The real loop: the card write fails on the first look, and the loop + # stays, refusing the two saves that arrive afterwards. + run_loop(watch, _Arrives(CODE_SCREEN), cdp, paused, poll_s=0.01, stop=stop) assert watch.failed is not None and watch.lost == "watch_failed" assert watch.stop_code() == 4 - # A save paused at that moment, and any later one, is refused. - for rid in ("2", "3"): - assert _decide(cdp, watch, _paused(rid=rid)) is True + assert paused == [] assert _decisions(cdp) == ["Fetch.fulfillRequest", "Fetch.fulfillRequest"] assert all( p["responseCode"] == 409 for m, p in cdp.sent if m.startswith("Fetch.") @@ -391,3 +405,87 @@ def broken(w: ExceptionWatch, **_kw: object) -> int: assert cli.cmd_watch(args) == 4 out = json.loads(capsys.readouterr().out.strip().splitlines()[-1]) assert out["lost"] == "watch_failed" and out["failed"] == "ValueError" + + +def test_cleanup_decides_every_paused_save_when_one_is_refused( + tmp_path: Path, roster +) -> None: + """Paused saves go on when the session detaches, so each one is decided + first; a decision the browser refuses doesn't stop the rest.""" + + from openadapt_flow.exceptions.watch import drain + + class _Refuses(_Cdp): + def send(self, method: str, params: dict | None = None) -> dict: + self.sent.append((method, params or {})) + if (params or {}).get("requestId") == "2": + raise RuntimeError("Invalid InterceptionId") + return {} + + watch = _watch(tmp_path, roster) + watch.observe(CODE_SCREEN) # a card is open: every save is refused + cdp = _Refuses() + paused = [_paused(rid=r) for r in ("1", "2", "3")] + drain(cdp, watch, paused) + assert paused == [] + assert [(m, p["requestId"]) for m, p in cdp.sent] == [ + ("Fetch.fulfillRequest", "1"), + ("Fetch.fulfillRequest", "2"), + ("Fetch.fulfillRequest", "3"), + ] + + +def test_an_interrupt_with_a_card_open_exits_6( + tmp_path: Path, roster, monkeypatch: pytest.MonkeyPatch, capsys +) -> None: + import argparse + + from openadapt_flow.exceptions import cli, watch + + (tmp_path / "verify.yaml").write_text( + "schema_version: openadapt.verify/v1\n" + "verifier: {kind: rest, base_url: 'http://127.0.0.1:8123'," + " records_path: /api/records}\n" + "effects: [{kind: record_written, match: {note: {param: note}}}]\n" + ) + config = tmp_path / "guard.yaml" + config.write_text( + "schema_version: openadapt.agent-guard/v1\n" + f"app_url: {APP}/\n" + "verify: verify.yaml\n" + ) + + def interrupted(w: ExceptionWatch, **_kw: object) -> int: + w.observe(CODE_SCREEN) + raise KeyboardInterrupt + + monkeypatch.setattr(watch, "watch_browser", interrupted) + key_dir, key = roster + args = argparse.Namespace( + approver_root=public_hex(key), + key_dir=str(key_dir), + config=str(config), + run_ref="watch-run", + run_dir=str(tmp_path / "run"), + registry=str(tmp_path / "registry"), + task_id=None, + deadline_s=None, + stall_s=None, + cdp="http://127.0.0.1:9", + page_url=None, + poll_s=0.5, + max_s=None, + ) + assert cli.cmd_watch(args) == 6 + out = json.loads(capsys.readouterr().out.strip().splitlines()[-1]) + assert out["lost"] is None and out["failed"] is None + + +def test_the_lost_message_names_no_card_when_none_was_open( + tmp_path: Path, roster, capsys +) -> None: + watch = _watch(tmp_path, roster) + watch.fail(OSError("disk full")) + err = capsys.readouterr().err + assert "every write is refused until the watch exits" in err + assert "card was open" not in err and "run was stopped" not in err From 95f8d19fdf353b97706583ba25cb860396cdadf0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 03:18:05 -0500 Subject: [PATCH 11/11] fix(flow): CI for the exception queue (binary descriptors, CDP readiness, a doc link) - The registry opened its card and answer files with a plain os.open, so on Windows os.read and os.write used text mode (the Windows guards job, test_binary_file_descriptors). It now uses private_file.open_binary. - The watch attached over CDP without the rendering check every other attach makes (test_browser_readiness). It now calls require_rendering_ready on the tab it selected, and is in the inventory of CDP attaches. - The exceptions command note linked EXCEPTION_QUEUE.md with a path that only works from the repo root, which the link check reads relative to the note's folder. It now names the path as code. --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- .../flow/docs/commands/03-run-and-answer/exceptions.md | 2 +- packages/flow/openadapt_flow/exceptions/registry.py | 8 +++++--- packages/flow/openadapt_flow/exceptions/watch.py | 8 +++++++- packages/flow/tests/test_binary_file_descriptors.py | 1 + packages/flow/tests/test_browser_readiness.py | 1 + 7 files changed, 17 insertions(+), 7 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index b30862938e..078d46e646 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -424,7 +424,7 @@ A test fails when a command has no file or this list is out of date. - `business-decisions` - `console` - `deferred` -- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md). +- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See `packages/flow/docs/EXCEPTION_QUEUE.md`. - `explain` - `item-approval` - `replay` diff --git a/llms-full.txt b/llms-full.txt index 3fbdf3f12e..9b4f0f96c5 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -884,7 +884,7 @@ A test fails when a command has no file or this list is out of date. - `business-decisions` - `console` - `deferred` -- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EXCEPTION_QUEUE.md). +- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See `packages/flow/docs/EXCEPTION_QUEUE.md`. - `explain` - `item-approval` - `replay` diff --git a/packages/flow/docs/commands/03-run-and-answer/exceptions.md b/packages/flow/docs/commands/03-run-and-answer/exceptions.md index 001a2e5dbb..441819d1de 100644 --- a/packages/flow/docs/commands/03-run-and-answer/exceptions.md +++ b/packages/flow/docs/commands/03-run-and-answer/exceptions.md @@ -1 +1 @@ -Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md). +Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See `packages/flow/docs/EXCEPTION_QUEUE.md`. diff --git a/packages/flow/openadapt_flow/exceptions/registry.py b/packages/flow/openadapt_flow/exceptions/registry.py index 92aad562db..8392cf917f 100644 --- a/packages/flow/openadapt_flow/exceptions/registry.py +++ b/packages/flow/openadapt_flow/exceptions/registry.py @@ -54,6 +54,8 @@ card_digest, ) +from openadapt_flow.private_file import open_binary + #: How long a card waits for a person by default, and at most. DEFAULT_DEADLINE_S = 15 * 60 MAX_DEADLINE_S = 24 * 60 * 60 @@ -258,7 +260,7 @@ def _read_regular(path: Path, *, limit: int = _MAX_FILE_BYTES) -> Optional[bytes for a link, a non-regular file or one over ``limit``.""" try: - fd = os.open(path, _flags(os.O_RDONLY)) + fd = open_binary(path, _flags(os.O_RDONLY)) except FileNotFoundError: return None try: @@ -282,7 +284,7 @@ def _write_exclusive(path: Path, payload: bytes) -> None: """Create ``path`` once, 0600. Raises ``FileExistsError`` if it's there.""" tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") - fd = os.open(tmp, _flags(os.O_WRONLY | os.O_CREAT | os.O_EXCL), 0o600) + fd = open_binary(tmp, _flags(os.O_WRONLY | os.O_CREAT | os.O_EXCL), 0o600) try: view = memoryview(payload) while view: @@ -298,7 +300,7 @@ def _write_exclusive(path: Path, payload: bytes) -> None: except OSError: pass try: - dfd = os.open(path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + dfd = open_binary(path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) except OSError: return try: diff --git a/packages/flow/openadapt_flow/exceptions/watch.py b/packages/flow/openadapt_flow/exceptions/watch.py index 20cd2fb68d..5a9542b238 100644 --- a/packages/flow/openadapt_flow/exceptions/watch.py +++ b/packages/flow/openadapt_flow/exceptions/watch.py @@ -522,6 +522,8 @@ def watch_browser( from playwright.sync_api import sync_playwright + from openadapt_flow._browser_readiness import require_rendering_ready + pw = sync_playwright().start() try: deadline = time.monotonic() + attach_wait_s @@ -530,7 +532,11 @@ def watch_browser( try: browser = pw.chromium.connect_over_cdp(cdp_endpoint) page = _page(browser, watch.app_origin, page_url) - except Exception: # noqa: BLE001 - not up yet + if page is not None: + # The tab must render before its screen is trusted, as + # for every other CDP attach (the guard's included). + require_rendering_ready(browser, attached_page=page) + except Exception: # noqa: BLE001 - not up or not rendering yet page = None if page is None: if browser is not None: diff --git a/packages/flow/tests/test_binary_file_descriptors.py b/packages/flow/tests/test_binary_file_descriptors.py index d81c3ca8fd..e356e7c70d 100644 --- a/packages/flow/tests/test_binary_file_descriptors.py +++ b/packages/flow/tests/test_binary_file_descriptors.py @@ -100,6 +100,7 @@ def test_raw_descriptor_entry_points_cannot_fall_back_to_text_open(): covered = raw_descriptor_owners(source) assert "approval_mode/item_approval.py" in covered assert "write_ledger.py" in covered + assert "exceptions/registry.py" in covered def test_binary_open_refuses_an_explicit_text_mode( diff --git a/packages/flow/tests/test_browser_readiness.py b/packages/flow/tests/test_browser_readiness.py index 4617488ce0..1fc92a5a2b 100644 --- a/packages/flow/tests/test_browser_readiness.py +++ b/packages/flow/tests/test_browser_readiness.py @@ -321,6 +321,7 @@ def test_all_cdp_acquisitions_check_their_selected_page() -> None: "cli_worklist_pool.py": "_open", "agent_guard/session.py": "_connect", "copilot_runtime.py": "main", + "exceptions/watch.py": "watch_browser", } observed = {} for path in root.rglob("*.py"):