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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions packages/flow/openadapt_flow/form_tx/lookup_location.py
Original file line number Diff line number Diff line change
@@ -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]
29 changes: 29 additions & 0 deletions packages/flow/openadapt_flow/form_tx/reconciler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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.
Expand Down
49 changes: 48 additions & 1 deletion packages/flow/openadapt_flow/form_tx/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand All @@ -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."""
Expand Down
Loading
Loading