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