diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 99a45200e6..91a2f4d90d 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -159,7 +159,7 @@ improvising or retrying when something is off. | Read the saved record back from the system of record (API, database, FHIR, separate session) | Released | Real app (OpenEMR 12 of 12 fields) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md), `runtime/effects/` | | Read values out of an app as a workflow step (READ), with a records format, a signed review queue and export to CSV or a database | Released ([#1229](https://github.com/OpenAdaptAI/OpenAdapt/pull/1229), [#1215](https://github.com/OpenAdaptAI/OpenAdapt/pull/1215), [#1218](https://github.com/OpenAdaptAI/OpenAdapt/pull/1218)–[#1224](https://github.com/OpenAdaptAI/OpenAdapt/pull/1224)) | Synthetic (mock desktop apps) | `openadapt_flow/interchange/` | | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | -| Fill a multi-step browser form or quote wizard from an intake record, including forms in same-origin iframes and open shadow roots, typed type-aheads, radio groups and two-step or in-page popup estimators; stop for an operator on a prefill that disagrees with the intake, a question the intake does not answer, a sign-in wall or session-expiry banner, or a control it cannot act on; submit once; and give every typed, selected or kept field a read-back verdict (`passed`, `failed` or `not_checked`), including from summaries shown as page text. A field it cannot read back is `not_checked`, never passed; such a submit ends `readback_incomplete` with no receipt ([#2449](https://github.com/OpenAdaptAI/OpenAdapt/pull/2449), [#2448](https://github.com/OpenAdaptAI/OpenAdapt/pull/2448), [#2440](https://github.com/OpenAdaptAI/OpenAdapt/pull/2440), [#2441](https://github.com/OpenAdaptAI/OpenAdapt/pull/2441), [#2447](https://github.com/OpenAdaptAI/OpenAdapt/pull/2447)) | On main, prototype; not on PyPI until Flow 3.4.0 ([#2308](https://github.com/OpenAdaptAI/OpenAdapt/pull/2308)) | Synthetic only, pre-registered. Four new held-out quote portals, 33 cases: 6 correct, 5 wrong submitted, all flagged after submit and none with a receipt, but 2 of the 5 (`fc-s02`, `gw-s04`) were flagged on other fields, not the wrong one, because the wrong control had no binding, 1 verified with a receipt; 15 of 18 trap cases stopped before submit but none of those then ended correct; 10 of 15 clean cases stopped. Verdict: rework. On the first four portals (now a dev set) 20 of 32 correct, 10 verified, and 2 receipts for wrong quotes, because a receipt covers only the fields the pack binds. A sign-in mid-quote can reset fields the layer does not re-check (caught by read-back). Rule proposals from repeated operator answers had no measured effect ([RESULTS](packages/flow/benchmark/form_tx_heldout2_run/RESULTS.md)) | `openadapt_flow/form_tx/`, [FORM_TX.md](packages/flow/docs/FORM_TX.md) | +| Fill a multi-step browser form or quote wizard from an intake record, including forms in same-origin iframes and open shadow roots, typed type-aheads, radio groups and two-step or in-page popup estimators; stop for an operator on a prefill that disagrees with the intake, a question the intake does not answer, a sign-in wall or session-expiry banner, or a control it cannot act on; submit once; and give every typed, selected or kept field a read-back verdict (`passed`, `failed` or `not_checked`), including from summaries shown as page text. A field it cannot read back is `not_checked`, never passed; such a submit ends `readback_incomplete` with no receipt ([#2449](https://github.com/OpenAdaptAI/OpenAdapt/pull/2449), [#2448](https://github.com/OpenAdaptAI/OpenAdapt/pull/2448), [#2440](https://github.com/OpenAdaptAI/OpenAdapt/pull/2440), [#2441](https://github.com/OpenAdaptAI/OpenAdapt/pull/2441), [#2447](https://github.com/OpenAdaptAI/OpenAdapt/pull/2447)) After a sign-in or a jump back it walks the screens again before submit, or stops naming the fields it cannot re-check; a control no binding covers, or an intake value no binding enters, keeps a run from `verified_done`, and a receipt lists the keys it covers and what it does not; a bound field shown with no intake value stops unless the pack marks it optional, a review page that shows a different value stops before submit, and `form_tx/demo_compiler.py` derives proven defaults, row key cells, option codecs and unopened popups from dev-case demonstrations ([#2461](https://github.com/OpenAdaptAI/OpenAdapt/pull/2461)) | On main, prototype; not on PyPI until Flow 3.4.0 ([#2308](https://github.com/OpenAdaptAI/OpenAdapt/pull/2308)) | Synthetic only, pre-registered. Four new held-out quote portals, 33 cases: 6 correct, 5 wrong submitted, all flagged after submit and none with a receipt, but 2 of the 5 (`fc-s02`, `gw-s04`) were flagged on other fields, not the wrong one, because the wrong control had no binding, 1 verified with a receipt; 15 of 18 trap cases stopped before submit but none of those then ended correct; 10 of 15 clean cases stopped. Verdict: rework. On the first four portals (now a dev set) 20 of 32 correct, 10 verified, and 2 receipts for wrong quotes, because a receipt covers only the fields the pack binds. A sign-in mid-quote can reset fields the layer does not re-check (caught by read-back). Rule proposals from repeated operator answers had no measured effect ([RESULTS](packages/flow/benchmark/form_tx_heldout2_run/RESULTS.md)) | `openadapt_flow/form_tx/`, [FORM_TX.md](packages/flow/docs/FORM_TX.md) | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | | Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | PR [#2500](https://github.com/OpenAdaptAI/OpenAdapt/pull/2500), not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](packages/flow/docs/EFFECT_LOCATION.md) | diff --git a/llms-full.txt b/llms-full.txt index 6ce960ec5b..3841f1fb59 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -619,7 +619,7 @@ improvising or retrying when something is off. | Read the saved record back from the system of record (API, database, FHIR, separate session) | Released | Real app (OpenEMR 12 of 12 fields) | [VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFICATION.md), `runtime/effects/` | | Read values out of an app as a workflow step (READ), with a records format, a signed review queue and export to CSV or a database | Released ([#1229](https://github.com/OpenAdaptAI/OpenAdapt/pull/1229), [#1215](https://github.com/OpenAdaptAI/OpenAdapt/pull/1215), [#1218](https://github.com/OpenAdaptAI/OpenAdapt/pull/1218)–[#1224](https://github.com/OpenAdaptAI/OpenAdapt/pull/1224)) | Synthetic (mock desktop apps) | `openadapt_flow/interchange/` | | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | -| Fill a multi-step browser form or quote wizard from an intake record, including forms in same-origin iframes and open shadow roots, typed type-aheads, radio groups and two-step or in-page popup estimators; stop for an operator on a prefill that disagrees with the intake, a question the intake does not answer, a sign-in wall or session-expiry banner, or a control it cannot act on; submit once; and give every typed, selected or kept field a read-back verdict (`passed`, `failed` or `not_checked`), including from summaries shown as page text. A field it cannot read back is `not_checked`, never passed; such a submit ends `readback_incomplete` with no receipt ([#2449](https://github.com/OpenAdaptAI/OpenAdapt/pull/2449), [#2448](https://github.com/OpenAdaptAI/OpenAdapt/pull/2448), [#2440](https://github.com/OpenAdaptAI/OpenAdapt/pull/2440), [#2441](https://github.com/OpenAdaptAI/OpenAdapt/pull/2441), [#2447](https://github.com/OpenAdaptAI/OpenAdapt/pull/2447)) | On main, prototype; not on PyPI until Flow 3.4.0 ([#2308](https://github.com/OpenAdaptAI/OpenAdapt/pull/2308)) | Synthetic only, pre-registered. Four new held-out quote portals, 33 cases: 6 correct, 5 wrong submitted, all flagged after submit and none with a receipt, but 2 of the 5 (`fc-s02`, `gw-s04`) were flagged on other fields, not the wrong one, because the wrong control had no binding, 1 verified with a receipt; 15 of 18 trap cases stopped before submit but none of those then ended correct; 10 of 15 clean cases stopped. Verdict: rework. On the first four portals (now a dev set) 20 of 32 correct, 10 verified, and 2 receipts for wrong quotes, because a receipt covers only the fields the pack binds. A sign-in mid-quote can reset fields the layer does not re-check (caught by read-back). Rule proposals from repeated operator answers had no measured effect ([RESULTS](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/form_tx_heldout2_run/RESULTS.md)) | `openadapt_flow/form_tx/`, [FORM_TX.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FORM_TX.md) | +| Fill a multi-step browser form or quote wizard from an intake record, including forms in same-origin iframes and open shadow roots, typed type-aheads, radio groups and two-step or in-page popup estimators; stop for an operator on a prefill that disagrees with the intake, a question the intake does not answer, a sign-in wall or session-expiry banner, or a control it cannot act on; submit once; and give every typed, selected or kept field a read-back verdict (`passed`, `failed` or `not_checked`), including from summaries shown as page text. A field it cannot read back is `not_checked`, never passed; such a submit ends `readback_incomplete` with no receipt ([#2449](https://github.com/OpenAdaptAI/OpenAdapt/pull/2449), [#2448](https://github.com/OpenAdaptAI/OpenAdapt/pull/2448), [#2440](https://github.com/OpenAdaptAI/OpenAdapt/pull/2440), [#2441](https://github.com/OpenAdaptAI/OpenAdapt/pull/2441), [#2447](https://github.com/OpenAdaptAI/OpenAdapt/pull/2447)) After a sign-in or a jump back it walks the screens again before submit, or stops naming the fields it cannot re-check; a control no binding covers, or an intake value no binding enters, keeps a run from `verified_done`, and a receipt lists the keys it covers and what it does not; a bound field shown with no intake value stops unless the pack marks it optional, a review page that shows a different value stops before submit, and `form_tx/demo_compiler.py` derives proven defaults, row key cells, option codecs and unopened popups from dev-case demonstrations ([#2461](https://github.com/OpenAdaptAI/OpenAdapt/pull/2461)) | On main, prototype; not on PyPI until Flow 3.4.0 ([#2308](https://github.com/OpenAdaptAI/OpenAdapt/pull/2308)) | Synthetic only, pre-registered. Four new held-out quote portals, 33 cases: 6 correct, 5 wrong submitted, all flagged after submit and none with a receipt, but 2 of the 5 (`fc-s02`, `gw-s04`) were flagged on other fields, not the wrong one, because the wrong control had no binding, 1 verified with a receipt; 15 of 18 trap cases stopped before submit but none of those then ended correct; 10 of 15 clean cases stopped. Verdict: rework. On the first four portals (now a dev set) 20 of 32 correct, 10 verified, and 2 receipts for wrong quotes, because a receipt covers only the fields the pack binds. A sign-in mid-quote can reset fields the layer does not re-check (caught by read-back). Rule proposals from repeated operator answers had no measured effect ([RESULTS](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/form_tx_heldout2_run/RESULTS.md)) | `openadapt_flow/form_tx/`, [FORM_TX.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FORM_TX.md) | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | | Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | PR [#2500](https://github.com/OpenAdaptAI/OpenAdapt/pull/2500), not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EFFECT_LOCATION.md) | diff --git a/packages/flow/openadapt_flow/form_tx/demo_compiler.py b/packages/flow/openadapt_flow/form_tx/demo_compiler.py new file mode 100644 index 0000000000..fd6b72771b --- /dev/null +++ b/packages/flow/openadapt_flow/form_tx/demo_compiler.py @@ -0,0 +1,347 @@ +"""Pack-authoring report compiled from dev-case demonstrations, at setup time. + +A demonstration is the JSONL a recorder writes while a careful person fills a +form: before each interaction, what ``PlaywrightFormSurface`` sees (controls +with labels, values, options and row cells; page-text pairs; banners). From +one or more demonstrations and their intakes this module derives the pack +data a person would otherwise have to guess: + +- **defaults table**: the value each bound control shows before anyone + touches it. A value is a *proven* portal default only when it is the same + blank value in every demonstration and at least one intake asked for + something else, so it cannot be that client's data. Everything else is + reported, never asserted. +- **row key cells**: for identical buttons in table rows ("Select"), the + intake keys whose value is a cell of exactly one row. +- **option codecs**: a select's option codes and their visible text, as an + ``ENUM_MAP`` codec, so a code entered and a label shown read back the same. +- **unopened launchers**: buttons the demonstrations showed but never + clicked and the pack does not cover, so the author covers or marks them. +- **error routes** (suggest-only): a validation message seen in a banner and + the field whose label it names. + +Only proven defaults, exact row cells and exact option maps are offered as +pack data. Inferred mappings (error routes, a control the demonstration +skipped) are suggestions: the compiler never writes them into a pack, and +they never count toward a verified read-back. + +Zero model calls; no application names. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Iterable, Literal, Mapping, Optional, Sequence + +from pydantic import BaseModel, ConfigDict, Field + +from openadapt_flow.form_tx.codecs import collapse_whitespace +from openadapt_flow.form_tx.surface import ( + AmbiguousAnchorError, + match_anchor_in_snapshot, +) +from openadapt_flow.form_tx.types import ( + ControlKind, + FieldBindingSpec, + FieldCodecSpec, + FormCodecKind, + FormPack, + FormSnapshot, + ObservedControl, +) + +__all__ = [ + "DefaultFinding", + "DemoReport", + "compile_demo_report", + "load_demo", +] + + +def _norm(text: Any) -> str: + return collapse_whitespace(str(text)).casefold() + + +def load_demo(path: str | Path) -> list[dict[str, Any]]: + """Rows of a recorded demonstration (``FORM_TX_DEMO`` lines or plain JSONL).""" + rows: list[dict[str, Any]] = [] + for line in Path(path).read_text().splitlines(): + line = line.strip() + if not line: + continue + if line.startswith("FORM_TX_DEMO "): + line = line[len("FORM_TX_DEMO ") :] + elif not line.startswith("{"): + continue + row = json.loads(line) + if isinstance(row, dict) and "controls" in row: + rows.append(row) + return rows + + +def _snapshot(row: Mapping[str, Any]) -> FormSnapshot: + controls = [] + for raw in row.get("controls") or (): + data = {k: v for k, v in raw.items() if k in ObservedControl.model_fields} + data.setdefault("control_id", data.get("dom_selector") or "ctrl") + data.setdefault("dom_selector", data["control_id"]) + if "options" in data: + data["options"] = tuple(data["options"]) + if "row_cells" in data: + data["row_cells"] = tuple(data["row_cells"]) + controls.append(ObservedControl.model_validate(data)) + return FormSnapshot( + url_origin_and_path=str(row.get("frame_url") or ""), + controls=tuple(controls), + banner_errors=tuple(row.get("banners") or ()), + ) + + +def _shown(ctrl: ObservedControl) -> str: + if ctrl.input_type.casefold() in ("checkbox",) or ctrl.role == "checkbox": + return "true" if ctrl.checked else "false" + if ctrl.input_type.casefold() == "radio" or ctrl.role == "radio": + return ctrl.current_value if ctrl.checked else "" + return ctrl.current_value + + +class DefaultFinding(BaseModel): + """What one bound control showed before anyone touched it, per demo.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + binding_id: str + dossier_key: str + blank_values: tuple[str, ...] + intake_values: tuple[str, ...] + status: Literal[ + "proven_default", "unproven_same_as_intake", "differs_between_demos", "blank" + ] + + +class RowKeySuggestion(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + button_label: str + dossier_keys: tuple[str, ...] + rows_seen: int + + +class DemoReport(BaseModel): + """Everything the compiler found, and what it offers as pack data.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + demos_used: int + defaults: tuple[DefaultFinding, ...] = () + row_keys: tuple[RowKeySuggestion, ...] = () + option_codecs: dict[str, FieldCodecSpec] = Field(default_factory=dict) + unopened_launchers: tuple[str, ...] = () + suggested_error_routes: tuple[tuple[str, str], ...] = () + unseen_bindings: tuple[str, ...] = () + + def proven_defaults(self) -> dict[str, tuple[str, ...]]: + """binding_id -> values safe to put in ``portal_default_values``.""" + return { + f.binding_id: tuple(sorted(set(f.blank_values))) + for f in self.defaults + if f.status == "proven_default" + } + + +def _first_sightings( + rows: Sequence[Mapping[str, Any]], bindings: Sequence[FieldBindingSpec] +) -> dict[str, ObservedControl]: + """The first time each binding's control is seen in a demonstration.""" + seen: dict[str, ObservedControl] = {} + for row in rows: + snap = _snapshot(row) + for b in bindings: + if b.binding_id in seen: + continue + try: + ctrl = match_anchor_in_snapshot(b.anchor, snap, include_readonly=False) + except AmbiguousAnchorError: + continue + if ctrl is not None: + seen[b.binding_id] = ctrl + return seen + + +def _clicked_text(rows: Sequence[Mapping[str, Any]]) -> str: + return " ".join(_norm(r.get("why") or "") for r in rows) + + +def compile_demo_report( + pack: FormPack, + demos: Sequence[tuple[Sequence[Mapping[str, Any]], Mapping[str, Any]]], +) -> DemoReport: + """Compile a report from ``(demo rows, intake facts)`` pairs.""" + bindings = [ + b + for b in ( + *pack.bindings, + *(b for s in pack.popup_subroutines for b in s.bindings), + ) + if b.control_kind + not in (ControlKind.POPUP_LAUNCHER, ControlKind.READONLY_OUTPUT) + ] + sightings = [_first_sightings(rows, bindings) for rows, _ in demos] + + defaults: list[DefaultFinding] = [] + for b in bindings: + firsts = [s.get(b.binding_id) for s in sightings] + if any(c is None for c in firsts): + continue + blanks = tuple(_shown(c) for c in firsts if c is not None) + intakes = tuple( + "" if facts.get(b.dossier_key) is None else str(facts.get(b.dossier_key)) + for _, facts in demos + ) + if not any(_norm(v) for v in blanks): + status = "blank" + elif len({_norm(v) for v in blanks}) > 1: + status = "differs_between_demos" + elif any(_norm(i) != _norm(blanks[0]) for i in intakes): + status = "proven_default" + else: + status = "unproven_same_as_intake" + defaults.append( + DefaultFinding( + binding_id=b.binding_id, + dossier_key=b.dossier_key, + blank_values=blanks, + intake_values=intakes, + status=status, # type: ignore[arg-type] + ) + ) + + unseen = tuple( + sorted( + b.binding_id + for b in bindings + if any(b.binding_id not in s for s in sightings) + ) + ) + + # Option codecs: exact code -> text maps from the selects themselves. + codecs: dict[str, FieldCodecSpec] = {} + for b in bindings: + if b.control_kind != ControlKind.SELECT: + continue + for s in sightings: + ctrl = s.get(b.binding_id) + if ctrl is None or not ctrl.options: + continue + aliases: dict[str, tuple[str, ...]] = { + o.value: (o.label,) + for o in ctrl.options + if o.value and o.label and _norm(o.value) != _norm(o.label) + } + if aliases: + codecs[b.binding_id] = FieldCodecSpec( + kind=FormCodecKind.ENUM_MAP, enum_aliases=aliases + ) + break + + # Row key cells and unopened launchers, from every row of every demo. + row_keys: dict[str, RowKeySuggestion] = {} + buttons: dict[str, str] = {} + routes: set[tuple[str, str]] = set() + clicked = " ".join(_clicked_text(rows) for rows, _ in demos) + covered_labels = _pack_button_labels(pack) + for rows, facts in demos: + values = { + k: _norm(v) for k, v in facts.items() if v is not None and str(v).strip() + } + for row in rows: + snap = _snapshot(row) + by_label: dict[str, list[ObservedControl]] = {} + for c in snap.controls: + if c.tag == "button" or c.input_type in ("button", "submit"): + label = collapse_whitespace(c.label_text or c.current_value) + if label: + by_label.setdefault(label, []).append(c) + buttons.setdefault(_norm(label), label) + for label, group in by_label.items(): + if len(group) < 2 or not all(c.row_cells for c in group): + continue + keys = tuple( + sorted( + k + for k, v in values.items() + if sum(1 for c in group if v in {_norm(x) for x in c.row_cells}) + == 1 + ) + ) + if keys: + row_keys[label] = RowKeySuggestion( + button_label=label, dossier_keys=keys, rows_seen=len(group) + ) + for banner in snap.banner_errors: + text = _norm(banner) + for c in snap.controls: + label = collapse_whitespace(c.label_text) + if len(label) >= 4 and _norm(label) in text: + routes.add((collapse_whitespace(banner)[:120], label)) + unopened = tuple( + sorted( + label + for key, label in buttons.items() + if key not in clicked and key not in covered_labels + ) + ) + return DemoReport( + demos_used=len(demos), + defaults=tuple(defaults), + row_keys=tuple(row_keys.values()), + option_codecs=codecs, + unopened_launchers=unopened, + suggested_error_routes=tuple(sorted(routes)), + unseen_bindings=unseen, + ) + + +def _pack_button_labels(pack: FormPack) -> set[str]: + """Normalized literal labels of every button the pack already handles.""" + anchors: list[Any] = [] + for s in pack.screens: + anchors += [s.next_button_anchor, s.commit_button_anchor] + for sub in pack.popup_subroutines: + anchors += [sub.trigger_anchor, sub.commit_anchor, *sub.compute_anchors] + anchors += [u.anchor for u in pack.unbound_controls] + out: set[str] = set() + for a in anchors: + if a is None: + continue + for p in a.label_patterns: + out.add(_norm(p.strip("^$").replace("\\", ""))) + return out + + +def _main(argv: Optional[Iterable[str]] = None) -> int: + import argparse + import importlib + + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("pack_module", help="module exporting PACK") + ap.add_argument( + "--demo", + nargs=2, + action="append", + metavar=("DEMO_JSONL", "INTAKE_JSON"), + required=True, + ) + args = ap.parse_args(list(argv) if argv is not None else None) + pack = importlib.import_module(args.pack_module).PACK + demos = [] + for demo_path, intake_path in args.demo: + intake = json.loads(Path(intake_path).read_text()) + demos.append((load_demo(demo_path), intake.get("facts", intake))) + print(compile_demo_report(pack, demos).model_dump_json(indent=1)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(_main()) diff --git a/packages/flow/openadapt_flow/form_tx/judge.py b/packages/flow/openadapt_flow/form_tx/judge.py index 4d8375d36f..36aeedab16 100644 --- a/packages/flow/openadapt_flow/form_tx/judge.py +++ b/packages/flow/openadapt_flow/form_tx/judge.py @@ -12,13 +12,16 @@ from __future__ import annotations +import re from typing import Any, Mapping, Optional, Sequence from urllib.parse import urlsplit from openadapt_flow.form_tx.codecs import ( + _MONTH_MAP, CodecValueError, collapse_whitespace, normalize_with_codec, + parse_iso_date_strict, values_equivalent, ) from openadapt_flow.form_tx.surface import ( @@ -184,6 +187,40 @@ def _text_pair_matches( return False +def _pattern_value(pattern: str, text: str) -> Any: + """The one value ``pattern``'s first group finds in ``text``. + + ``None`` when it finds nothing, ``False`` when matches disagree. + """ + try: + found = { + collapse_whitespace(m.group(1)) + for m in re.finditer(pattern, text or "") + if m.groups() and m.group(1) and m.group(1).strip() + } + except re.error: + return False + if not found: + return None + if len(found) > 1: + return False + return found.pop() + + +def _split_date_expected(day: Any, month: Any, year: Any) -> Optional[str]: + """ISO date from day, month (number or name) and year values, or None.""" + try: + d = int(str(day).strip()) + y = int(str(year).strip()) + m_raw = str(month).strip() + m = int(m_raw) if m_raw.isdigit() else _MONTH_MAP.get(m_raw.casefold()) + if m is None: + return None + return parse_iso_date_strict(f"{y:04d}-{m:02d}-{d:02d}") + except (ValueError, CodecValueError): + return None + + def _extract_present_outputs( snapshot: FormSnapshot, output_specs: Sequence[OutputExtractionSpec], @@ -199,6 +236,17 @@ def _extract_present_outputs( except AmbiguousAnchorError: invalid_keys.add(spec.output_key) continue + if ctrl is None and spec.value_pattern: + found = _pattern_value(spec.value_pattern, snapshot.page_text) + if found is False: + invalid_keys.add(spec.output_key) + continue + if found: + try: + extracted[spec.output_key] = normalize_with_codec(found, spec.codec) + except CodecValueError: + invalid_keys.add(spec.output_key) + continue if ctrl is None: # A read-only summary may show the output (a quote number, a # premium) as page text rather than in a control. @@ -251,6 +299,9 @@ def evaluate( known_outputs: Optional[Mapping[str, Any]] = None, supplemental_facts: Optional[Mapping[str, DossierFact]] = None, writes: Sequence[FieldWriteRecord] = (), + uncovered: Optional[Mapping[str, str]] = None, + unentered_intake_keys: Sequence[str] = (), + review_skipped: Optional[Mapping[str, str]] = None, ) -> SummaryVerdict: """Navigate/search if configured, verify all read-backs, and extract outputs.""" active_surface = surface if surface is not None else self._surface @@ -293,6 +344,10 @@ def evaluate( ), *observation_screens, ) + # How the read was produced (reporting only): the page the run + # landed on after commit, or a new navigation or search that fetched + # it from the server again. + read_route = "same_screen" snapshot = active_surface.snapshot(screens=observation_screens) seeded_outputs: dict[str, Any] = dict(known_outputs or {}) pre_outputs, _ = _extract_present_outputs(snapshot, summary_check.outputs) @@ -303,6 +358,7 @@ def evaluate( snapshot.url_origin_and_path, summary_check.summary_url_path ): active_surface.goto(summary_check.summary_url_path) + read_route = "fresh_navigation" snapshot = active_surface.snapshot(screens=observation_screens) # Execute search-by-key lookup when configured. @@ -343,6 +399,7 @@ def evaluate( input_ctrl.dom_selector, str(lookup_val) ) active_surface.click(submit_ctrl.dom_selector) + read_route = "fresh_navigation" snapshot = active_surface.snapshot(screens=observation_screens) verdicts: list[ReadbackFieldVerdict] = [] @@ -392,6 +449,8 @@ def _failed( declared_keys = { binding.dossier_key for binding in summary_check.field_readbacks } + for sd in summary_check.split_date_readbacks: + declared_keys |= {sd.day_key, sd.month_key, sd.year_key} expected_keys = { binding.dossier_key for binding in active_pack.bindings @@ -617,36 +676,112 @@ def _where(field_writes: Sequence[FieldWriteRecord]) -> str: ) ) - observations: dict[str, set[str]] = {} - for rb in summary_check.field_readbacks: + # A date typed in day, month and year boxes, shown as one value. + for sd in summary_check.split_date_readbacks: + keys = (sd.day_key, sd.month_key, sd.year_key) + facts3 = [expected_facts.get(k) for k in keys] + if all(f is None for f in facts3): + continue + provs = [ + f.provenance if f is not None else ProvenanceKind.INTAKE_DOCUMENT + for f in facts3 + ] + expected_iso = ( + _split_date_expected(*(f.value for f in facts3 if f is not None)) + if all(f is not None for f in facts3) + else None + ) + shown_date: Optional[str] = None + reason = "" try: - oc = match_anchor_in_snapshot( - rb.anchor, snapshot, include_readonly=True + ctrl = match_anchor_in_snapshot( + sd.anchor, snapshot, include_readonly=True ) - except AmbiguousAnchorError: + if ctrl is not None: + shown_date = ctrl.current_value + else: + pair = match_text_pair_in_snapshot(sd.anchor, snapshot) + shown_date = pair.value if pair is not None else None + except AmbiguousAnchorError as exc: + reason = f"Date is shown more than once: {exc}" + if expected_iso is None: + for k, prov in zip(keys, provs): + verdicts.append( + _not_checked( + k, prov, "Day, month and year do not form a date to compare" + ) + ) continue - if oc is not None: - observations.setdefault(rb.dossier_key, set()).add(oc.dom_selector) + if shown_date is None or not shown_date.strip(): + for k, prov in zip(keys, provs): + verdicts.append( + _not_checked( + k, prov, reason or "The summary does not show this date" + ) + ) continue - # A value shown as page text, not in a control, is an observation - # too; two read-backs that land on the same shown pair are one. try: - pair = match_text_pair_in_snapshot(rb.anchor, snapshot) - except AmbiguousAnchorError: - continue - if pair is not None: - observations.setdefault(rb.dossier_key, set()).add( - f"text|{pair.source}|{pair.section_text}|{pair.label}" + shown_iso = parse_iso_date_strict(shown_date, date_order=sd.date_order) + except CodecValueError: + shown_iso = None + for k, prov in zip(keys, provs): + if shown_iso == expected_iso: + verdicts.append( + ReadbackFieldVerdict( + dossier_key=k, + codec_kind=FormCodecKind.ISO_DATE, + passed=True, + status=ReadbackStatus.PASSED, + provenance=prov, + reason="Read back as one date with its day, month and year", + ) + ) + elif shown_iso is None: + verdicts.append( + _not_checked( + k, prov, f"Shown date {shown_date!r} could not be read" + ) + ) + else: + verdicts.append( + _failed( + k, + FormCodecKind.ISO_DATE, + prov, + f"Summary shows the date {shown_iso}, not {expected_iso}", + ) + ) + + # Fields no binding covers that held a value this run did not set. + for label, shown in sorted((uncovered or {}).items()): + verdicts.append( + _not_checked( + f"unbound:{label}", + ProvenanceKind.INTAKE_DOCUMENT, + f"No binding covers {label!r}, which held {shown!r} that this " + "run did not set", + ) + ) + + # Review read-backs that were skipped before submit. + for key, why in sorted((review_skipped or {}).items()): + verdicts.append( + _not_checked( + f"review:{key}", + ProvenanceKind.INTAKE_DOCUMENT, + f"The review page check for {key!r} was skipped: {why}", + ) + ) + + # Intake values no binding entered: the record may lack them. + for key in sorted(set(unentered_intake_keys)): + verdicts.append( + _not_checked( + f"intake:{key}", + ProvenanceKind.INTAKE_DOCUMENT, + f"The intake has a value for {key!r}, but no binding enters it", ) - evaluated_subjects = read_subjects(writes, active_resolutions) - verdicts.extend( - uncovered_subject_verdicts( - evaluated_subjects, - verdicts, - _codec_for, - {k: len(v) for k, v in observations.items()}, ) - ) # A value that came only from a popup is no better checked than the # popup inputs that produced it. If one of those inputs is not @@ -689,6 +824,54 @@ def _where(field_writes: Sequence[FieldWriteRecord]) -> str: f"{unchecked_inputs} are not checked, and was not " "compared with the popup's displayed result", ) + observations: dict[str, set[str]] = {} + for rb in summary_check.field_readbacks: + try: + oc = match_anchor_in_snapshot( + rb.anchor, snapshot, include_readonly=True + ) + except AmbiguousAnchorError: + continue + if oc is not None: + observations.setdefault(rb.dossier_key, set()).add(oc.dom_selector) + continue + # A value shown as page text, not in a control, is an observation + # too; two read-backs that land on the same shown pair are one. + try: + pair = match_text_pair_in_snapshot(rb.anchor, snapshot) + except AmbiguousAnchorError: + continue + if pair is not None: + observations.setdefault(rb.dossier_key, set()).add( + f"text|{pair.source}|{pair.section_text}|{pair.label}" + ) + # A split date shown once is one observation for each of its parts. + for sd in summary_check.split_date_readbacks: + date_seen: Optional[str] = None + try: + oc = match_anchor_in_snapshot( + sd.anchor, snapshot, include_readonly=True + ) + if oc is not None: + date_seen = oc.dom_selector + else: + tp = match_text_pair_in_snapshot(sd.anchor, snapshot) + if tp is not None: + date_seen = f"text|{tp.source}|{tp.section_text}|{tp.label}" + except AmbiguousAnchorError: + continue + if date_seen is not None: + for k in (sd.day_key, sd.month_key, sd.year_key): + observations.setdefault(k, set()).add(date_seen) + evaluated_subjects = read_subjects(writes, active_resolutions) + verdicts.extend( + uncovered_subject_verdicts( + evaluated_subjects, + verdicts, + _codec_for, + {k: len(v) for k, v in observations.items()}, + ) + ) screen_problems: list[str] = [] if snapshot.auth_wall_present: @@ -762,6 +945,7 @@ def _where(field_writes: Sequence[FieldWriteRecord]) -> str: ) return SummaryVerdict( + read_route=read_route, # type: ignore[arg-type] passed=passed, checked_count=sum( 1 for v in verdicts if v.status != ReadbackStatus.NOT_CHECKED diff --git a/packages/flow/openadapt_flow/form_tx/playwright_surface.py b/packages/flow/openadapt_flow/form_tx/playwright_surface.py index c73f99e826..d85c14ea90 100644 --- a/packages/flow/openadapt_flow/form_tx/playwright_surface.py +++ b/packages/flow/openadapt_flow/form_tx/playwright_surface.py @@ -698,7 +698,8 @@ def _strip_url_to_origin_and_path(raw_url: str) -> str: 'input:not([type="hidden"]), select, textarea, [role="combobox"], [role="checkbox"], [role="radio"]' ); if (innerControls.length <= 1) { - for (const sel of (cfg.fieldErrorSelectors || [])) { + // An alert inside the field's own box is that field's error. + for (const sel of [...(cfg.fieldErrorSelectors || []), ...(cfg.errorBannerSelectors || [])]) { for (const errNode of safeQueryAll(container, sel)) { if (errNode === el || isInteractiveElement(errNode)) continue; if (isVisible(errNode)) { @@ -738,6 +739,47 @@ def _strip_url_to_origin_and_path(raw_url: str) -> str: return null; }; + // The text of a control's own row: the nearest table row or list item, + // else the largest ancestor holding no other field (a radio group is one + // field). Table rows also give their cell texts. + const FIELD_SEL = 'input:not([type="hidden"]):not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="image"]), select, textarea, [role="combobox"], [role="checkbox"], [role="radio"]'; + const fieldCount = (node) => { + let n = 0; + const groups = new Set(); + for (const x of safeQueryAll(node, FIELD_SEL)) { + const isRadio = (x.tagName === 'INPUT' && (x.getAttribute('type') || '').toLowerCase() === 'radio') || + (x.getAttribute('role') || '').toLowerCase() === 'radio'; + if (isRadio) { + const g = x.getAttribute('name') || + (x.closest('[role="radiogroup"]') ? computeDomSelector(x.closest('[role="radiogroup"]')) : ''); + if (g) { + if (groups.has(g)) continue; + groups.add(g); + } + } + n += 1; + } + return n; + }; + const rowInfoFor = (el) => { + const row = el.closest('tr, [role="row"], li'); + if (row) { + const cells = Array.from(row.children) + .filter((c) => c.tagName === 'TD' || c.tagName === 'TH' || + ['cell', 'gridcell', 'rowheader'].includes((c.getAttribute('role') || '').toLowerCase())) + .map((c) => cleanText(c.textContent)); + return {text: cleanText(row.textContent).slice(0, 500), cells}; + } + let box = el.parentElement; + let best = null; + while (box && box !== document.body && box !== document.documentElement && box.tagName !== 'FORM') { + if (fieldCount(box) > 1) break; + best = box; + box = box.parentElement; + } + return {text: best ? cleanText(best.textContent).slice(0, 500) : '', cells: []}; + }; + // 1. Controls const rawControlNodes = safeQueryAll( document, @@ -758,7 +800,7 @@ def _strip_url_to_origin_and_path(raw_url: str) -> str: const domSelector = computeDomSelector(el); const nameAttr = el.getAttribute('name') || ''; const idAttr = el.id || ''; - const labelText = resolveLabelText(el, tag, inputType, role); + let labelText = resolveLabelText(el, tag, inputType, role); const sectionText = resolveSectionText(el); const isSecret = detectSecret(el, inputType, nameAttr, idAttr); @@ -851,6 +893,15 @@ def _strip_url_to_origin_and_path(raw_url: str) -> str: currentValue = ''; } else if (tag === 'output' || el.hasAttribute('data-readonly-output')) { currentValue = cleanText(el.value !== undefined ? el.value : el.textContent); + // An output with no label of its own that shows "Label: value" + // is read as that label and that value. + if (!labelText) { + const m = /^([^:]{2,80}):\s*(\S.*)$/.exec(currentValue); + if (m) { + labelText = cleanText(m[1]); + currentValue = cleanText(m[2]); + } + } } else { currentValue = String(el.value ?? ''); } @@ -906,6 +957,10 @@ def _strip_url_to_origin_and_path(raw_url: str) -> str: radio_value: radioValue, radio_group: radioGroup, group_label: groupLabel, + ...(() => { + const ri = rowInfoFor(el); + return {row_text: ri.text, row_cells: ri.cells}; + })(), modal_container: (() => { const m = closestOpenModal(el); @@ -1576,6 +1631,10 @@ def mutation_count(self) -> int: """Count of non-ignored state-changing HTTP requests since construction/reset.""" return self._mutation_count + # This surface sees the page's HTTP traffic, so a count of 0 means + # nothing was sent; on a backend without it, 0 means unknown. + observes_network = True + @property def confirmed_mutation_count(self) -> int: """Non-ignored state-changing requests the server answered with 2xx/3xx.""" @@ -1995,6 +2054,7 @@ def snapshot( context_id = self._document_context_id() raw = self._page.evaluate(_SNAPSHOT_WALKER_JS, walker_cfg) text_pairs = self._read_text_pairs() + page_text = self._read_page_text() if self._document_context_id() != context_id: raise SurfaceContextError("Form document changed while taking a snapshot") self._last_snapshot_context_id = context_id @@ -2037,6 +2097,8 @@ def snapshot( radio_value=str(item.get("radio_value") or ""), radio_group=str(item.get("radio_group") or ""), group_label=str(item.get("group_label") or ""), + row_text=str(item.get("row_text") or ""), + row_cells=tuple(str(c) for c in (item.get("row_cells") or ())), modal_container=str(item.get("modal_container") or ""), ) ) @@ -2084,8 +2146,21 @@ def snapshot( banner_errors=tuple(str(b) for b in (raw.get("banner_errors") or ())), inflight_mutations=self.inflight_mutations, text_pairs=text_pairs, + page_text=page_text, ) + def _read_page_text(self) -> str: + """The page's visible text, capped; empty when it cannot be read.""" + try: + return str( + self._page.evaluate( + "() => (document.body ? document.body.innerText || '' : '').slice(0, 50000)" + ) + or "" + ) + except Exception: + return "" + def _read_text_pairs(self) -> tuple[ObservedTextPair, ...]: """Read label and value pairs shown as page text. diff --git a/packages/flow/openadapt_flow/form_tx/receipt.py b/packages/flow/openadapt_flow/form_tx/receipt.py index ca60f1f115..b504c48f89 100644 --- a/packages/flow/openadapt_flow/form_tx/receipt.py +++ b/packages/flow/openadapt_flow/form_tx/receipt.py @@ -155,6 +155,7 @@ def issue_form_tx_receipt( receipt_id: Optional[str] = None, salt_hex: Optional[str] = None, timestamp_utc: Optional[str] = None, + not_covered: Sequence[str] = (), writes: Optional[Sequence[FieldWriteRecord]] = None, ) -> SignedFormTxReceipt: """Issue a value-scrubbed, Ed25519-signed ``SignedFormTxReceipt``.""" @@ -333,6 +334,18 @@ def issue_form_tx_receipt( len(summary_verdict.not_checked_keys) if summary_verdict is not None else 0 ), salted_output_digests=salted_outputs, + covered_keys=( + tuple( + sorted( + v.dossier_key + for v in summary_verdict.field_verdicts + if v.passed and not v.dossier_key.startswith("__") + ) + ) + if summary_verdict is not None + else () + ), + not_covered=tuple(not_covered), readback_evidence=( summary_verdict.readback_evidence if summary_verdict is not None @@ -360,6 +373,8 @@ def issue_form_tx_receipt( _LATER_V1_FIELDS: dict[str, Any] = { "readback_not_checked_count": 0, "readback_evidence": "acting_session_reread", + "covered_keys": [], + "not_covered": [], } RECEIPT_FORMAT_CURRENT = "v1" diff --git a/packages/flow/openadapt_flow/form_tx/reconciler.py b/packages/flow/openadapt_flow/form_tx/reconciler.py index edd4f5645c..bdd939998f 100644 --- a/packages/flow/openadapt_flow/form_tx/reconciler.py +++ b/packages/flow/openadapt_flow/form_tx/reconciler.py @@ -38,6 +38,7 @@ MissingAnchorError, collapse_radio_groups, compute_field_signature, + is_radio, match_anchor_in_snapshot, match_text_pair_in_snapshot, radio_group_key, @@ -71,6 +72,7 @@ PrefillPolicy, ProvenanceKind, UIProfileSpec, + UnboundControlSpec, WizardScreenSpec, canonical_sha256, read_subjects, @@ -213,6 +215,23 @@ def __init__( # Keyed by field, selector and popup, so a popup input never hides a # main-form write of the same dossier key. self._writes: dict[tuple[str, str, str, str], FieldWriteRecord] = {} + # Screens in the order this run reached them, and whether a sign-in + # or a jump back interrupted the run after fields were entered. An + # interrupted run re-walks its screens (or stops) before submit. + self._screens_visited: list[str] = [] + self._interrupted: bool = False + self._rewalks: int = 0 + # Controls no binding covers, keyed by label: the value each showed + # that this run did not set (keeps the run from verified_done), the + # value first seen (a later change is reported too), and the + # pack-declared ones seen at their blank value (named on the receipt). + self._uncovered: dict[str, str] = {} + self._unbound_first_seen: dict[str, str] = {} + self._not_covered: set[str] = set() + # Optional bound fields the page showed and the run left blank. + self._optional_blank: set[str] = set() + # Review read-backs that could not be compared, and why. + self._review_skipped: dict[str, str] = {} # Every control this run actuated: its popup, screen and selector, and # the selectors that may stand for it in the write ledger (a radio # option or its group's peers). Checked against the ledger before @@ -281,6 +300,46 @@ def _subject_selector(ctrl: ObservedControl, snapshot: FormSnapshot) -> str: return peers[0] if peers else ctrl.dom_selector +def _field_label(ctrl: Optional[ObservedControl]) -> str: + """The name a person reads for ``ctrl``: a radio's group, else its label.""" + if ctrl is None: + return "" + if is_radio(ctrl): + if ctrl.group_label.strip(): + return ctrl.group_label + # A group with no legend is named by its table row's header cell. + header = collapse_whitespace(ctrl.row_cells[0]) if ctrl.row_cells else "" + header = header.rstrip(":*").strip() + if header and header.casefold() != ctrl.label_text.strip().casefold(): + return header + return ctrl.label_text + + +_FREE_TEXT_INPUT_TYPES = frozenset( + {"", "text", "email", "tel", "number", "search", "url", "date", "month"} +) + + +def _is_free_text(ctrl: ObservedControl) -> bool: + if ctrl.tag.casefold() == "textarea": + return True + if ctrl.role.casefold() == "combobox": + return ctrl.tag.casefold() == "input" + return ( + ctrl.tag.casefold() == "input" + and ctrl.input_type.casefold() in _FREE_TEXT_INPUT_TYPES + ) + + +def _key_tokens(key: str) -> set[str]: + last = key.rsplit(".", 1)[-1] + return {t for t in re.split(r"[^a-z0-9]+", last.casefold()) if t} + + +def _label_tokens(label: str) -> set[str]: + return {t for t in re.split(r"[^a-z0-9]+", label.casefold()) if t} + + def _is_action_button(ctrl: ObservedControl) -> bool: tag = ctrl.tag.casefold() itype = ctrl.input_type.casefold() @@ -353,23 +412,8 @@ def _control_matches_fact( if _is_radio_control(ctrl) and ctrl.checked is not True: return False - if ( - binding.control_kind == ControlKind.PORTAL_COMBOBOX - and binding.typeahead_query_chars is not None - ): - # A type-ahead that keeps only the leading part of its pick (see - # _is_leading_part_of_choice); typed text alone never matches. - try: - formatted = format_for_text_entry(intended_value, binding.codec) - except CodecValueError: - formatted = "" - if formatted and _is_leading_part_of_choice( - ctrl.current_value, - formatted, - formatted[: binding.typeahead_query_chars], - ): - return True - + # partial-match-as-match: only the whole intended value matches. A field + # that shows a leading part of it (whoever put it there) is not a match. if values_equivalent(intended_value, ctrl.current_value, binding.codec): return True @@ -551,24 +595,6 @@ def _is_editable_combobox(ctrl: ObservedControl) -> bool: ) -def _is_leading_part_of_choice(shown: str, label: str, typed: str) -> bool: - """True when a pick left the leading part of its label in the input. - - Some type-aheads put only the first part of the chosen suggestion in the - input ("2210 Juniper Loop" from "2210 Juniper Loop Apt 4, Brackenfield, - OR") and fill the rest into other fields. That counts only when the input - shows more than was typed, so text left over from typing never passes. - """ - shown_n = collapse_whitespace(shown).casefold() - label_n = collapse_whitespace(label).casefold() - typed_n = collapse_whitespace(typed).casefold() - if not shown_n or shown_n == typed_n or len(shown_n) <= len(typed_n): - return False - if not label_n.startswith(shown_n) or len(label_n) == len(shown_n): - return False - return label_n[len(shown_n)] in " ,;-/(" - - def _surface_action_halt( run_id: str, snapshot: FormSnapshot, @@ -581,7 +607,7 @@ def _surface_action_halt( ) -> FormHaltItem: """A stop for a person when the surface could not act on a control.""" target = ctrl.dom_selector if ctrl is not None else locator - label = ctrl.label_text if ctrl is not None else "" + label = _field_label(ctrl) sig = ( compute_field_signature(ctrl) if ctrl is not None @@ -669,6 +695,81 @@ def _auth_wall_reason( return None +def _editable_fields(snapshot: FormSnapshot) -> list[ObservedControl]: + """Visible, enabled, non-button fields, one per radio group.""" + return [ + c + for c in collapse_radio_groups(snapshot.controls) + if c.visible + and not c.disabled + and not c.readonly + and not c.is_secret + and not _is_action_button(c) + and c.tag.casefold() != "output" + ] + + +def _locate_errored_control( + snapshot: FormSnapshot, + before: Optional[FormSnapshot] = None, +) -> tuple[Optional[ObservedControl], str]: + """The field a validation stop is about, and the message for it. + + In order: a field with its own error text; a field whose label an error + banner names; a field whose row gained text after the click (a "Required" + marker next to it); a required field left empty. ``(None, "")`` when no + field can be named. + """ + fields = _editable_fields(snapshot) + for c in snapshot.controls: + if c.visible and c.error_text.strip(): + return c, collapse_whitespace(c.error_text) + + banners = [collapse_whitespace(b).casefold() for b in snapshot.banner_errors] + if banners: + named: list[tuple[int, ObservedControl]] = [] + for c in fields: + label = collapse_whitespace(_field_label(c)).rstrip(":*").strip() + if len(label) < 4: + continue + if any(label.casefold() in b for b in banners): + named.append((len(label), c)) + if named: + named.sort(key=lambda item: -item[0]) + if len(named) == 1 or named[0][0] > named[1][0]: + return named[0][1], "; ".join(snapshot.banner_errors) + + if before is not None: + old_rows: dict[str, str] = {} + for c in collapse_radio_groups(before.controls): + old_rows[c.dom_selector] = collapse_whitespace(c.row_text) + old_rows.setdefault( + f"label|{collapse_whitespace(_field_label(c)).casefold()}", + collapse_whitespace(c.row_text), + ) + grew: list[tuple[ObservedControl, str]] = [] + for c in fields: + now = collapse_whitespace(c.row_text) + was = old_rows.get(c.dom_selector) + if was is None: + was = old_rows.get( + f"label|{collapse_whitespace(_field_label(c)).casefold()}" + ) + # Only strict growth counts: the old row text is still there and + # something was added to it (a "Required" marker). + if was is None or not now or now == was or was not in now: + continue + added = now.replace(was, " ").strip() if was and was in now else now + grew.append((c, collapse_whitespace(added))) + if grew: + return grew[0][0], grew[0][1] + + for c in fields: + if c.required and _is_control_empty(c): + return c, "required and empty" + return None, "" + + def _collect_surface_errors(snapshot: FormSnapshot) -> list[str]: errors = [collapse_whitespace(b) for b in snapshot.banner_errors if b.strip()] for ctrl in snapshot.controls: @@ -1155,6 +1256,10 @@ def _actuate_control_unguarded( typed_query = format_for_text_entry(intended_value, codec) if typeahead_query_chars is not None: typed_query = typed_query[:typeahead_query_chars] + elif len(typed_query) > 2: + # Leave the last character to the pick, so a pick that + # took is visible as a change in the field. + typed_query = typed_query[:-1] opts = typer(ctrl.dom_selector, typed_query) else: opts = surface.open_portal_combobox_options(ctrl.dom_selector) @@ -1177,7 +1282,7 @@ def _actuate_control_unguarded( screen_id=snapshot.screen_id, control_id=ctrl.control_id, dom_selector=ctrl.dom_selector, - field_label=ctrl.label_text, + field_label=_field_label(ctrl), section_text=ctrl.section_text, dossier_key=dossier_key, dossier_value=intended_value, @@ -1190,6 +1295,34 @@ def _actuate_control_unguarded( ), available_options=opts, ) + before_value = "" + pre: Optional[FormSnapshot] = None + if typed_query is not None: + # The baseline for "did the click change the field" is the + # control as it stands just before the click; without it + # the pick cannot be proven, so the run stops. + pre = surface.snapshot() + pre_ctrl = next( + ( + c + for c in pre.controls + if c.visible and c.dom_selector == ctrl.dom_selector + ), + None, + ) + if pre_ctrl is None: + return _surface_action_halt( + run_id, + snapshot, + MissingAnchorError( + f"{ctrl.label_text or ctrl.dom_selector!r} was redrawn " + "while typing, so the pick cannot be checked" + ), + ctrl=ctrl, + dossier_key=dossier_key, + dossier_value=intended_value, + ) + before_value = pre_ctrl.current_value surface.choose_portal_combobox_option(ctrl.dom_selector, opt) if typed_query is not None: return self._verify_typeahead_choice( @@ -1202,6 +1335,8 @@ def _actuate_control_unguarded( dossier_key=dossier_key, run_id=run_id, typed_query=typed_query, + before_value=before_value, + pre_click=pre, ) return None @@ -1263,7 +1398,7 @@ def _actuate_control_unguarded( screen_id=snapshot.screen_id, control_id=ctrl.control_id, dom_selector=ctrl.dom_selector, - field_label=ctrl.label_text, + field_label=_field_label(ctrl), section_text=ctrl.section_text, dossier_key=dossier_key, dossier_value=intended_value, @@ -1289,6 +1424,8 @@ def _verify_typeahead_choice( dossier_key: Optional[str], run_id: str, typed_query: str = "", + before_value: str = "", + pre_click: Optional[FormSnapshot] = None, ) -> Optional[FormHaltItem]: """Stop unless the type-ahead now holds the chosen suggestion. @@ -1316,8 +1453,16 @@ def _key(c: ObservedControl) -> tuple[str, str, str]: ) if collapse_whitespace(ctrl.label_text): + # Only a control that was not on the page before the pick can + # be the redrawn input; an existing look-alike never is. + baseline = pre_click if pre_click is not None else snapshot + before_selectors = {c.dom_selector for c in baseline.controls} same = [ - c for c in after.controls if c.visible and _key(c) == _key(ctrl) + c + for c in after.controls + if c.visible + and c.dom_selector not in before_selectors + and _key(c) == _key(ctrl) ] if len(same) == 1: live = same[0] @@ -1332,8 +1477,11 @@ def _key(c: ObservedControl) -> tuple[str, str, str]: and ( shown.casefold() in accepted or values_equivalent(intended_value, live.current_value, codec) - or _is_leading_part_of_choice(shown, option.label, typed_query) ) + # The click must be what changed the field: a value that was + # already there before it (typed text, an inline completion) + # proves nothing about the pick. + and collapse_whitespace(before_value).casefold() != shown.casefold() ): return None reason = ( @@ -1392,7 +1540,10 @@ def _reconcile_bindings_pass( try: ctrl = match_anchor_in_snapshot( - binding.anchor, snapshot, include_readonly=False + binding.anchor, + snapshot, + include_readonly=False, + facts=session.effective_facts, ) except AmbiguousAnchorError as exc: sig = f"ambiguous_anchor|{binding.binding_id}|{binding.dossier_key}" @@ -1438,6 +1589,20 @@ def _reconcile_bindings_pass( ) is_empty = _is_control_empty(ctrl, binding.placeholder_values) fact = session.effective_facts.get(binding.dossier_key) + # A blank-form default (pack data) holds no client data: with a + # dossier value it is written over. Never for a control this run + # already wrote, so a reset to the default is still re-checked. + if ( + not is_empty + and not was_filled_by_session + and fact is not None + and binding.portal_default_values + and any( + _control_matches_fact(ctrl, default, binding) + for default in binding.portal_default_values + ) + ): + is_empty = True # Prefill Value Conflict Check if not is_empty and not was_filled_by_session: @@ -1458,13 +1623,13 @@ def _reconcile_bindings_pass( screen_id=snapshot.screen_id, control_id=ctrl.control_id, dom_selector=ctrl.dom_selector, - field_label=ctrl.label_text, + field_label=_field_label(ctrl), section_text=ctrl.section_text, dossier_key=binding.dossier_key, portal_value=ctrl.current_value, dossier_value=fact.value if fact is not None else None, message=( - f"Prefilled value on {ctrl.label_text or ctrl.dom_selector!r} " + f"Prefilled value on {_field_label(ctrl) or ctrl.dom_selector!r} " f"conflicts with grounded dossier state for {binding.dossier_key!r}" ), allowed_actions=( @@ -1518,7 +1683,7 @@ def _reconcile_bindings_pass( session.record_write( source="auto_fill", dossier_key=binding.dossier_key, - label=ctrl.label_text, + label=_field_label(ctrl), selector=_subject_selector(ctrl, snapshot), in_popup_subroutine=in_popup_subroutine, ) @@ -1536,7 +1701,7 @@ def _reconcile_bindings_pass( session.record_write( source="kept_matching", dossier_key=binding.dossier_key, - label=ctrl.label_text, + label=_field_label(ctrl), selector=_subject_selector(ctrl, snapshot), in_popup_subroutine=in_popup_subroutine, keep_existing=True, @@ -1544,6 +1709,418 @@ def _reconcile_bindings_pass( return edited_any, False, None + def _review_mismatch_halt( + self, session: ReconcilerSession, snapshot: FormSnapshot + ) -> Optional[FormHaltItem]: + """Stop before submit when the review screen shows a different value.""" + check = session.pack.summary_check + if check is None or not check.review_readbacks: + return None + from openadapt_flow.form_tx.judge import ( + _observed_control_matches, + _text_pair_matches, + ) + + for rb in check.review_readbacks: + fact = session.effective_facts.get(rb.dossier_key) + # Every skip is recorded and becomes not_checked on the result, + # never a silent pass (absent-evidence-as-success). + if fact is None: + session._review_skipped[rb.dossier_key] = "no intake value" + continue + try: + ctrl = match_anchor_in_snapshot( + rb.anchor, snapshot, include_readonly=True + ) + pair = ( + match_text_pair_in_snapshot(rb.anchor, snapshot) + if ctrl is None + else None + ) + except AmbiguousAnchorError: + session._review_skipped[rb.dossier_key] = "shown more than once" + continue + if ctrl is None and pair is None: + session._review_skipped[rb.dossier_key] = "not shown on the review" + continue + session._review_skipped.pop(rb.dossier_key, None) + ok = ( + _observed_control_matches(fact.value, ctrl, rb) + if ctrl is not None + else pair is not None and _text_pair_matches(fact.value, pair, rb) + ) + if ok: + continue + shown = ( + ctrl.current_value if ctrl is not None else (pair.value if pair else "") + ) + label = ( + _field_label(ctrl) if ctrl is not None else (pair.label if pair else "") + ) or rb.dossier_key + sig = f"review|{rb.dossier_key}|{shown}" + halt_id = _deterministic_halt_id( + session.run_id, + FormHaltKind.PREFILL_VALUE_CONFLICT, + snapshot.screen_id, + rb.dossier_key, + sig, + ) + halt = FormHaltItem( + halt_id=halt_id, + kind=FormHaltKind.PREFILL_VALUE_CONFLICT, + screen_id=snapshot.screen_id, + field_label=collapse_whitespace(label).rstrip(":").strip(), + dossier_key=rb.dossier_key, + portal_value=shown, + dossier_value=fact.value, + message=( + f"The review page shows {shown!r} for {label!r}, but the intake " + f"has {fact.value!r}; nothing was submitted" + ), + allowed_actions=( + HumanDecisionAction.ESCALATE_TO_OWNER, + HumanDecisionAction.ABORT_RUN, + ), + ) + session._halt_metadata[halt_id] = {"field_signature": sig} + return halt + return None + + @staticmethod + def _note_screen(session: ReconcilerSession, screen_id: str) -> None: + """Track screen order; a jump back to a screen already left interrupts the run. + + Landing back on the first screen is itself a full re-walk, so it + clears the interruption instead. + """ + visited = session._screens_visited + if screen_id not in visited: + visited.append(screen_id) + return + if visited[-1] == screen_id: + return + idx = visited.index(screen_id) + del visited[idx + 1 :] + if idx == 0: + session._interrupted = False + elif session.writes: + session._interrupted = True + + def _recheck_after_interruption( + self, + surface: FormSurfaceBackend, + session: ReconcilerSession, + snapshot: FormSnapshot, + current_screen: WizardScreenSpec, + ) -> Any: + """Before submit on an interrupted run: re-walk the screens, or stop. + + Returns ``"rewalk"`` after clicking back to the earliest visited + screen that can be revisited (the forward walk then re-checks and + re-fills every bound field), a stop naming each field entered on + another screen when no screen can be revisited, or ``None``. + """ + if not session._interrupted: + return None + earlier = [ + sid for sid in session._screens_visited if sid != current_screen.screen_id + ] + specs = {spec.screen_id: spec for spec in session.pack.screens} + on_screen = {c.dom_selector for c in snapshot.controls if c.visible} + elsewhere = sorted( + { + collapse_whitespace(w.label or "") or w.field_key + for w in session.writes + if not w.in_popup_subroutine and (w.selector or "") not in on_screen + } + ) + if not earlier and not elsewhere: + session._interrupted = False + return None + # Only a walk from the first screen the run visited re-checks every + # earlier field; starting later would skip the first screen's fields. + first = specs.get(earlier[0]) if earlier else None + target = first if first is not None and first.revisit_selector else None + if target is not None and session._rewalks < 2: + session._rewalks += 1 + try: + surface.click(str(target.revisit_selector)) + except Exception as exc: # noqa: BLE001 + if not _is_surface_action_error(exc): + raise + else: + session._interrupted = False + session._screens_visited = [] + return "rewalk" + if not elsewhere: + session._interrupted = False + return None + sig = f"recheck|{current_screen.screen_id}|{','.join(elsewhere)}" + halt_id = _deterministic_halt_id( + session.run_id, + FormHaltKind.FIELDS_NOT_RECHECKED, + snapshot.screen_id, + current_screen.screen_id, + sig, + ) + msg = ( + "A sign-in or a jump back interrupted this quote after fields were " + "entered, and these fields cannot be re-checked from here before " + f"submit: {elsewhere}" + ) + halt = FormHaltItem( + halt_id=halt_id, + kind=FormHaltKind.FIELDS_NOT_RECHECKED, + screen_id=snapshot.screen_id, + field_label=elsewhere[0], + portal_value=list(elsewhere), + message=msg, + allowed_actions=( + HumanDecisionAction.FIXED_ON_SCREEN, + HumanDecisionAction.ESCALATE_TO_OWNER, + HumanDecisionAction.ABORT_RUN, + ), + ) + session._halt_metadata[halt_id] = {"field_signature": sig} + return self._build_result( + session, + outcome=FormTxOutcome.HALTED_NEEDS_HUMAN, + safe_to_retry=True, + halts=(halt,), + what_happened=msg, + ) + + @staticmethod + def _consumed_keys(pack: FormPack) -> set[str]: + keys = {b.dossier_key for b in pack.bindings} + for sub in pack.popup_subroutines: + keys |= {b.dossier_key for b in sub.bindings} + keys.add(sub.return_output_key) + if sub.condition_dossier_key: + keys.add(sub.condition_dossier_key) + for rule in pack.modal_rules: + if rule.dossier_flag_key: + keys.add(rule.dossier_flag_key) + if pack.summary_check is not None: + keys |= {b.dossier_key for b in pack.summary_check.field_readbacks} + for sd in pack.summary_check.split_date_readbacks: + keys |= {sd.day_key, sd.month_key, sd.year_key} + if pack.summary_check.search_by_output_key: + keys.add(pack.summary_check.search_by_output_key) + for spec in pack.screens: + for anchor in (spec.next_button_anchor, spec.commit_button_anchor): + if anchor is not None: + keys |= set(anchor.row_cell_dossier_keys) + for sub in pack.popup_subroutines: + for anchor in (sub.trigger_anchor, sub.commit_anchor, *sub.compute_anchors): + keys |= set(anchor.row_cell_dossier_keys) + return keys + + def _unconsumed_intake_keys( + self, session: ReconcilerSession, *, include_ignored: bool = True + ) -> list[str]: + consumed = self._consumed_keys(session.pack) + if not include_ignored: + consumed |= set(session.pack.ignored_intake_keys) + out = [] + for key, fact in session.dossier.facts.items(): + if key in consumed: + continue + value = getattr(fact, "value", None) + if value is None or (isinstance(value, str) and not value.strip()): + continue + out.append(key) + return sorted(out) + + def _scan_unbound_controls( + self, session: ReconcilerSession, snapshot: FormSnapshot + ) -> Optional[FormHaltItem]: + """Watch every visible field no binding covers. + + Free text holding a value this run did not type stops. Any other + value it did not set is kept as ``uncovered`` (the run then cannot + end ``verified_done``). An empty field whose label names an intake + key that no binding enters stops. Pack-declared unbound controls at + their blank value are only named on the receipt. + """ + pack = session.pack + bound_selectors: set[str] = set() + bound_groups: set[str] = set() + anchors = [b.anchor for b in pack.bindings] + for sub in pack.popup_subroutines: + anchors.extend([sub.trigger_anchor, sub.parent_return_anchor]) + for anchor in anchors: + try: + m = match_anchor_in_snapshot( + anchor, + snapshot, + include_readonly=True, + facts=session.effective_facts, + ) + except AmbiguousAnchorError: + continue + if m is not None: + bound_selectors.add(m.dom_selector) + group = radio_group_key(m) + if group is not None: + bound_groups.add(group) + declared: dict[str, Any] = {} + for spec in pack.unbound_controls: + try: + m = match_anchor_in_snapshot( + spec.anchor, + snapshot, + include_readonly=True, + facts=session.effective_facts, + ) + except AmbiguousAnchorError: + continue + if m is not None: + declared[m.dom_selector] = spec + group = radio_group_key(m) + if group is not None: + declared[f"group|{group}"] = spec + unconsumed: Optional[list[str]] = None + fold = FieldCodecSpec(kind=FormCodecKind.CASEFOLD) + + # Read-only text boxes (filled by a lookup) count only for the + # intake-key check below: an empty one the intake has a value for. + readonly_text = [ + c + for c in snapshot.controls + if c.visible + and c.readonly + and not c.disabled + and not c.is_secret + and c.tag.casefold() == "input" + and c.input_type.casefold() in _FREE_TEXT_INPUT_TYPES + and _is_control_empty(c) + ] + for ctrl in [*_editable_fields(snapshot), *readonly_text]: + if ctrl.modal_container: + continue + group = radio_group_key(ctrl) + if ctrl.dom_selector in bound_selectors or ( + group is not None and group in bound_groups + ): + continue + ctrl_sig = compute_field_signature(ctrl) + if ( + ctrl.dom_selector in session._filled_selectors + or ctrl_sig in session._human_accepted_control_signatures + ): + continue + label = collapse_whitespace(_field_label(ctrl)) or ctrl.dom_selector + empty = _is_control_empty(ctrl) + shown = "" + if not empty: + shown = ctrl.current_value + if ctrl.options: + opt = [o for o in ctrl.options if o.value == ctrl.current_value] + if len(opt) == 1 and opt[0].label: + shown = opt[0].label + declared_spec: Optional[UnboundControlSpec] = declared.get( + ctrl.dom_selector + ) or (declared.get(f"group|{group}") if group is not None else None) + if declared_spec is not None: + blank = (empty and "" in declared_spec.blank_values) or any( + values_equivalent(b, shown, fold) + or values_equivalent(b, ctrl.current_value, fold) + for b in declared_spec.blank_values + if b + ) + if blank: + session._not_covered.add(label) + else: + session._uncovered[label] = shown + continue + if empty: + if not _is_free_text(ctrl): + continue + if unconsumed is None: + unconsumed = self._unconsumed_intake_keys(session) + label_toks = _label_tokens(label) + for key in unconsumed: + toks = _key_tokens(key) + if not toks or not toks <= label_toks: + continue + fact = session.dossier.facts.get(key) + halt_id = _deterministic_halt_id( + session.run_id, + FormHaltKind.UNGROUNDED_REQUIRED_FIELD, + snapshot.screen_id, + ctrl.dom_selector, + f"unbound_intake|{key}|{ctrl_sig}", + ) + halt = FormHaltItem( + halt_id=halt_id, + kind=FormHaltKind.UNGROUNDED_REQUIRED_FIELD, + screen_id=snapshot.screen_id, + control_id=ctrl.control_id, + dom_selector=ctrl.dom_selector, + field_label=label, + section_text=ctrl.section_text, + dossier_key=key, + dossier_value=getattr(fact, "value", None), + message=( + f"The intake has {key!r}, but no binding enters it, and " + f"the field {label!r} is empty" + ), + allowed_actions=( + HumanDecisionAction.PROVIDE_VALUE, + HumanDecisionAction.FIXED_ON_SCREEN, + HumanDecisionAction.ESCALATE_TO_OWNER, + HumanDecisionAction.ABORT_RUN, + ), + ) + session._halt_metadata[halt_id] = { + "field_signature": ctrl_sig, + "control": ctrl, + "binding": None, + } + return halt + continue + first = session._unbound_first_seen.setdefault(label, shown) + if _is_free_text(ctrl): + halt_id = _deterministic_halt_id( + session.run_id, + FormHaltKind.PREFILL_VALUE_CONFLICT, + snapshot.screen_id, + ctrl.dom_selector, + ctrl_sig, + ) + halt = FormHaltItem( + halt_id=halt_id, + kind=FormHaltKind.PREFILL_VALUE_CONFLICT, + screen_id=snapshot.screen_id, + control_id=ctrl.control_id, + dom_selector=ctrl.dom_selector, + field_label=label, + section_text=ctrl.section_text, + portal_value=ctrl.current_value, + message=( + f"{label!r} holds a value this run did not type, and no " + "binding covers it" + ), + allowed_actions=( + HumanDecisionAction.ACCEPT_PORTAL_PREFILL, + HumanDecisionAction.PROVIDE_VALUE, + HumanDecisionAction.FIXED_ON_SCREEN, + HumanDecisionAction.ESCALATE_TO_OWNER, + HumanDecisionAction.ABORT_RUN, + ), + available_options=ctrl.options, + ) + session._halt_metadata[halt_id] = { + "field_signature": ctrl_sig, + "control": ctrl, + "binding": None, + } + return halt + note = shown if first == shown else f"{shown} (was {first})" + session._uncovered[label] = note + return None + @staticmethod def _controls_were_replaced( surface: FormSurfaceBackend, snapshot: FormSnapshot @@ -1566,7 +2143,10 @@ def _collect_ungrounded_required_halts( for candidate_binding in bindings: try: matched = match_anchor_in_snapshot( - candidate_binding.anchor, snapshot, include_readonly=False + candidate_binding.anchor, + snapshot, + include_readonly=False, + facts=session.effective_facts, ) except AmbiguousAnchorError: continue @@ -1588,18 +2168,33 @@ def _collect_ungrounded_required_halts( group = radio_group_key(ctrl) if binding is None and group is not None: binding = matched_by_group.get(group) - is_required = ctrl.required or ( - binding is not None and binding.required_in_pack - ) - if not is_required: - continue - ctrl_sig = compute_field_signature(ctrl) fact = ( session.effective_facts.get(binding.dossier_key) if binding is not None else None ) + # A bound field the page shows, with no intake value, that nobody + # answered: a value no one supplied must never be covered + # (absent-evidence-as-success). It stops, unless the pack marks + # it optional; then it is named on the receipt as not covered. + unanswered = ( + binding is not None + and fact is None + and _is_control_empty(ctrl, binding.placeholder_values) + and ctrl.dom_selector not in session._filled_selectors + and ctrl_sig not in session._human_accepted_control_signatures + ) + if unanswered and binding is not None and binding.optional: + session._optional_blank.add(binding.dossier_key) + continue + is_required = ( + ctrl.required + or (binding is not None and binding.required_in_pack) + or unanswered + ) + if not is_required: + continue if ( fact is not None and binding is not None @@ -1631,12 +2226,15 @@ def _collect_ungrounded_required_halts( screen_id=snapshot.screen_id, control_id=ctrl.control_id, dom_selector=ctrl.dom_selector, - field_label=ctrl.label_text, + field_label=_field_label(ctrl), section_text=ctrl.section_text, dossier_key=binding.dossier_key if binding is not None else None, message=( - f"Required control {ctrl.label_text or ctrl.dom_selector!r} has no " + f"Required control {_field_label(ctrl) or ctrl.dom_selector!r} has no " f"grounded value in dossier" + if not unanswered or ctrl.required + else f"{_field_label(ctrl) or ctrl.dom_selector!r} is shown with no " + "intake value; answer it, or the pack must mark it optional" ), allowed_actions=( HumanDecisionAction.PROVIDE_VALUE, @@ -1743,10 +2341,16 @@ def _run_popup_subroutine_steps( """Execute ``subroutine``, returning ``None`` on verified return or halts on failure.""" try: trigger_ctrl = match_anchor_in_snapshot( - subroutine.trigger_anchor, parent_snapshot, include_readonly=False + subroutine.trigger_anchor, + parent_snapshot, + include_readonly=False, + facts=session.effective_facts, ) return_before = match_anchor_in_snapshot( - subroutine.parent_return_anchor, parent_snapshot, include_readonly=True + subroutine.parent_return_anchor, + parent_snapshot, + include_readonly=True, + facts=session.effective_facts, ) except AmbiguousAnchorError as exc: sig = f"popup_anchor|{subroutine.subroutine_id}" @@ -1947,7 +2551,10 @@ def _popup_snapshot(surface: FormSurfaceBackend) -> FormSnapshot: popup_snap = _popup_snapshot(popup_surface) try: step_ctrl = match_anchor_in_snapshot( - step_anchor, popup_snap, include_readonly=False + step_anchor, + popup_snap, + include_readonly=False, + facts=session.effective_facts, ) except AmbiguousAnchorError as exc: step_ctrl = None @@ -1999,7 +2606,10 @@ def _popup_snapshot(surface: FormSurfaceBackend) -> FormSnapshot: try: popup_commit = match_anchor_in_snapshot( - subroutine.commit_anchor, popup_snap, include_readonly=False + subroutine.commit_anchor, + popup_snap, + include_readonly=False, + facts=session.effective_facts, ) except AmbiguousAnchorError as exc: popup_commit = None @@ -2062,6 +2672,7 @@ def _popup_snapshot(surface: FormSurfaceBackend) -> FormSnapshot: subroutine.parent_return_anchor, after_parent_snap, include_readonly=True, + facts=session.effective_facts, ) if return_after is None or not _is_valid_non_zero_return_value( return_after.current_value, subroutine.return_codec @@ -2293,7 +2904,10 @@ def _check_popup_entries_before_apply( fact = session.effective_facts.get(binding.dossier_key) try: ctrl = match_anchor_in_snapshot( - binding.anchor, snap, include_readonly=False + binding.anchor, + snap, + include_readonly=False, + facts=session.effective_facts, ) except AmbiguousAnchorError: ctrl = None @@ -2423,6 +3037,7 @@ def _emit_validation_blocked( errors: Sequence[str], *, safe_to_retry: bool, + before: Optional[FormSnapshot] = None, ) -> FormTxResult: bound = session._bound_surface or self._surface auth_reason = _auth_wall_reason( @@ -2436,20 +3051,30 @@ def _emit_validation_blocked( auth_reason, delivery_uncertain=(not safe_to_retry) or session._commit_attempted, ) - errored_ctrl = next( - (c for c in snapshot.controls if c.visible and c.error_text.strip()), - None, - ) + errored_ctrl, field_message = _locate_errored_control(snapshot, before) + if errored_ctrl is not None: + name = collapse_whitespace(_field_label(errored_ctrl)) + if name and not any(name.casefold() in e.casefold() for e in errors): + errors = [*errors, f"{name}: {field_message or 'not accepted'}"] matched_binding: Optional[FieldBindingSpec] = None if errored_ctrl is not None: for b in session.pack.bindings: try: m = match_anchor_in_snapshot( - b.anchor, snapshot, include_readonly=False + b.anchor, + snapshot, + include_readonly=False, + facts=session.effective_facts, ) except AmbiguousAnchorError: continue - if m is not None and m.dom_selector == errored_ctrl.dom_selector: + if m is not None and ( + m.dom_selector == errored_ctrl.dom_selector + or ( + radio_group_key(m) is not None + and radio_group_key(m) == radio_group_key(errored_ctrl) + ) + ): matched_binding = b break @@ -2477,7 +3102,7 @@ def _emit_validation_blocked( screen_id=snapshot.screen_id, control_id=errored_ctrl.control_id if errored_ctrl else None, dom_selector=errored_ctrl.dom_selector if errored_ctrl else None, - field_label=errored_ctrl.label_text if errored_ctrl else "", + field_label=_field_label(errored_ctrl), section_text=errored_ctrl.section_text if errored_ctrl else "", dossier_key=matched_binding.dossier_key if matched_binding else None, portal_value=list(errors), @@ -2564,8 +3189,12 @@ def _finalize_commit( pack.pack_id, sig, ) + observes = getattr(surface, "observes_network", False) msg = ( - "The commit control was clicked but no save request was seen" + "This surface cannot observe saves, so whether one was sent " + "is unknown" + if delta_mutations == 0 and not observes + else "The commit control was clicked but no save request was seen" if delta_mutations == 0 else "No save request was answered with success" if no_confirmed_save @@ -2631,6 +3260,15 @@ def _finalize_commit( human_resolutions=session.human_resolutions, supplemental_facts=session.effective_facts, writes=session.writes, + uncovered=session._uncovered, + # Intake values the portal never asked for: only pack-required ones + # block; the rest are named on the receipt as not covered. + unentered_intake_keys=[ + k + for k in self._unconsumed_intake_keys(session, include_ignored=False) + if k in session.pack.required_intake_keys + ], + review_skipped=session._review_skipped, ) extracted_outputs = dict(verdict.extracted_outputs) if not verdict.passed or verdict.missing_required_outputs: @@ -2709,6 +3347,11 @@ def _not_signed(reason: str) -> FormTxResult: commit_mutations_observed=delta_mutations, summary_verdict=verdict, outputs=extracted_outputs, + not_covered=( + *sorted(session._not_covered), + *(f"optional-blank:{k}" for k in sorted(session._optional_blank)), + *(f"intake:{k}" for k in self._unconsumed_intake_keys(session)), + ), writes=session.writes, ) except ValueError as exc: @@ -3029,7 +3672,10 @@ def _run_until_halt_or_done_unguarded( continue try: trig = match_anchor_in_snapshot( - sub.trigger_anchor, snapshot, include_readonly=False + sub.trigger_anchor, + snapshot, + include_readonly=False, + facts=session.effective_facts, ) except AmbiguousAnchorError: # Delegated to _run_popup_subroutine to emit structured halt @@ -3125,10 +3771,40 @@ def _run_until_halt_or_done_unguarded( # 6. Screen Transition / Commit & Validation Check current_screen = _identify_wizard_screen(snapshot, pack.screens) + if current_screen is not None: + self._note_screen(session, current_screen.screen_id) + + # Controls no binding covers, before the screen is left. + unbound_halt = self._scan_unbound_controls(session, snapshot) + if unbound_halt is not None: + return self._build_result( + session, + outcome=FormTxOutcome.HALTED_NEEDS_HUMAN, + safe_to_retry=True, + halts=(unbound_halt,), + what_happened=unbound_halt.message, + ) + if current_screen is not None and ( current_screen.is_commit_screen or current_screen.commit_button_anchor is not None ): + recheck = self._recheck_after_interruption( + active_surface, session, snapshot, current_screen + ) + if recheck == "rewalk": + continue + if isinstance(recheck, FormTxResult): + return recheck + review_halt = self._review_mismatch_halt(session, snapshot) + if review_halt is not None: + return self._build_result( + session, + outcome=FormTxOutcome.HALTED_NEEDS_HUMAN, + safe_to_retry=True, + halts=(review_halt,), + what_happened=review_halt.message, + ) if current_screen.commit_button_anchor is None: raise ValueError( f"Commit screen {current_screen.screen_id!r} has no commit_button_anchor" @@ -3138,6 +3814,7 @@ def _run_until_halt_or_done_unguarded( current_screen.commit_button_anchor, snapshot, include_readonly=False, + facts=session.effective_facts, ) except AmbiguousAnchorError as exc: sig = f"commit_anchor|{current_screen.screen_id}" @@ -3207,6 +3884,7 @@ def _run_until_halt_or_done_unguarded( post_snap, post_errors, safe_to_retry=(delta == 0), + before=snapshot, ) return self._finalize_commit( @@ -3222,6 +3900,7 @@ def _run_until_halt_or_done_unguarded( current_screen.next_button_anchor, snapshot, include_readonly=False, + facts=session.effective_facts, ) except AmbiguousAnchorError as exc: sig = f"next_anchor|{current_screen.screen_id}" @@ -3260,10 +3939,14 @@ def _run_until_halt_or_done_unguarded( safe_to_retry=True, ) + # The visible field labels are part of the screen: a form that + # asks one question at a time in the same control advances + # when the question changes. before_sig = ( snapshot.screen_id, snapshot.url_origin_and_path, snapshot.title, + tuple(_field_label(c) for c in _editable_fields(snapshot)), ) active_surface.click(next_ctrl.dom_selector) post_snap = active_surface.snapshot( @@ -3279,6 +3962,7 @@ def _run_until_halt_or_done_unguarded( post_snap.screen_id, post_snap.url_origin_and_path, post_snap.title, + tuple(_field_label(c) for c in _editable_fields(post_snap)), ) if post_errors and (after_sig == before_sig or post_snap.banner_errors): return self._emit_validation_blocked( @@ -3286,6 +3970,7 @@ def _run_until_halt_or_done_unguarded( post_snap, post_errors, safe_to_retry=True, + before=snapshot, ) if after_sig == before_sig: return self._emit_validation_blocked( @@ -3296,6 +3981,7 @@ def _run_until_halt_or_done_unguarded( f"Screen {current_screen.screen_id!r} did not advance after clicking Next" ], safe_to_retry=True, + before=snapshot, ) continue @@ -3584,7 +4270,15 @@ def _append_record(resolved_val: Any) -> HumanResolutionRecord: if action == HumanDecisionAction.PROVIDE_VALUE: val = resolution.provided_value - if val is None or (isinstance(val, str) and not val.strip()): + # Clearing a prefilled value is a value too ("leave it blank"). + clearing = ( + active_halt.kind == FormHaltKind.PREFILL_VALUE_CONFLICT + and isinstance(val, str) + and not val.strip() + ) + if not clearing and ( + val is None or (isinstance(val, str) and not val.strip()) + ): raise ValueError("PROVIDE_VALUE requires a non-empty provided_value") if effective_dossier_key: @@ -3835,6 +4529,16 @@ def _append_record(resolved_val: Any) -> HumanResolutionRecord: ) return _cache_and_return(res) _append_record("authenticated") + # A sign-in in the middle may have reset what was entered. + if session.writes: + session._interrupted = True + res = self._resume_after_resolution(session, active_surface) + return _cache_and_return(res) + + if active_halt.kind == FormHaltKind.FIELDS_NOT_RECHECKED: + # The operator checked those fields on their screens. + session._interrupted = False + _append_record("rechecked_by_operator") res = self._resume_after_resolution(session, active_surface) return _cache_and_return(res) @@ -3861,7 +4565,10 @@ def _append_record(resolved_val: Any) -> HumanResolutionRecord: if live_ctrl is None and binding is not None: try: live_ctrl = match_anchor_in_snapshot( - binding.anchor, post_snap, include_readonly=True + binding.anchor, + post_snap, + include_readonly=True, + facts=session.effective_facts, ) except AmbiguousAnchorError: live_ctrl = None diff --git a/packages/flow/openadapt_flow/form_tx/surface.py b/packages/flow/openadapt_flow/form_tx/surface.py index fd60fe151f..e6d37b8eb4 100644 --- a/packages/flow/openadapt_flow/form_tx/surface.py +++ b/packages/flow/openadapt_flow/form_tx/surface.py @@ -8,7 +8,15 @@ from __future__ import annotations import re -from typing import ContextManager, Optional, Protocol, Sequence, runtime_checkable +from typing import ( + Any, + ContextManager, + Mapping, + Optional, + Protocol, + Sequence, + runtime_checkable, +) from openadapt_flow.form_tx.codecs import collapse_whitespace from openadapt_flow.form_tx.types import ( @@ -121,14 +129,23 @@ def _matches_any_pattern(text: str, patterns: Sequence[str]) -> bool: return False +def _cell_norm(text: str) -> str: + return " ".join(text.split()).casefold() + + def match_anchor_in_snapshot( anchor: FieldAnchorSpec, snapshot: FormSnapshot, *, include_readonly: bool = False, + facts: Optional[Mapping[str, Any]] = None, ) -> Optional[ObservedControl]: """Deterministically resolve ``anchor`` to at most one ``ObservedControl``. + With ``anchor.row_cell_dossier_keys`` and ``facts`` (dossier key to fact + or value), several matches narrow to the one whose table row has a cell + equal to each of those values. + Raises ``AmbiguousAnchorError`` when more than one visible control matches. Returns ``None`` when no visible control matches (for example, a conditional field that has not materialized on the current screen). @@ -188,6 +205,24 @@ def match_anchor_in_snapshot( if len(both) == 1: return both[0] + if len(candidates) > 1 and anchor.row_cell_dossier_keys and facts is not None: + wanted: list[str] = [] + for key in anchor.row_cell_dossier_keys: + fact = facts.get(key) + value = getattr(fact, "value", fact) + if value is None or not str(value).strip(): + wanted = [] + break + wanted.append(_cell_norm(str(value))) + if wanted: + in_row = [ + c + for c in candidates + if all(w in {_cell_norm(cell) for cell in c.row_cells} for w in wanted) + ] + if len(in_row) == 1: + return in_row[0] + if len(candidates) > 1: labels = [ f"{c.label_text or c.dom_selector} ({c.dom_selector})" for c in candidates diff --git a/packages/flow/openadapt_flow/form_tx/types.py b/packages/flow/openadapt_flow/form_tx/types.py index e685808807..87ae3e3d08 100644 --- a/packages/flow/openadapt_flow/form_tx/types.py +++ b/packages/flow/openadapt_flow/form_tx/types.py @@ -110,6 +110,9 @@ class FormHaltKind(str, Enum): MODAL_CONFIRMATION_REQUIRED = "modal_confirmation_required" AUTH_WALL_DETECTED = "auth_wall_detected" MUTATION_BUDGET_EXCEEDED = "mutation_budget_exceeded" + # A sign-in or a jump back interrupted the run after fields were entered, + # and some of them cannot be re-checked before submit. + FIELDS_NOT_RECHECKED = "fields_not_rechecked" class FormTxOutcome(str, Enum): @@ -297,6 +300,11 @@ class FieldAnchorSpec(BaseModel): section_patterns: tuple[str, ...] = () css_selector: Optional[str] = None role: Optional[str] = None + # When several controls match (a results table with one "Select" button + # per row), keep only the one whose table row has a cell equal to the + # value of each of these dossier keys. Without facts, or with no single + # row left, the anchor stays ambiguous. + row_cell_dossier_keys: tuple[str, ...] = () @model_validator(mode="after") def _require_at_least_one_signal(self) -> "FieldAnchorSpec": @@ -337,6 +345,16 @@ class FieldBindingSpec(BaseModel): # Type-ahead comboboxes: type only this many leading characters of the # formatted value before reading suggestions. None types the whole value. typeahead_query_chars: Optional[int] = Field(default=None, ge=1, le=200) + # Values a blank form shows before anyone types (seen on the dev case's + # first screen). A control still showing one of these, that this run has + # not written, holds no client data, so the dossier value is written + # over it. With no dossier value it still stops. Never applies to a + # control the run already wrote. + portal_default_values: tuple[str, ...] = () + # A field the form may leave blank. Without this, a bound field the page + # shows with no intake value stops before submit; with it, a blank one is + # named on the receipt as not covered, never as covered. + optional: bool = False class EntityTableSpec(BaseModel): @@ -411,6 +429,11 @@ class WizardScreenSpec(BaseModel): next_button_anchor: Optional[FieldAnchorSpec] = None is_commit_screen: bool = False commit_button_anchor: Optional[FieldAnchorSpec] = None + # A CSS selector (a tab, a step link, a "Change" link) that brings this + # screen back. After a sign-in or a jump back interrupts the run, the + # layer returns to the earliest visited screen that has one and walks + # forward again, re-checking every field, before it submits. + revisit_selector: Optional[str] = None class OutputExtractionSpec(BaseModel): @@ -422,6 +445,24 @@ class OutputExtractionSpec(BaseModel): anchor: FieldAnchorSpec codec: FieldCodecSpec = Field(default_factory=FieldCodecSpec) required: bool = True + # A regular expression with one group, searched in the page's visible + # text, for an output shown inside a sentence ("Quote number FC-Q-1 was + # issued"). Used when the anchor finds no control or text pair. Every + # match must give the same value. + value_pattern: Optional[str] = None + + +class SplitDateReadbackSpec(BaseModel): + """A date entered in day, month and year boxes but shown as one value.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + anchor: FieldAnchorSpec + day_key: str = Field(min_length=1) + month_key: str = Field(min_length=1) + year_key: str = Field(min_length=1) + # How the summary orders a numeric date ("03/04/1988"). + date_order: Literal["YMD", "MDY", "DMY"] = "MDY" class SummaryCheckSpec(BaseModel): @@ -435,9 +476,24 @@ class SummaryCheckSpec(BaseModel): search_submit_anchor: Optional[FieldAnchorSpec] = None search_by_output_key: Optional[str] = None field_readbacks: tuple[FieldBindingSpec, ...] = () + # Read-backs on the pre-submit review screen. Checked just before the + # commit click: a value shown there that differs from the intake stops + # before submit (a value the portal derived or changed). A value the + # review does not show is left to the post-submit read-back. + review_readbacks: tuple[FieldBindingSpec, ...] = () + split_date_readbacks: tuple[SplitDateReadbackSpec, ...] = () outputs: tuple[OutputExtractionSpec, ...] = () +class UnboundControlSpec(BaseModel): + """A control the pack does not fill, and the value it shows when blank.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + anchor: FieldAnchorSpec + blank_values: tuple[str, ...] = ("",) + + class FormPack(BaseModel): """Data-only per-target form contract. Zero executable code.""" @@ -455,6 +511,20 @@ class FormPack(BaseModel): summary_check: Optional[SummaryCheckSpec] = None commit_url_patterns: tuple[str, ...] = () max_commit_mutations: int = Field(default=1, ge=0, le=10) + # Controls the pack knowingly leaves alone, with the value a blank form + # shows in each. Every other visible control that no binding covers is + # watched: free text holding a value the run did not type stops before + # submit, and any other value it did not set keeps the run from + # ``verified_done``. These are listed as not covered on the receipt. + unbound_controls: tuple["UnboundControlSpec", ...] = () + # Intake keys this pack enters some other way (through derived facts) or + # knowingly does not enter. Any other intake key with a value that no + # binding enters keeps the run from ``verified_done``. + ignored_intake_keys: tuple[str, ...] = () + # Intake keys that must be entered. An intake value no binding enters is + # otherwise named on the receipt as not covered; one listed here keeps + # the run from verified_done instead. + required_intake_keys: tuple[str, ...] = () def digest(self) -> str: return canonical_sha256(self) @@ -499,6 +569,11 @@ class ObservedControl(BaseModel): # radiogroup container), and the group's visible label, if any. radio_group: str = "" group_label: str = "" + # Text of the control's own row: the nearest table row or list item, else + # the largest ancestor that holds no other field. ``row_cells`` lists the + # row's cell texts when it is a table row. + row_text: str = "" + row_cells: tuple[str, ...] = () # Selector of the open dialog that holds this control, if any. modal_container: str = "" @@ -571,6 +646,8 @@ class FormSnapshot(BaseModel): banner_errors: tuple[str, ...] = () inflight_mutations: int = 0 text_pairs: tuple[ObservedTextPair, ...] = () + # The visible text of the page (capped), for outputs shown in a sentence. + page_text: str = "" class FormHaltItem(BaseModel): @@ -726,6 +803,12 @@ class SummaryVerdict(BaseModel): # did the work, so it is "acting_session_reread"; only a read by a fresh, # separate session may be called independent. readback_evidence: ReadbackEvidence = "acting_session_reread" + # Reporting only: whether the read was the page the run landed on after + # commit ("same_screen"), a new navigation or search that fetched the + # record again ("fresh_navigation"), or a separate session. + read_route: Literal["same_screen", "fresh_navigation", "separate_session"] = ( + "same_screen" + ) # Distinct summary control observations per dossier key, populated by # SummaryJudge.evaluate so downstream signers can verify subject coverage # without counting repeated verdicts for the same control as distinct reads. @@ -910,6 +993,12 @@ class FormTxReceiptPayload(BaseModel): readback_passed: bool readback_not_checked_count: int = Field(default=0, ge=0) salted_output_digests: dict[str, str] = Field(default_factory=dict) + # What the receipt covers: the dossier keys whose read-back passed. A + # receipt says nothing about any other field. ``not_covered`` names the + # controls the run saw but did not check (pack-declared unbound controls, + # shown at their blank value) and intake keys no binding entered. + covered_keys: tuple[str, ...] = () + not_covered: tuple[str, ...] = () readback_evidence: ReadbackEvidence = "acting_session_reread" @model_validator(mode="after") diff --git a/packages/flow/tests/test_form_tx_demo_compiler.py b/packages/flow/tests/test_form_tx_demo_compiler.py new file mode 100644 index 0000000000..bba5b2e3a5 --- /dev/null +++ b/packages/flow/tests/test_form_tx_demo_compiler.py @@ -0,0 +1,150 @@ +"""Pack-authoring report from dev-case demonstrations (setup time, no browser).""" + +from __future__ import annotations + +from openadapt_flow.form_tx.demo_compiler import compile_demo_report +from openadapt_flow.form_tx.types import ( + ControlKind, + FieldAnchorSpec, + FieldBindingSpec, + FormCodecKind, + FormPack, + PopupSubroutineSpec, + WizardScreenSpec, +) + + +def _ctrl(label: str, value: str = "", **kw): + return { + "control_id": label, + "dom_selector": f"#{label.replace(' ', '_')}", + "tag": kw.pop("tag", "select"), + "label_text": label, + "current_value": value, + **kw, + } + + +def _row(*controls, why: str = "before click x", banners=()): + return { + "step": 0, + "why": why, + "frame_url": "http://x/", + "controls": list(controls), + "banners": list(banners), + } + + +DED_OPTS = [{"value": "500", "label": "$500"}, {"value": "1000", "label": "$1,000"}] + +PACK = FormPack( + pack_id="p", + domain_schema="test/v1", + ui_profile_id="t", + bindings=( + FieldBindingSpec( + binding_id="ded", + dossier_key="coverage.deductible", + anchor=FieldAnchorSpec(label_patterns=("^Deductible$",)), + control_kind=ControlKind.SELECT, + ), + FieldBindingSpec( + binding_id="lim", + dossier_key="coverage.limit", + anchor=FieldAnchorSpec(label_patterns=("^Limit$",)), + control_kind=ControlKind.SELECT, + ), + ), + screens=( + WizardScreenSpec( + screen_id="s", + landmark_selector="#s", + next_button_anchor=FieldAnchorSpec(label_patterns=("^Next$",)), + ), + ), +) + + +def test_defaults_are_proven_only_when_an_intake_asked_for_something_else() -> None: + demo = [ + _row( + _ctrl("Deductible", "500", options=DED_OPTS), + _ctrl("Limit", "300000"), + _ctrl("Next", tag="button"), + ) + ] + report = compile_demo_report( + PACK, + [(demo, {"coverage.deductible": "1000", "coverage.limit": "300000"})], + ) + status = {f.binding_id: f.status for f in report.defaults} + assert status == {"ded": "proven_default", "lim": "unproven_same_as_intake"} + assert report.proven_defaults() == {"ded": ("500",)} + assert report.demos_used == 1 + codec = report.option_codecs["ded"] + assert codec.kind == FormCodecKind.ENUM_MAP and codec.enum_aliases["1000"] == ( + "$1,000", + ) + + +def test_a_second_demo_that_shows_another_blank_value_is_not_a_default() -> None: + a = [_row(_ctrl("Deductible", "500"), _ctrl("Limit", ""))] + b = [_row(_ctrl("Deductible", "1000"), _ctrl("Limit", ""))] + report = compile_demo_report( + PACK, + [(a, {"coverage.deductible": "1000"}), (b, {"coverage.deductible": "500"})], + ) + status = {f.binding_id: f.status for f in report.defaults} + assert status["ded"] == "differs_between_demos" + assert status["lim"] == "blank" + assert report.proven_defaults() == {} + + +def test_row_key_cells_and_unopened_launchers() -> None: + sel = dict(tag="input", input_type="button") + demo = [ + _row( + _ctrl("Select", "Select", row_cells=["2021 Okel", "Kite", "4D", ""], **sel), + { + **_ctrl( + "Select", + "Select", + row_cells=["2021 Okel", "Kite Wagon", "4D", ""], + **sel, + ), + "dom_selector": "#s2", + }, + _ctrl("Estimate replacement cost", tag="button"), + _ctrl("Next", tag="button"), + why="before click ", + ) + ] + report = compile_demo_report( + PACK, [(demo, {"vehicle.model": "Kite Wagon", "vehicle.year": "2021"})] + ) + (rk,) = report.row_keys + assert rk.button_label == "Select" and rk.dossier_keys == ("vehicle.model",) + assert "Estimate replacement cost" in report.unopened_launchers + assert "Next" not in report.unopened_launchers + + +def test_a_popup_the_pack_covers_is_not_listed() -> None: + pack = PACK.model_copy( + update={ + "popup_subroutines": ( + PopupSubroutineSpec( + subroutine_id="est", + trigger_anchor=FieldAnchorSpec( + label_patterns=("^Estimate replacement cost$",) + ), + commit_anchor=FieldAnchorSpec(label_patterns=("^Use$",)), + parent_return_anchor=FieldAnchorSpec( + label_patterns=("^Dwelling$",) + ), + return_output_key="coverage.dwelling", + ), + ) + } + ) + demo = [_row(_ctrl("Estimate replacement cost", tag="button"))] + assert compile_demo_report(pack, [(demo, {})]).unopened_launchers == () diff --git a/packages/flow/tests/test_form_tx_expiry_and_radios.py b/packages/flow/tests/test_form_tx_expiry_and_radios.py index f74211f606..ccaf20ca53 100644 --- a/packages/flow/tests/test_form_tx_expiry_and_radios.py +++ b/packages/flow/tests/test_form_tx_expiry_and_radios.py @@ -345,7 +345,16 @@ def test_expiry_redirect_is_a_sign_in_wall_and_sign_in_resumes( assert portal.records == [] _sign_in(page) - done = _resolve(reconciler, session, halt, HumanDecisionAction.FIXED_ON_SCREEN) + resumed = _resolve(reconciler, session, halt, HumanDecisionAction.FIXED_ON_SCREEN) + # The sign-in came after fields were entered on step 1, and this pack + # gives no way back to step 1, so the layer stops before submit and + # names them; the operator checks them and the run goes on. + assert resumed.outcome == FormTxOutcome.HALTED_NEEDS_HUMAN, resumed.what_happened + (recheck,) = resumed.halts + assert recheck.kind == FormHaltKind.FIELDS_NOT_RECHECKED + assert set(recheck.portal_value) == {"First name", "Does the home have a pool?"} + assert portal.records == [] + done = _resolve(reconciler, session, recheck, HumanDecisionAction.FIXED_ON_SCREEN) assert done.outcome == FormTxOutcome.VERIFIED_DONE, done.what_happened assert portal.records == [{"first_name": "Avery", "pool": "no"}] statuses = {v.dossier_key: v.status for v in done.summary_verdict.field_verdicts} diff --git a/packages/flow/tests/test_form_tx_fail_open_classes.py b/packages/flow/tests/test_form_tx_fail_open_classes.py index 86b50cf58b..200072739f 100644 --- a/packages/flow/tests/test_form_tx_fail_open_classes.py +++ b/packages/flow/tests/test_form_tx_fail_open_classes.py @@ -240,7 +240,8 @@ def test_receipt_signed_before_later_fields_still_verifies_as_older() -> None: old = { k: v for k, v in payload.model_dump(mode="json").items() - if k not in ("readback_not_checked_count", "readback_evidence") + if k + not in ("readback_not_checked_count", "readback_evidence", "covered_keys", "not_covered") } old_bytes = canonical_json_bytes(old) receipt = SignedFormTxReceipt( diff --git a/packages/flow/tests/test_form_tx_layout_fixes.py b/packages/flow/tests/test_form_tx_layout_fixes.py index 44811f03ca..e42a3e63a7 100644 --- a/packages/flow/tests/test_form_tx_layout_fixes.py +++ b/packages/flow/tests/test_form_tx_layout_fixes.py @@ -221,12 +221,13 @@ def _run_address(browser: Any, inert: bool) -> tuple[Any, list[dict]]: ctx.close() -def test_pick_that_keeps_the_leading_part_of_its_label_is_accepted( +def test_pick_that_keeps_only_the_leading_part_of_its_label_stops( browser: Any, ) -> None: + # partial-match-as-match (#2448): a leading part is not the value. result, submissions = _run_address(browser, inert=False) - assert not result.halts, [h.message for h in result.halts] - assert submissions == [{"addr": "2210 Juniper Loop"}] + assert submissions == [] + assert result.halts, result.what_happened def test_typed_text_left_in_the_input_is_not_taken_as_a_pick(browser: Any) -> None: diff --git a/packages/flow/tests/test_form_tx_partial_pick.py b/packages/flow/tests/test_form_tx_partial_pick.py index 282efea073..e1c328ddec 100644 --- a/packages/flow/tests/test_form_tx_partial_pick.py +++ b/packages/flow/tests/test_form_tx_partial_pick.py @@ -68,7 +68,6 @@ """ - @pytest.fixture(scope="module") def browser() -> Any: with sync_api.sync_playwright() as pw: @@ -153,8 +152,15 @@ def _address_pack() -> FormPack: ) -def _run_address(browser: Any, inert: bool) -> tuple[Any, list[dict]]: +def _run_address( + browser: Any, inert: bool, prefill: str = "" +) -> tuple[Any, list[dict]]: body = ADDRESS.replace(" +""" + + +def _tabbed_pack(*, revisit: bool, first_revisit: bool = True) -> FormPack: + def screen(sid: str, landmark: str, tab: str) -> WizardScreenSpec: + on = revisit and (first_revisit or sid != "app") + return WizardScreenSpec( + screen_id=sid, + landmark_selector=landmark, + next_button_anchor=FieldAnchorSpec(label_patterns=("^Save and continue$",)), + revisit_selector=tab if on else None, + ) + + return FormPack( + commit_url_patterns=("/api/submit",), + pack_id="test-tabbed", + domain_schema="test.quote/v1", + ui_profile_id=_PROFILE.profile_id, + bindings=( + _bind("applicant.first_name", "First name"), + _bind( + "coverage.deductible", + "Deductible", + ControlKind.SELECT, + codec=_MONEY, + portal_default_values=("500",), + ), + ), + screens=( + screen("app", "#fn", "#tab-app"), + screen("cov", "#ded", "#tab-cov"), + WizardScreenSpec( + screen_id="rev", + landmark_selector="#submit", + is_commit_screen=True, + commit_button_anchor=FieldAnchorSpec( + label_patterns=("^Request quote$",) + ), + ), + ), + summary_check=SummaryCheckSpec( + field_readbacks=( + _shown("applicant.first_name", "First name"), + _shown("coverage.deductible", "Deductible", codec=_MONEY), + ) + ), + ) + + +def _sign_in_again(page: Any) -> None: + page.fill("#pw", "synthetic-test-pass") + page.click("#rl-go") + + +def test_sign_in_mid_quote_rewalks_and_refills_before_submit( + site: tuple[_Site, str], browser: Any +) -> None: + s, base = site + s.pages["/"] = _TABBED + page, _, reconciler, session = _start( + browser, + base, + "/", + _tabbed_pack(revisit=True), + _dossier(**{"applicant.first_name": "Avery", "coverage.deductible": "2500"}), + ) + first = reconciler.run_until_halt_or_done(session) + assert first.outcome == FormTxOutcome.AUTH_REQUIRED, first.what_happened + assert s.records == [] + _sign_in_again(page) + done = _resolve( + reconciler, session, first.halts[0], HumanDecisionAction.FIXED_ON_SCREEN + ) + assert done.outcome == FormTxOutcome.VERIFIED_DONE, done.what_happened + assert len(s.records) == 1 + assert s.records[0]["first_name"] == "Avery" + assert s.records[0]["deductible"] == "2500" + + +@pytest.mark.parametrize("later_only", [False, True]) +def test_sign_in_mid_quote_without_a_way_back_stops_naming_fields( + site: tuple[_Site, str], browser: Any, later_only: bool +) -> None: + # later_only: only a screen after the first can be revisited, so a walk + # from there would skip the first screen's fields; it must stop instead. + s, base = site + s.pages["/"] = _TABBED + page, _, reconciler, session = _start( + browser, + base, + "/", + _tabbed_pack(revisit=later_only, first_revisit=False), + _dossier(**{"applicant.first_name": "Avery", "coverage.deductible": "2500"}), + ) + first = reconciler.run_until_halt_or_done(session) + _sign_in_again(page) + stop = _resolve( + reconciler, session, first.halts[0], HumanDecisionAction.FIXED_ON_SCREEN + ) + assert stop.outcome == FormTxOutcome.HALTED_NEEDS_HUMAN, stop.what_happened + (halt,) = stop.halts + assert halt.kind == FormHaltKind.FIELDS_NOT_RECHECKED + assert set(halt.portal_value) == {"First name", "Deductible"} + assert s.records == [] + + +# --------------------------------------------------------------------------- +# 2. Controls no binding covers. + +_UNBOUND = """ +

About you

+
+
+
+
+
+
+ +""" + + +def _unbound_pack(*, declare_paperless: bool, declare_client: bool = True) -> FormPack: + unbound = [ + UnboundControlSpec(anchor=FieldAnchorSpec(label_patterns=("^Roommate$",))) + ] + if declare_paperless: + unbound.append( + UnboundControlSpec( + anchor=FieldAnchorSpec(label_patterns=("^Paperless documents$",)), + blank_values=("Yes",), + ) + ) + if declare_client: + unbound.append( + UnboundControlSpec( + anchor=FieldAnchorSpec(label_patterns=("^Client number$",)) + ) + ) + return FormPack( + commit_url_patterns=("/api/submit",), + pack_id="test-unbound", + domain_schema="test.quote/v1", + ui_profile_id=_PROFILE.profile_id, + bindings=(_bind("applicant.first_name", "First name"),), + screens=( + WizardScreenSpec( + screen_id="form", + landmark_selector="#form", + is_commit_screen=True, + commit_button_anchor=FieldAnchorSpec(label_patterns=("^Get quote$",)), + ), + ), + summary_check=SummaryCheckSpec( + field_readbacks=(_shown("applicant.first_name", "First name"),) + ), + unbound_controls=tuple(unbound), + ) + + +def test_unbound_free_text_with_a_value_stops_and_can_be_cleared( + site: tuple[_Site, str], browser: Any +) -> None: + s, base = site + s.pages["/"] = _UNBOUND + pack = _unbound_pack(declare_paperless=True).model_copy( + update={ + "unbound_controls": _unbound_pack(declare_paperless=True).unbound_controls[ + 1: + ] + } + ) + _, _, reconciler, session = _start( + browser, base, "/", pack, _dossier(**{"applicant.first_name": "Avery"}) + ) + first = reconciler.run_until_halt_or_done(session) + assert first.outcome == FormTxOutcome.HALTED_NEEDS_HUMAN, first.what_happened + (halt,) = first.halts + assert halt.kind == FormHaltKind.PREFILL_VALUE_CONFLICT + assert halt.field_label == "Roommate" + assert halt.portal_value == "Jasper Vellacott" + assert s.records == [] + done = _resolve(reconciler, session, halt, HumanDecisionAction.PROVIDE_VALUE, "") + assert s.records and s.records[0]["roommate"] == "" + # The cleared field has no read-back, so the run is not verified. + assert done.outcome == FormTxOutcome.READBACK_INCOMPLETE, done.what_happened + assert done.receipt is None + + +def test_unbound_choice_value_keeps_the_run_from_verified( + site: tuple[_Site, str], browser: Any +) -> None: + s, base = site + s.pages["/"] = _UNBOUND.replace(' value="Jasper Vellacott"', "") + _, _, reconciler, session = _start( + browser, + base, + "/", + _unbound_pack(declare_paperless=False), + _dossier(**{"applicant.first_name": "Avery"}), + ) + done = reconciler.run_until_halt_or_done(session) + assert len(s.records) == 1 + assert done.outcome == FormTxOutcome.READBACK_INCOMPLETE, done.what_happened + assert "unbound:Paperless documents" in done.summary_verdict.not_checked_keys + + +def test_declared_unbound_control_at_its_blank_value_is_named_on_the_receipt( + site: tuple[_Site, str], browser: Any +) -> None: + s, base = site + s.pages["/"] = _UNBOUND.replace(' value="Jasper Vellacott"', "") + _, _, reconciler, session = _start( + browser, + base, + "/", + _unbound_pack(declare_paperless=True), + _dossier(**{"applicant.first_name": "Avery"}), + ) + done = reconciler.run_until_halt_or_done(session) + assert done.outcome == FormTxOutcome.VERIFIED_DONE, done.what_happened + payload = done.receipt.payload + assert payload.covered_keys == ("applicant.first_name",) + assert {"Paperless documents", "Roommate", "Client number"} <= set( + payload.not_covered + ) + + +@pytest.mark.parametrize("readonly", [False, True]) +def test_intake_key_matching_an_empty_unbound_field_stops( + site: tuple[_Site, str], browser: Any, readonly: bool +) -> None: + s, base = site + html = _UNBOUND.replace(' value="Jasper Vellacott"', "") + if readonly: + # Set only by a client lookup the pack does not run. + html = html.replace('name="client_no">', 'name="client_no" readonly>') + s.pages["/"] = html + _, _, reconciler, session = _start( + browser, + base, + "/", + _unbound_pack(declare_paperless=True, declare_client=False), + _dossier( + **{"applicant.first_name": "Avery", "history.client_number": "FC-C-20418"} + ), + ) + first = reconciler.run_until_halt_or_done(session) + assert first.outcome == FormTxOutcome.HALTED_NEEDS_HUMAN, first.what_happened + (halt,) = first.halts + assert halt.kind == FormHaltKind.UNGROUNDED_REQUIRED_FIELD + assert halt.field_label == "Client number" + assert halt.dossier_key == "history.client_number" + assert s.records == [] + + +# --------------------------------------------------------------------------- +# 3. Stops name the field. + +_STEP = """ +

Details

+
+
+
+
+
+
+
+ +""" + + +def _step_pack() -> FormPack: + return FormPack( + commit_url_patterns=("/api/submit",), + pack_id="test-step", + domain_schema="test.quote/v1", + ui_profile_id=_PROFILE.profile_id, + bindings=(_bind("property.units", "Number of units"),), + screens=( + WizardScreenSpec( + screen_id="step", + landmark_selector="#step", + next_button_anchor=FieldAnchorSpec(label_patterns=("^Next$",)), + ), + ), + unbound_controls=( + UnboundControlSpec( + anchor=FieldAnchorSpec(label_patterns=("^Has any driver",)) + ), + UnboundControlSpec( + anchor=FieldAnchorSpec(label_patterns=("^Unit occupancy$",)) + ), + ), + ) + + +@pytest.mark.parametrize( + ("mode", "label"), + [ + ("marker", "Unit occupancy"), + ("summary", "Has any driver under 25 had a moving violation?"), + ("alert", "Unit occupancy"), + ], +) +def test_validation_stop_names_the_field( + site: tuple[_Site, str], browser: Any, mode: str, label: str +) -> None: + s, base = site + s.pages["/"] = _STEP.replace("__MODE__", mode) + _, _, reconciler, session = _start( + browser, base, "/", _step_pack(), _dossier(**{"property.units": "2"}) + ) + stop = reconciler.run_until_halt_or_done(session) + assert stop.outcome == FormTxOutcome.VALIDATION_BLOCKED, stop.what_happened + (halt,) = stop.halts + assert halt.kind == FormHaltKind.PORTAL_VALIDATION_BLOCKED + assert halt.field_label == label + assert halt.dom_selector + + +_RADIOS = """ +
Umbrella limit + +
+
+""" + + +def _radio_pack(*, defaults: tuple[str, ...]) -> FormPack: + return FormPack( + commit_url_patterns=("/api/submit",), + pack_id="test-radios", + domain_schema="test.quote/v1", + ui_profile_id=_PROFILE.profile_id, + bindings=( + FieldBindingSpec( + binding_id="lim", + dossier_key="coverage.umbrella_limit", + anchor=FieldAnchorSpec(label_patterns=("^Umbrella limit$",)), + control_kind=ControlKind.RADIO_GROUP, + codec=_MONEY, + prefill_policy=PrefillPolicy.HALT_ON_CONFLICT, + portal_default_values=defaults, + ), + ), + screens=( + WizardScreenSpec( + screen_id="form", + landmark_selector="#form", + next_button_anchor=FieldAnchorSpec(css_selector="#nowhere"), + ), + ), + ) + + +def test_radio_conflict_names_the_group(site: tuple[_Site, str], browser: Any) -> None: + s, base = site + s.pages["/"] = _RADIOS + _, _, reconciler, session = _start( + browser, + base, + "/", + _radio_pack(defaults=()), + _dossier(**{"coverage.umbrella_limit": "2000000"}), + ) + stop = reconciler.run_until_halt_or_done(session) + (halt,) = stop.halts + assert halt.kind == FormHaltKind.PREFILL_VALUE_CONFLICT + assert halt.field_label == "Umbrella limit" + + +def test_declared_blank_default_is_written_over( + site: tuple[_Site, str], browser: Any +) -> None: + s, base = site + s.pages["/"] = _RADIOS + page, _, reconciler, session = _start( + browser, + base, + "/", + _radio_pack(defaults=("1000000",)), + _dossier(**{"coverage.umbrella_limit": "2000000"}), + ) + stop = reconciler.run_until_halt_or_done(session) + # No prefill stop: the default is replaced (the run then stops at the + # missing Next button, which this page does not have). + assert all(h.kind != FormHaltKind.PREFILL_VALUE_CONFLICT for h in stop.halts) + assert page.locator("input[value='2000000']").is_checked() + + +# --------------------------------------------------------------------------- +# 4. Row choice, split date, sentence output, "Label: value" output. + +_ROWS = """ +

Vehicle Lookup

+ + +
2021 OkelKite4D Hatchback
2021 OkelKite Wagon4D Wagon
+Estimated value: $18,500
+""" + + +def test_select_button_chosen_by_its_row_and_label_value_output( + site: tuple[_Site, str], browser: Any +) -> None: + s, base = site + s.pages["/"] = _ROWS + _, surface, _, _ = _start( + browser, + base, + "/", + _radio_pack(defaults=()), + _dossier(), + ) + snap = surface.snapshot() + anchor = FieldAnchorSpec( + label_patterns=("^Select$",), row_cell_dossier_keys=("vehicle.model",) + ) + with pytest.raises(AmbiguousAnchorError): + match_anchor_in_snapshot(anchor, snap) + pick = match_anchor_in_snapshot(anchor, snap, facts={"vehicle.model": "Kite Wagon"}) + assert pick is not None and "Kite Wagon" in pick.row_cells + other = match_anchor_in_snapshot(anchor, snap, facts={"vehicle.model": "Kite"}) + assert other is not None and other.dom_selector != pick.dom_selector + with pytest.raises(AmbiguousAnchorError): + match_anchor_in_snapshot(anchor, snap, facts={"vehicle.model": "Harrier"}) + out = match_anchor_in_snapshot( + FieldAnchorSpec(label_patterns=("^Estimated value$",)), + snap, + include_readonly=True, + ) + assert out is not None and out.current_value == "$18,500" + + +_DATE_FORM = """ +
Date of birth + + +
+
+ +""" + + +@pytest.mark.parametrize(("year", "verified"), [("1988", True), ("1989", False)]) +def test_split_date_and_sentence_quote_number_read_back( + site: tuple[_Site, str], browser: Any, year: str, verified: bool +) -> None: + s, base = site + s.pages["/"] = _DATE_FORM + keys = ("applicant.dob_day", "applicant.dob_month", "applicant.dob_year") + pack = FormPack( + commit_url_patterns=("/api/submit",), + pack_id="test-date", + domain_schema="test.quote/v1", + ui_profile_id=_PROFILE.profile_id, + bindings=tuple( + FieldBindingSpec( + binding_id=k, + dossier_key=k, + anchor=FieldAnchorSpec(name_or_id_patterns=(rf"^{n}(?:\s|$)",)), + ) + for k, n in zip(keys, ("dob_day", "dob_month", "dob_year")) + ), + screens=( + WizardScreenSpec( + screen_id="form", + landmark_selector="#form", + is_commit_screen=True, + commit_button_anchor=FieldAnchorSpec(label_patterns=("^Apply$",)), + ), + ), + summary_check=SummaryCheckSpec( + summary_landmark_selector="#done", + split_date_readbacks=( + SplitDateReadbackSpec( + anchor=FieldAnchorSpec(label_patterns=("^Date of birth$",)), + day_key=keys[0], + month_key=keys[1], + year_key=keys[2], + ), + ), + outputs=( + OutputExtractionSpec( + output_key="quote_number", + anchor=FieldAnchorSpec(label_patterns=("^Quote number$",)), + value_pattern=r"quote number is\s+([A-Z]{2}-\d+)", + ), + ), + ), + ) + page, _, reconciler, session = _start( + browser, base, "/", pack, _dossier(**dict(zip(keys, ("4", "3", "1988")))) + ) + if not verified: + # The portal stores a different year than was typed. + page.evaluate( + "y => { const b = document.getElementById('submit'); const f = b.onclick;" + " b.onclick = () => { document.getElementById('y').value = y; f(); }; }", + year, + ) + done = reconciler.run_until_halt_or_done(session) + statuses = {v.dossier_key: v.status for v in done.summary_verdict.field_verdicts} + if verified: + assert done.outcome == FormTxOutcome.VERIFIED_DONE, done.what_happened + assert done.outputs["quote_number"] == "VW-12345" + assert all(statuses[k] == ReadbackStatus.PASSED for k in keys) + else: + assert done.outcome == FormTxOutcome.READBACK_REFUTED, done.what_happened + assert all(statuses[k] == ReadbackStatus.FAILED for k in keys) + + +# --------------------------------------------------------------------------- +# 5. Intake values no binding enters; radio groups named by their row; a +# form that asks one question at a time in the same control. + + +@pytest.mark.parametrize("ignored", [False, True]) +def test_intake_value_no_binding_enters_keeps_the_run_from_verified( + site: tuple[_Site, str], browser: Any, ignored: bool +) -> None: + s, base = site + s.pages["/"] = _UNBOUND.replace(' value="Jasper Vellacott"', "") + pack = _unbound_pack(declare_paperless=True) + if ignored: + pack = pack.model_copy(update={"ignored_intake_keys": ("drivers.additional",)}) + _, _, reconciler, session = _start( + browser, + base, + "/", + pack, + _dossier(**{"applicant.first_name": "Avery", "drivers.additional": "Pavel"}), + ) + done = reconciler.run_until_halt_or_done(session) + assert len(s.records) == 1 + # An intake value the portal never asks for is named on the receipt as + # not covered; it blocks verified_done only when the pack requires it. + assert done.outcome == FormTxOutcome.VERIFIED_DONE, done.what_happened + assert "intake:drivers.additional" in done.receipt.payload.not_covered + assert "drivers.additional" not in done.receipt.payload.covered_keys + + +def test_required_intake_value_no_binding_enters_blocks_verified( + site: tuple[_Site, str], browser: Any +) -> None: + s, base = site + s.pages["/"] = _UNBOUND.replace(' value="Jasper Vellacott"', "") + pack = _unbound_pack(declare_paperless=True).model_copy( + update={"required_intake_keys": ("drivers.additional",)} + ) + _, _, reconciler, session = _start( + browser, + base, + "/", + pack, + _dossier(**{"applicant.first_name": "Avery", "drivers.additional": "Pavel"}), + ) + done = reconciler.run_until_halt_or_done(session) + assert done.outcome == FormTxOutcome.READBACK_INCOMPLETE, done.what_happened + assert "intake:drivers.additional" in done.summary_verdict.not_checked_keys + + +_ROW_RADIO = """ +
+ +
Completed a driver training course?: + +
+ +""" + + +def test_radio_group_without_legend_is_named_by_its_row( + site: tuple[_Site, str], browser: Any +) -> None: + s, base = site + s.pages["/"] = _ROW_RADIO + pack = _step_pack().model_copy(update={"unbound_controls": ()}) + _, _, reconciler, session = _start(browser, base, "/", pack, _dossier()) + stop = reconciler.run_until_halt_or_done(session) + (halt,) = stop.halts + assert halt.field_label == "Completed a driver training course?" + + +_ONE_AT_A_TIME = """ +
+
+ +""" + + +def test_one_question_at_a_time_in_the_same_control_advances( + site: tuple[_Site, str], browser: Any +) -> None: + s, base = site + s.pages["/"] = _ONE_AT_A_TIME + pack = FormPack( + commit_url_patterns=("/api/submit",), + pack_id="test-ask", + domain_schema="test.quote/v1", + ui_profile_id=_PROFILE.profile_id, + bindings=( + _bind("applicant.first_name", "First name"), + _bind("applicant.last_name", "Last name"), + ), + screens=( + WizardScreenSpec( + screen_id="ask", + landmark_selector="#ask", + next_button_anchor=FieldAnchorSpec(label_patterns=("^Continue$",)), + ), + ), + summary_check=SummaryCheckSpec( + summary_landmark_selector="#done", + field_readbacks=( + _shown("applicant.first_name", "First name"), + _shown("applicant.last_name", "Last name"), + ), + ), + max_commit_mutations=1, + ) + _, _, reconciler, session = _start( + browser, + base, + "/", + pack, + _dossier(**{"applicant.first_name": "Avery", "applicant.last_name": "Quist"}), + ) + done = reconciler.run_until_halt_or_done(session) + assert s.records == [{"First name": "Avery", "Last name": "Quist"}] + assert done.outcome != FormTxOutcome.VALIDATION_BLOCKED, done.what_happened + + +# --------------------------------------------------------------------------- +# 6. A bound field shown with no intake value (cv-s04 class). + +_SHOWN_BLANK = """ +

Household

+
+
+
+ +""" + + +@pytest.mark.parametrize("optional", [False, True]) +def test_bound_field_shown_with_no_intake_value( + site: tuple[_Site, str], browser: Any, optional: bool +) -> None: + s, base = site + s.pages["/"] = _SHOWN_BLANK + pack = FormPack( + commit_url_patterns=("/api/submit",), + pack_id="test-shown-blank", + domain_schema="test.quote/v1", + ui_profile_id=_PROFILE.profile_id, + bindings=( + _bind("applicant.first_name", "First name"), + _bind("household.dog_breeds", "Breed of each dog", optional=optional), + ), + screens=( + WizardScreenSpec( + screen_id="form", + landmark_selector="#form", + is_commit_screen=True, + commit_button_anchor=FieldAnchorSpec(label_patterns=("^Get quote$",)), + ), + ), + summary_check=SummaryCheckSpec( + field_readbacks=(_shown("applicant.first_name", "First name"),) + ), + ) + _, _, reconciler, session = _start( + browser, base, "/", pack, _dossier(**{"applicant.first_name": "Avery"}) + ) + done = reconciler.run_until_halt_or_done(session) + if not optional: + assert s.records == [] + (halt,) = done.halts + assert halt.kind == FormHaltKind.UNGROUNDED_REQUIRED_FIELD + assert halt.field_label == "Breed of each dog" + else: + assert len(s.records) == 1 + assert done.outcome == FormTxOutcome.VERIFIED_DONE, done.what_happened + payload = done.receipt.payload + assert "household.dog_breeds" not in payload.covered_keys + assert "optional-blank:household.dog_breeds" in payload.not_covered + + +# --------------------------------------------------------------------------- +# 7. The review page shows a value the portal changed: stop before submit. + +_REVIEW = """ +
+ +""" + + +def test_review_page_value_that_differs_stops_before_submit( + site: tuple[_Site, str], browser: Any +) -> None: + s, base = site + s.pages["/"] = _REVIEW + pack = FormPack( + commit_url_patterns=("/api/submit",), + pack_id="test-review", + domain_schema="test.quote/v1", + ui_profile_id=_PROFILE.profile_id, + bindings=( + _bind( + "boat.hp", + "Total horsepower", + codec=FieldCodecSpec(kind=FormCodecKind.INTEGER), + ), + ), + screens=( + WizardScreenSpec( + screen_id="s1", + landmark_selector="#s1", + next_button_anchor=FieldAnchorSpec(label_patterns=("^Continue$",)), + ), + WizardScreenSpec( + screen_id="rev", + landmark_selector="#rev", + is_commit_screen=True, + commit_button_anchor=FieldAnchorSpec( + label_patterns=("^Get my quote$",) + ), + ), + ), + summary_check=SummaryCheckSpec( + review_readbacks=( + FieldBindingSpec( + binding_id="rv_hp", + dossier_key="boat.hp", + anchor=FieldAnchorSpec( + label_patterns=("^Total horsepower$",), + section_patterns=("^Review$",), + ), + codec=FieldCodecSpec(kind=FormCodecKind.INTEGER), + ), + ) + ), + ) + _, _, reconciler, session = _start( + browser, base, "/", pack, _dossier(**{"boat.hp": "400"}) + ) + stop = reconciler.run_until_halt_or_done(session) + assert s.records == [] + (halt,) = stop.halts + assert halt.kind == FormHaltKind.PREFILL_VALUE_CONFLICT + assert halt.field_label == "Total horsepower" + assert halt.portal_value == "800"