diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0319-hub-pages-whose-sections-open-in-dialogs-a-dia.md b/capabilities/04-the-core-a-checked-entry-every-time/0319-hub-pages-whose-sections-open-in-dialogs-a-dia.md new file mode 100644 index 0000000000..e6a5678813 --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0319-hub-pages-whose-sections-open-in-dialogs-a-dia.md @@ -0,0 +1 @@ +| Hub pages whose sections open in dialogs: a dialog holding any editable control is a form, never a confirmation; each section's completion is read from its card on the hub after save, with the demonstrated writes, never assumed from the click | On main ([#2502](https://github.com/OpenAdaptAI/OpenAdapt/pull/2502)) | Synthetic: an EMR-like chart hub, a SaaS onboarding checklist (headless Chromium) and a desktop preferences window read as an accessibility tree | `openadapt_flow.gui.hub`, `packages/flow/tests/gui` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index b2d403f417..2eaf699e1a 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -23,6 +23,10 @@ no intake value or derived fact can tick one. An undeclared box, changed wording, a missing grant or an attestation bound to a field stops the run before any box is ticked. +- Hub pages of section dialogs (`openadapt_flow.gui.hub`). A dialog holding + 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. ## v4.0.0 (2026-11-24) diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index f7cc47c3ab..220d4c2f5d 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -295,6 +295,8 @@ Done: the demonstrated writes; an unlisted step role is not checked. - [x] `gui.attestations.judge_attestations` (C1 C2 C5): new. The plan's boxes are the obligations; a box the plan never saw is unexpected. +- [x] `gui.hub.judge_hub` (C1 C2): new. The planned sections are the + obligations; completion is read from the hub, never from the save click. Next, most bug-prone first: diff --git a/packages/flow/openadapt_flow/gui/__init__.py b/packages/flow/openadapt_flow/gui/__init__.py index 65a3e2124b..64bcd04108 100644 --- a/packages/flow/openadapt_flow/gui/__init__.py +++ b/packages/flow/openadapt_flow/gui/__init__.py @@ -10,6 +10,8 @@ and the step that commits is the one the demonstration showed writing. - :mod:`openadapt_flow.gui.attestations`: a checkbox that states something 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. 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/hub.py b/packages/flow/openadapt_flow/gui/hub.py new file mode 100644 index 0000000000..c557958db9 --- /dev/null +++ b/packages/flow/openadapt_flow/gui/hub.py @@ -0,0 +1,524 @@ +"""Hub pages whose sections open in dialogs, with completion tracked per section. + +Many apps put a long record behind one page of cards or a checklist. A chart +has Allergies, Medications and Vitals. An onboarding page has Company, Billing +and Team. Each section's Edit button opens a dialog, Save closes it, and the +card shows that the section is done. Two things went wrong on such pages +before: + +- the page had no "Next" control, so a wizard walk stopped on the hub; and +- the section dialog was taken for a confirmation modal, which either stops + the run or, worse, gets "confirmed". + +This module treats the hub as its own shape: + +- :func:`classify_dialog` sorts an open dialog by what is in it. A dialog + holding any editable control is a *form* dialog, whatever its words. It is + a declared section's form only when its name matches that section, and + every other form dialog stops the run. Only a dialog with no editable + control can be a confirmation, and that is left to the caller's modal rules. +- :class:`SectionSpec` is pack data for one section: its opener on the hub, + the dialog it opens, the save control in the dialog, the card that shows + its status, and the card tokens that mean done. :func:`learn_hub` derives + them from a demonstration: the tokens the card gained when the section was + saved, minus the values typed in the dialog. +- :func:`run_section` opens one section, lets the caller fill the dialog, and + saves it. It stops if any of these fails: no other dialog may be open, the + card must not already show done, exactly the declared dialog must open, the + dialog must close on save with the demonstrated number of writes, and the + card must then show done on a fresh read of the hub. +- :func:`judge_hub` is a verdict site. Its obligations are the planned + sections, fixed before any is opened, and it settles them against a fresh + read of the hub. Completion is read from the hub, never inferred from + having clicked Save. + +:func:`expected_writes` gives the writes the planned sections should make, so +a caller with a write budget can size it to the sections instead of to one +commit. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from enum import Enum +from typing import Any, Callable, Iterable, Mapping, Optional, Sequence + +from openadapt_flow.gui.model import ( + Actuator, + AmbiguousControl, + ControlSpec, + DemoStep, + Dialog, + 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__ = [ + "DialogKind", + "HubVerdict", + "SectionLearned", + "SectionOutcome", + "SectionSpec", + "card_reading", + "card_tokens", + "classify_dialog", + "expected_writes", + "judge_hub", + "judge_hub_screen", + "learn_hub", + "run_section", +] + + +def card_tokens(text: str) -> tuple[str, ...]: + """A card's text as case-folded word tokens; a symbol (a check mark) is + a token of its own.""" + + return tuple(re.findall(r"\w+|[^\w\s]", norm(text))) + + +@dataclass(frozen=True) +class SectionSpec: + """Pack data for one section of a hub. + + ``card`` is the name of the hub container that holds the opener and shows + the section's status. The section is done when the card's tokens include + every ``done_tokens`` entry and none of ``pending_tokens``.""" + + section_id: str + opener: ControlSpec + dialog_name: str + save: ControlSpec + card: str + done_tokens: tuple[str, ...] + pending_tokens: tuple[str, ...] = () + save_writes: int = 1 + required: bool = True + + def __post_init__(self) -> None: + if not self.done_tokens: + raise ValueError( + "a section needs card tokens that show it is done; without " + "them completion cannot be read from the hub" + ) + if self.save_writes < 0: + raise ValueError("save_writes is a count") + if set(self.done_tokens) & set(self.pending_tokens): + raise ValueError("a token cannot mean both done and pending") + + +# -- dialogs ---------------------------------------------------------------------- + + +class DialogKind(str, Enum): + SECTION_FORM = "section_form" + UNDECLARED_FORM = "undeclared_form" + CONFIRMATION = "confirmation" + + +def classify_dialog( + screen: Screen, dialog: Dialog, sections: Sequence[SectionSpec] = () +) -> tuple[DialogKind, Optional[SectionSpec]]: + """What an open dialog is. Any editable control inside makes it a form + dialog, never a confirmation. It is a declared section's form only when + exactly one section names it.""" + + editable = [c for c in screen.in_dialog(dialog.handle) if c.editable] + if not editable: + return DialogKind.CONFIRMATION, None + named = [s for s in sections if norm(s.dialog_name) == norm(dialog.name)] + if len(named) == 1: + return DialogKind.SECTION_FORM, named[0] + return DialogKind.UNDECLARED_FORM, None + + +# -- reading a card --------------------------------------------------------------- + + +@dataclass(frozen=True) +class CardReading: + """What a fresh read of the hub shows for one section's card.""" + + found: bool + done: Optional[bool] + reason: str = "" + + +def card_reading(screen: Screen, section: SectionSpec) -> CardReading: + """Find the section's card through its opener (outside any dialog) and + read whether it shows done.""" + + opener = ControlSpec( + section.opener.role, + section.opener.name, + section.opener.containers, + section.opener.target, + dialog=False, + ) + try: + ctrl = match_one(opener, screen) + except (MissingControl, AmbiguousControl) as exc: + return CardReading(False, None, str(exc)) + cards = [c for c in ctrl.containers if norm(c.name) == norm(section.card)] + if len(cards) != 1: + return CardReading(False, None, f"{len(cards)} cards named {section.card!r}") + tokens = set(card_tokens(cards[0].text)) + if set(section.pending_tokens) & tokens: + return CardReading(True, False, "the card still shows it pending") + if not set(section.done_tokens) <= tokens: + return CardReading(True, False, "the card does not show it done") + return CardReading(True, True) + + +# -- the verdict ------------------------------------------------------------------ + + +@dataclass(frozen=True) +class HubVerdict: + settlement: Settlement + status: Status + + +@verdict_site("gui.hub.judge", classes="C1 C2") +def judge_hub( + planned: Sequence[str], + cards: Sequence[Mapping[str, Any]], + *, + run_id: str, + complete: bool = True, + open_dialogs: int = 0, +) -> HubVerdict: + """Settle the planned sections against a fresh read of the hub. + + ``planned`` is the section ids the run set out to complete, fixed before + any was opened. ``cards`` rows carry ``section_id``, ``found``, ``done`` + and ``run_id``. A section holds only when its card was found and shows + done, on a complete read with no dialog left open. A card that shows it + not done is refuted. One that was not found, or whose state is not a + bool, is not checked. A section nobody planned is unexpected.""" + + obligations = Obligations.fix( + ( + Subject(run_id=run_id, surface="gui", key=str(s), field="section") + for s in planned + ), + source="hub plan", + ) + results = [] + for row in cards: + subject = Subject( + run_id=str(row.get("run_id") or ""), + surface="gui", + key=str(row.get("section_id")), + field="section", + ) + obs = Observed(dict(row), complete=complete is True) + done = row.get("done") + if row.get("found") is not True or not isinstance(done, bool): + results.append(Result.not_checked(subject, "the card was not read")) + elif done is False: + results.append(Result.refuted(subject, obs, "the card does not show done")) + elif complete is not True: + results.append(Result.not_checked(subject, "the hub was read in part")) + elif type(open_dialogs) is not int or open_dialogs != 0: + results.append(Result.not_checked(subject, "a dialog is still open")) + else: + results.append(Result.held(subject, obs, "the card shows done")) + 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 HubVerdict(settlement, status) + + +def judge_hub_screen( + screen: Screen, + sections: Sequence[SectionSpec], + planned: Iterable[str], + *, + run_id: str, +) -> HubVerdict: + """:func:`judge_hub` on a fresh read of the hub.""" + + planned = list(planned) + rows = [] + for section in sections: + if section.section_id not in planned: + continue + reading = card_reading(screen, section) + rows.append( + { + "section_id": section.section_id, + "found": reading.found, + "done": reading.done, + "run_id": run_id, + } + ) + return judge_hub( + planned, + rows, + run_id=run_id, + complete=screen.complete, + open_dialogs=len(screen.dialogs), + ) + + +def expected_writes(sections: Sequence[SectionSpec], planned: Iterable[str]) -> int: + """Writes the planned sections' saves should make, in total.""" + + wanted = set(planned) + return sum(s.save_writes for s in sections if s.section_id in wanted) + + +# -- running one section ---------------------------------------------------------- + + +@dataclass(frozen=True) +class SectionOutcome: + """How one section went. ``status`` is HELD only when :func:`judge_hub` + held for the section on a fresh read of the hub (``verdict``).""" + + section_id: str + status: Status + reason: str + opened: bool = False + saved: bool = False + hub: Optional[Screen] = None + verdict: Optional[HubVerdict] = None + + @property + def held(self) -> bool: + return self.status is Status.HELD + + +def run_section( + actuator: Actuator, + section: SectionSpec, + fill: Callable[[Screen, Dialog], None], + *, + sections: Sequence[SectionSpec] = (), + run_id: str = "", +) -> SectionOutcome: + """Open ``section``, let ``fill`` enter its values, save it, and confirm + on the hub that it is done. + + ``fill`` gets the screen with the dialog open and the dialog. It must + act only inside that dialog.""" + + sid = section.section_id + + def stop(reason: str, **kw: Any) -> SectionOutcome: + return SectionOutcome(sid, Status.NOT_CHECKED, reason, **kw) + + hub = actuator.observe() + if hub.dialogs: + return stop("a dialog is already open on the hub") + before = card_reading(hub, section) + if not before.found: + return stop(f"the section's card is not on the hub: {before.reason}") + if before.done: + return stop("the card shows done before the run opened the section") + try: + opener = match_one( + ControlSpec( + section.opener.role, + section.opener.name, + section.opener.containers, + section.opener.target, + dialog=False, + ), + hub, + ) + except (MissingControl, AmbiguousControl) as exc: + return stop(str(exc)) + w0 = actuator.write_count() + if w0 is None: + return stop("this backend cannot count writes; a section save cannot be shown") + actuator.click(opener.handle) + opened = actuator.observe() + if len(opened.dialogs) != 1: + return stop(f"{len(opened.dialogs)} dialogs opened", opened=True) + dialog = opened.dialogs[0] + kind, owner = classify_dialog(opened, dialog, sections or (section,)) + if kind is not DialogKind.SECTION_FORM or owner is None or owner.section_id != sid: + return stop( + f"the dialog that opened is a {kind.value} dialog, not {sid!r}", opened=True + ) + if actuator.write_count() != w0: + return stop("opening the section wrote", opened=True) + fill(opened, dialog) + filled = actuator.observe() + if [d.handle for d in filled.dialogs] != [dialog.handle]: + return stop("the dialog changed while it was filled", opened=True) + try: + save = match_one( + ControlSpec( + section.save.role, + section.save.name, + section.save.containers, + section.save.target, + dialog=True, + ), + filled, + ) + except (MissingControl, AmbiguousControl) as exc: + return stop(str(exc), opened=True) + if save.dialog != dialog.handle: + return stop("the save control is outside the section's dialog", opened=True) + w1 = actuator.write_count() + actuator.click(save.handle) + w2 = actuator.write_count() + after = actuator.observe() + if after.dialogs: + errors = [c.error for c in after.controls if c.error] or list(after.errors) + reason = ( + f"the dialog did not close: {errors[0]}" + if errors + else "the dialog did not close" + ) + return SectionOutcome(sid, Status.REFUTED, reason, True, False, after) + if w1 is None or w2 is None: + return SectionOutcome( + sid, + Status.NOT_CHECKED, + "the save's writes were not counted", + True, + True, + after, + ) + if w2 - w1 != section.save_writes: + reason = f"saving wrote {w2 - w1}; the demo wrote {section.save_writes}" + return SectionOutcome(sid, Status.REFUTED, reason, True, True, after) + verdict = judge_hub_screen(after, (section,), [sid], run_id=run_id) + reading = card_reading(after, section) + reason = ( + "the card shows done" + if verdict.status is Status.HELD + else (reading.reason or "the card was not read") + ) + return SectionOutcome(sid, verdict.status, reason, True, True, after, verdict) + + +# -- from a demonstration ---------------------------------------------------------- + + +@dataclass(frozen=True) +class SectionLearned: + """One section found in a demonstration. ``spec`` is None when the card + showed no new token on save (``reason`` says why); the pack author must + then say how the hub shows the section done.""" + + opener_index: int + save_index: int + spec: Optional[SectionSpec] + reason: str = "" + + +def learn_hub(demo: Sequence[DemoStep]) -> tuple[SectionLearned, ...]: + """Find each open, fill, save cycle: a click that opened one form dialog, + then a click inside it that closed it. The card is the opener's innermost + named container. Its done tokens are those it gained on save, less any + token of a value typed in the dialog; its pending tokens are those it lost.""" + + out = [] + i = 0 + while i < len(demo): + step = demo[i] + new = [ + d + for d in step.after.dialogs + if d.handle not in {x.handle for x in step.before.dialogs} + ] + if step.action != "click" or step.target.dialog or len(new) != 1: + i += 1 + continue + dialog = new[0] + typed: set[str] = set() + j = i + 1 + closed_by: Optional[int] = None + while j < len(demo) and demo[j].target.dialog == dialog.handle: + if demo[j].value: + typed |= set(card_tokens(demo[j].value)) + if demo[j].action == "click" and dialog.handle not in { + d.handle for d in demo[j].after.dialogs + }: + closed_by = j + break + j += 1 + if closed_by is None: + # The dialog was left some other way (or never closed): not a + # section cycle the demo showed whole. + i = j + continue + out.append(_learned(step, demo[closed_by], dialog, typed, i, closed_by)) + i = closed_by + 1 + return tuple(out) + + +def _learned( + open_step: DemoStep, + save_step: DemoStep, + dialog: Dialog, + typed: set[str], + i: int, + j: int, +) -> SectionLearned: + opener = open_step.target + named = [c for c in opener.containers if c.name and c.kind != "dialog"] + if not named: + return SectionLearned(i, j, None, "the opener sits in no named card") + card = named[-1] + after_ctrl = save_step.after.control(opener.handle) + after_card = None + if after_ctrl is not None: + after_card = next( + (c for c in after_ctrl.containers if c.handle == card.handle), None + ) + if after_card is None: + return SectionLearned(i, j, None, "the card was not on the hub after saving") + before_t, after_t = set(card_tokens(card.text)), set(card_tokens(after_card.text)) + done = tuple(sorted(after_t - before_t - typed)) + pending = tuple(sorted(before_t - after_t - typed)) + open_spec = spec_for(opener, open_step.before) + save_spec = spec_for(save_step.target, save_step.before) + if not done: + return SectionLearned( + i, j, None, "the card gained no token when the section was saved" + ) + if open_spec is None or save_spec is None: + return SectionLearned( + i, j, None, "the opener or the save control is not unique" + ) + if save_step.writes is None: + return SectionLearned( + i, j, None, "the backend could not count the save's writes" + ) + return SectionLearned( + i, + j, + SectionSpec( + section_id=norm(card.name).replace(" ", "_"), + opener=open_spec, + dialog_name=dialog.name, + save=save_spec, + card=card.name, + done_tokens=done, + pending_tokens=pending, + save_writes=save_step.writes, + ), + ) diff --git a/packages/flow/tests/failopen/sites/gui_hub.py b/packages/flow/tests/failopen/sites/gui_hub.py new file mode 100644 index 0000000000..5a7e1951ab --- /dev/null +++ b/packages/flow/tests/failopen/sites/gui_hub.py @@ -0,0 +1,100 @@ +"""gui.hub.judge (C1 C2): every planned section's card shows done on a fresh +read of the hub, with no dialog left open. + +The obligations are the sections the run planned before opening any. A card +that shows not done is refuted; one that was not found or not read is not +checked; a section nobody planned is unexpected; an empty plan never passes. +""" + +from __future__ import annotations + +import copy +from typing import Any + +from openadapt_flow.gui.hub import judge_hub +from openadapt_flow.verdict import Status +from tests.failopen.harness import Seed, SiteSpec, index, key, register + +RUN = "run-1" + + +def _card(sid: str, done: Any = True, found: Any = True) -> dict[str, Any]: + return {"section_id": sid, "found": found, "done": done, "run_id": RUN} + + +def _good() -> dict[str, Any]: + return { + "planned": ["allergies", "medications"], + "cards": [_card("allergies"), _card("medications")], + "complete": True, + "open_dialogs": 0, + } + + +def _run(ev: dict[str, Any]) -> Any: + return judge_hub( + ev["planned"], + ev["cards"], + run_id=RUN, + complete=ev.get("complete"), + open_dialogs=ev.get("open_dialogs"), + ) + + +def _bad(item: dict[str, Any]) -> dict[str, Any]: + out = copy.deepcopy(item) + out["done"] = False + return out + + +def _inflate(ev: dict[str, Any], n: int) -> dict[str, Any]: + planned = [f"s{i}" for i in range(n)] + cards = [_card(f"s{i}", done=i != n - 1) for i in range(n)] + return {**ev, "planned": planned, "cards": cards} + + +register( + SiteSpec( + id="gui.hub.judge", + classes="C1 C2", + target="openadapt_flow.gui.hub:judge_hub", + run=_run, + is_pass=lambda out: out.status is Status.HELD, + level=lambda out: out.status, + seeds=lambda: [ + Seed(_good(), True), + Seed( + { + **_good(), + "cards": [_card("allergies"), _card("medications", done=False)], + }, + False, + "one card not done", + ), + Seed( + {**_good(), "cards": [_card("allergies")]}, + False, + "a planned section with no card", + ), + Seed({**_good(), "open_dialogs": 1}, False, "a dialog left open"), + Seed( + {**_good(), "cards": _good()["cards"] + [_card("vitals")]}, + False, + "a section nobody planned", + ), + ], + items=key("cards"), + plan=key("planned"), + bad_item=_bad, + inflate=_inflate, + fields=index(key("cards"), 0), + values=( + key("done", "cards", 0), + key("found", "cards", 0), + key("section_id", "cards", 0), + key("open_dialogs"), + ), + subject=key("run_id", "cards", 0), + partial=lambda ev: [("complete", {**ev, "complete": False})], + ) +) diff --git a/packages/flow/tests/gui/test_gui_hub.py b/packages/flow/tests/gui/test_gui_hub.py new file mode 100644 index 0000000000..3fca8cbc8e --- /dev/null +++ b/packages/flow/tests/gui/test_gui_hub.py @@ -0,0 +1,381 @@ +"""Hub pages of section dialogs on three kinds of app. + +- an EMR-like chart hub (Allergies, Medications) whose cards open dialogs; +- a SaaS onboarding checklist, where a dialog that says "Confirm" but holds a + field is a form, not a confirmation; +- a desktop preferences window read as an accessibility tree, no browser. + +Sections are learned from one demonstration and replayed with other values. +Completion is read from the hub after each save, never assumed. +""" + +from __future__ import annotations + +from typing import Any, Optional + +import pytest + +from openadapt_flow.gui.adapters import screen_from_tree +from openadapt_flow.gui.dom import PageActuator +from openadapt_flow.gui.hub import ( + DialogKind, + SectionSpec, + classify_dialog, + expected_writes, + judge_hub, + judge_hub_screen, + learn_hub, + run_section, +) +from openadapt_flow.gui.model import ControlSpec, Recorder, Screen, match_one +from openadapt_flow.verdict import Status +from tests.gui import _apps + +# -- an EMR-like chart hub --------------------------------------------------------- + +CHART_JS = """ +function openS(id){document.getElementById('dlg-'+id).hidden=false;} +function saveS(id, field){ + const v=document.getElementById(field).value; + if(!v){document.getElementById('err-'+id).textContent='Enter a value'; + document.getElementById(field).setAttribute('aria-invalid','true');return;} + fetch('/save/'+id,{method:'POST',body:JSON.stringify({v:v})}).then(r=>r.json()).then(j=>{ + if(j.ok){document.getElementById('st-'+id).textContent=j.status; + document.getElementById('dlg-'+id).hidden=true;}}); +}""" + + +def _card( + sid: str, title: str, field: str, status: str, dialog_name: Optional[str] = None +) -> str: + return f"""

{title}

+

{status}

+""" + + +def chart_hub( + *, + ignore_saves: bool = False, + allergies_status: str = "Not reviewed", + allergy_dialog: Optional[str] = None, +) -> _apps.App: + def hub(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Chart", + "

Chart: Test Patient C

" + + _card("al", "Allergies", "Allergy", allergies_status, allergy_dialog) + + _card("md", "Medications", "Medication", "Not reviewed") + + "" + + f"
", + ) + + def save(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + sid = path.rsplit("/", 1)[1] + if ignore_saves: + return 200, '{"ok": true, "status": "Not reviewed"}' + app.state[sid] = f["v"][0] + return 200, '{"ok": true, "status": "Reviewed \\u2713 ' + f["v"][0] + '"}' + + return _apps.App( + "chart.test", + { + ("GET", "/chart"): hub, + ("POST", "/save/al"): save, + ("POST", "/save/md"): save, + ("POST", "/sign"): lambda a, p, m, f: (200, "{}"), + }, + ) + + +def _fill_with(value: str): + def fill(screen: Screen, dialog: Any) -> None: + (field,) = [c for c in screen.in_dialog(dialog.handle) if c.editable] + ACT[0].set_text(field.handle, value) + + return fill + + +ACT: list[Any] = [] + + +def _record_chart(page: Any, app: _apps.App) -> list: + act = PageActuator(page) + page.goto(f"{app.origin}/chart") + rec = Recorder(act) + for title, field, value in ( + ("Allergies", "Allergy", "Penicillin"), + ("Medications", "Medication", "Drug D 5 mg"), + ): + rec.click( + match_one( + ControlSpec("button", f"Edit {title.lower()}"), act.observe() + ).handle + ) + s = act.observe() + rec.set_text( + match_one(ControlSpec("textbox", field, dialog=True), s).handle, value + ) + rec.click( + match_one(ControlSpec("button", "Save", dialog=True), act.observe()).handle + ) + return rec.steps + + +def _learned_chart(page: Any) -> list[SectionSpec]: + with _apps.serve(page, chart_hub()) as app: + learned = learn_hub(_record_chart(page, app)) + assert all(s.spec is not None for s in learned), [s.reason for s in learned] + return [s.spec for s in learned] # type: ignore[misc] + + +def test_emr_hub_sections_are_learned_from_the_card_tokens(page) -> None: + specs = _learned_chart(page) + assert [(s.section_id, s.card, s.dialog_name) for s in specs] == [ + ("allergies", "Allergies", "Allergies"), + ("medications", "Medications", "Medications"), + ] + # "Reviewed" was on the card before and after; the typed value is not a + # done token. What the card gained is the check mark; it lost "not". + assert specs[0].done_tokens == ("✓",) + assert specs[0].pending_tokens == ("not",) + assert specs[0].save_writes == 1 + assert expected_writes(specs, ["allergies", "medications"]) == 2 + + +def test_emr_hub_replays_each_section_and_reads_completion_from_the_hub(page) -> None: + specs = _learned_chart(page) + app = chart_hub() + with _apps.serve(page, app): + act = PageActuator(page) + ACT[:] = [act] + page.goto(f"{app.origin}/chart") + before = judge_hub_screen( + act.observe(), specs, ["allergies", "medications"], run_id="r1" + ) + assert before.status is Status.REFUTED + for spec, value in zip(specs, ("Latex", "Drug E 2 mg")): + out = run_section(act, spec, _fill_with(value), sections=specs, run_id="r1") + assert out.held, out.reason + verdict = judge_hub_screen( + act.observe(), specs, ["allergies", "medications"], run_id="r1" + ) + assert verdict.status is Status.HELD + assert app.state == {"al": "Latex", "md": "Drug E 2 mg"} + + +@pytest.mark.parametrize( + ("variant", "value", "status", "reason"), + [ + ({"ignore_saves": True}, "Latex", Status.REFUTED, "still shows it pending"), + ({}, "", Status.REFUTED, "did not close: Enter a value"), + ( + {"allergies_status": "Reviewed ✓ Sulfa"}, + "Latex", + Status.NOT_CHECKED, + "before the run opened", + ), + ( + {"allergy_dialog": "Allergy history import"}, + "Latex", + Status.NOT_CHECKED, + "undeclared_form", + ), + ], +) +def test_emr_hub_section_that_does_not_complete_stops( + page, variant, value, status, reason +) -> None: + specs = _learned_chart(page) + app = chart_hub(**variant) + with _apps.serve(page, app): + act = PageActuator(page) + ACT[:] = [act] + page.goto(f"{app.origin}/chart") + out = run_section(act, specs[0], _fill_with(value), sections=specs, run_id="r2") + assert out.status is status and reason in out.reason + + +# -- SaaS onboarding checklist: form dialogs are never confirmations ----------------- + + +def onboarding() -> _apps.App: + def hub(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Get started", + """

Get started

+ + + +
""", + ) + + def co(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + app.state["company"] = f["cn"][0] + return 200, "{}" + + return _apps.App("app.test", {("GET", "/start"): hub, ("POST", "/co"): co}) + + +def test_saas_dialog_with_a_field_is_a_form_even_when_it_says_confirm(page) -> None: + section = SectionSpec( + "company", + ControlSpec("button", "Set up", ("Company profile",)), + "Company profile", + ControlSpec("button", "Confirm", ("Company profile",)), + card="Company profile", + done_tokens=("done",), + pending_tokens=("to",), + ) + app = onboarding() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/start") + for dlg, kind in ( + ("d2", DialogKind.UNDECLARED_FORM), + ("d3", DialogKind.CONFIRMATION), + ): + page.evaluate(f"{dlg}.hidden=false") + screen = act.observe() + (dialog,) = screen.dialogs + assert classify_dialog(screen, dialog, [section])[0] is kind + page.evaluate(f"{dlg}.hidden=true") + ACT[:] = [act] + out = run_section(act, section, _fill_with("Acme Test Co"), run_id="r3") + assert out.held, out.reason + assert app.state["company"] == "Acme Test Co" + + +# -- desktop preferences window, read as an accessibility tree ----------------------- + + +class Prefs: + """A native preferences window: each group shows a status and opens a + dialog whose OK button saves.""" + + def __init__(self, *, ok_saves: bool = True) -> None: + self.status = {"Account": "Not set", "Proxy": "Not set"} + self.values: dict[str, str] = {} + self.open: Optional[str] = None + self.draft = "" + self.writes = 0 + self.ok_saves = ok_saves + + def tree(self) -> dict[str, Any]: + groups = [ + { + "role": "group", + "name": g, + "handle": f"grp:{g}", + "text": f"{g} {self.status[g]}", + "children": [ + {"role": "push button", "name": "Change", "handle": f"chg:{g}"} + ], + } + for g in self.status + ] + if self.open: + groups.append( + { + "role": "dialog", + "name": f"{self.open} settings", + "handle": "dlg", + "children": [ + { + "role": "edit", + "name": "Value", + "value": self.draft, + "handle": "dlg:val", + }, + {"role": "push button", "name": "OK", "handle": "dlg:ok"}, + ], + } + ) + return {"role": "window", "name": "Preferences", "children": groups} + + def observe(self) -> Screen: + return screen_from_tree(self.tree(), location="prefs") + + def click(self, handle: str) -> None: + if handle.startswith("chg:"): + self.open, self.draft = handle[4:], "" + elif handle == "dlg:ok" and self.open: + if self.ok_saves: + self.values[self.open] = self.draft + self.status[self.open] = "Configured" + self.writes += 1 + self.open = None + + def set_text(self, handle: str, value: str) -> None: + self.draft = value + + def set_checked(self, handle: str, checked: bool) -> None: + raise KeyError(handle) + + def write_count(self) -> Optional[int]: + return self.writes + + +def _record_prefs() -> list[SectionSpec]: + app = Prefs() + rec = Recorder(app) + for group, value in (("Account", "tester"), ("Proxy", "proxy.example.test:3128")): + rec.click(f"chg:{group}") + rec.set_text("dlg:val", value) + rec.click("dlg:ok") + learned = learn_hub(rec.steps) + assert all(s.spec for s in learned), [s.reason for s in learned] + return [s.spec for s in learned] # type: ignore[misc] + + +def test_desktop_prefs_hub_learns_and_replays_without_a_browser() -> None: + specs = _record_prefs() + assert [(s.card, s.done_tokens, s.pending_tokens) for s in specs] == [ + ("Account", ("configured",), ("not", "set")), + ("Proxy", ("configured",), ("not", "set")), + ] + app = Prefs() + + def fill(value: str): + return lambda screen, dialog: app.set_text("dlg:val", value) + + for spec, value in zip(specs, ("other", "proxy2.example.test:8080")): + assert run_section(app, spec, fill(value), sections=specs, run_id="d1").held + assert ( + judge_hub_screen(app.observe(), specs, ["account", "proxy"], run_id="d1").status + is Status.HELD + ) + + +def test_desktop_prefs_ok_that_saves_nothing_is_refuted() -> None: + specs = _record_prefs() + app = Prefs(ok_saves=False) + out = run_section( + app, specs[0], lambda s, d: app.set_text("dlg:val", "x"), sections=specs + ) + assert out.status is Status.REFUTED and "saving wrote 0" in out.reason + + +def test_judge_hub_never_passes_empty_unread_or_unplanned() -> None: + row = {"section_id": "a", "found": True, "done": True, "run_id": "r"} + assert judge_hub(["a"], [row], run_id="r").status is Status.HELD + assert judge_hub([], [], run_id="r").status is not Status.HELD + assert ( + judge_hub(["a"], [row, {**row, "section_id": "b"}], run_id="r").status + is not Status.HELD + ) + assert ( + judge_hub(["a"], [{**row, "found": False}], run_id="r").status + is Status.NOT_CHECKED + ) + assert judge_hub(["a"], [row], run_id="r", open_dialogs=1).status is not Status.HELD + assert judge_hub(["a", "b"], [row], run_id="r").status is not Status.HELD