diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 2a16a24535..132af8b99e 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, stop for an operator on a prefill that disagrees with the intake or a question the intake does not answer (decided in a Chrome side panel), submit once, and give every typed, selected or kept field a read-back verdict: `passed`, `failed` or `not_checked`. A field it cannot read back is `not_checked`, never passed; such a submit ends `readback_incomplete` with no receipt | On main, prototype; not on PyPI until Flow 3.4.0 ([#2308](https://github.com/OpenAdaptAI/OpenAdapt/pull/2308)) | Synthetic only. Four quote portals built separately from the layer, 32 scored cases, pre-registered: 6 correct submissions, 0 wrong values submitted, 0 verified (every field on the one workable portal is `not_checked`, because its summary is plain text). The surface cannot see iframe or shadow-DOM forms or fill type-aheads, so 3 of 4 portals submitted nothing. Estimator, session-timeout and type-ahead traps were never reached. Rule proposals from repeated operator answers (`form_tx/learning.py`) had no measured effect: none qualified ([RESULTS](packages/flow/benchmark/form_tx_heldout_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, stop for an operator on a prefill that disagrees with the intake or a question the intake does not answer (decided in a Chrome side panel), submit once, and give every typed, selected or kept field a read-back verdict: `passed`, `failed` or `not_checked`. A field it cannot read back is `not_checked`, never passed; such a submit ends `readback_incomplete` with no receipt. A summary shown as page text (definition list, table, "Label: value" lines, open shadow roots) is read back by label; a label shown twice is `not_checked` ([#2449](https://github.com/OpenAdaptAI/OpenAdapt/pull/2449)) | On main, prototype; not on PyPI until Flow 3.4.0 ([#2308](https://github.com/OpenAdaptAI/OpenAdapt/pull/2308)) | Synthetic only. Four quote portals built separately from the layer, 32 scored cases, pre-registered: 6 correct submissions, 0 wrong values submitted, 0 verified (every field on the one workable portal is `not_checked`, because its summary is plain text). The surface cannot see iframe or shadow-DOM forms or fill type-aheads, so 3 of 4 portals submitted nothing. Estimator, session-timeout and type-ahead traps were never reached. Rule proposals from repeated operator answers (`form_tx/learning.py`) had no measured effect: none qualified ([RESULTS](packages/flow/benchmark/form_tx_heldout_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/packages/flow/docs/FORM_TX.md b/packages/flow/docs/FORM_TX.md index 0d547bd1ea..f675b0704a 100644 --- a/packages/flow/docs/FORM_TX.md +++ b/packages/flow/docs/FORM_TX.md @@ -57,6 +57,35 @@ re-read from their controls just before the popup's apply button. A mismatch stops the run before apply. A match does not count as a read-back of the record: unless the summary shows the field, it stays `not_checked`. +#### Summaries shown as page text + +Many confirmation pages show the stored quote as text, not in form controls. +When a read-back anchor finds no control, the judge looks for the field in +label and value pairs read from the page text: + +- definition lists (`dt` then `dd`); +- two-cell table rows (`th` or `td`, then `td`); +- tables with one header row and exactly one data row (each header names the + cell below it); +- "Label: value" text in a block element, and a block with two leaf + children whose first ends in a colon or is a `dt`, `th`, `label`, + `strong` or `b`. + +Open shadow roots are read too; closed ones are not. Only an anchor's +`label_patterns`, narrowed by `section_patterns`, can match page text, because +text has no name, id or selector. The rules: + +- a label shown more than once (even with the same value) makes the field + `not_checked`; +- an empty or placeholder value is `failed` when a value was expected; +- a different value under the field's codec is `failed`; +- the same value is `passed`, with a reason that says it was read from page + text. + +A control always wins over page text. Outputs such as a quote number are read +from page text the same way. The pairs are kept apart from the form controls, +so the layer never fills or halts on them. + The summary must match its declared landmark when one is configured. This is the configured browser read-back only. It does not prove server-side isolation, the absence of changes in other records, or atomic rollback of a @@ -69,10 +98,6 @@ Measured on four held-out synthetic portals - It reads only the top document: a form inside an iframe shows no controls, and controls inside shadow DOM are invisible. -- It reads values back only from form controls (`input`, `select`, - `textarea`, `output`, `[data-readonly-output]`). A summary or confirmation - page that shows values as plain text cannot be read, so every field ends - `not_checked`. - A popup routine has one apply button; an estimator that needs Calculate and then Use This Value stops for a person. - A type-ahead that fetches suggestions only after typing cannot be filled: diff --git a/packages/flow/openadapt_flow/form_tx/__init__.py b/packages/flow/openadapt_flow/form_tx/__init__.py index 8752d201b4..376accdcc8 100644 --- a/packages/flow/openadapt_flow/form_tx/__init__.py +++ b/packages/flow/openadapt_flow/form_tx/__init__.py @@ -68,6 +68,7 @@ MissingAnchorError, compute_field_signature, match_anchor_in_snapshot, + match_text_pair_in_snapshot, ) from openadapt_flow.form_tx.types import ( FORM_DOSSIER_SCHEMA, @@ -100,6 +101,7 @@ ObservedEntityRow, ObservedModal, ObservedOption, + ObservedTextPair, OutputExtractionSpec, PackPatchCandidate, PopupSubroutineSpec, @@ -156,6 +158,7 @@ "MissingAnchorError", "ModalRuleSpec", "ObservedControl", + "ObservedTextPair", "ObservedEntityRow", "ObservedModal", "ObservedOption", @@ -202,6 +205,7 @@ "load_or_create_ed25519_key", "load_ui_profile", "match_anchor_in_snapshot", + "match_text_pair_in_snapshot", "normalize_boolean_yes_no", "normalize_currency_cents", "normalize_phone_digits", diff --git a/packages/flow/openadapt_flow/form_tx/judge.py b/packages/flow/openadapt_flow/form_tx/judge.py index f37ebd0402..f80cd05fc1 100644 --- a/packages/flow/openadapt_flow/form_tx/judge.py +++ b/packages/flow/openadapt_flow/form_tx/judge.py @@ -25,11 +25,13 @@ AmbiguousAnchorError, FormSurfaceBackend, match_anchor_in_snapshot, + match_text_pair_in_snapshot, ) from openadapt_flow.form_tx.types import ( ControlKind, DossierFact, FieldBindingSpec, + FieldCodecSpec, FieldWriteRecord, FormCodecKind, FormHaltKind, @@ -39,6 +41,7 @@ HumanResolutionRecord, InputDossier, ObservedControl, + ObservedTextPair, OutputExtractionSpec, ProvenanceKind, ReadbackFieldVerdict, @@ -161,6 +164,25 @@ def _observed_control_matches( return False +def _text_pair_matches( + expected_val: Any, + pair: ObservedTextPair, + binding: FieldBindingSpec, +) -> bool: + """Compare an expected value with a value shown as page text.""" + if _is_placeholder_or_empty(pair.value, binding.placeholder_values): + return False + if values_equivalent(expected_val, pair.value, binding.codec): + return True + if binding.control_kind in (ControlKind.CHECKBOX, ControlKind.RADIO_GROUP): + return values_equivalent( + expected_val, + pair.value, + FieldCodecSpec(kind=FormCodecKind.BOOLEAN_YES_NO), + ) + return False + + def _extract_present_outputs( snapshot: FormSnapshot, output_specs: Sequence[OutputExtractionSpec], @@ -177,6 +199,21 @@ def _extract_present_outputs( 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. + try: + pair = match_text_pair_in_snapshot(spec.anchor, snapshot) + except AmbiguousAnchorError: + invalid_keys.add(spec.output_key) + continue + if pair is None or not pair.value.strip(): + continue + try: + extracted[spec.output_key] = normalize_with_codec( + pair.value.strip(), spec.codec + ) + except CodecValueError: + invalid_keys.add(spec.output_key) continue raw_val = ctrl.current_value.strip() if not raw_val: @@ -450,12 +487,34 @@ def _where(field_writes: Sequence[FieldWriteRecord]) -> str: ) continue - if fact is None: - has_ungrounded_screen_val = ( - observed_ctrl is not None - and not _is_placeholder_or_empty( - observed_ctrl.current_value, binding.placeholder_values + # With no control, the summary may show the value as page text. + observed_text: Optional[ObservedTextPair] = None + if observed_ctrl is None: + try: + observed_text = match_text_pair_in_snapshot( + binding.anchor, snapshot + ) + except AmbiguousAnchorError as exc: + verdicts.append( + _not_checked( + binding.dossier_key, + prov, + f"Page text shows {binding.dossier_key!r} more than " + f"once, so it cannot be read back: {exc}", + ) ) + continue + + if fact is None: + shown_value = ( + observed_ctrl.current_value + if observed_ctrl is not None + else observed_text.value + if observed_text is not None + else "" + ) + has_ungrounded_screen_val = not _is_placeholder_or_empty( + shown_value, binding.placeholder_values ) if has_ungrounded_screen_val: verdicts.append( @@ -490,6 +549,41 @@ def _where(field_writes: Sequence[FieldWriteRecord]) -> str: ) continue + if observed_ctrl is None and observed_text is not None: + if _text_pair_matches(fact.value, observed_text, binding): + verdicts.append( + ReadbackFieldVerdict( + dossier_key=binding.dossier_key, + codec_kind=binding.codec.kind, + passed=True, + status=ReadbackStatus.PASSED, + provenance=prov, + reason=( + "Read from page text " + f"({observed_text.source}: {observed_text.label!r})" + ), + ) + ) + else: + shown = ( + "an empty value" + if _is_placeholder_or_empty( + observed_text.value, binding.placeholder_values + ) + else "a different value" + ) + verdicts.append( + _failed( + binding.dossier_key, + binding.codec.kind, + prov, + f"Page text shows {shown} for {binding.dossier_key!r} " + f"({observed_text.source}: {observed_text.label!r}) " + f"under codec {binding.codec.kind.value!r}", + ) + ) + continue + if observed_ctrl is None: verdicts.append( _not_checked( @@ -532,6 +626,17 @@ def _where(field_writes: Sequence[FieldWriteRecord]) -> str: 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}" + ) evaluated_subjects = read_subjects(writes, active_resolutions) verdicts.extend( uncovered_subject_verdicts( diff --git a/packages/flow/openadapt_flow/form_tx/playwright_surface.py b/packages/flow/openadapt_flow/form_tx/playwright_surface.py index 35b181cab9..223199bc9d 100644 --- a/packages/flow/openadapt_flow/form_tx/playwright_surface.py +++ b/packages/flow/openadapt_flow/form_tx/playwright_surface.py @@ -33,6 +33,7 @@ ObservedEntityRow, ObservedModal, ObservedOption, + ObservedTextPair, UIProfileSpec, WizardScreenSpec, ) @@ -919,6 +920,275 @@ def _strip_url_to_origin_and_path(raw_url: str) -> str: """ +# Label and value pairs shown as page text (definition lists, tables and +# "Label: value" lines). Kept out of the controls so nothing fills them; only +# read-back and output extraction use them. Open shadow roots are traversed; +# closed ones cannot be read. +_TEXT_PAIRS_JS = r""" +(cfg) => { + const MAX_PAIRS = cfg.maxPairs || 500; + const MAX_LEN = cfg.maxValueLength || 500; + const MAX_LABEL = 120; + const cleanText = (s) => String(s || '').replace(/\s+/g, ' ').trim(); + + const parentOf = (el) => { + if (el.parentElement) return el.parentElement; + const root = el.getRootNode ? el.getRootNode() : null; + return (root && root.host) ? root.host : null; + }; + + const isVisible = (el) => { + if (!el || !(el instanceof Element)) return false; + let cur = el; + while (cur && cur !== document.documentElement) { + if (cur.hasAttribute('hidden')) return false; + if (cur.tagName === 'DIALOG' && !cur.open && + cur.getAttribute('data-modal-open') !== 'true') { + return false; + } + const cs = window.getComputedStyle(cur); + if (cs.display === 'none' || cs.visibility === 'hidden' || + cs.visibility === 'collapse') { + return false; + } + cur = parentOf(cur); + } + const rect = el.getBoundingClientRect(); + return rect.width > 0 && rect.height > 0; + }; + + // Hidden by style or attribute; an empty element with no size still counts + // as shown, so an empty value reads as empty rather than vanishing. + const isShown = (el) => { + let cur = el; + while (cur && cur !== document.documentElement) { + if (cur.hasAttribute('hidden')) return false; + const cs = window.getComputedStyle(cur); + if (cs.display === 'none' || cs.visibility === 'hidden' || + cs.visibility === 'collapse') { + return false; + } + cur = parentOf(cur); + } + return true; + }; + + // Every open shadow root, nested ones included. + const roots = [document]; + for (let i = 0; i < roots.length && roots.length < 2000; i += 1) { + for (const el of roots[i].querySelectorAll('*')) { + if (el.shadowRoot) roots.push(el.shadowRoot); + } + } + const deepAll = (sel) => { + const out = []; + for (const r of roots) { + try { + for (const el of r.querySelectorAll(sel)) out.push(el); + } catch (e) {} + } + return out; + }; + + const CONTROL_SEL = 'input:not([type="hidden"]), select, textarea, button, ' + + '[role="combobox"], [role="listbox"], [role="checkbox"], [role="radio"], [contenteditable="true"]'; + const STRIP_SEL = CONTROL_SEL + ', option, script, style, noscript, template'; + const hasControl = (el) => { + try { + return Boolean(el.querySelector(CONTROL_SEL)); + } catch (e) { + return false; + } + }; + const textOf = (el) => { + const clone = el.cloneNode(true); + try { + for (const child of Array.from(clone.querySelectorAll(STRIP_SEL))) child.remove(); + } catch (e) {} + return cleanText(clone.textContent); + }; + const normLabel = (s) => cleanText(String(s || '').replace(/[::]\s*$/, '').replace(/\*\s*$/, '')); + + const HEADING_SEL = 'h1, h2, h3, h4, legend, caption'; + const headings = deepAll(HEADING_SEL).filter(isVisible); + const sectionOf = (el) => { + let best = ''; + const root = el.getRootNode(); + for (const h of headings) { + if (h.getRootNode() !== root) continue; + if (h === el || h.contains(el)) { + if (h.tagName === 'CAPTION' || h.tagName === 'LEGEND') best = cleanText(h.textContent); + continue; + } + if (h.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) { + best = cleanText(h.textContent); + } + } + // A table's caption names the rows inside it. + const table = el.closest ? el.closest('table') : null; + if (table && table.caption && cleanText(table.caption.textContent)) { + return cleanText(table.caption.textContent); + } + return best; + }; + + const pairs = []; + const consumed = new Set(); + const push = (label, value, el, source) => { + if (pairs.length >= MAX_PAIRS) return; + const l = normLabel(label); + if (!l || l.length > MAX_LABEL || !/[A-Za-z0-9À-￿]/.test(l)) return; + pairs.push({ + label: l, + value: cleanText(value).slice(0, MAX_LEN), + section_text: sectionOf(el), + source, + }); + }; + const isConsumed = (el) => { + let cur = el; + for (let d = 0; cur && d < 12; d += 1) { + if (consumed.has(cur)) return true; + cur = parentOf(cur); + } + return false; + }; + + // 1. Definition lists: dt then its dd(s). + for (const dl of deepAll('dl')) { + if (!isVisible(dl) || hasControl(dl)) continue; + const items = []; + for (const child of Array.from(dl.children)) { + if (child.tagName === 'DT' || child.tagName === 'DD') { + items.push(child); + } else if (child.tagName === 'DIV') { + for (const g of Array.from(child.children)) { + if (g.tagName === 'DT' || g.tagName === 'DD') items.push(g); + } + } + } + let labels = []; + let values = []; + let anchor = null; + const flush = () => { + if (labels.length && anchor) { + for (const l of labels) push(l, values.join(', '), anchor, 'dl'); + } + labels = []; + values = []; + anchor = null; + }; + // A hidden dd still ends its group: it counts as an empty value, so + // a later dd is never joined onto earlier labels. A hidden dt starts a + // group nobody can see, and its dd values are dropped. + let hiddenGroup = false; + for (const it of items) { + consumed.add(it); + const shown = isShown(it); + if (it.tagName === 'DT') { + if (values.length || !shown) flush(); + hiddenGroup = !shown; + if (!shown) continue; + labels.push(textOf(it)); + if (!anchor) anchor = it; + } else if (hiddenGroup) { + continue; + } else if (labels.length) { + values.push(shown ? textOf(it) : ''); + } + } + flush(); + consumed.add(dl); + } + + // 2. Tables without form controls. + for (const table of deepAll('table')) { + if (!isVisible(table)) continue; + const rows = Array.from(table.rows || []).filter( + (r) => r.closest('table') === table && isVisible(r) + ); + if (!rows.length) continue; + const cellsOf = (r) => Array.from(r.cells || []); + const first = cellsOf(rows[0]); + const headerRow = first.length >= 2 && first.every((c) => c.tagName === 'TH'); + const dataRows = rows.slice(1); + if (headerRow && dataRows.length === 1 && !hasControl(table)) { + const cells = cellsOf(dataRows[0]); + if (cells.length === first.length) { + for (let i = 0; i < cells.length; i += 1) { + push(textOf(first[i]), textOf(cells[i]), cells[i], 'table_columns'); + } + consumed.add(table); + continue; + } + } + for (const row of rows) { + const cells = cellsOf(row); + if (cells.length !== 2) continue; + if (hasControl(row)) continue; + if (cells[0].tagName === 'TH' && cells[1].tagName === 'TH') continue; + if (cells[0].colSpan > 1 || cells[1].colSpan > 1) continue; + push(textOf(cells[0]), textOf(cells[1]), cells[0], 'table_row'); + consumed.add(row); + } + } + + // 3. Two leaf children:
Label:value
. + const INLINE = new Set([ + 'B', 'STRONG', 'EM', 'I', 'SPAN', 'SMALL', 'LABEL', 'ABBR', 'CODE', 'BR', + 'A', 'TIME', 'MARK', 'SUP', 'SUB', 'U', 'DATA', 'OUTPUT', 'BDI', + ]); + const isLeaf = (el) => Array.from(el.children).every((c) => INLINE.has(c.tagName) && c.children.length === 0); + const BLOCK_SEL = 'p, li, div, span, td, dd'; + const emitted = new Set(); + for (const el of deepAll(BLOCK_SEL)) { + if (pairs.length >= MAX_PAIRS) break; + if (isConsumed(el) || !isVisible(el) || hasControl(el)) continue; + const kids = Array.from(el.children).filter((c) => c.tagName !== 'BR' && textOf(c)); + if (kids.length !== 2) continue; + if (!kids.every((k) => k.children.length === 0 || isLeaf(k))) continue; + const loose = Array.from(el.childNodes).filter( + (n) => n.nodeType === Node.TEXT_NODE && cleanText(n.textContent) + ); + if (loose.length) continue; + const firstText = textOf(kids[0]); + const labelish = /[::]\s*$/.test(firstText) || + ['DT', 'TH', 'LABEL', 'STRONG', 'B'].includes(kids[0].tagName); + if (!labelish) continue; + push(firstText, textOf(kids[1]), el, 'inline'); + emitted.add(el); + consumed.add(el); + } + + // 4. "Label: value" text in a leaf block. + const LINE_RE = /^([^::]{1,120})[::]\s*([\s\S]*)$/; + const candidates = deepAll(BLOCK_SEL).filter( + (el) => !isConsumed(el) && isLeaf(el) && !hasControl(el) && isVisible(el) + ); + const candSet = new Set(candidates); + for (const el of candidates) { + if (pairs.length >= MAX_PAIRS) break; + let up = parentOf(el); + let nested = false; + for (let d = 0; up && d < 6; d += 1) { + if (candSet.has(up)) { + nested = true; + break; + } + up = parentOf(up); + } + if (nested) continue; + const text = textOf(el); + const m = LINE_RE.exec(text); + if (!m) continue; + if (/^\/\//.test(m[2])) continue; // a URL, not a label + push(m[1], m[2], el, 'inline'); + } + return pairs; +} +""" + + # Browser error texts for a request the client itself cancelled (Chromium, # Firefox, WebKit), as opposed to a network or server failure. _CLIENT_ABORT_MARKERS = ("err_aborted", "ns_binding_aborted", "cancelled") @@ -1374,6 +1644,7 @@ def snapshot( } raw = self._page.evaluate(_SNAPSHOT_WALKER_JS, walker_cfg) + text_pairs = self._read_text_pairs() url_clean = _strip_url_to_origin_and_path(str(self._page.url or "")) title = str(raw.get("title") or "") @@ -1454,8 +1725,36 @@ def snapshot( active_modals=active_modals_list, banner_errors=tuple(str(b) for b in (raw.get("banner_errors") or ())), inflight_mutations=self.inflight_mutations, + text_pairs=text_pairs, ) + def _read_text_pairs(self) -> tuple[ObservedTextPair, ...]: + """Read label and value pairs shown as page text. + + A failure to read them leaves the tuple empty, so any read-back that + needs them ends ``not_checked``, never passed. + """ + try: + raw_pairs = self._page.evaluate( + _TEXT_PAIRS_JS, {"maxPairs": 500, "maxValueLength": 500} + ) + except Exception: + return () + pairs: list[ObservedTextPair] = [] + for item in raw_pairs or (): + source = str(item.get("source") or "inline") + if source not in ("dl", "table_row", "table_columns", "inline"): + source = "inline" + pairs.append( + ObservedTextPair( + label=str(item.get("label") or ""), + value=str(item.get("value") or ""), + section_text=str(item.get("section_text") or ""), + source=source, # type: ignore[arg-type] + ) + ) + return tuple(pairs) + def _resolve_live_locator(self, dom_selector: str) -> Any: if not dom_selector or not dom_selector.strip(): raise MissingAnchorError("Empty dom_selector") diff --git a/packages/flow/openadapt_flow/form_tx/surface.py b/packages/flow/openadapt_flow/form_tx/surface.py index 2704aee607..87dcf86e8c 100644 --- a/packages/flow/openadapt_flow/form_tx/surface.py +++ b/packages/flow/openadapt_flow/form_tx/surface.py @@ -16,6 +16,7 @@ FormSnapshot, ObservedControl, ObservedOption, + ObservedTextPair, UIProfileSpec, ) @@ -192,6 +193,38 @@ def match_anchor_in_snapshot( return None +def match_text_pair_in_snapshot( + anchor: FieldAnchorSpec, + snapshot: FormSnapshot, +) -> Optional[ObservedTextPair]: + """Resolve ``anchor`` to at most one label and value pair shown as page text. + + Only ``label_patterns`` (narrowed by ``section_patterns``) can match page + text: it has no name, id or selector. Raises ``AmbiguousAnchorError`` when + more than one pair matches, even if their values agree, so a summary that + shows a label twice is never read as proof. Returns ``None`` when the + anchor has no label patterns or nothing matches. + """ + if not anchor.label_patterns: + return None + matches = [ + pair + for pair in snapshot.text_pairs + if _matches_any_pattern(pair.label, anchor.label_patterns) + and ( + not anchor.section_patterns + or _matches_any_pattern(pair.section_text, anchor.section_patterns) + ) + ] + if len(matches) > 1: + labels = [f"{p.label} ({p.source})" for p in matches] + raise AmbiguousAnchorError( + f"Anchor {anchor.model_dump(exclude_none=True)} matched " + f"{len(matches)} labels in the page text: {labels}" + ) + return matches[0] if matches else None + + def compute_field_signature(ctrl: ObservedControl) -> str: """Stable value-free structural signature for an observed control.""" section = collapse_whitespace(ctrl.section_text).casefold() diff --git a/packages/flow/openadapt_flow/form_tx/types.py b/packages/flow/openadapt_flow/form_tx/types.py index cb98f88758..953689d84e 100644 --- a/packages/flow/openadapt_flow/form_tx/types.py +++ b/packages/flow/openadapt_flow/form_tx/types.py @@ -469,6 +469,23 @@ class ObservedModal(BaseModel): message_text: str = "" +class ObservedTextPair(BaseModel): + """A label and value shown as page text, not in a form control. + + Read-only summary pages often show stored values as a definition list, a + table or "Label: value" text. These pairs are kept apart from ``controls`` + so nothing ever treats them as fillable; only the read-back judge and + output extraction look at them. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + label: str + value: str = "" + section_text: str = "" + source: Literal["dl", "table_row", "table_columns", "inline"] = "inline" + + class FormSnapshot(BaseModel): """Complete structural snapshot of the current form surface.""" @@ -484,6 +501,7 @@ class FormSnapshot(BaseModel): active_modals: tuple[ObservedModal, ...] = () banner_errors: tuple[str, ...] = () inflight_mutations: int = 0 + text_pairs: tuple[ObservedTextPair, ...] = () class FormHaltItem(BaseModel): diff --git a/packages/flow/tests/test_form_tx_text_readback.py b/packages/flow/tests/test_form_tx_text_readback.py new file mode 100644 index 0000000000..a19b4c0818 --- /dev/null +++ b/packages/flow/tests/test_form_tx_text_readback.py @@ -0,0 +1,397 @@ +"""Read-back of quote summaries that show stored values as page text. + +Headless Chromium against pages served through ``context.route`` (no sockets). +A small form is filled and submitted; the response is a read-only summary +laid out as a definition list, a two-column table, a header-row table, +"Label: value" lines, or a definition list inside an open shadow root. The +server can show a different value, an empty value, or a label twice. +Zero application or vendor names. +""" + +from __future__ import annotations + +import html +from typing import Any, Callable +from urllib.parse import parse_qs + +import pytest + +sync_api = pytest.importorskip("playwright.sync_api") + +from cryptography.hazmat.primitives.asymmetric.ed25519 import ( # noqa: E402 + Ed25519PrivateKey, +) + +from openadapt_flow.form_tx.playwright_surface import PlaywrightFormSurface # noqa: E402 +from openadapt_flow.form_tx.reconciler import FormReconciler # noqa: E402 +from openadapt_flow.form_tx.surface import ( # noqa: E402 + AmbiguousAnchorError, + match_anchor_in_snapshot, + match_text_pair_in_snapshot, +) +from openadapt_flow.form_tx.types import ( # noqa: E402 + ControlKind, + DossierFact, + FieldAnchorSpec, + FieldBindingSpec, + FormPack, + FormSnapshot, + FormTxOutcome, + InputDossier, + ObservedTextPair, + OutputExtractionSpec, + ProvenanceKind, + ReadbackStatus, + SummaryCheckSpec, + UIProfileSpec, + WizardScreenSpec, +) + +ORIGIN = "http://portal.local" + +FORM_HTML = """Quote +

New quote

+

Roof material: see the inspection report

+
+ + + + +
""" + +ROOF_LABELS = {"metal": "Metal", "slate": "Slate", "": ""} + + +def _rows(stored: dict[str, str], mutation: str) -> list[tuple[str, str]]: + roof = ROOF_LABELS.get(stored.get("rm", ""), "") + if mutation == "differs": + roof = "Slate" if roof != "Slate" else "Metal" + if mutation == "empty": + roof = "" + rows = [ + ("First name", stored.get("fn", "")), + ("Roof material", roof), + ("Quote number", "Q-1001"), + ] + if mutation == "duplicate": + rows.append(("First name", stored.get("fn", ""))) + return rows + + +def _esc(s: str) -> str: + return html.escape(s, quote=True) + + +def _dl(rows: list[tuple[str, str]]) -> str: + items = "".join(f"
{_esc(k)}
{_esc(v)}
" for k, v in rows) + return f"
{items}
" + + +def _table_rows(rows: list[tuple[str, str]]) -> str: + body = "".join(f"{_esc(k)}{_esc(v)}" for k, v in rows) + return f"{body}
Your quote
" + + +def _table_columns(rows: list[tuple[str, str]]) -> str: + head = "".join(f"{_esc(k)}" for k, _ in rows) + cells = "".join(f"{_esc(v)}" for _, v in rows) + return f"{head}{cells}
" + + +def _inline(rows: list[tuple[str, str]]) -> str: + out = [] + for i, (k, v) in enumerate(rows): + if i % 3 == 0: + out.append(f"

{_esc(k)}: {_esc(v)}

") + elif i % 3 == 1: + out.append(f"

{_esc(k)}: {_esc(v)}

") + else: + out.append(f"
{_esc(k)}:{_esc(v)}
") + return f"
{''.join(out)}
" + + +def _shadow(rows: list[tuple[str, str]]) -> str: + inner = _dl(rows).replace("id='summary'", "") + return ( + "
" + ) + + +LAYOUTS: dict[str, Callable[[list[tuple[str, str]]], str]] = { + "dl": _dl, + "table_row": _table_rows, + "table_columns": _table_columns, + "inline": _inline, + "shadow": _shadow, +} + + +def _summary_page(layout: str, stored: dict[str, str], mutation: str) -> str: + body = LAYOUTS[layout](_rows(stored, mutation)) + return ( + "Quote saved" + f"

Quote saved

{body}" + ) + + +class _Portal: + def __init__(self, layout: str, mutation: str) -> None: + self.layout = layout + self.mutation = mutation + self.submissions: list[dict[str, str]] = [] + + def handle(self, route: Any) -> None: + req = route.request + path = req.url[len(ORIGIN) :].split("?")[0] + if path == "/submit" and req.method == "POST": + form = {k: v[0] for k, v in parse_qs(req.post_data or "").items() if v} + self.submissions.append(form) + page = _summary_page(self.layout, form, self.mutation) + route.fulfill(status=200, content_type="text/html", body=page) + return + route.fulfill(status=200, content_type="text/html", body=FORM_HTML) + + +def _profile() -> UIProfileSpec: + return UIProfileSpec( + profile_id="text-readback-test", + debounce_grace_ms=40, + settle_window_ms=60, + max_settle_ms=8000, + ) + + +def _binding(key: str, label: str, kind: ControlKind) -> FieldBindingSpec: + return FieldBindingSpec( + binding_id=key, + dossier_key=key, + anchor=FieldAnchorSpec(label_patterns=(f"^{label}$",)), + control_kind=kind, + ) + + +def _pack() -> FormPack: + bindings = ( + _binding("applicant.first_name", "First name", ControlKind.TEXT), + _binding("property.roof_material", "Roof material", ControlKind.SELECT), + ) + return FormPack( + commit_url_patterns=("/submit",), + pack_id="text-readback-test", + domain_schema="test.quote/v1", + ui_profile_id="text-readback-test", + bindings=bindings, + screens=( + WizardScreenSpec( + screen_id="form", + landmark_selector="#f", + is_commit_screen=True, + commit_button_anchor=FieldAnchorSpec( + label_patterns=("^Submit quote$",) + ), + ), + ), + summary_check=SummaryCheckSpec( + summary_landmark_selector="#summary", + field_readbacks=bindings, + outputs=( + OutputExtractionSpec( + output_key="quote.number", + anchor=FieldAnchorSpec(label_patterns=("^Quote number$",)), + ), + ), + ), + ) + + +def _dossier() -> InputDossier: + values = {"applicant.first_name": "Marisol", "property.roof_material": "Metal"} + return InputDossier( + dossier_id="d-1", + request_id="r-1", + facts={ + k: DossierFact( + key=k, + value=v, + provenance=ProvenanceKind.INTAKE_DOCUMENT, + source_id="intake", + ) + for k, v in values.items() + }, + ) + + +@pytest.fixture(scope="module") +def browser() -> Any: + with sync_api.sync_playwright() as pw: + try: + b = pw.chromium.launch(channel="chromium", headless=True) + except Exception: + b = pw.chromium.launch(headless=True) + try: + yield b + finally: + b.close() + + +def _run(browser: Any, layout: str, mutation: str) -> tuple[Any, _Portal]: + portal = _Portal(layout, mutation) + context = browser.new_context() + try: + context.route(f"{ORIGIN}/**", portal.handle) + page = context.new_page() + surface = PlaywrightFormSurface(page, _profile(), base_origin=ORIGIN) + surface.goto(f"{ORIGIN}/form") + reconciler = FormReconciler(surface, signing_key=Ed25519PrivateKey.generate()) + session = reconciler.create_session(_pack(), _dossier()) + result = reconciler.run_until_halt_or_done(session) + finally: + context.close() + return result, portal + + +def _verdicts(result: Any) -> dict[str, Any]: + assert result.summary_verdict is not None, result.what_happened + return {v.dossier_key: v for v in result.summary_verdict.field_verdicts} + + +@pytest.mark.parametrize("layout", sorted(LAYOUTS)) +def test_text_summary_that_matches_is_verified_with_a_receipt( + browser: Any, layout: str +) -> None: + result, portal = _run(browser, layout, "none") + assert portal.submissions == [{"fn": "Marisol", "rm": "metal"}] + assert result.outcome == FormTxOutcome.VERIFIED_DONE, result.what_happened + verdicts = _verdicts(result) + for key in ("applicant.first_name", "property.roof_material"): + assert verdicts[key].status == ReadbackStatus.PASSED + assert "page text" in verdicts[key].reason + assert result.receipt is not None + assert result.outputs["quote.number"] == "Q-1001" + + +@pytest.mark.parametrize("layout", sorted(LAYOUTS)) +def test_text_summary_showing_a_different_value_is_refuted( + browser: Any, layout: str +) -> None: + result, _ = _run(browser, layout, "differs") + assert result.outcome == FormTxOutcome.READBACK_REFUTED, result.what_happened + verdicts = _verdicts(result) + assert verdicts["property.roof_material"].status == ReadbackStatus.FAILED + assert verdicts["applicant.first_name"].status == ReadbackStatus.PASSED + assert result.receipt is None + + +@pytest.mark.parametrize("layout", ["dl", "table_row", "inline"]) +def test_text_summary_showing_an_empty_value_fails(browser: Any, layout: str) -> None: + result, _ = _run(browser, layout, "empty") + assert result.outcome == FormTxOutcome.READBACK_REFUTED, result.what_happened + verdict = _verdicts(result)["property.roof_material"] + assert verdict.status == ReadbackStatus.FAILED + assert "empty" in verdict.reason + assert result.receipt is None + + +@pytest.mark.parametrize( + "layout", ["dl", "table_row", "table_columns", "inline", "shadow"] +) +def test_label_shown_twice_is_not_checked(browser: Any, layout: str) -> None: + result, _ = _run(browser, layout, "duplicate") + assert result.outcome == FormTxOutcome.READBACK_INCOMPLETE, result.what_happened + verdicts = _verdicts(result) + assert verdicts["applicant.first_name"].status == ReadbackStatus.NOT_CHECKED + assert verdicts["property.roof_material"].status == ReadbackStatus.PASSED + assert result.receipt is None + + +HIDDEN_DD = """

Quote saved

+
Middle name
+
Last name
Smith
+
Suffix
Jr
+
City
Saltmarsh
+
""" + + +def test_hidden_dd_never_lets_a_later_value_join_earlier_labels( + browser: Any, +) -> None: + context = browser.new_context() + try: + context.route( + f"{ORIGIN}/**", + lambda route: route.fulfill( + status=200, content_type="text/html", body=HIDDEN_DD + ), + ) + page = context.new_page() + surface = PlaywrightFormSurface(page, _profile(), base_origin=ORIGIN) + surface.goto(f"{ORIGIN}/summary") + pairs = {p.label: p.value for p in surface.snapshot().text_pairs} + finally: + context.close() + # The hidden dd is an empty value, not "Smith"; the hidden dt's value is + # dropped rather than joined onto "Last name". + assert pairs.get("Middle name", "") == "" + assert pairs["Last name"] == "Smith" + assert "Suffix" not in pairs + assert pairs["City"] == "Saltmarsh" + snap_pairs = [p for p in pairs.values() if "Jr" in p] + assert not snap_pairs + + +def test_page_text_is_never_a_fill_target(browser: Any) -> None: + context = browser.new_context() + try: + context.route(f"{ORIGIN}/**", _Portal("dl", "none").handle) + page = context.new_page() + surface = PlaywrightFormSurface(page, _profile(), base_origin=ORIGIN) + surface.goto(f"{ORIGIN}/form") + snap = surface.snapshot() + finally: + context.close() + # The hint line is read as page text but never becomes a control. + assert any(p.label == "Roof material" for p in snap.text_pairs) + assert all(c.tag in ("input", "select", "button") for c in snap.controls) + anchor = FieldAnchorSpec(label_patterns=("^Roof material$",)) + ctrl = match_anchor_in_snapshot(anchor, snap) + assert ctrl is not None and ctrl.tag == "select" + + +def test_text_pair_matcher_rules() -> None: + snap = FormSnapshot( + url_origin_and_path=f"{ORIGIN}/summary", + text_pairs=( + ObservedTextPair(label="Roof year", value="2016", section_text="Home"), + ObservedTextPair(label="Roof year", value="2016", section_text="Prior"), + ObservedTextPair(label="City", value="Saltmarsh"), + ), + ) + # Name or selector anchors never match page text. + assert ( + match_text_pair_in_snapshot( + FieldAnchorSpec(name_or_id_patterns=("city",)), snap + ) + is None + ) + city = match_text_pair_in_snapshot( + FieldAnchorSpec(label_patterns=("^City$",)), snap + ) + assert city is not None and city.value == "Saltmarsh" + # A label shown twice is ambiguous even when the values agree. + with pytest.raises(AmbiguousAnchorError): + match_text_pair_in_snapshot( + FieldAnchorSpec(label_patterns=("^Roof year$",)), snap + ) + # A section narrows it to one. + home = match_text_pair_in_snapshot( + FieldAnchorSpec(label_patterns=("^Roof year$",), section_patterns=("^Home$",)), + snap, + ) + assert home is not None and home.section_text == "Home"