diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0320-repeating-structures-add-another-traveller-a-tab.md b/capabilities/04-the-core-a-checked-entry-every-time/0320-repeating-structures-add-another-traveller-a-tab.md new file mode 100644 index 0000000000..719f70ef3e --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0320-repeating-structures-add-another-traveller-a-tab.md @@ -0,0 +1 @@ +| Repeating structures ("add another traveller", a table row, a line item) learned from one demonstration: instances are added to match the intake, filled in order and each read back by the container it was written into; a prefilled instance, more instances than items, or an add that did not add exactly one blank instance stops the run before writing | On main ([#2512](https://github.com/OpenAdaptAI/OpenAdapt/pull/2512)) | Synthetic: a web form, an EMR-like medication table, a SaaS invoice (headless Chromium) and a spreadsheet-like grid with no browser | `openadapt_flow.gui.repeating`, `packages/flow/tests/gui` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 5667eabb56..38afd686ec 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -27,6 +27,11 @@ an editable control is a form, never a confirmation. Each section is opened, filled and saved, and its completion is read from its card on the hub after the save, with the demonstrated number of writes. +- Repeating structures (`openadapt_flow.gui.repeating`). An "add another" + group is learned from a demonstration. A run adds instances until the count + matches the intake, fills them in order and reads each one back by the + container it was written into. It never deletes an instance and stops on a + prefilled one. ## v4.0.0 (2026-11-24) diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index 38d8b24883..366c57adea 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -300,6 +300,9 @@ Done: - [x] `verify_draft.judge_case` (C3 C5): admission cases settle on the verdict kernel via allow-listed outcome maps; untestable, error, or unknown codes never hold. +- [x] `gui.repeating.judge_instances` (C1 C2 C5): new. Item-by-slot + obligations from the intake, checked in the instance each item was written + into; an instance nobody planned is refuted. Next, most bug-prone first: diff --git a/packages/flow/openadapt_flow/gui/__init__.py b/packages/flow/openadapt_flow/gui/__init__.py index 64bcd04108..c0621df80f 100644 --- a/packages/flow/openadapt_flow/gui/__init__.py +++ b/packages/flow/openadapt_flow/gui/__init__.py @@ -12,6 +12,8 @@ is ticked only on a person's grant, never through a fact. - :mod:`openadapt_flow.gui.hub`: a hub page whose sections open in dialogs, each section's completion read back from the hub. +- :mod:`openadapt_flow.gui.repeating`: "add another" groups, added to match + the intake and checked instance by instance. Per-app facts (which control, which words, how many writes) are pack data, learned from a demonstration or declared by the pack author. The engine holds diff --git a/packages/flow/openadapt_flow/gui/repeating.py b/packages/flow/openadapt_flow/gui/repeating.py new file mode 100644 index 0000000000..f3a50cb725 --- /dev/null +++ b/packages/flow/openadapt_flow/gui/repeating.py @@ -0,0 +1,599 @@ +"""Repeating structures: "add another traveller", "add a row", "add a line item". + +A form that asks for a list shows one instance of a block of fields (a +traveller, a medication row, an invoice line) and a control that adds +another. A run whose intake has three items must add instances until there +are three, fill each one with its own item, and check each one. Packs used to +work around this with a stop or a popup that cannot exist. This module +handles it once: + +- :func:`learn_repeats` finds the shape in a demonstration. It looks for a + click after which a new block of editable controls appeared inside a new + container of one kind (a fieldset, a row, a list item). When the block + repeats the fields of an instance already on the screen, that is the group + (a list that starts empty is learned from its second add). + It yields a :class:`RepeatSpec`: the add control, the instance's container + kind and its field slots. :func:`map_slots` proposes which item key feeds + each slot, from the values the demonstration typed. +- :func:`find_instances` reads the instances on a screen: each container of + the declared kind that holds exactly one control per slot, in document + order. A slot control outside any instance, or an instance with a missing + or doubled slot, makes the read unusable. +- :func:`fill_instances` fixes the obligations from the intake first (every + item, every slot). It then adds instances until the count matches, fills + them in document order and reads them back. It stops before writing when: + - an instance already holds data the run did not enter; + - the screen already has more instances than the intake (the run never + deletes one); + - the add control is missing or ambiguous, or one click did not add exactly + one blank instance; + - adding wrote anything; + - an item lacks a slot's key. +- :func:`judge_instances` is a verdict site. It settles item-by-slot + obligations against a fresh read, keyed by the instance each item was + written into (its container handle, bound when it was filled, never a + position guess). A wrong value is refuted, an instance nobody planned is + unexpected and refuted, and a missing instance is missing. + +:func:`location_rows` exports the per-instance checks as plain rows shaped +like the effect-location record (``openadapt.effect-location/v1``), so the +shared verifier layer can take them over without this module importing it. +""" + +from __future__ import annotations + +from collections import Counter +from dataclasses import dataclass +from typing import Any, Mapping, Optional, Sequence + +from openadapt_flow.gui.model import ( + Actuator, + AmbiguousControl, + Container, + Control, + ControlSpec, + DemoStep, + MissingControl, + Screen, + match_one, + norm, + spec_for, +) +from openadapt_flow.verdict import ( + Obligations, + Observed, + Result, + Settlement, + Status, + Subject, + settle, +) +from openadapt_flow.verdict_sites import verdict_site + +__all__ = [ + "Instance", + "InstanceRead", + "RepeatSpec", + "RepeatVerdict", + "Slot", + "FillOutcome", + "fill_instances", + "find_instances", + "judge_instances", + "learn_repeats", + "location_rows", + "map_slots", + "planned_rows", + "seen_rows", +] + +#: Container kinds an instance can be. +INSTANCE_KINDS = frozenset({"group", "region", "row", "item"}) + + +@dataclass(frozen=True) +class Slot: + """One field of an instance, and the item key that feeds it ("" until + the pack author or :func:`map_slots` sets it).""" + + role: str + name: str + item_key: str = "" + + +@dataclass(frozen=True) +class RepeatSpec: + """Pack data for one repeating group. + + ``within`` names containers the whole group sits in, to tell two groups + with the same fields apart. ``add_writes`` is how many writes one add made + in the demonstration (usually 0).""" + + group_id: str + add: ControlSpec + instance_kind: str + slots: tuple[Slot, ...] + within: tuple[str, ...] = () + add_writes: int = 0 + max_instances: int = 50 + + def __post_init__(self) -> None: + if self.instance_kind not in INSTANCE_KINDS: + raise ValueError(f"unknown instance kind {self.instance_kind!r}") + if not self.slots: + raise ValueError("a repeating group has at least one field") + keys = [(s.role, norm(s.name)) for s in self.slots] + if len(keys) != len(set(keys)): + raise ValueError("two slots have the same role and name") + + +# -- reading instances ---------------------------------------------------------- + + +@dataclass(frozen=True) +class Instance: + handle: str + name: str + #: The control for each slot, in slot order. + controls: tuple[Control, ...] + + def values(self) -> tuple[Optional[str], ...]: + return tuple(_shown(c) for c in self.controls) + + def blank(self) -> bool: + """Every slot reads empty or unticked. A box whose state was not read + is not blank.""" + + return all(v is not None and (not v or v == "false") for v in self.values()) + + +@dataclass(frozen=True) +class InstanceRead: + instances: tuple[Instance, ...] + problem: str = "" + + @property + def usable(self) -> bool: + return not self.problem + + +def _shown(ctrl: Control) -> Optional[str]: + """What a slot shows; None for a box whose state was not read.""" + + if ctrl.role in ("checkbox", "switch", "radio"): + if ctrl.checked is None: + return None + return "true" if ctrl.checked else "false" + return ctrl.value.strip() + + +def _slot_of(spec: RepeatSpec, ctrl: Control) -> Optional[int]: + for n, slot in enumerate(spec.slots): + if ctrl.role == slot.role and norm(ctrl.name) == norm(slot.name): + return n + return None + + +def _in_scope(spec: RepeatSpec, ctrl: Control) -> bool: + names = ctrl.container_names() + at = 0 + for name in names: + if at < len(spec.within) and name == norm(spec.within[at]): + at += 1 + return at == len(spec.within) + + +def _instance_box(spec: RepeatSpec, ctrl: Control) -> Optional[Container]: + boxes = [c for c in ctrl.containers if c.kind == spec.instance_kind] + return boxes[-1] if boxes else None + + +def find_instances(screen: Screen, spec: RepeatSpec) -> InstanceRead: + """The group's instances on ``screen``, in document order.""" + + order: list[str] = [] + by_box: dict[str, dict[int, list[Control]]] = {} + names: dict[str, str] = {} + for ctrl in screen.controls: + slot = _slot_of(spec, ctrl) + if slot is None or not _in_scope(spec, ctrl) or ctrl.dialog: + continue + box = _instance_box(spec, ctrl) + if box is None: + return InstanceRead((), f"{ctrl.name!r} sits in no {spec.instance_kind}") + if box.handle not in by_box: + order.append(box.handle) + by_box[box.handle] = {} + names[box.handle] = box.name + by_box[box.handle].setdefault(slot, []).append(ctrl) + out = [] + for handle in order: + slots = by_box[handle] + if sorted(slots) != list(range(len(spec.slots))) or any( + len(v) != 1 for v in slots.values() + ): + return InstanceRead( + (), + f"instance {names[handle] or handle!r} does not hold each field once", + ) + out.append( + Instance( + handle, + names[handle], + tuple(slots[n][0] for n in range(len(spec.slots))), + ) + ) + if not screen.complete: + return InstanceRead(tuple(out), "the screen was read in part") + return InstanceRead(tuple(out)) + + +# -- the verdict ------------------------------------------------------------------ + + +@dataclass(frozen=True) +class RepeatVerdict: + settlement: Settlement + status: Status + + +@verdict_site("gui.repeating.judge", classes="C1 C2 C5") +def judge_instances( + planned: Sequence[Mapping[str, Any]], + bound: Mapping[str, str], + seen: Sequence[Mapping[str, Any]], + *, + run_id: str, + complete: bool = True, +) -> RepeatVerdict: + """Settle item-by-slot obligations against a fresh read. + + ``planned`` rows carry ``item`` (the item's index as text), ``slot`` and + ``expected``, one per item and slot, fixed from the intake before any + instance was added. ``bound`` maps each item to the container handle it + was written into. ``seen`` rows carry ``handle``, ``slot``, ``value`` and + ``run_id``, one per slot of every instance on the screen. A value must + equal the expected text exactly. An instance no item was bound to is + refuted and unexpected; a value that is not text is not checked.""" + + obligations = Obligations.fix( + ( + Subject( + run_id=run_id, + surface="gui", + key=str(p.get("item")), + field=str(p.get("slot")), + ) + for p in planned + ), + source="intake items", + ) + expected = { + (str(p.get("item")), str(p.get("slot"))): p.get("expected") for p in planned + } + item_of = {str(h): str(i) for i, h in bound.items()} + if len(item_of) != len(bound): + item_of = {} # two items bound to one instance: nothing can settle + results = [] + for row in seen: + handle, slot = str(row.get("handle")), str(row.get("slot")) + item = item_of.get(handle) + subject = Subject( + run_id=str(row.get("run_id") or ""), + surface="gui", + key=item if item is not None else f"unplanned:{handle}", + field=slot, + ) + obs = Observed(dict(row), complete=complete is True) + value = row.get("value") + want = expected.get((item, slot)) if item is not None else None + if item is None: + results.append( + Result.refuted(subject, obs, "an instance no item was written into") + ) + elif not isinstance(value, str) or not isinstance(want, str): + results.append( + Result.not_checked(subject, "the value was not read as text") + ) + elif value != want: + results.append( + Result.refuted(subject, obs, f"shows {value!r}, the item has {want!r}") + ) + elif complete is not True: + results.append(Result.not_checked(subject, "the screen was read in part")) + else: + results.append(Result.held(subject, obs, "as entered")) + settlement = settle(obligations, results) + status = settlement.label(precedence=(Status.REFUTED, Status.NOT_CHECKED)) + seen_wrong = [r for r in results if r.status is Status.REFUTED] + if status is not Status.HELD and seen_wrong: + status = Status.REFUTED + return RepeatVerdict(settlement, status) + + +def _item_text(item: Mapping[str, Any], slot: Slot) -> Optional[str]: + if slot.item_key not in item: + return None + value = item[slot.item_key] + if slot.role in ("checkbox", "switch"): + if not isinstance(value, bool): + return None + return "true" if value else "false" + if value is None or isinstance(value, bool): + return None + return str(value).strip() + + +def planned_rows( + spec: RepeatSpec, items: Sequence[Mapping[str, Any]] +) -> list[dict[str, Any]]: + return [ + {"item": str(i), "slot": slot.name, "expected": _item_text(item, slot)} + for i, item in enumerate(items) + for slot in spec.slots + ] + + +def seen_rows( + read: InstanceRead, spec: RepeatSpec, run_id: str +) -> list[dict[str, Any]]: + return [ + {"handle": inst.handle, "slot": slot.name, "value": value, "run_id": run_id} + for inst in read.instances + for slot, value in zip(spec.slots, inst.values()) + ] + + +# -- filling ---------------------------------------------------------------------- + + +@dataclass(frozen=True) +class FillOutcome: + group_id: str + status: Status + reason: str + #: Item index (as text) to the container handle it was written into. + bound: Mapping[str, str] + added: int = 0 + wrote: bool = False + verdict: Optional[RepeatVerdict] = None + + @property + def held(self) -> bool: + return self.status is Status.HELD + + +def fill_instances( + actuator: Actuator, + spec: RepeatSpec, + items: Sequence[Mapping[str, Any]], + *, + run_id: str = "", +) -> FillOutcome: + """Add, fill and check one instance per item (see the module doc).""" + + gid = spec.group_id + + def stop(reason: str, **kw: Any) -> FillOutcome: + return FillOutcome(gid, Status.NOT_CHECKED, reason, kw.pop("bound", {}), **kw) + + planned = planned_rows(spec, items) + missing = [p for p in planned if p["expected"] is None] + if missing: + return stop( + f"item {missing[0]['item']} has no usable value for {missing[0]['slot']!r}" + ) + if len(items) > spec.max_instances: + return stop(f"{len(items)} items is more than the group's {spec.max_instances}") + read = find_instances(actuator.observe(), spec) + if not read.usable: + return stop(read.problem) + if any(not inst.blank() for inst in read.instances): + return stop("an instance already holds data the run did not enter") + if len(read.instances) > len(items): + return stop( + f"the screen shows {len(read.instances)} instances for {len(items)} items; " + "the run never deletes one" + ) + added = 0 + while len(read.instances) < len(items): + try: + add = match_one(spec.add, actuator.observe()) + except (MissingControl, AmbiguousControl) as exc: + return stop(str(exc), added=added) + w0 = actuator.write_count() + actuator.click(add.handle) + w1 = actuator.write_count() + added += 1 + if w0 is None or w1 is None: + return stop( + "this backend cannot count writes, so an add cannot be shown safe", + added=added, + ) + if w1 - w0 != spec.add_writes: + return stop( + f"adding an instance wrote {w1 - w0} times; the demo wrote {spec.add_writes}", + added=added, + wrote=True, + ) + after = find_instances(actuator.observe(), spec) + if not after.usable: + return stop(after.problem, added=added) + old = {i.handle for i in read.instances} + new = [i for i in after.instances if i.handle not in old] + if len(after.instances) != len(read.instances) + 1 or len(new) != 1: + return stop( + f"one add went from {len(read.instances)} to {len(after.instances)} instances", + added=added, + ) + if not new[0].blank(): + return stop("the added instance is not blank", added=added) + read = after + bound = {str(i): inst.handle for i, inst in enumerate(read.instances)} + for i, inst in enumerate(read.instances): + for slot, ctrl in zip(spec.slots, inst.controls): + value = _item_text(items[i], slot) + assert value is not None # checked above + if slot.role in ("checkbox", "switch"): + actuator.set_checked(ctrl.handle, value == "true") + else: + actuator.set_text(ctrl.handle, value) + final = find_instances(actuator.observe(), spec) + if not final.usable: + return FillOutcome(gid, Status.NOT_CHECKED, final.problem, bound, added, True) + verdict = judge_instances( + planned, bound, seen_rows(final, spec, run_id), run_id=run_id, complete=True + ) + reason = ( + "every instance shows its item" + if verdict.status is Status.HELD + else ("an instance does not show its item") + ) + return FillOutcome(gid, verdict.status, reason, bound, added, True, verdict) + + +def location_rows( + spec: RepeatSpec, items: Sequence[Mapping[str, Any]], bound: Mapping[str, str] +) -> list[dict[str, Any]]: + """The per-instance checks as rows shaped like effect locations: one per + item and slot, found by the instance's container and the slot's name, + expected once, read on the same screen.""" + + return [ + { + "id": f"{spec.group_id}:{i}:{slot.name}", + "keys": [f"{spec.group_id}[{i}].{slot.item_key}"], + "start": "same_screen", + "locator": {"kind": "region", "value": bound[str(i)], "column": slot.name}, + "expected": { + f"{spec.group_id}[{i}].{slot.item_key}": _item_text(item, slot) + }, + "expected_count": 1, + } + for i, item in enumerate(items) + if str(i) in bound + for slot in spec.slots + ] + + +# -- from a demonstration ---------------------------------------------------------- + + +def _common_box(ctrls: Sequence[Control]) -> Optional[Container]: + """The innermost container every control shares.""" + + if not ctrls: + return None + shared = list(ctrls[0].containers) + for ctrl in ctrls[1:]: + handles = [c.handle for c in ctrl.containers] + shared = [c for c in shared if c.handle in handles] + return shared[-1] if shared else None + + +def learn_repeats(demo: Sequence[DemoStep]) -> tuple[RepeatSpec, ...]: + """Each click that added a block of editable controls in a new container, + where the block's fields (role and name) match the fields of a container of + the same kind already on the screen. A list that starts empty is learned + from its second add, when the first added block is the sibling.""" + + out: list[RepeatSpec] = [] + for index, step in enumerate(demo): + if step.action != "click" or not step.target.activatable: + continue + before = {c.handle for c in step.before.controls} + new = [c for c in step.after.controls if c.editable and c.handle not in before] + if not new: + continue + box = _common_box(new) + if box is None or box.kind not in INSTANCE_KINDS: + continue + if box.handle in {b.handle for c in step.before.controls for b in c.containers}: + continue # the controls appeared inside an existing container + fields = Counter((c.role, norm(c.name)) for c in new) + if any(n != 1 for n in fields.values()): + continue + siblings: dict[str, Counter[tuple[str, str]]] = {} + for ctrl in step.before.controls: + if not ctrl.editable: + continue + kin = [b for b in ctrl.containers if b.kind == box.kind] + if kin: + siblings.setdefault(kin[-1].handle, Counter())[ + (ctrl.role, norm(ctrl.name)) + ] += 1 + if not any(sig == fields for sig in siblings.values()): + continue + add = spec_for(step.target, step.before) + if add is None or step.writes is None: + continue + slots = tuple(Slot(c.role, c.name) for c in new) + out.append( + RepeatSpec( + group_id=f"group-{index}", + add=add, + instance_kind=box.kind, + slots=slots, + add_writes=step.writes, + ) + ) + seen: set[tuple[Any, ...]] = set() + unique = [] + for spec in out: + key = (spec.add, spec.instance_kind, spec.slots) + if key not in seen: + seen.add(key) + unique.append(spec) + return tuple(unique) + + +def map_slots( + spec: RepeatSpec, + demo: Sequence[DemoStep], + items: Sequence[Mapping[str, Any]], +) -> tuple[RepeatSpec, dict[str, str]]: + """Propose the item key for each slot from the demonstration's typed + values: a slot maps to key ``k`` when, for every instance the demo filled, + the value typed there equals ``items[i][k]`` and no other key fits. Slots + that do not map are returned with a reason. A proposal, for the author.""" + + final = demo[-1].after if demo else Screen() + read = find_instances(final, spec) + problems: dict[str, str] = {} + if not read.usable or len(read.instances) != len(items): + return spec, { + s.name: "the demo's instances do not line up with its items" + for s in spec.slots + } + typed: dict[str, str] = {} + for step in demo: + if step.action == "type": + typed[step.target.handle] = step.value.strip() + slots = [] + for n, slot in enumerate(spec.slots): + keys: Optional[set[str]] = None + for i, inst in enumerate(read.instances): + value = typed.get(inst.controls[n].handle) + fit = { + k + for k, v in items[i].items() + if value is not None and str(v).strip() == value + } + keys = fit if keys is None else keys & fit + if keys and len(keys) == 1: + slots.append(Slot(slot.role, slot.name, next(iter(keys)))) + else: + slots.append(slot) + problems[slot.name] = "no single item key matches what the demo typed" + return ( + RepeatSpec( + spec.group_id, + spec.add, + spec.instance_kind, + tuple(slots), + spec.within, + spec.add_writes, + spec.max_instances, + ), + problems, + ) diff --git a/packages/flow/tests/failopen/sites/gui_repeating.py b/packages/flow/tests/failopen/sites/gui_repeating.py new file mode 100644 index 0000000000..540ea37645 --- /dev/null +++ b/packages/flow/tests/failopen/sites/gui_repeating.py @@ -0,0 +1,145 @@ +"""gui.repeating.judge (C1 C2 C5): every intake item shows in the instance it +was written into, slot by slot. + +The obligations are item-by-slot, fixed from the intake before any instance +was added. A value must equal the item's text exactly. An instance no item +was written into is refuted and unexpected; a missing instance is missing; an +empty intake never passes. +""" + +from __future__ import annotations + +import copy +from typing import Any + +from openadapt_flow.gui.repeating import judge_instances +from openadapt_flow.verdict import Status +from tests.failopen.harness import Seed, SiteSpec, index, key, register + +RUN = "run-1" + + +def _good() -> dict[str, Any]: + return { + "planned": [ + {"item": "0", "slot": "Full name", "expected": "Ann Example"}, + {"item": "0", "slot": "Date of birth", "expected": "1990-01-02"}, + {"item": "1", "slot": "Full name", "expected": "Ben Example"}, + {"item": "1", "slot": "Date of birth", "expected": "1988-03-04"}, + ], + "bound": {"0": "#p1", "1": "#p2"}, + "seen": [ + { + "handle": "#p1", + "slot": "Full name", + "value": "Ann Example", + "run_id": RUN, + }, + { + "handle": "#p1", + "slot": "Date of birth", + "value": "1990-01-02", + "run_id": RUN, + }, + { + "handle": "#p2", + "slot": "Full name", + "value": "Ben Example", + "run_id": RUN, + }, + { + "handle": "#p2", + "slot": "Date of birth", + "value": "1988-03-04", + "run_id": RUN, + }, + ], + "complete": True, + } + + +def _run(ev: dict[str, Any]) -> Any: + return judge_instances( + ev["planned"], ev["bound"], ev["seen"], run_id=RUN, complete=ev.get("complete") + ) + + +def _bad(item: dict[str, Any]) -> dict[str, Any]: + out = copy.deepcopy(item) + out["value"] = str(out.get("value")) + " (other)" + return out + + +def _inflate(ev: dict[str, Any], n: int) -> dict[str, Any]: + planned = [{"item": str(i), "slot": "v", "expected": f"x{i}"} for i in range(n)] + bound = {str(i): f"#r{i}" for i in range(n)} + seen = [ + { + "handle": f"#r{i}", + "slot": "v", + "value": f"x{i}" if i != n - 1 else "no", + "run_id": RUN, + } + for i in range(n) + ] + return {**ev, "planned": planned, "bound": bound, "seen": seen} + + +def _swapped() -> dict[str, Any]: + ev = _good() + ev["bound"] = {"0": "#p2", "1": "#p1"} + return ev + + +register( + SiteSpec( + id="gui.repeating.judge", + classes="C1 C2 C5", + target="openadapt_flow.gui.repeating:judge_instances", + run=_run, + is_pass=lambda out: out.status is Status.HELD, + level=lambda out: out.status, + seeds=lambda: [ + Seed(_good(), True), + Seed(_swapped(), False, "items in each other's instances"), + Seed( + {**_good(), "seen": _good()["seen"][:2]}, False, "an item never added" + ), + Seed( + { + **_good(), + "seen": _good()["seen"] + + [ + { + "handle": "#p3", + "slot": "Full name", + "value": "", + "run_id": RUN, + } + ], + }, + False, + "an instance nobody planned", + ), + Seed( + {**_good(), "bound": {"0": "#p1", "1": "#p1"}}, + False, + "two items, one instance", + ), + ], + items=key("seen"), + plan=key("planned"), + bad_item=_bad, + inflate=_inflate, + fields=index(key("seen"), 0), + values=( + key("value", "seen", 0), + key("handle", "seen", 0), + key("slot", "seen", 0), + key("expected", "planned", 0), + key("0", "bound"), + ), + subject=key("run_id", "seen", 0), + partial=lambda ev: [("complete", {**ev, "complete": False})], + ) +) diff --git a/packages/flow/tests/gui/test_gui_repeating.py b/packages/flow/tests/gui/test_gui_repeating.py new file mode 100644 index 0000000000..0c6587cbcc --- /dev/null +++ b/packages/flow/tests/gui/test_gui_repeating.py @@ -0,0 +1,421 @@ +"""Repeating structures on four kinds of app. + +- a web form (group booking) with "Add another attendee"; +- an EMR-like medication table that starts empty, with unlabeled rows; +- a spreadsheet-like grid with no browser ("Insert row"); +- a SaaS invoice whose "Add line item" control is a link. + +Each group is learned from one demonstration, then filled for an intake with +a different number of items. Every instance is read back against its own item. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from openadapt_flow.gui.dom import PageActuator +from openadapt_flow.gui.model import ControlSpec, Recorder, match_all, match_one +from openadapt_flow.gui.repeating import ( + RepeatSpec, + Slot, + fill_instances, + find_instances, + judge_instances, + learn_repeats, + location_rows, + map_slots, +) +from openadapt_flow.verdict import Status +from tests.gui import _apps +from tests.gui._grid import GridApp, Sheet + +# -- web form: group booking ------------------------------------------------------- + + +def booking( + *, + start: int = 1, + prefill: str = "", + add: str = "one", + add_posts: bool = False, + upper: bool = False, + auto_blank: bool = False, +) -> _apps.App: + adds = {"one": "addOne();", "none": "", "two": "addOne();addOne();"}[add] + post = "fetch('/draft',{method:'POST',body:'{}'});" if add_posts else "" + blur = "this.value=this.value.toUpperCase();" if upper else "" + auto = "autoAdd(this);" if auto_blank else "" + + def form(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Book", + f"""

Group booking

+
+ +
+
""", + ) + + def book(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + app.state["booking"] = {k: v[0] for k, v in f.items()} + return 200, _apps.page("Booked", "

Booked

") + + return _apps.App( + "book.test", + { + ("GET", "/book"): form, + ("POST", "/book"): book, + ("POST", "/draft"): lambda a, p, m, f: (200, "{}"), + }, + ) + + +DEMO_PEOPLE = [ + {"name": "Ann Example", "dob": "1990-01-02"}, + {"name": "Ben Example", "dob": "1988-03-04"}, +] +PEOPLE = [ + {"name": "Cal Sample", "dob": "1975-05-06"}, + {"name": "Dot Sample", "dob": "1979-07-08"}, + {"name": "Eve Sample", "dob": "2001-09-10"}, +] + + +def _record_booking(page: Any) -> tuple[RepeatSpec, list]: + app = booking() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/book") + rec = Recorder(act) + + def fill(n: int, person: dict) -> None: + s = act.observe() + names = match_all(ControlSpec("textbox", "Full name"), s) + dobs = match_all(ControlSpec("textbox", "Date of birth"), s) + rec.set_text(names[n].handle, person["name"]) + rec.set_text(dobs[n].handle, person["dob"]) + + fill(0, DEMO_PEOPLE[0]) + rec.click( + match_one( + ControlSpec("button", "Add another attendee"), act.observe() + ).handle + ) + fill(1, DEMO_PEOPLE[1]) + (spec,) = learn_repeats(rec.steps) + mapped, problems = map_slots(spec, rec.steps, DEMO_PEOPLE) + assert not problems, problems + return mapped, rec.steps + + +def test_web_form_group_is_learned_with_its_fields_and_item_keys(page) -> None: + spec, _ = _record_booking(page) + assert spec.add == ControlSpec("button", "Add another attendee", dialog=False) + assert spec.instance_kind == "group" + assert spec.slots == ( + Slot("textbox", "Full name", "name"), + Slot("textbox", "Date of birth", "dob"), + ) + + +def test_web_form_adds_fills_and_checks_one_instance_per_item(page) -> None: + spec, _ = _record_booking(page) + app = booking() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/book") + out = fill_instances(act, spec, PEOPLE, run_id="r1") + assert out.held, out.reason + assert out.added == 2 + act.click(match_one(ControlSpec("button", "Book"), act.observe()).handle) + assert app.state["booking"] == { + "name1": "Cal Sample", + "dob1": "1975-05-06", + "name2": "Dot Sample", + "dob2": "1979-07-08", + "name3": "Eve Sample", + "dob3": "2001-09-10", + } + + +@pytest.mark.parametrize( + ("variant", "items", "reason", "status"), + [ + ({"add": "none"}, PEOPLE, "from 1 to 1 instances", Status.NOT_CHECKED), + ({"add": "two"}, PEOPLE, "from 1 to 3 instances", Status.NOT_CHECKED), + ({"prefill": "Zed Other"}, PEOPLE, "already holds data", Status.NOT_CHECKED), + ({"add_posts": True}, PEOPLE, "wrote 1 times", Status.NOT_CHECKED), + ({"start": 3}, PEOPLE[:2], "never deletes", Status.NOT_CHECKED), + ({"upper": True}, PEOPLE, "does not show its item", Status.REFUTED), + ({"auto_blank": True}, PEOPLE, "does not show its item", Status.REFUTED), + ], +) +def test_web_form_group_that_does_not_line_up_stops( + page, variant, items, reason, status +) -> None: + spec, _ = _record_booking(page) + app = booking(**variant) + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/book") + out = fill_instances(act, spec, items, run_id="r2") + assert out.status is status and reason in out.reason, out.reason + if status is Status.NOT_CHECKED: + assert not out.wrote or "wrote" in out.reason + + +def test_an_item_missing_a_key_stops_before_anything_is_added(page) -> None: + spec, _ = _record_booking(page) + app = booking() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/book") + out = fill_instances(act, spec, [PEOPLE[0], {"name": "No Dob"}]) + assert ( + out.status is Status.NOT_CHECKED and out.added == 0 and "dob" not in out.bound + ) + + +# -- EMR-like medication table: starts empty, rows have no labels -------------------- + + +def meds(*, sort_after: bool = False) -> _apps.App: + sorter = ( + "document.getElementById('tb').addEventListener('change',()=>{" + "const rows=[...document.querySelectorAll('#tb tr')];" + "if(rows.every(r=>r.querySelector('input').value)){" + "const vals=rows.map(r=>[...r.querySelectorAll('input')].map(i=>i.value)).sort();" + "rows.forEach((r,k)=>r.querySelectorAll('input').forEach((i,j)=>i.value=vals[k][j]));}});" + if sort_after + else "" + ) + + def chart(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Medications", + f"""

Chart: Test Patient D

+ +
DrugDose
+ +
""", + ) + + return _apps.App("chart.test", {("GET", "/meds"): chart}) + + +DEMO_MEDS = [{"drug": "Drug A", "dose": "10 mg"}, {"drug": "Drug B", "dose": "5 mg"}] +MEDS = [ + {"drug": "Drug Z", "dose": "1 mg"}, + {"drug": "Drug Y", "dose": "2 mg"}, + {"drug": "Drug X", "dose": "3 mg"}, +] + + +def _record_meds(page: Any) -> RepeatSpec: + app = meds() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/meds") + rec = Recorder(act) + for n, med in enumerate(DEMO_MEDS): + rec.click( + match_one(ControlSpec("button", "Add medication"), act.observe()).handle + ) + s = act.observe() + rec.set_text( + match_all(ControlSpec("textbox", "Drug"), s)[n].handle, med["drug"] + ) + rec.set_text( + match_all(ControlSpec("textbox", "Dose"), s)[n].handle, med["dose"] + ) + (spec,) = learn_repeats(rec.steps) + mapped, problems = map_slots(spec, rec.steps, DEMO_MEDS) + assert not problems + return mapped + + +def test_emr_table_that_starts_empty_is_learned_from_the_second_add(page) -> None: + spec = _record_meds(page) + assert spec.instance_kind == "row" + assert [(s.name, s.item_key) for s in spec.slots] == [ + ("Drug", "drug"), + ("Dose", "dose"), + ] + + +def test_emr_rows_are_checked_by_the_row_each_item_was_written_into(page) -> None: + spec = _record_meds(page) + app = meds() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/meds") + out = fill_instances(act, spec, MEDS, run_id="r3") + assert out.held, out.reason + assert len(set(out.bound.values())) == 3 + # The app sorts the rows once all are filled: each row now shows another + # item's values, so the check by row refutes even though every value is + # somewhere on the screen. + app = meds(sort_after=True) + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/meds") + out = fill_instances(act, spec, MEDS, run_id="r4") + assert out.status is Status.REFUTED + + +# -- spreadsheet-like grid ----------------------------------------------------------- + + +def _ledger(rows: list[list[str]] | None = None) -> GridApp: + return GridApp( + [Sheet("Expenses", ("Item", "Amount"), rows if rows is not None else [])] + ) + + +def _record_grid() -> RepeatSpec: + grid = _ledger() + rec = Recorder(grid) + demo = [{"item": "Rent", "amount": "1200"}, {"item": "Power", "amount": "90"}] + for r, row in enumerate(demo): + rec.click("tool:insert") + rec.set_text(f"cell:Expenses:{r}:0", row["item"]) + rec.set_text(f"cell:Expenses:{r}:1", row["amount"]) + (spec,) = learn_repeats(rec.steps) + mapped, problems = map_slots(spec, rec.steps, demo) + assert not problems + return mapped + + +def test_grid_rows_are_learned_and_filled_without_a_browser() -> None: + spec = _record_grid() + assert spec.add.name == "Insert row" and spec.instance_kind == "row" + grid = _ledger() + items = [ + {"item": "Rent", "amount": "1250"}, + {"item": "Water", "amount": "40"}, + {"item": "Net", "amount": "60"}, + ] + out = fill_instances(grid, spec, items, run_id="g1") + assert out.held, out.reason + assert grid.sheets[0].rows == [["Rent", "1250"], ["Water", "40"], ["Net", "60"]] + assert location_rows(spec, items, out.bound)[0] == { + "id": f"{spec.group_id}:0:Item", + "keys": [f"{spec.group_id}[0].item"], + "start": "same_screen", + "locator": {"kind": "region", "value": out.bound["0"], "column": "Item"}, + "expected": {f"{spec.group_id}[0].item": "Rent"}, + "expected_count": 1, + } + + +def test_grid_rows_already_holding_data_stop_and_nothing_is_added() -> None: + spec = _record_grid() + grid = _ledger([["Old", "5"]]) + out = fill_instances( + grid, spec, [{"item": "Rent", "amount": "1"}, {"item": "Tax", "amount": "2"}] + ) + assert out.status is Status.NOT_CHECKED and out.added == 0 + assert grid.sheets[0].rows == [["Old", "5"]] + + +# -- SaaS invoice: the add control is a link ------------------------------------------ + + +def invoice() -> _apps.App: + def page_(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Invoice", + """

New invoice

+Add line item +
""", + ) + + return _apps.App("app.test", {("GET", "/invoice"): page_}) + + +def test_saas_invoice_fills_lines_added_by_a_link(page) -> None: + spec = RepeatSpec( + "lines", + ControlSpec("link", "Add line item"), + "item", + (Slot("textbox", "Description", "desc"), Slot("textbox", "Amount", "amount")), + ) + app = invoice() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/invoice") + assert [i.name for i in find_instances(act.observe(), spec).instances] == [ + "Line 1" + ] + items = [ + {"desc": "Setup", "amount": "100.00"}, + {"desc": "Support", "amount": "40.00"}, + ] + out = fill_instances(act, spec, items, run_id="s1") + assert out.held, out.reason + + +# -- the verdict ------------------------------------------------------------------------ + + +def test_judge_instances_refuses_missing_extra_and_rebound_rows() -> None: + planned = [{"item": "0", "slot": "Name", "expected": "Ann"}] + seen = [{"handle": "#a", "slot": "Name", "value": "Ann", "run_id": "r"}] + assert judge_instances(planned, {"0": "#a"}, seen, run_id="r").status is Status.HELD + assert judge_instances([], {}, [], run_id="r").status is not Status.HELD + extra = seen + [{"handle": "#b", "slot": "Name", "value": "", "run_id": "r"}] + assert ( + judge_instances(planned, {"0": "#a"}, extra, run_id="r").status + is Status.REFUTED + ) + assert ( + judge_instances(planned, {"0": "#b"}, seen, run_id="r").status is Status.REFUTED + ) + assert ( + judge_instances(planned, {"0": "#a"}, [], run_id="r").status + is Status.NOT_CHECKED + ) + near = [{**seen[0], "value": "Ann "}] + assert ( + judge_instances(planned, {"0": "#a"}, near, run_id="r").status is Status.REFUTED + ) + + +def test_a_box_whose_state_was_not_read_is_neither_blank_nor_a_pass() -> None: + from openadapt_flow.gui.model import Container, Control, Screen + from openadapt_flow.gui.repeating import seen_rows + + spec = RepeatSpec( + "opts", + ControlSpec("button", "Add"), + "row", + (Slot("checkbox", "Insured", "ins"),), + ) + row = Container("r1", "row") + screen = Screen( + controls=( + Control("c1", "checkbox", "Insured", checked=None, containers=(row,)), + ) + ) + read = find_instances(screen, spec) + assert read.usable and not read.instances[0].blank() + planned = [{"item": "0", "slot": "Insured", "expected": "false"}] + got = judge_instances(planned, {"0": "r1"}, seen_rows(read, spec, "r"), run_id="r") + assert got.status is Status.NOT_CHECKED