diff --git a/packages/flow/openadapt_flow/form_tx/lookup_location.py b/packages/flow/openadapt_flow/form_tx/lookup_location.py new file mode 100644 index 0000000000..b0ab9870ce --- /dev/null +++ b/packages/flow/openadapt_flow/form_tx/lookup_location.py @@ -0,0 +1,106 @@ +"""The chosen row of a lookup table as an effect location: echo before commit. + +A lookup popup (a class finder, a directory search) shows one row per result, +each with its own commit button. The value the popup puts back in the parent +must be the one the chosen row showed. The row is read just before the commit +click (``row_reading``): the cells that fully match the subroutine's +``result_row_pattern`` are the matches. After the popup closes, the value in +the parent is judged against that reading by the shared evaluator +(``judge_returned_value``), as an ``openadapt.effect-location/v1`` record with +a ``row_key`` locator and start ``same_screen``. + +- ``held``: the row showed exactly that value once. +- ``refuted``: the row showed another value. +- ``not_checked``: the row showed no such cell or more than one, the value + can't be read, or the return codec is one the shared codecs don't read the + same way. The caller stops on anything but ``held``. +""" + +from __future__ import annotations + +import re +from typing import Any + +from openadapt_flow.effect_location import ( + Codec, + EffectLocation, + KeyResult, + Locator, + Reading, + evaluate, +) +from openadapt_flow.form_tx.codecs import CodecValueError, normalize_with_codec +from openadapt_flow.form_tx.types import ( + FieldCodecSpec, + FormCodecKind, + ObservedControl, + PopupSubroutineSpec, +) + +__all__ = ["judge_returned_value", "row_reading"] + + +def _codec(spec: FieldCodecSpec) -> Codec: + if spec.kind == FormCodecKind.WHITESPACE_COLLAPSE: + return Codec("text") + if spec.kind == FormCodecKind.CASEFOLD: + return Codec("fold") + if spec.kind == FormCodecKind.ISO_DATE: + return Codec("date", date_order=spec.date_order) + return Codec(f"form_tx:{spec.kind.value}") + + +def _location_id(subroutine: PopupSubroutineSpec) -> str: + return f"lookup_row:{subroutine.subroutine_id}" + + +def row_reading( + subroutine: PopupSubroutineSpec, commit_control: ObservedControl, *, run_id: str +) -> Reading: + """The chosen row's matching cells, read before the commit click.""" + + pattern = subroutine.result_row_pattern or "" + cells = tuple(" ".join(c.split()) for c in commit_control.row_cells) + try: + hits = tuple(c for c in cells if c and re.fullmatch(pattern, c)) + error = None if cells else "the commit control is not in a table row" + except re.error: + hits, error = (), "the result row pattern does not compile" + return Reading( + location_id=_location_id(subroutine), + run_id=run_id, + start="same_screen", + matches=tuple({"text": h} for h in hits), + complete=True, + error=error, + ) + + +def judge_returned_value( + subroutine: PopupSubroutineSpec, + reading: Reading, + returned: Any, + *, + run_id: str, +) -> KeyResult: + """Whether the value put back in the parent is the one the row showed.""" + + key = subroutine.return_output_key + try: + expected = normalize_with_codec(returned, subroutine.return_codec) + except CodecValueError: + return KeyResult( + key, "not_checked", "the value put back can't be read", code="bad_expected" + ) + location = EffectLocation( + id=_location_id(subroutine), + keys=(key,), + path=(), + start="same_screen", + locator=Locator(kind="row_key", value=subroutine.result_row_pattern or ""), + codec=_codec(subroutine.return_codec), + expected={key: expected}, + expected_count=1, + source="form_tx.popup_subroutines.result_row_pattern", + ) + return evaluate(location, reading, run_id=run_id).results[0] diff --git a/packages/flow/openadapt_flow/form_tx/reconciler.py b/packages/flow/openadapt_flow/form_tx/reconciler.py index 0e19114b86..068a90fa0a 100644 --- a/packages/flow/openadapt_flow/form_tx/reconciler.py +++ b/packages/flow/openadapt_flow/form_tx/reconciler.py @@ -17,6 +17,7 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from openadapt_flow.effect_location import Reading from openadapt_flow.form_tx.codecs import ( CodecValueError, collapse_whitespace, @@ -27,6 +28,7 @@ values_equivalent, ) from openadapt_flow.form_tx.judge import SummaryJudge +from openadapt_flow.form_tx.lookup_location import judge_returned_value, row_reading from openadapt_flow.form_tx.playwright_surface import ( PopupContractError, SurfaceSettleTimeoutError, @@ -2395,6 +2397,7 @@ def _popup_snapshot(surface: FormSurfaceBackend) -> FormSnapshot: ) commit_selector: Optional[str] = None displayed_result: Optional[str] = None + row_read: Optional[Reading] = None with popup_cm as popup_surface: popup_snap = _popup_snapshot(popup_surface) @@ -2562,6 +2565,9 @@ def _popup_snapshot(surface: FormSurfaceBackend) -> FormSnapshot: ) ] + if subroutine.result_row_pattern is not None: + # Echo before commit: read the chosen row before it closes. + row_read = row_reading(subroutine, popup_commit, run_id=session.run_id) commit_selector = popup_commit.dom_selector popup_surface.click(commit_selector) @@ -2634,6 +2640,29 @@ def _popup_snapshot(surface: FormSurfaceBackend) -> FormSnapshot: } return [halt] + if row_read is not None: + judged = judge_returned_value( + subroutine, row_read, return_after.current_value, run_id=session.run_id + ) + if judged.status != "held": + return [ + self._popup_contract_halt( + session, + after_parent_snap, + subroutine, + f"popup_row|{subroutine.subroutine_id}|{judged.code}", + f"Popup {subroutine.subroutine_id!r} put " + f"{return_after.current_value!r} in " + f"{subroutine.return_output_key!r}, and the chosen row " + f"does not show it: {judged.reason}", + ) + ] + # The row showed exactly this value: it is the popup's result, + # unless a declared result_anchor already gave one; that one is + # still compared below. + if displayed_result is None: + displayed_result = return_after.current_value + # The value put back in the parent must be the figure the popup showed. # An estimator that shows one figure and hands back another (rounded, # capped, stale) stops here rather than going through unseen. diff --git a/packages/flow/openadapt_flow/form_tx/types.py b/packages/flow/openadapt_flow/form_tx/types.py index ba7ce9c108..aa1da3536f 100644 --- a/packages/flow/openadapt_flow/form_tx/types.py +++ b/packages/flow/openadapt_flow/form_tx/types.py @@ -15,7 +15,14 @@ from enum import Enum from typing import Any, Literal, Optional -from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator +from pydantic import ( + BaseModel, + ConfigDict, + Field, + field_validator, + model_serializer, + model_validator, +) FORM_DOSSIER_SCHEMA: Literal["openadapt.form-dossier/v1"] = "openadapt.form-dossier/v1" UI_PROFILE_SCHEMA: Literal["openadapt.ui-profile/v1"] = "openadapt.ui-profile/v1" @@ -395,6 +402,14 @@ class PopupSubroutineSpec(BaseModel): # ``return_codec``, or the run stops before submit. A declared result that # cannot be read is also a stop. result_anchor: Optional[FieldAnchorSpec] = None + # For a lookup table (one row per result, each with its own commit + # button): a pattern that exactly one cell of the chosen row must match in + # full, such as a code column. That cell is read just before the commit + # click and the value put back in the parent must equal it under + # ``return_codec`` (``whitespace_collapse``, ``casefold`` or ``iso_date``), + # or the run stops before submit. A row with no such cell, or more than + # one, is also a stop. + result_row_pattern: Optional[str] = None commit_anchor: FieldAnchorSpec parent_return_anchor: FieldAnchorSpec return_output_key: str = Field(min_length=1) @@ -403,6 +418,38 @@ class PopupSubroutineSpec(BaseModel): ) condition_dossier_key: Optional[str] = None + @field_validator("result_row_pattern") + @classmethod + def _row_pattern_compiles(cls, value: Optional[str]) -> Optional[str]: + if value is not None: + try: + re.compile(value) + except re.error as exc: + raise ValueError(f"Invalid result row pattern {value!r}: {exc}") from exc + return value + + @model_validator(mode="after") + def _row_pattern_needs_a_text_codec(self) -> "PopupSubroutineSpec": + if self.result_row_pattern is not None and self.return_codec.kind not in ( + FormCodecKind.WHITESPACE_COLLAPSE, + FormCodecKind.CASEFOLD, + FormCodecKind.ISO_DATE, + ): + raise ValueError( + "result_row_pattern needs a whitespace_collapse, casefold or " + "iso_date return_codec" + ) + return self + + @model_serializer(mode="wrap") + def _omit_unset_row_pattern(self, handler: Any) -> Any: + # Left out while unset, so a pack written before the field existed + # dumps and hashes exactly as before. + data = handler(self) + if isinstance(data, dict) and data.get("result_row_pattern") is None: + data.pop("result_row_pattern", None) + return data + class ModalRuleSpec(BaseModel): """Declarative detection of dynamic confirmation/duplicate modals.""" diff --git a/packages/flow/tests/test_form_tx_lookup_row.py b/packages/flow/tests/test_form_tx_lookup_row.py new file mode 100644 index 0000000000..2db42229e8 --- /dev/null +++ b/packages/flow/tests/test_form_tx_lookup_row.py @@ -0,0 +1,325 @@ +"""A lookup table's chosen row as an effect location (headless Chromium, synthetic). + +A class finder shows one row per result, each with its own Select button. +With ``result_row_pattern`` the chosen row's code cell is read before Select, +and the value put back in the parent must be that code. Without it, the code +stays ``not_checked`` because it came from a popup whose search term is not +checked (the old behaviour, still the default). +""" + +from __future__ import annotations + +import json +from typing import Any, Optional + +import pytest +from playwright.sync_api import Browser, Route, sync_playwright + +from openadapt_flow.form_tx.playwright_surface import PlaywrightFormSurface +from openadapt_flow.form_tx.reconciler import FormReconciler +from openadapt_flow.form_tx.types import ( + DossierFact, + FieldAnchorSpec, + FieldBindingSpec, + FieldCodecSpec, + FormHaltKind, + FormPack, + FormTxOutcome, + InputDossier, + PopupSubroutineSpec, + ProvenanceKind, + ReadbackStatus, + SummaryCheckSpec, + UIProfileSpec, + WizardScreenSpec, +) + +ORIGIN = "http://lookup.local" +CLASSES = [("5461", "Bakery"), ("5812", "Restaurant"), ("7230", "Beauty salon")] + + +def _form(lie: Optional[str], anchor_text: Optional[str] = None) -> str: + rows = json.dumps(CLASSES) + put_back = json.dumps(lie) if lie is not None else "code" + return f"""Application + +

Application

+
+ + + + + + +
+ +

Class finder

+ + + + {f'{anchor_text}' if anchor_text else ""} + +
CodeDescription
+
+""" + + +def _summary(record: dict[str, Any]) -> str: + return f"""Summary +

Summary

+ + + + +""" + + +class _Portal: + def __init__( + self, lie: Optional[str] = None, anchor_text: Optional[str] = None + ) -> None: + self.lie = lie + self.anchor_text = anchor_text + self.submissions: list[dict[str, Any]] = [] + + def handle(self, route: Route) -> None: + req = route.request + path = req.url[len(ORIGIN) :].split("?")[0] + if path == "/app": + route.fulfill( + status=200, + content_type="text/html", + body=_form(self.lie, self.anchor_text), + ) + elif path == "/submit" and req.method == "POST": + self.submissions.append(json.loads(req.post_data or "{}")) + route.fulfill(status=200, content_type="application/json", body="{}") + elif path == "/summary": + record = self.submissions[-1] if self.submissions else {} + route.fulfill(status=200, content_type="text/html", body=_summary(record)) + else: + route.fulfill(status=404, body="not found") + + +def _pack(row_pattern: Optional[str], anchor: bool = False) -> FormPack: + return FormPack( + pack_id="lookup-row", + domain_schema="test.application/v1", + ui_profile_id="lookup-row-test", + bindings=( + FieldBindingSpec( + binding_id="biz", + dossier_key="business_name", + anchor=FieldAnchorSpec(label_patterns=("^Business name$",)), + ), + ), + popup_subroutines=( + PopupSubroutineSpec( + subroutine_id="class_finder", + popup_mode="in_page", + trigger_anchor=FieldAnchorSpec(label_patterns=(r"^Find class\.\.\.$",)), + bindings=( + FieldBindingSpec( + binding_id="kw", + dossier_key="class_keyword", + anchor=FieldAnchorSpec(label_patterns=("^Search classes$",)), + ), + ), + compute_anchors=(FieldAnchorSpec(label_patterns=("^Search$",)),), + result_row_pattern=row_pattern, + result_anchor=( + FieldAnchorSpec(label_patterns=("^Selected class$",)) + if anchor + else None + ), + commit_anchor=FieldAnchorSpec(label_patterns=("^Select$",)), + parent_return_anchor=FieldAnchorSpec(label_patterns=("^Class code$",)), + return_output_key="class_code", + return_codec=FieldCodecSpec(), + ), + ), + screens=( + WizardScreenSpec( + screen_id="app", + is_commit_screen=True, + commit_button_anchor=FieldAnchorSpec( + label_patterns=("^Submit application$",) + ), + ), + WizardScreenSpec(screen_id="summary"), + ), + summary_check=SummaryCheckSpec( + summary_url_path="/summary", + field_readbacks=( + FieldBindingSpec( + binding_id="rb_biz", + dossier_key="business_name", + anchor=FieldAnchorSpec(label_patterns=("^Business name$",)), + ), + FieldBindingSpec( + binding_id="rb_code", + dossier_key="class_code", + anchor=FieldAnchorSpec(label_patterns=("^Class code$",)), + ), + ), + ), + ) + + +def _dossier() -> InputDossier: + raw = {"business_name": "Crumb & Co", "class_keyword": "bakery"} + return InputDossier( + dossier_id="d1", + request_id="r1", + facts={ + k: DossierFact( + key=k, + value=v, + provenance=ProvenanceKind.INTAKE_DOCUMENT, + source_id="intake", + ) + for k, v in raw.items() + }, + ) + + +@pytest.fixture(scope="module") +def chromium_browser() -> Any: + with sync_playwright() as pw: + try: + browser = pw.chromium.launch(channel="chromium", headless=True) + except Exception: + browser = pw.chromium.launch(headless=True) + try: + yield browser + finally: + browser.close() + + +def _run( + browser: Browser, portal: _Portal, row_pattern: Optional[str], anchor: bool = False +) -> Any: + ctx = browser.new_context(viewport={"width": 1280, "height": 800}) + try: + ctx.route(f"{ORIGIN}/**", portal.handle) + page = ctx.new_page() + surface = PlaywrightFormSurface( + page, UIProfileSpec(profile_id="lookup-row-test"), base_origin=ORIGIN + ) + surface.goto(f"{ORIGIN}/app") + reconciler = FormReconciler(surface) + session = reconciler.create_session(_pack(row_pattern, anchor), _dossier()) + return reconciler.run_until_halt_or_done(session) + finally: + ctx.close() + + +def _status(result: Any, key: str) -> Any: + by_key = {v.dossier_key: v for v in result.summary_verdict.field_verdicts} + return by_key[key] + + +def test_without_a_row_pattern_the_code_stays_not_checked( + chromium_browser: Browser, +) -> None: + portal = _Portal() + result = _run(chromium_browser, portal, None) + assert portal.submissions == [{"biz": "Crumb & Co", "class_code": "5461"}], ( + result.outcome, + result.what_happened, + ) + assert _status(result, "class_code").status == ReadbackStatus.NOT_CHECKED + + +def test_the_chosen_row_lets_the_code_be_checked(chromium_browser: Browser) -> None: + portal = _Portal() + result = _run(chromium_browser, portal, r"\d{4}") + assert portal.submissions == [{"biz": "Crumb & Co", "class_code": "5461"}], ( + result.outcome, + result.what_happened, + result.halts, + ) + assert _status(result, "class_code").status == ReadbackStatus.PASSED + # The search term itself is still only re-read in the popup. + assert _status(result, "class_keyword").status == ReadbackStatus.NOT_CHECKED + assert result.outcome == FormTxOutcome.READBACK_INCOMPLETE + + +def test_a_popup_that_puts_back_another_code_stops_before_submit( + chromium_browser: Browser, +) -> None: + portal = _Portal(lie="9999") + result = _run(chromium_browser, portal, r"\d{4}") + assert portal.submissions == [] + assert result.outcome == FormTxOutcome.HALTED_NEEDS_HUMAN + assert result.halts[0].kind == FormHaltKind.POPUP_CONTRACT_FAILED + assert "chosen row" in result.halts[0].message + + +def test_a_row_with_no_matching_cell_stops_before_submit( + chromium_browser: Browser, +) -> None: + portal = _Portal() + result = _run(chromium_browser, portal, r"[A-Z]{3}-\d+") + assert portal.submissions == [] + assert result.outcome == FormTxOutcome.HALTED_NEEDS_HUMAN + assert result.halts[0].kind == FormHaltKind.POPUP_CONTRACT_FAILED + + +def test_a_declared_result_anchor_is_still_compared(chromium_browser: Browser) -> None: + # The row shows 5461 and 5461 is put back, but the popup's own result + # field says 5812: the anchor comparison still stops the run. + portal = _Portal(anchor_text="5812") + result = _run(chromium_browser, portal, r"\d{4}", anchor=True) + assert portal.submissions == [] + assert result.outcome == FormTxOutcome.HALTED_NEEDS_HUMAN + assert result.halts[0].kind == FormHaltKind.PREFILL_VALUE_CONFLICT + + +def test_an_unset_row_pattern_is_not_dumped() -> None: + spec = PopupSubroutineSpec( + subroutine_id="s", + trigger_anchor=FieldAnchorSpec(label_patterns=("x",)), + commit_anchor=FieldAnchorSpec(label_patterns=("y",)), + parent_return_anchor=FieldAnchorSpec(label_patterns=("z",)), + return_output_key="k", + return_codec=FieldCodecSpec(), + ) + assert "result_row_pattern" not in spec.model_dump(mode="json") + with pytest.raises(ValueError): + PopupSubroutineSpec.model_validate( + {**spec.model_dump(mode="json"), "result_row_pattern": "("} + ) + # The row is read through the shared text and date codecs only. + with pytest.raises(ValueError): + PopupSubroutineSpec.model_validate( + { + **spec.model_dump(mode="json"), + "result_row_pattern": r"\d+", + "return_codec": {"kind": "currency_cents"}, + } + )