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:
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)}
") + elif i % 3 == 1: + out.append(f"{_esc(k)}: {_esc(v)}
") + else: + out.append(f"