diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 3ab171d6a7..56a50d3a2a 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -354,7 +354,7 @@ improvising or retrying when something is off. | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](packages/flow/docs/WRITE_RECEIPTS.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](packages/seal-view/README.md) | -| Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | +| Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here. The quickstart offers its checked and its stopped run's Seals in one question, showing one line per card and the exact file to be uploaded | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | | Run authorizations signed with the authorizer's GitHub SSH key (`ssh-keygen -Y sign`, after a summary of what it allows), naming the signing key and bound to the bundle digest, items, profile and Seal keys, and referenced by each Seal; the identity checked against github.com (`--live`) or pinned allowed signers; a pseudonymous operator profile counted from anchored Seals only | Released ([#1401](https://github.com/OpenAdaptAI/OpenAdapt/pull/1401)) | Unit tests with synthetic data; signatures checked against OpenSSH's `ssh-keygen` both ways | `openadapt-flow local-seal authorize`, `local-seal run --authorization`, `local-seal profile`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#run-authorizations-who-authorized-the-runs) | | Run reports redacted before they are sealed: session and CSRF tokens, OAuth grants and credential headers become `` and are listed in `redactions`; a Seal refuses a report that still holds one; per-app policy | Released ([#1407](https://github.com/OpenAdaptAI/OpenAdapt/pull/1407)) | Unit tests with generated tokens; 7,773 local reports scanned, only OpenEMR `token_main` matched | `openadapt-flow redact-report`, `local-seal run --allow-unredacted`; [REPORT_REDACTION.md](packages/flow/docs/REPORT_REDACTION.md) | | Strict no-outbound mode and an unattended on-prem service | Released | Synthetic | `openadapt-flow no-outbound`, `service`; [ON_PREM.md](packages/flow/docs/ON_PREM.md) | diff --git a/llms-full.txt b/llms-full.txt index 1843b8a9ba..bde50e7c9b 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -789,7 +789,7 @@ improvising or retrying when something is off. | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRITE_RECEIPTS.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/seal-view/README.md) | -| Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | +| Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here. The quickstart offers its checked and its stopped run's Seals in one question, showing one line per card and the exact file to be uploaded | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | | Run authorizations signed with the authorizer's GitHub SSH key (`ssh-keygen -Y sign`, after a summary of what it allows), naming the signing key and bound to the bundle digest, items, profile and Seal keys, and referenced by each Seal; the identity checked against github.com (`--live`) or pinned allowed signers; a pseudonymous operator profile counted from anchored Seals only | Released ([#1401](https://github.com/OpenAdaptAI/OpenAdapt/pull/1401)) | Unit tests with synthetic data; signatures checked against OpenSSH's `ssh-keygen` both ways | `openadapt-flow local-seal authorize`, `local-seal run --authorization`, `local-seal profile`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#run-authorizations-who-authorized-the-runs) | | Run reports redacted before they are sealed: session and CSRF tokens, OAuth grants and credential headers become `` and are listed in `redactions`; a Seal refuses a report that still holds one; per-app policy | Released ([#1407](https://github.com/OpenAdaptAI/OpenAdapt/pull/1407)) | Unit tests with generated tokens; 7,773 local reports scanned, only OpenEMR `token_main` matched | `openadapt-flow redact-report`, `local-seal run --allow-unredacted`; [REPORT_REDACTION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/REPORT_REDACTION.md) | | Strict no-outbound mode and an unattended on-prem service | Released | Synthetic | `openadapt-flow no-outbound`, `service`; [ON_PREM.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ON_PREM.md) | diff --git a/openadapt/cli.py b/openadapt/cli.py index 51653a9f90..ead1c56b8f 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -911,12 +911,12 @@ def _quickstart_publish_offer(): if not _public_seals_available(): return None - def offer(run_dir: Path, say, ask) -> bool: + def offer(run_dirs: list[Path], say, ask) -> bool: from openadapt.seal_publish import ( PublishError, endpoint, hosted_seals_live, - publish, + publish_quickstart, ) try: @@ -924,19 +924,10 @@ def offer(run_dir: Path, say, ask) -> bool: return False except PublishError: return False - say( - "Put this Seal online? This is the exact summary that would be " - f"uploaded ({run_dir / 'public-seal.json'}):" - ) + which = "these runs" if len(run_dirs) > 1 else "this run" + say(f"See {which} on app.openadapt.ai? It would upload:") try: - publish( - run_dir, - interactive=True, - ask=ask, - say=say, - provenance="synthetic-tutorial", - command=_hint, - ) + publish_quickstart(run_dirs, ask=ask, say=say, command=_hint) except PublishError as exc: say(str(exc)) except (KeyboardInterrupt, EOFError): diff --git a/openadapt/quickstart/__init__.py b/openadapt/quickstart/__init__.py index 8a45c08410..b5732ac15a 100644 --- a/openadapt/quickstart/__init__.py +++ b/openadapt/quickstart/__init__.py @@ -32,7 +32,7 @@ def next_steps( keep: Optional[str] = None, shadow: Optional[Callable[[], Optional[str]]] = None, offer_publish: Optional[ - Callable[[Path, Callable[[str], None], Callable[[str], str]], bool] + Callable[[list[Path], Callable[[str], None], Callable[[str], str]], bool] ] = None, ) -> Callable[[Outcome], NextSteps]: """The finale's commands, spelled by the launcher's ``hint`` helper. @@ -41,7 +41,7 @@ def next_steps( check (run once, at the finale) for an older ``openadapt`` on PATH. ``offer_publish`` is given only in a terminal outside CI, with an engine that can build public Seals. At the finale it asks once whether to put - the Seal online, and only when Cloud says hosted Seals are live. Otherwise + the checked and the stopped run's Seals online, and only when Cloud says hosted Seals are live. Otherwise the finale says nothing about publishing. """ diff --git a/openadapt/quickstart/story.py b/openadapt/quickstart/story.py index a7af623978..b8ce9f1ef8 100644 --- a/openadapt/quickstart/story.py +++ b/openadapt/quickstart/story.py @@ -110,11 +110,11 @@ class NextSteps: #: The command that checks one run folder, for its Seal page. verify_run: Optional[Callable[[Path], str]] = None #: In a terminal and outside CI only: asks once whether to publish the - #: run's public Seal, and does so on a yes. Called as - #: ``offer_publish(run_dir, say, ask)``; returns False, having said - #: nothing, when hosted Seals are not live. + #: public Seals of the checked run and the stopped run, and does so on a + #: yes. Called as ``offer_publish(run_dirs, say, ask)``; returns False, + #: having said nothing, when hosted Seals are not live. offer_publish: Optional[ - Callable[[Path, Callable[[str], None], Callable[[str], str]], bool] + Callable[[list[Path], Callable[[str], None], Callable[[str], str]], bool] ] = None diff --git a/openadapt/quickstart/view.py b/openadapt/quickstart/view.py index eede4f7a84..8407ed35df 100644 --- a/openadapt/quickstart/view.py +++ b/openadapt/quickstart/view.py @@ -360,13 +360,19 @@ def seal_page_note(outcome: Outcome) -> str: return note -def publish_run(outcome: Outcome) -> Optional[Path]: - """The run whose Seal the finale offers to publish: the first checked run.""" +def publish_runs(outcome: Outcome) -> list[Path]: + """The runs whose Seals the finale offers: the first checked run, then the + stopped run when Act 3 signed one. The stopped run is the point of the + quickstart, so it goes online with the checked run or not at all.""" page = outcome.seal_pages.verified if outcome.seal is None or page is None: - return None - return page.parent + return [] + runs = [page.parent] + broken = outcome.seal_pages.broken + if broken is not None and (broken.parent / "seal.json").is_file(): + runs.append(broken.parent) + return runs def next_step(steps: NextSteps) -> tuple[str, str, str]: @@ -622,11 +628,9 @@ def _ask(self, prompt: str) -> str: return input() def _publish(self, outcome: Outcome, steps: NextSteps) -> None: - run = publish_run(outcome) - if run is None: - return - if steps.offer_publish is not None: - steps.offer_publish(run, lambda line: self._say(f" {line}"), self._ask) + runs = publish_runs(outcome) + if runs and steps.offer_publish is not None: + steps.offer_publish(runs, lambda line: self._say(f" {line}"), self._ask) def confirm(self, prompt: str) -> None: self.stream.write(f" {prompt} ") @@ -1296,8 +1300,8 @@ def finale(self, outcome: Outcome, steps: NextSteps) -> None: self.console.print() if outcome.seal is not None: self._seal(outcome, seal_card(outcome)) - run = publish_run(outcome) - if run is not None and steps.offer_publish is not None: + runs = publish_runs(outcome) + if runs and steps.offer_publish is not None: spoken: list[bool] = [] def say(line: str) -> None: @@ -1307,7 +1311,7 @@ def say(line: str) -> None: self.console.print() self.console.print(_escape(line), soft_wrap=True) - steps.offer_publish(run, say, self._ask) + steps.offer_publish(runs, say, self._ask) self.console.print() self.console.print(Rule(style="cyan")) if all_clear(outcome): diff --git a/openadapt/seal_publish.py b/openadapt/seal_publish.py index 1fc232374a..6f42326b75 100644 --- a/openadapt/seal_publish.py +++ b/openadapt/seal_publish.py @@ -143,12 +143,24 @@ def hosted_seals_live( """True only when ``origin`` answers 200 ``{"enabled": true}`` within ``timeout_s``. Anything else (an error, a timeout, a 404 from a Cloud without the route, - ``{"enabled": false}``) is False. The wait is bounded with a thread, since - a socket timeout does not bound the DNS lookup. + ``{"enabled": false}``) is False. + """ + return _status_true(origin + STATUS_PATH, transport=transport, timeout_s=timeout_s) + + +def _status_true( + url: str, + *, + transport: Optional[Transport] = None, + timeout_s: float = STATUS_TIMEOUT_S, +) -> bool: + """GET ``url``; True only for 200 ``{"enabled": true}`` within ``timeout_s``. + + The wait is bounded with a thread, since a socket timeout does not bound + the DNS lookup. """ import threading - url = origin + STATUS_PATH headers = {"Accept": "application/json"} if transport is None: real = _module_transport() @@ -161,7 +173,7 @@ def transport(method, url, body, headers): # type: ignore[no-redef] def ask() -> None: try: answer.append(transport("GET", url, None, headers)) - except Exception: # noqa: BLE001 - any failure means "do not offer" + except Exception: # noqa: BLE001 - any failure means "no" pass worker = threading.Thread(target=ask, name="seal-status", daemon=True) @@ -607,6 +619,95 @@ def publish( return str(record["url"]) +#: Answers ``{"enabled": true}`` only while Cloud shows two Seals on one page +#: (``/seal#,``). Older Clouds answer 404, and the CLI prints one link +#: per Seal instead. +PAIRS_STATUS_PATH = "/api/public/local-seal-pairs/status" + +#: The quickstart's one question, for both of its Seals. +QUICKSTART_PROMPT = ( + "This uploads the {count} summaries above to {host} and gives you a link. " + "Anyone with the link can see them. They hold no inputs, screenshots or " + "records, and the runs used synthetic data. Publish? [y/N] " +) + + +def card_summary(doc: Mapping[str, Any]) -> str: + """One line per uploaded card: what a reader of the link will see.""" + card = doc["card"] + checks = card.get("checks") or {} + confirmed = sum(int(c.get("confirmed", 0)) for c in checks.values()) + required = sum(int(c.get("required", 0)) for c in checks.values()) + return ( + f"{card.get('outcome', 'UNKNOWN')}: {card.get('steps_ok', 0)} of " + f"{card.get('steps_total', 0)} steps, {confirmed} of {required} checks, " + f"{card.get('model_calls', 0)} model calls" + ) + + +def pair_link(origin: str, seal_ids: list[str]) -> str: + return f"{origin}/seal#{','.join(seal_ids)}" + + +def pairs_live(origin: str, *, transport: Optional[Transport] = None) -> bool: + """True only when Cloud's pair status route answers ``{"enabled": true}``.""" + return _status_true(origin + PAIRS_STATUS_PATH, transport=transport) + + +def publish_quickstart( + run_dirs: list[Path], + *, + ask: Callable[[str], str], + say: Callable[[str], None] = print, + endpoint_value: Optional[str] = None, + transport: Optional[Transport] = None, + command: Callable[[str], str] = lambda rest: f"openadapt {rest}", +) -> Optional[str]: + """Offer the quickstart's Seals (the checked run, then the stopped run) at once. + + Each card is built and written to its run's ``public-seal.json`` first, and + a one-line summary of each is shown with that file's path, so the exact + bytes can be read before answering. One y/N question, default No, covers + both. Returns the link to open (one page for both when Cloud supports it), + or None when nothing was sent. + """ + origin = endpoint(endpoint_value) + docs = [] + for run_dir in run_dirs: + docs.append( + (Path(run_dir), build(Path(run_dir), provenance="synthetic-tutorial")) + ) + for run_dir, doc in docs: + say(f" {card_summary(doc)} ({run_dir / 'public-seal.json'})") + try: + answer = ask(QUICKSTART_PROMPT.format(count=len(docs), host=host_of(origin))) + except EOFError: + answer = "" + if answer.strip().lower() not in ("y", "yes"): + say("Not published.") + return None + sender = transport or _module_transport() + records = [] + for run_dir, doc in docs: + existing = read_record(run_dir) + if existing is not None and existing.get("id"): + records.append(existing) + continue + records.append(upload(run_dir, doc, origin=origin, transport=sender)) + ids = [str(record["id"]) for record in records] + if len(ids) > 1 and pairs_live(origin, transport=transport): + link = pair_link(origin, ids) + say(f"Published. Both runs on one page: {link}") + else: + link = str(records[-1]["url"]) + for (run_dir, doc), record in zip(docs, records): + say(f"Published {doc['card'].get('outcome', '')}: {record['url']}") + say("Each run folder keeps its delete token. To take one down:") + for run_dir, _ in docs: + say(f" {command(f'seal unpublish {_quote(run_dir)}')}") + return link + + __all__ = [ "DEFAULT_ENDPOINT", "ENV_ENDPOINT", @@ -623,7 +724,10 @@ def publish( "hosted_seals_live", "in_ci", "parse_link", + "pair_link", + "pairs_live", "publish", + "publish_quickstart", "unpublish", "upload", ] diff --git a/tests/test_seal_publish.py b/tests/test_seal_publish.py index d0d369cbcd..bfa3409926 100644 --- a/tests/test_seal_publish.py +++ b/tests/test_seal_publish.py @@ -685,7 +685,7 @@ def transport(method, url, body, headers, *_timeout): def ask(_question): raise AssertionError("asked while hosted Seals are not live") - assert offer(run, said.append, ask) is False + assert offer([run], said.append, ask) is False assert said == [] assert not (run / "public-seal.json").exists() # One status check, to production's status route, and nothing else. @@ -694,31 +694,34 @@ def ask(_question): ] -def test_the_quickstart_offer_shows_the_card_then_asks_once( +def test_the_quickstart_offer_shows_each_card_then_asks_once( make_run, tmp_path, monkeypatch ): - run = make_run() + checked = make_run() + stopped = make_run("run-broken", execution_outcome="HALTED", success=False) _terminal(monkeypatch) transport = Recorder(_status(True)) monkeypatch.setattr(seal_publish, "urllib_transport", transport) offer = cli._quickstart_publish_offer() events: list[tuple[str, str]] = [] offer( - run, + [checked, stopped], lambda line: events.append(("say", line)), lambda q: events.append(("ask", q)) or "", ) asks = [i for i, (kind, _) in enumerate(events) if kind == "ask"] assert len(asks) == 1 and events[asks[0]][1].endswith("Publish? [y/N] ") - # The exact card that would be uploaded is printed before the question. - card = json.loads((run / "public-seal.json").read_text())["card"] - shown = [ - json.loads(line) for kind, line in events[: asks[0]] if line.startswith("{") - ] - assert shown and shown[0]["card"] == card - assert card["provenance"] == "synthetic-tutorial" + assert "2 summaries" in events[asks[0]][1] and "synthetic" in events[asks[0]][1] + # Before the question: one line per card, naming the exact file uploaded. + before = [line for kind, line in events[: asks[0]] if kind == "say"] + for run in (checked, stopped): + card = json.loads((run / "public-seal.json").read_text())["card"] + assert card["provenance"] == "synthetic-tutorial" + (line,) = [x for x in before if str(run / "public-seal.json") in x] + assert line.strip().startswith(f"{card['outcome']}: ") assert events[-1] == ("say", "Not published.") - assert not (run / "seal.publish.json").exists() + assert not (checked / "seal.publish.json").exists() + assert not (stopped / "seal.publish.json").exists() # Only the status check was sent; a No uploads nothing. assert [r[0] for r in transport.requests] == ["GET"] @@ -728,7 +731,7 @@ def test_the_tutorial_card_carries_the_program_name(make_run, tmp_path, monkeypa run = make_run() _terminal(monkeypatch) monkeypatch.setattr(seal_publish, "urllib_transport", Recorder(_status(True))) - cli._quickstart_publish_offer()(run, lambda _line: None, lambda _q: "") + cli._quickstart_publish_offer()([run], lambda _line: None, lambda _q: "") card = json.loads((run / "public-seal.json").read_text())["card"] assert card["program_name"] == "local-quickstart" @@ -743,8 +746,8 @@ def test_the_finale_offers_once_after_the_seal_card(tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) calls: list[Path] = [] - def offer(run_dir, say, ask): - calls.append(run_dir) + def offer(run_dirs, say, ask): + calls.append(run_dirs) say("offer shown") return True @@ -756,7 +759,7 @@ def offer(run_dir, say, ask): next_steps=next_steps(cli._hint, cli._shell_quote, True, offer_publish=offer), clock=_clock(), ) - assert calls == [root / "run-1"] + assert calls == [[root / "run-1"]] text = stream.getvalue() assert text.index("Your Seal:") < text.index("offer shown") < text.index("Next:") assert "seal publish" not in text @@ -806,13 +809,13 @@ def test_the_terminal_finale_offers_once_between_the_seal_and_next( monkeypatch.chdir(tmp_path) calls: list[Path] = [] - def offer(run_dir, say, ask): - calls.append(run_dir) + def offer(run_dirs, say, ask): + calls.append(run_dirs) say("offer shown") return True text = _rich_finale(tmp_path, offer) - assert calls == [tmp_path / "openadapt-quickstart" / "run-1"] + assert calls == [[tmp_path / "openadapt-quickstart" / "run-1"]] assert text.index("Your Seal") < text.index("offer shown") < text.index("Next ") assert "Put it online" not in text @@ -858,3 +861,123 @@ def test_read_card_needs_both_files(tmp_path): assert card is not None assert (card.steps_ok, card.effects_confirmed, card.model_calls) == (6, 2, 0) assert card.short_digest == "6dd4a7f2d1ea" + + +# -- the quickstart's two Seals ------------------------------------------------- + +OTHER_ID = "C" * 43 + + +def _created(seal_id: str) -> Response: + body = {"id": seal_id, "url": f"{ORIGIN}/seal#{seal_id}", "delete_token": TOKEN} + return Response(201, {}, json.dumps(body).encode()) + + +def _quickstart_pair(make_run): + return [ + make_run(), + make_run("run-broken", execution_outcome="HALTED", success=False), + ] + + +def test_a_yes_uploads_both_and_gives_one_page_when_cloud_has_pairs(make_run): + runs = _quickstart_pair(make_run) + transport = Recorder(_created(SEAL_ID), _created(OTHER_ID), _status(True)) + said: list[str] = [] + link = seal_publish.publish_quickstart( + runs, + ask=lambda _q: "y", + say=said.append, + endpoint_value=ORIGIN, + transport=transport, + ) + assert link == f"{ORIGIN}/seal#{SEAL_ID},{OTHER_ID}" + posts = [r for r in transport.requests if r[0] == "POST"] + assert [r[2] for r in posts] == [ + (run / "public-seal.json").read_bytes() for run in runs + ] + assert transport.requests[-1][:2] == ( + "GET", + f"{ORIGIN}{seal_publish.PAIRS_STATUS_PATH}", + ) + assert any(link in line for line in said) + for run in runs: + assert json.loads((run / "seal.publish.json").read_text())["delete_token"] + assert any(f"seal unpublish {run}" in line for line in said) + + +@pytest.mark.parametrize( + "pairs", [Response(404, {}, b'{"error":"not_found"}'), _status(False)] +) +def test_an_older_cloud_gets_one_link_per_seal(make_run, pairs): + runs = _quickstart_pair(make_run) + transport = Recorder(_created(SEAL_ID), _created(OTHER_ID), pairs) + said: list[str] = [] + link = seal_publish.publish_quickstart( + runs, + ask=lambda _q: "yes", + say=said.append, + endpoint_value=ORIGIN, + transport=transport, + ) + assert link == f"{ORIGIN}/seal#{OTHER_ID}" + assert any(f"/seal#{SEAL_ID}" in line for line in said) + assert any(f"/seal#{OTHER_ID}" in line for line in said) + assert not any("," in line and "/seal#" in line for line in said) + + +def test_a_quickstart_run_already_online_is_not_uploaded_twice(make_run): + runs = _quickstart_pair(make_run) + (runs[0] / "seal.publish.json").write_text( + json.dumps( + {"id": SEAL_ID, "url": f"{ORIGIN}/seal#{SEAL_ID}", "delete_token": TOKEN} + ) + ) + transport = Recorder(_created(OTHER_ID), _status(True)) + link = seal_publish.publish_quickstart( + runs, + ask=lambda _q: "y", + say=lambda _l: None, + endpoint_value=ORIGIN, + transport=transport, + ) + assert link == f"{ORIGIN}/seal#{SEAL_ID},{OTHER_ID}" + assert [r[0] for r in transport.requests] == ["POST", "GET"] + + +@pytest.mark.parametrize("answer", ["", "n", "no", "anything"]) +def test_anything_but_yes_uploads_nothing(make_run, answer): + runs = _quickstart_pair(make_run) + transport = Recorder() + said: list[str] = [] + assert ( + seal_publish.publish_quickstart( + runs, + ask=lambda _q: answer, + say=said.append, + endpoint_value=ORIGIN, + transport=transport, + ) + is None + ) + assert transport.requests == [] and said[-1] == "Not published." + + +def test_the_finale_offers_the_stopped_run_with_the_checked_one(tmp_path): + from openadapt.quickstart.engine import SealFacts, SealPages + from openadapt.quickstart.story import Outcome + from openadapt.quickstart.view import publish_runs + + root = tmp_path / "openadapt-quickstart" + for name in ("run-1", "run-broken"): + (root / name).mkdir(parents=True) + (root / name / "seal.html").write_text("") + pages = SealPages( + verified=root / "run-1" / "seal.html", broken=root / "run-broken" / "seal.html" + ) + outcome = Outcome(root=root, seal=SealFacts("", 1), seal_pages=pages) + # The stopped run is offered only once it has its own Seal. + assert publish_runs(outcome) == [root / "run-1"] + (root / "run-broken" / "seal.json").write_text("{}") + assert publish_runs(outcome) == [root / "run-1", root / "run-broken"] + assert publish_runs(Outcome(root=root, seal=None, seal_pages=pages)) == []