From e05788f8e717f6f8cf0ade91fb108398e5675cd1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 19:31:36 -0500 Subject: [PATCH 1/7] fix(quickstart): run headless, retry an unready start, and settle a window that draws no frames The founder's first quickstart in Terminal.app halted at step one with 'starting state not ready'. Flow's page settle waited for two animation frames after the last change; a headed Chrome window that macOS reports as covered draws none, so the readiness gate timed out after 10 s. The settle now hands a page that has drawn no frame for a second (or is hidden) to the screenshot check when every other page signal is quiet. The quickstart runs the browser hidden by default (--watch shows it), prints a link to the Seal page instead of opening it (--open), retries once a run that never got a ready screen and otherwise explains it in plain words, caps its width at 100 columns, always shows the screen and the database as text, shows a short publish summary (show or seal publish --show for the JSON), drops the alias notice, documents uvx --python 3.12 openadapt@latest quickstart, and reruns itself on Python 3.12 under uvx on 3.13 or newer. --- CAPABILITIES.md | 1 + CHANGELOG.md | 35 ++ README.md | 9 +- llms-full.txt | 10 +- openadapt/cli.py | 149 +++++++- openadapt/cli_tasks.py | 8 +- openadapt/quickstart/__init__.py | 16 +- openadapt/quickstart/engine.py | 130 ++++++- openadapt/quickstart/images.py | 121 +++++- openadapt/quickstart/scene.py | 10 + openadapt/quickstart/story.py | 11 +- openadapt/quickstart/view.py | 156 +++++--- openadapt/seal_publish.py | 58 ++- packages/flow/CHANGELOG.md | 7 + .../backends/_page_quiescence.py | 53 ++- packages/flow/tests/test_page_settle.py | 59 +++ scripts/capture_quickstart_pty.py | 182 +++++++++ tests/test_cli_quickstart_polish.py | 27 +- tests/test_cli_uvx_hints.py | 2 +- tests/test_quickstart.py | 68 +++- tests/test_quickstart_command.py | 31 ++ tests/test_quickstart_robust.py | 351 ++++++++++++++++++ tests/test_seal_publish.py | 43 ++- 23 files changed, 1407 insertions(+), 130 deletions(-) create mode 100644 scripts/capture_quickstart_pty.py create mode 100644 tests/test_quickstart_command.py create mode 100644 tests/test_quickstart_robust.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 646eeef048..e2b9bb00c1 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -150,6 +150,7 @@ improvising or retrying when something is off. | --- | --- | --- | --- | | Compile one or more demonstrations into a deterministic program | Released | Real app (OpenEMR referral, 62 timed runs) | `openadapt-flow record`, `compile`; [packages/flow](packages/flow/README.md) | | Try the three acts on a real app: `openadapt quickstart --app openemr` runs the certified OpenEMR referral program in Docker, five referrals at once checked in OpenEMR's record, then a possible duplicate stopped before saving; without Docker or a clone it says so and exits 2 | On main ([#1431](https://github.com/OpenAdaptAI/OpenAdapt/pull/1431)) | Real app (local OpenEMR 8.0.0.3, synthetic patients) | `openadapt quickstart --app openemr`; [docs/quickstart](docs/quickstart/README.md#on-a-real-app---app-openemr) | +| Run the quickstart without taking over the screen: `uvx --python 3.12 openadapt@latest quickstart` keeps the browser hidden and shows progress in the terminal (`--watch` shows the window, `--open` opens the Seal page), runs a run whose starting screen never settles once more in a new folder and otherwise says why in plain words, and reruns itself with Python 3.12 under `uvx` on an unsupported Python. Flow's page settle hands a page that draws no frames (a covered headed window) to the screenshot check instead of waiting out its timeout | On main | Unit tests; headless terminal captures at 80, 120 and 250 columns for Terminal.app, WezTerm and iTerm2 settings; a headed covered-window run is not reproduced here | `openadapt quickstart`; [openadapt/quickstart](openadapt/quickstart/__init__.py), [_page_quiescence.py](packages/flow/openadapt_flow/backends/_page_quiescence.py) | | Classify common local edits without a person (select-all, Enter in a field or dropdown, an in-form tab, an informational dialog's dismiss), only when the recording's network capture shows no write and a runtime check confirms only the expected change | Released ([#1366](https://github.com/OpenAdaptAI/OpenAdapt/pull/1366)) | Synthetic; OpenEMR referral recording re-admitted offline (violations 12 to 1 under `permissive`) | [LOCAL_EDIT_CLASSIFICATION.md](packages/flow/docs/design/LOCAL_EDIT_CLASSIFICATION.md), `compiler/local_edit.py` | | Keep the empty search result a person confirmed through (a duplicate check's "No matches were found.") as an exact check after the click that opens the dialog and again right before Confirm, so a run whose dialog lists a match stops before the save; only fixed-vocabulary search-result statements shown once, never text with a name or search term, and a confirmation dialog without one is noted in `compile_notes.json` | On main | Real app frames (an OpenEMR referral recording, compiled offline) | `compiler/empty_result_guard.py` | | Mine that check in any language: induction keeps the one line a named dialog adds (not its title or buttons, not a question, no typed value or number) when two or more demonstrations whose typed values all differ show the same line, refuses when the demonstrations disagree on a mined check instead of copying the first one's, and qualification then needs a business-rule run that halts at it | On main | Synthetic (a search dialog recorded in Chromium by the real recorder, German statement, real OCR) | `compiler/empty_result_guard.py`, `compiler/induction.py` | diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e7871aaf4..6df3c2da2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,41 @@ +## Unreleased + +### Fixes + +- `openadapt quickstart` keeps the browser hidden and shows each step in the + terminal, so it no longer opens a window over your work. `--watch` shows + the window, and the older `--headed` still does too. `--headless` is now the + default and changes nothing. The Seal page is no longer opened at the end: + the finale prints a link to it (an OSC 8 hyperlink where the terminal + supports one, the `file://` address elsewhere, Terminal.app included), and + `--open` opens it. +- A run whose starting screen never finishes drawing (it stopped before its + first click and wrote nothing) runs once more in a new folder. When the + second try stops the same way, the quickstart says why in plain words and + skips the break-it act instead of printing that OpenAdapt "stopped, but not + at the check this act sets off". +- The quickstart's output is at most 100 columns wide, and each step's timing + follows its text instead of sitting at the window's right edge. +- The screen and the database are shown as text side by side in every + terminal, with the saved message read from the screen. The screenshot is + drawn under them only where the terminal answers an image-protocol query + (iTerm2, Kitty, Ghostty). WezTerm drew blank rows for it and gets the text + unless `OPENADAPT_INLINE_IMAGES=iterm2` is set. +- The "Put this Seal online?" question shows four lines on what would be + uploaded and the path of the full JSON instead of printing the JSON. + Answering `show` prints the full card and asks again; the default is still + No. `openadapt seal publish --show` prints the full card and uploads nothing. +- `openadapt quickstart` no longer prints that it is also available as + `openadapt demo quickstart`. +- The documented first command is `uvx --python 3.12 openadapt@latest + quickstart`, and the printed next steps under `uvx` use `openadapt@latest`. + Under `uvx` on Python 3.13 or newer, the launcher reruns the same command + with Python 3.12 (`uvx --python 3.12 openadapt@ ...`) instead of + stopping. Elsewhere on those Pythons it prints that one-line command first. + ## v1.23.0 (2026-11-19) ### Fixes diff --git a/README.md b/README.md index dce82fc919..803d952ff8 100644 --- a/README.md +++ b/README.md @@ -94,13 +94,14 @@ has the method, the raw runs and the cost. ## Try it in one command ```bash -uvx --python 3.12 openadapt demo quickstart --break-it +uvx --python 3.12 openadapt@latest quickstart --break-it ``` No account or API key. [uv](https://docs.astral.sh/uv/getting-started/installation/) -fetches Python 3.12 if you need it; with Python 3.10 to 3.12 already installed, -`python -m pip install --upgrade openadapt` then `openadapt demo quickstart --break-it` -does the same. +fetches Python 3.12 if you need it, and `@latest` runs the newest release. With +Python 3.10 to 3.12 already installed, `python -m pip install --upgrade openadapt` +then `openadapt quickstart --break-it` does the same. The browser runs hidden +and progress shows in the terminal; add `--watch` to see the browser window. ### What it shows diff --git a/llms-full.txt b/llms-full.txt index 4328f3f979..c0681f08b3 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -104,13 +104,14 @@ has the method, the raw runs and the cost. ## Try it in one command ```bash -uvx --python 3.12 openadapt demo quickstart --break-it +uvx --python 3.12 openadapt@latest quickstart --break-it ``` No account or API key. [uv](https://docs.astral.sh/uv/getting-started/installation/) -fetches Python 3.12 if you need it; with Python 3.10 to 3.12 already installed, -`python -m pip install --upgrade openadapt` then `openadapt demo quickstart --break-it` -does the same. +fetches Python 3.12 if you need it, and `@latest` runs the newest release. With +Python 3.10 to 3.12 already installed, `python -m pip install --upgrade openadapt` +then `openadapt quickstart --break-it` does the same. The browser runs hidden +and progress shows in the terminal; add `--watch` to see the browser window. ### What it shows @@ -584,6 +585,7 @@ improvising or retrying when something is off. | --- | --- | --- | --- | | Compile one or more demonstrations into a deterministic program | Released | Real app (OpenEMR referral, 62 timed runs) | `openadapt-flow record`, `compile`; [packages/flow](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/README.md) | | Try the three acts on a real app: `openadapt quickstart --app openemr` runs the certified OpenEMR referral program in Docker, five referrals at once checked in OpenEMR's record, then a possible duplicate stopped before saving; without Docker or a clone it says so and exits 2 | On main ([#1431](https://github.com/OpenAdaptAI/OpenAdapt/pull/1431)) | Real app (local OpenEMR 8.0.0.3, synthetic patients) | `openadapt quickstart --app openemr`; [docs/quickstart](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/docs/quickstart/README.md#on-a-real-app---app-openemr) | +| Run the quickstart without taking over the screen: `uvx --python 3.12 openadapt@latest quickstart` keeps the browser hidden and shows progress in the terminal (`--watch` shows the window, `--open` opens the Seal page), runs a run whose starting screen never settles once more in a new folder and otherwise says why in plain words, and reruns itself with Python 3.12 under `uvx` on an unsupported Python. Flow's page settle hands a page that draws no frames (a covered headed window) to the screenshot check instead of waiting out its timeout | On main | Unit tests; headless terminal captures at 80, 120 and 250 columns for Terminal.app, WezTerm and iTerm2 settings; a headed covered-window run is not reproduced here | `openadapt quickstart`; [openadapt/quickstart](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/openadapt/quickstart/__init__.py), [_page_quiescence.py](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/openadapt_flow/backends/_page_quiescence.py) | | Classify common local edits without a person (select-all, Enter in a field or dropdown, an in-form tab, an informational dialog's dismiss), only when the recording's network capture shows no write and a runtime check confirms only the expected change | Released ([#1366](https://github.com/OpenAdaptAI/OpenAdapt/pull/1366)) | Synthetic; OpenEMR referral recording re-admitted offline (violations 12 to 1 under `permissive`) | [LOCAL_EDIT_CLASSIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/design/LOCAL_EDIT_CLASSIFICATION.md), `compiler/local_edit.py` | | Keep the empty search result a person confirmed through (a duplicate check's "No matches were found.") as an exact check after the click that opens the dialog and again right before Confirm, so a run whose dialog lists a match stops before the save; only fixed-vocabulary search-result statements shown once, never text with a name or search term, and a confirmation dialog without one is noted in `compile_notes.json` | On main | Real app frames (an OpenEMR referral recording, compiled offline) | `compiler/empty_result_guard.py` | | Mine that check in any language: induction keeps the one line a named dialog adds (not its title or buttons, not a question, no typed value or number) when two or more demonstrations whose typed values all differ show the same line, refuses when the demonstrations disagree on a mined check instead of copying the first one's, and qualification then needs a business-rule run that halts at it | On main | Synthetic (a search dialog recorded in Chromium by the real recorder, German statement, real OCR) | `compiler/empty_result_guard.py`, `compiler/induction.py` | diff --git a/openadapt/cli.py b/openadapt/cli.py index 0d589300fa..c2333b2a6d 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -200,7 +200,9 @@ def main(): training/evaluation commands are research. \b - Quick Start (Python 3.10-3.12): + Quick Start (uv fetches Python 3.12 if needed): + uvx --python 3.12 openadapt@latest quickstart + Or, on Python 3.10-3.12: python -m pip install --upgrade openadapt openadapt quickstart @@ -345,6 +347,7 @@ def __getattr__(self, name): def _invoke_flow(argv: list[str]) -> int: """Invoke the canonical engine once and return its exit code.""" if not _python_supported(): + _rerun_with_supported_python() _echo_python_remedy() return 1 try: @@ -399,6 +402,15 @@ def _run_flow(argv: list[str]) -> None: # classifiers, and the CI guard matrix in step. _SUPPORTED_PYTHON = ((3, 10), (3, 12)) +#: The documented first command: the newest launcher, on a Python the engine +#: supports, with nothing installed first. tests/test_quickstart_command.py +#: keeps README.md, llms.txt and the docs on exactly this spelling. +QUICKSTART_COMMAND = "uvx --python 3.12 openadapt@latest quickstart" + +#: Set on the rerun under Python 3.12, so a rerun that still lands on an +#: unsupported Python prints the fix instead of running again. +_PYTHON_RERUN_ENV = "OPENADAPT_PYTHON_RERUN" + def _host_platform() -> str: return sys.platform @@ -420,11 +432,12 @@ def _python_fix() -> str: "OpenAdaptAI/OpenAdapt/main/packages/flow/scripts/install.sh" ) return ( - "Install OpenAdapt with uv, which downloads Python 3.12 if you don't " - "have it:\n" + "Run it with uv, which downloads Python 3.12 if you don't have it:\n" + f" {QUICKSTART_COMMAND}\n" + "No uv yet? Install it first:\n" f"{installer}" - " uv tool install --python 3.12 openadapt\n" - f"Then run: openadapt quickstart{script}" + "To keep OpenAdapt installed: uv tool install --python 3.12 openadapt" + f"{script}" ) @@ -489,10 +502,61 @@ def _require_supported_python() -> None: with the remedy instead of an ImportError or a misleading reinstall hint. """ if not _python_supported(): + _rerun_with_supported_python() _echo_python_remedy() raise click.exceptions.Exit(1) +def _rerun_command() -> Optional[tuple[list[str], str]]: + """Under ``uvx`` on an unsupported Python: the same command on 3.12. + + Returns the argv to run and its shell spelling, or None when this isn't a + ``uvx`` run, uv can't be found, or this already is the rerun. The rerun + pins this launcher's own release (``openadapt@X.Y.Z``) so it runs the + same version; a development build reruns ``openadapt@latest``. + """ + import shutil + + if os.environ.get(_PYTHON_RERUN_ENV) or not _under_uvx(): + return None + uv = os.environ.get("UV") or shutil.which("uv") + if not uv: + return None + pin = __version__ if re.fullmatch(r"\d+\.\d+\.\d+", __version__) else "latest" + spec = ["--python", "3.12", f"openadapt@{pin}", *sys.argv[1:]] + shown = " ".join(["uvx", *(_shell_quote(part) for part in spec)]) + return [uv, "tool", "run", *spec], shown + + +def _rerun_with_supported_python() -> None: + """Rerun this command with Python 3.12 under ``uvx``; return if it can't. + + ``uvx openadapt@latest quickstart`` on Python 3.13 or newer installs only + the launcher (the engine needs 3.10 to 3.12). uv can fetch 3.12 itself, + so the same command runs again with ``--python 3.12`` and its exit code + becomes this one's. Elsewhere this returns and the caller prints the fix. + """ + import subprocess + + rerun = _rerun_command() + if rerun is None: + return + argv, shown = rerun + current = "{}.{}".format(*_python_minor()) + click.echo( + f"Python {current} can't run the OpenAdapt engine (it needs 3.10 to " + f"3.12), so this runs it with Python 3.12:\n {shown}", + err=True, + ) + try: + code = subprocess.call(argv, env={**os.environ, _PYTHON_RERUN_ENV: "1"}) + except OSError: + return + except KeyboardInterrupt: + code = 130 + raise click.exceptions.Exit(code) + + # openadapt-agent 2.0.1 requires `serve --bundles`. The bundle-free # `serve --allow-run` that generates and serves the synthetic tutorial ships # after it, so the quickstart offers that command only when it will work. @@ -567,6 +631,8 @@ def _is_externally_managed_error(error: BaseException) -> bool: { "--out", "--app", + "--watch", + "--open", "--headless", "--no-break", "--verbose", @@ -671,9 +737,21 @@ def _quickstart_root(out: Optional[Path]) -> Path: ), ) @click.option( - "--headless", + "--watch", is_flag=True, - help="Hide the browser. It is shown by default when a display is available.", + help=( + "Show the browser window while it runs. By default the browser is " + "hidden and progress shows in the terminal." + ), +) +@click.option( + "--open", + "open_seal", + is_flag=True, + help=( + "Open your Seal page in the browser at the end. By default the " + "finale prints a link to it." + ), ) @click.option( "--no-break", @@ -694,18 +772,24 @@ def _quickstart_root(out: Optional[Path]) -> Path: "--out) and exit. Runs nothing." ), ) +# --headed is the older spelling of --watch. --headless was the opt-out when +# the window showed by default; hidden is the default now, so it changes +# nothing and is kept so older commands still run. @click.option("--headed", is_flag=True, hidden=True) +@click.option("--headless", is_flag=True, hidden=True) @click.option("--break-it", "break_it", is_flag=True, hidden=True) @click.pass_context def quickstart( command_ctx: click.Context, out: Optional[Path], app: str, - headless: bool, + watch: bool, + open_seal: bool, no_break: bool, verbose: bool, more: bool, headed: bool, + headless: bool, break_it: bool, ) -> None: """Show a task once, run it, then watch it catch a save that didn't happen. @@ -722,7 +806,8 @@ def quickstart( chart, where the program stops before saving. It runs from a clone of the repository and needs Docker; without either it says so and exits 2. - Other flags of the engine tutorial (for example --guided or + The browser runs hidden, so nothing takes over the screen; --watch shows + its window. Other flags of the engine tutorial (for example --guided or --interactive-record) run that tutorial instead, unchanged. """ if more: @@ -737,13 +822,12 @@ def quickstart( # Engine-owned flags (--guided, --interactive-record, and future # engine additions) run the engine's own tutorial, as before. So does # a Flow older than the pieces the three-act quickstart uses. - _engine_tutorial(root, out is None, headed, break_it, command_ctx.args) + _engine_tutorial(root, out is None, watch or headed, break_it, command_ctx.args) return from openadapt.quickstart import next_steps, run_quickstart - from openadapt.quickstart.engine import display_available - visible = not headless and (headed or display_available()) + visible = _watch_window(watch or headed) steps = next_steps( _hint, _shell_quote, @@ -761,6 +845,7 @@ def quickstart( verbose=verbose, steps=steps, openemr=openemr, + open_seal=open_seal, ) except KeyboardInterrupt: click.echo(f"\nStopped. Anything written so far is in {root}", err=True) @@ -784,6 +869,26 @@ def quickstart( raise click.exceptions.Exit(1) +def _watch_window(watch: bool) -> bool: + """Whether the quickstart shows its browser window (``--watch`` only). + + Linux without X11 or Wayland has nowhere to show a window, so the run + stays hidden there and says so instead of failing to start the browser. + """ + if not watch: + return False + if _host_platform().startswith("linux") and not ( + os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY") + ): + click.echo( + "No display here (DISPLAY and WAYLAND_DISPLAY are unset), so the " + "browser stays hidden.", + err=True, + ) + return False + return True + + def _public_seals_available() -> bool: from openadapt.seal_publish import available @@ -819,10 +924,7 @@ 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'}):" - ) + say("Put this Seal online? What would be uploaded:") try: publish( run_dir, @@ -831,6 +933,7 @@ def offer(run_dir: Path, say, ask) -> bool: say=say, provenance="synthetic-tutorial", command=_hint, + brief=True, ) except PublishError as exc: say(str(exc)) @@ -959,16 +1062,18 @@ def _engine_tutorial( def _hint(rest: str) -> str: - """Spell an ``openadapt`` command the way it reaches this same version. + """Spell an ``openadapt`` command so it works as printed. Under ``uvx`` this process runs from a throwaway environment in uv's cache, so the shell may have no ``openadapt`` or an older one that lacks the verb. - Repeat the ``uvx`` form there; otherwise keep the plain command. + Repeat the ``uvx`` form there, with ``openadapt@latest`` so it reaches the + newest release (this one or later) and this Python's version; otherwise + keep the plain command. """ if _under_uvx(): major, minor = sys.version_info[:2] - return f"uvx --python {major}.{minor} openadapt {rest}" + return f"uvx --python {major}.{minor} openadapt@latest {rest}" return f"openadapt {rest}" @@ -2066,6 +2171,12 @@ def _seal_publish_parser() -> argparse.ArgumentParser: action="store_true", help="write and print public-seal.json; upload nothing", ) + parser.add_argument( + "--show", + dest="dry_run", + action="store_true", + help="print the full card that would be uploaded and exit (same as --dry-run)", + ) parser.add_argument( "--github", metavar="LOGIN", diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index 61bb8854d7..63edd56872 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -177,6 +177,12 @@ def matches(prefix: Sequence[str]) -> bool: return raw +#: Short spellings that stay first-class and never print an alias notice: +#: ``setup`` is its own command, and ``quickstart`` is the documented first +#: command (``openadapt demo quickstart`` reaches the same thing). +_UNANNOUNCED = frozenset({("setup",), ("quickstart",)}) + + def alias_notice(argv: Sequence[str], prog: str) -> None: """Show old native spellings only when all three streams are terminals.""" if not argv or any( @@ -218,7 +224,7 @@ def legacy_names(argv: Sequence[str]) -> tuple[str, str] | None: if ( native_old != native_canonical and tuple(argv[: len(native_old)]) == native_old - and native_old != ("setup",) + and native_old not in _UNANNOUNCED ): return " ".join(native_old), " ".join(native_canonical) return None diff --git a/openadapt/quickstart/__init__.py b/openadapt/quickstart/__init__.py index 4bcf4e28ab..8a45c08410 100644 --- a/openadapt/quickstart/__init__.py +++ b/openadapt/quickstart/__init__.py @@ -82,11 +82,14 @@ def run_quickstart( stream: Optional[IO[str]] = None, interactive: Optional[bool] = None, openemr: Optional[Path] = None, + open_seal: bool = False, ) -> Outcome: """Run the quickstart into ``root`` and print it to ``stream``. ``openemr`` is a clone's ``packages/flow`` folder: the three acts then run - on OpenEMR in Docker instead of the bundled MockMed. + on OpenEMR in Docker instead of the bundled MockMed. ``open_seal`` + (``--open``) opens the Seal page in the browser at the end; otherwise the + finale only prints a link to it. """ from openadapt.quickstart.engine import FlowEngine, display_available, open_page @@ -115,9 +118,14 @@ def run_quickstart( break_it=break_it, interactive=interactive, verbose=verbose, - # Only when this output is the terminal a person is reading: - # a captured or redirected stream never opens a browser. - open_page=open_page if _shown(stream, display_available) else None, + # Only on request (--open), and only when this output is the + # terminal a person is reading: a captured or redirected + # stream never opens a browser. + open_page=( + open_page + if open_seal and _shown(stream, display_available) + else None + ), ) finally: close = getattr(view, "close", None) diff --git a/openadapt/quickstart/engine.py b/openadapt/quickstart/engine.py index f332599042..e3a3fee07c 100644 --- a/openadapt/quickstart/engine.py +++ b/openadapt/quickstart/engine.py @@ -72,14 +72,58 @@ class RunFacts: #: "Stopped before saving", ...), from its transaction outcome. plain_label: str = "" #: True when this run is a repeat: its first try, in a worker, stalled - #: and was stopped. + #: and was stopped, or its first try never got a ready screen. repeated: bool = False + #: True when the run stopped before its first action because the app's + #: screen never finished drawing (see :func:`starting_state_not_ready`). + not_ready: bool = False + #: Why it stopped, in plain words, when ``not_ready``. + explanation: str = "" @property def report_md(self) -> Path: return self.run_dir / "REPORT.md" +#: The engine's words for a run its readiness gate stopped before step one. +_NOT_READY_MARK = "starting state not ready" + + +def starting_state_not_ready( + execution_outcome: object, transaction_outcome: object, halt_reason: object +) -> bool: + """True when a run stopped before its first action, on an unready screen. + + The readiness gate halts a run whose starting screen never settles (still + loading, animating, or, for a visible window, not drawing at all). Only + ``HALTED_BEFORE_EFFECT`` counts: that outcome proves nothing was written, + so running again in a fresh folder is safe. + """ + + return ( + str(execution_outcome) == "HALTED" + and transaction_outcome == "HALTED_BEFORE_EFFECT" + and _NOT_READY_MARK in str(halt_reason or "") + ) + + +def not_ready_explanation(visible: bool) -> str: + """Why a run stopped before its first click, in plain words.""" + + if visible: + return ( + "The browser window never finished drawing, so OpenAdapt stopped " + "before its first click and saved nothing. A window that is " + "covered or on another desktop doesn't draw. Run it again without " + "--watch, or keep the window in view." + ) + return ( + "The app's page never finished loading, so OpenAdapt stopped before " + "its first click and saved nothing. Run it again; if it happens " + "again, the report says what kept changing." + ) + + @dataclass class BreakFacts: """The rerun against a database that rejects the write.""" @@ -103,6 +147,11 @@ class BreakFacts: #: whose cause the evidence doesn't show, stays False, and the views then #: describe a generic stop instead of the demonstration. stop_attributed: bool = False + #: True when this run stopped before its first action because the app's + #: screen never finished drawing, even on a second try. + not_ready: bool = False + #: Why it stopped, in plain words, when ``not_ready``. + explanation: str = "" result: Any = field(default=None, repr=False) @property @@ -288,7 +337,7 @@ def run_program( ) if report.execution_outcome == "VERIFIED": write_receipt(_build_tutorial_receipt(report), run_dir) - return RunFacts( + facts = RunFacts( index=index, note=note, run_dir=run_dir, @@ -304,7 +353,15 @@ def run_program( plain_label=plain_result( report.transaction_outcome, report.execution_outcome ).label, + not_ready=starting_state_not_ready( + report.execution_outcome, + report.transaction_outcome, + getattr(getattr(report, "halt", None), "reason", ""), + ), ) + if facts.not_ready: + facts.explanation = not_ready_explanation(visible) + return facts class EarlyScreenRead: @@ -534,6 +591,18 @@ def run_all( (index, note if varied else None, f"run-{index}") for index, note in enumerate(notes, 1) ] + retry: list[tuple[int, Optional[str], str]] = [] + + def finish(run: RunFacts) -> None: + # A run that never got a ready screen wrote nothing; it runs once + # more, here, in a new folder, and only that try is reported. + if run.not_ready and not run.repeated: + retry.append( + (run.index, jobs[run.index - 1][1], f"{run.run_dir.name}-retry") + ) + return + on_finish(run) + leftover = jobs pool = self._started_pool() if pool is not None: @@ -541,13 +610,17 @@ def run_all( jobs, bundle_dir=self.bundle_dir, root=self.root, - on_finish=on_finish, + on_finish=finish, ) # Act 2 is their only job: let them shut down during Act 3. pool.release() for index, note, folder in leftover: run = self.run(index, note, folder) run.repeated = folder != f"run-{index}" + finish(run) + for index, note, folder in retry: + run = self.run(index, note, folder) + run.repeated = True on_finish(run) # -- act 3 ------------------------------------------------------------ @@ -565,13 +638,24 @@ def before_prompt(self) -> None: return_focus_to_terminal(visible=self.visible) def break_it(self) -> BreakFacts: - """Rerun the same program while the database rejects the save.""" + """Rerun the same program while the database rejects the save. + A run that never got a ready screen (it stopped before its first + action and wrote nothing) runs once more in ``run-broken-retry``. + """ + + broken = self._break_once(self.root / "run-broken") + if broken.not_ready: + again = self._break_once(self.root / "run-broken-retry") + again.seconds += broken.seconds + return again + return broken + + def _break_once(self, run_dir: Path) -> BreakFacts: from openadapt_flow.demo_proof import _final_frame, _load_report from openadapt_flow.tutorial import _run_break_it, consequential_step assert self.workflow is not None - run_dir = self.root / "run-broken" save = consequential_step(self.workflow).id # The save step's screenshot lands before the engine's wait on the # database, so it can be read during that wait. @@ -591,7 +675,7 @@ def break_it(self) -> BreakFacts: report = _load_report(Path(result.run_dir)) screenshot = _final_frame(Path(result.run_dir), report) if report else None screen_text = None # read by read_screen(), alongside the page - return BreakFacts( + broken = BreakFacts( run_dir=Path(result.run_dir), fault=result.fault, execution_outcome=str(result.execution_outcome), @@ -608,20 +692,36 @@ def break_it(self) -> BreakFacts: # The record check read the save back and refuted it: the # silent failure this act injects, not some other refusal. stop_attributed=int(result.effects_refuted) > 0, + not_ready=starting_state_not_ready( + result.execution_outcome, + result.transaction_outcome, + result.halt_reason, + ), result=result, ) + if broken.not_ready: + broken.explanation = not_ready_explanation(self.visible) + return broken def read_screen(self, broken: BreakFacts) -> Optional[str]: - """What the halted run's screenshot says (see :func:`read_screen_text`).""" + """What the halted run's screen said. - if broken.screenshot is None: - return None - early = getattr(self, "_early", None) - if early is not None: - text = early.text_for(broken.screenshot) - if text is not None: - return text - return read_screen_text(broken.screenshot) + The saved message read off its screenshot (:func:`read_screen_text`), + else the success text the engine itself observed on screen when it + checked the step, else None. + """ + + text = None + if broken.screenshot is not None: + early = getattr(self, "_early", None) + if early is not None: + text = early.text_for(broken.screenshot) + if text is None: + text = read_screen_text(broken.screenshot) + if text is None: + claim = getattr(broken.result, "screen_claim_text", None) + text = str(claim).strip() if claim else None + return text # -- finale ----------------------------------------------------------- diff --git a/openadapt/quickstart/images.py b/openadapt/quickstart/images.py index c45c625f91..c5c5c7b1ba 100644 --- a/openadapt/quickstart/images.py +++ b/openadapt/quickstart/images.py @@ -1,11 +1,17 @@ """Show a screenshot inline on terminals that can draw images. -Two protocols cover the terminals that support it: iTerm2's inline images -(iTerm2 and WezTerm) and Kitty's graphics protocol (Kitty and Ghostty). Each -terminal is recognized from the variables it sets for its own sessions. Nothing -is assumed: an unknown terminal, a terminal multiplexer (tmux and screen don't -pass images through unless configured to), or output that isn't a terminal -gets ``None``, and the caller draws a text box instead. +Two protocols cover the terminals that support it: iTerm2's inline images and +Kitty's graphics protocol (Kitty and Ghostty). A terminal is a candidate when +the variables it sets for its own sessions name it, and it is used only when +it also answers a query for that protocol (:func:`terminal_answers`). An +unknown terminal, a terminal multiplexer (tmux and screen don't pass images +through unless configured to), output that isn't a terminal, or a terminal +that doesn't answer gets ``None``, and the caller shows the text description +alone. + +WezTerm sets ``TERM_PROGRAM=WezTerm`` and speaks the iTerm2 protocol, but a +WezTerm run showed blank rows where the image should have been, so it is not +a candidate on its own; ``OPENADAPT_INLINE_IMAGES=iterm2`` turns it on. """ from __future__ import annotations @@ -13,8 +19,11 @@ import base64 import io import os +import re +import sys +import time from pathlib import Path -from typing import Mapping, Optional +from typing import Callable, Mapping, Optional ITERM2 = "iterm2" KITTY = "kitty" @@ -27,7 +36,11 @@ def detect_image_protocol( environ: Optional[Mapping[str, str]] = None, *, isatty: bool ) -> Optional[str]: - """Return the image protocol this terminal speaks, or None when unsure.""" + """Return the image protocol this terminal names itself for, or None. + + This reads only the environment. :func:`image_protocol` also asks the + terminal before anything is drawn. + """ env = os.environ if environ is None else environ override = (env.get(OVERRIDE_ENV) or "").strip().lower() @@ -43,8 +56,6 @@ def detect_image_protocol( program = env.get("TERM_PROGRAM", "") if program == "iTerm.app" or env.get("LC_TERMINAL") == "iTerm2": return ITERM2 - if program == "WezTerm": - return ITERM2 if env.get("KITTY_WINDOW_ID") or term == "xterm-kitty": return KITTY if program == "ghostty" or term == "xterm-ghostty": @@ -52,6 +63,94 @@ def detect_image_protocol( return None +def image_protocol( + environ: Optional[Mapping[str, str]] = None, + *, + isatty: bool, + answers: Optional[Callable[[str], bool]] = None, +) -> Optional[str]: + """The protocol to draw with: named by the terminal and answered by it. + + ``OPENADAPT_INLINE_IMAGES`` set to a protocol is used as given, without a + query, for setups detection can't see. + """ + + env = os.environ if environ is None else environ + candidate = detect_image_protocol(env, isatty=isatty) + if candidate is None: + return None + if (env.get(OVERRIDE_ENV) or "").strip().lower() == candidate: + return candidate + return candidate if (answers or terminal_answers)(candidate) else None + + +#: Kitty's graphics query (a 1x1 image it checks but doesn't store), and +#: iTerm2's cell-size report. Each is followed by Primary Device Attributes, +#: which every terminal answers, so a terminal that ignores the first query +#: is known as soon as its device attributes arrive. +_QUERIES = { + KITTY: "\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\", + ITERM2: "\x1b]1337;ReportCellSize\x07", +} +_ANSWERS = { + KITTY: re.compile(rb"\x1b_Gi=31;OK"), + ITERM2: re.compile(rb"\x1b\]1337;ReportCellSize="), +} +_DEVICE_ATTRIBUTES = "\x1b[c" +_DEVICE_ANSWER = re.compile(rb"\x1b\[\?[0-9;]*c") + + +def terminal_answers(protocol: str, *, timeout_s: float = 0.5) -> bool: + """Ask the controlling terminal whether it speaks ``protocol``. + + Writes the protocol's query and a device-attributes request to + ``/dev/tty`` with echo off, then reads until the device attributes arrive + or ``timeout_s`` passes. True only when the protocol's own answer came + back. Windows, or no controlling terminal, is False. + """ + + if sys.platform == "win32": + return False + try: + import select + import termios + import tty + except ImportError: + return False + try: + fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY) + except OSError: + return False + try: + try: + saved = termios.tcgetattr(fd) + except termios.error: + return False + try: + tty.setcbreak(fd) + os.write(fd, (_QUERIES[protocol] + _DEVICE_ATTRIBUTES).encode("ascii")) + reply = b"" + deadline = time.monotonic() + timeout_s + while not _DEVICE_ANSWER.search(reply): + left = deadline - time.monotonic() + if left <= 0: + break + ready, _, _ = select.select([fd], [], [], left) + if not ready: + break + chunk = os.read(fd, 1024) + if not chunk: + break + reply += chunk + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, saved) + return bool(_ANSWERS[protocol].search(reply)) + except OSError: + return False + finally: + os.close(fd) + + def crop_png(path: Path, box: tuple[int, int, int, int]) -> bytes: """Return the ``(left, top, right, bottom)`` part of a PNG, as PNG bytes.""" @@ -122,5 +221,7 @@ def beside_image( "beside_image", "crop_png", "detect_image_protocol", + "image_protocol", "image_sequence", + "terminal_answers", ] diff --git a/openadapt/quickstart/scene.py b/openadapt/quickstart/scene.py index bbda53183a..421c849796 100644 --- a/openadapt/quickstart/scene.py +++ b/openadapt/quickstart/scene.py @@ -104,6 +104,8 @@ def screen_words(self, broken: "BreakFacts") -> str: return broken.screen_text if self.screen_observed(broken): return self.screen_default + if getattr(broken, "not_ready", False): + return "never reached: the run stopped before its first click" return self.screen_unread def screen_line(self, broken: "BreakFacts") -> str: @@ -125,6 +127,14 @@ def verdict(self, broken: "BreakFacts") -> str: def why_line(self, broken: "BreakFacts") -> str: if not broken.stopped: return "OpenAdapt did not stop. Treat this build as broken." + if getattr(broken, "not_ready", False) and not broken.stop_attributed: + # Stopped before the first click: say why in plain words rather + # than that this act's check didn't run. + return getattr(broken, "explanation", "") or ( + "OpenAdapt stopped before its first click because the screen " + "never finished drawing, so this run doesn't reach the save. " + "Nothing was saved." + ) if not broken.stop_attributed: if broken.new_records: return ( diff --git a/openadapt/quickstart/story.py b/openadapt/quickstart/story.py index 78bac2054b..a7af623978 100644 --- a/openadapt/quickstart/story.py +++ b/openadapt/quickstart/story.py @@ -297,12 +297,21 @@ def finished(run: RunFacts) -> None: engine.run_all(inputs, finished) outcome.act2_seconds = clock() - act_start view.runs_total(outcome) + # A run that stopped before its first click, even on its second try, + # never reached the save. Say why in plain words; when no run got a + # ready screen, Act 3 would only stop the same way, so it is skipped. + unready = [run for run in outcome.runs if run.not_ready] + skip_break = bool(outcome.runs) and len(unready) == len(outcome.runs) + if unready: + note = getattr(view, "not_ready", None) + if note is not None: + note(unready[0].explanation, break_it and skip_break) # Sign the checked runs' reports while Act 3 runs; the finale waits. sealing = _in_background(lambda: engine.seal(list(outcome.runs))) # Act 3: break it. paging = None - if break_it: + if break_it and not skip_break: view.act(3, "Break it", scene.act3_subtitle) view.break_setup() if interactive: diff --git a/openadapt/quickstart/view.py b/openadapt/quickstart/view.py index 37c230da43..eede4f7a84 100644 --- a/openadapt/quickstart/view.py +++ b/openadapt/quickstart/view.py @@ -15,7 +15,6 @@ from __future__ import annotations import contextlib -import io import os import sys import time @@ -49,6 +48,37 @@ MORE_COMMAND = "quickstart --more" #: The pause before each read-back field ticks, on a live terminal only. _TICK_S = 0.08 +#: The widest the live view draws, in columns. Rules, panels and step lines +#: stop here in a wide window, so a timing stays next to its row. +MAX_WIDTH = 100 +#: Terminals that make OSC 8 hyperlinks clickable, by ``TERM_PROGRAM``. +_HYPERLINK_PROGRAMS = frozenset( + {"iTerm.app", "WezTerm", "vscode", "ghostty", "Hyper", "Tabby", "rio"} +) + + +def hyperlinks_supported(environ: Optional[Mapping[str, str]] = None) -> bool: + """True when this terminal makes OSC 8 hyperlinks clickable. + + Elsewhere (Terminal.app among them) a link is printed as its ``file://`` + address, which those terminals make clickable themselves. + """ + + env = os.environ if environ is None else environ + if env.get("TMUX") or env.get("STY"): + return False + if env.get("TERM_PROGRAM", "") in _HYPERLINK_PROGRAMS: + return True + if env.get("KITTY_WINDOW_ID") or env.get("WT_SESSION"): + return True + if env.get("TERM", "") in ("xterm-kitty", "xterm-ghostty", "foot"): + return True + if env.get("KONSOLE_VERSION") or env.get("DOMTERM"): + return True + try: + return int(env.get("VTE_VERSION", "0")) >= 5000 + except ValueError: + return False # --------------------------------------------------------------------------- @@ -83,13 +113,25 @@ def compiled_line(outcome: Outcome, scene: Scene = MOCKMED) -> str: return scene.compiled_line(outcome.program_steps) +#: A run's status when it stopped before its first click. +NOT_READY_STATUS = "Stopped before its first click" + + def run_status(run: RunFacts, marks: Marks, scene: Scene = MOCKMED) -> str: if run.checked: again = " (on a second try)" if run.repeated else "" return f"{marks.ok} {scene.checked_in}{again}" + if run.not_ready: + return f"{marks.stop} {NOT_READY_STATUS}" return f"{marks.stop} {run.plain_label or run.execution_outcome}" +def skipped_break_line(scene: Scene = MOCKMED) -> str: + """Why Act 3 didn't run when no run got a ready screen.""" + + return f"Skipped the last part ({scene.break_title.lower()}): it would stop the same way." + + def runs_total_line(outcome: Outcome, marks: Marks) -> str: dot = f" {marks.dot} " return dot.join( @@ -566,6 +608,11 @@ def runs_total(self, outcome: Outcome) -> None: self._say(f" {self.marks.ok} {name:<{width}} {value}") self._say(f" {clean_footer(outcome, self.marks)}") + def not_ready(self, explanation: str, skipped_break: bool) -> None: + self._say(f" {explanation}") + if skipped_break: + self._say(f" {skipped_break_line(self.scene)}") + def break_setup(self) -> None: self._say(f" {self.scene.break_setup}") @@ -724,14 +771,19 @@ def __init__( ) -> None: from rich.console import Console - from openadapt.quickstart.images import detect_image_protocol + from openadapt.quickstart.images import image_protocol self.console = console or Console( file=stream, highlight=False, soft_wrap=False, width=width ) + if width is None and console is None and self.console.width > MAX_WIDTH: + self.console.width = MAX_WIDTH self.scene = scene self.marks = Marks(getattr(stream, "encoding", None) or "utf-8") - self.image_protocol = detect_image_protocol(environ, isatty=True) + # Only a real terminal is asked about images: the query is written + # to the controlling terminal, which a stand-in stream isn't. + self.image_protocol = image_protocol(environ, isatty=_real_tty(stream)) + self.hyperlinks = hyperlinks_supported(environ) if animate is None: isatty = getattr(stream, "isatty", None) animate = bool(callable(isatty) and isatty() and self.console.is_terminal) @@ -782,17 +834,19 @@ def _step_line( ) -> None: from rich.table import Table - grid = Table.grid(padding=(0, 1), expand=True) + # Not expanded: the timing follows its row's text instead of sitting + # at the window's right edge. + grid = Table.grid(padding=(0, 1)) grid.add_column(width=2, no_wrap=True) - grid.add_column(ratio=1) - grid.add_column(justify="right", no_wrap=True) + grid.add_column() + grid.add_column(no_wrap=True) text = f"[bold]{_escape(title)}[/]" if detail: text += f" [dim]{_escape(detail)}[/]" grid.add_row( f"[{style}]{mark}[/]", text, - f"[dim]{seconds(took)}[/]" if took is not None else "", + f"[dim] {seconds(took)}[/]" if took is not None else "", ) self.console.print(grid) @@ -802,10 +856,15 @@ def _flush_ready(self) -> None: self._ready = None def _link(self, path: Path, text: str) -> str: + """A clickable link to ``path``: an OSC 8 hyperlink showing ``text`` + where the terminal supports one, else the ``file://`` address.""" + try: uri = path.resolve().as_uri() except ValueError: return _escape(text) + if not self.hyperlinks: + return _escape(uri) return f"[link={uri}]{_escape(text)}[/link]" # -- the story -------------------------------------------------------- @@ -894,7 +953,11 @@ def _run_text(self, run: RunFacts) -> str: status = "checked" + (" on a second try" if run.repeated else "") else: mark = f"[red]{self.marks.stop}[/]" - status = run.plain_label or run.execution_outcome + status = ( + NOT_READY_STATUS + if run.not_ready + else run.plain_label or run.execution_outcome + ) return ( f" {mark} {_escape(run.note):<{_LABEL_WIDTH - 6}} " f"[dim]{_escape(status)} {seconds(run.seconds)}[/]" @@ -1035,6 +1098,11 @@ def card(shown: int) -> Any: else: self.console.print(card(len(rows))) + def not_ready(self, explanation: str, skipped_break: bool) -> None: + self.console.print(f"[yellow]{_escape(explanation)}[/]") + if skipped_break: + self.console.print(f"[dim]{_escape(skipped_break_line(self.scene))}[/]") + def break_setup(self) -> None: self._step_line( self.marks.arrow, @@ -1056,11 +1124,12 @@ def breaking(self): return self._spinning(self.scene.break_title, self.scene.breaking) def break_result(self, broken: BreakFacts) -> None: - drawn = False + # The screen and the record as text, in every terminal; the + # screenshot is drawn under them only where the terminal answered + # for an image protocol. + self._side_by_side(broken) if self.image_protocol and broken.screenshot is not None: - drawn = self._draw_beside_screenshot(broken, self._record_lines(broken)) - if not drawn: - self._side_by_side(broken) + self._draw_screenshot(broken) self._pause(0.25) self._verdicts(broken) @@ -1072,12 +1141,6 @@ def _record_text(self, broken: BreakFacts) -> str: return f"[bold red]{self.marks.no} {line}[/]" return f"[bold]{line}[/]" - def _record_lines(self, broken: BreakFacts) -> list[str]: - return [ - f"[bold]{_escape(self.scene.record_title)}[/]", - self._record_text(broken), - ] - def _side_by_side(self, broken: BreakFacts) -> None: from rich.panel import Panel from rich.table import Table @@ -1145,20 +1208,18 @@ def _verdicts(self, broken: BreakFacts) -> None: self.console.print() self.console.print(_escape(aha)) - def _draw_beside_screenshot(self, broken: BreakFacts, right: list[str]) -> bool: + def _draw_screenshot(self, broken: BreakFacts) -> bool: from openadapt.quickstart.images import beside_image, crop_png, image_sequence try: png = crop_png(broken.screenshot, self.scene.screen_crop) - except Exception: # noqa: BLE001 - fall back to the text boxes + except Exception: # noqa: BLE001 - the text above already says it return False cols, rows = 40, 10 - rendered = [self._ansi(line) for line in right] - self.console.print() - self.console.print("[bold]The screen[/] [dim](its screenshot)[/]") + self.console.print("[dim]The screen's screenshot:[/]") block = beside_image( image_sequence(png, self.image_protocol, cols=cols, rows=rows), - rendered, + [], indent=3, cols=cols, rows=rows, @@ -1167,19 +1228,6 @@ def _draw_beside_screenshot(self, broken: BreakFacts, right: list[str]) -> bool: self.console.file.flush() return True - def _ansi(self, markup: str) -> str: - from rich.console import Console - - buffer = io.StringIO() - Console( - file=buffer, - force_terminal=True, - color_system=self.console.color_system, - width=200, - highlight=False, - ).print(markup, end="") - return buffer.getvalue() - def _seal_emblem(self, card: Optional[SealCard], steps: int) -> str: """One pip per program step; the save, read back, is the diamond.""" @@ -1213,20 +1261,31 @@ def _seal(self, outcome: Outcome, card: Optional[SealCard]) -> None: padding=(1, 3), ) ) + page = outcome.seal_pages.verified + if page is not None and not self.hyperlinks: + # The terminal makes plain addresses clickable, not OSC 8 links: + # print the file:// address on one line it may wrap but never + # breaks, so the whole address stays one link. + self.console.print( + f"[bold]Open it[/] [bold cyan]{self._link(page, '')}[/]", + soft_wrap=True, + ) links = Table.grid(padding=(0, 2)) links.add_column(no_wrap=True) links.add_column(overflow="fold") - page = outcome.seal_pages.verified if page is not None: - links.add_row( - "[bold]Open it[/]", - f"[bold cyan]{self._link(page, str(display_path(page)))}[/]", - ) + if self.hyperlinks: + links.add_row( + "[bold]Open it[/]", + f"[bold cyan]{self._link(page, str(display_path(page)))}[/]", + ) links.add_row("", f"[dim]{_escape(seal_page_note(outcome))}[/]") - links.add_row( - "[dim]Real Seals[/]", - f"[cyan][link={REAL_SEALS_URL}]{REAL_SEALS_URL}[/link][/]", + real = ( + f"[link={REAL_SEALS_URL}]{REAL_SEALS_URL}[/link]" + if self.hyperlinks + else REAL_SEALS_URL ) + links.add_row("[dim]Real Seals[/]", f"[cyan]{real}[/]") self.console.print(links) def finale(self, outcome: Outcome, steps: NextSteps) -> None: @@ -1290,6 +1349,13 @@ def detail(self, lines: list[str]) -> None: self.console.print(f" [dim]{_escape(line)}[/]") +def _real_tty(stream: IO[str]) -> bool: + try: + return os.isatty(stream.fileno()) + except (AttributeError, OSError, ValueError): + return False + + def _escape(text: str) -> str: from rich.markup import escape diff --git a/openadapt/seal_publish.py b/openadapt/seal_publish.py index 1fc232374a..e2513db08c 100644 --- a/openadapt/seal_publish.py +++ b/openadapt/seal_publish.py @@ -303,6 +303,41 @@ def card_text(doc: Mapping[str, Any]) -> str: ) +def _shown_path(path: Path) -> Path: + """``path`` relative to the current folder when it is inside it.""" + try: + return path.resolve().relative_to(Path.cwd().resolve()) + except ValueError: + return path + + +#: The answers to the publish question that print the full card first. +SHOW_ANSWERS = ("show", "s", "--show") + + +def card_summary(doc: Mapping[str, Any], path: Path) -> str: + """Four short lines on what the card holds, for the quickstart's question. + + ``path`` is the ``public-seal.json`` with the exact bytes; answering + ``show`` prints the full card before the question is asked again. + """ + card = doc.get("card") or {} + facts = [ + str(card.get("program_name") or "unnamed program"), + str(card.get("outcome") or "unknown outcome"), + f"{card.get('steps_ok', '?')} of {card.get('steps_total', '?')} steps", + f"{card.get('model_calls', '?')} model calls", + ] + return "\n".join( + [ + " " + " \u00b7 ".join(facts), + " Also: the step strip, check counts, digests and the hour it ran", + " Not included: inputs, typed values, screenshots or record contents", + f' Full JSON: {path} (type "show" to print it)', + ] + ) + + # -- publishing --------------------------------------------------------------- @@ -568,12 +603,17 @@ def publish( say: Callable[[str], None] = print, transport: Optional[Transport] = None, command: Callable[[str], str] = lambda rest: f"openadapt {rest}", + brief: bool = False, ) -> Optional[str]: """Build, show, ask, upload. Returns the link, or None when nothing was sent. The exact card is always printed before anything is asked or sent; ``yes`` skips the question, never the card. Raises :class:`PublishError` with an exit code for each refusal. + + ``brief`` (the quickstart's question) prints :func:`card_summary` and the + path of the exact bytes instead; answering ``show`` at the question + prints the full card and asks again. It never applies with ``yes``. """ run_dir = Path(run_dir) origin = endpoint(endpoint_value) @@ -583,7 +623,22 @@ def publish( say(f"To take it down: {command(f'seal unpublish {_quote(run_dir)}')}") return str(existing["url"]) doc = build(run_dir, names=names, github=github, provenance=provenance) - say(card_text(doc)) + brief = brief and not yes and not dry_run + say( + card_summary(doc, _shown_path(run_dir / "public-seal.json")) + if brief + else card_text(doc) + ) + if brief: + plain_ask = ask + + def ask(prompt: str) -> str: + while True: + answer = plain_ask(prompt) + if answer.strip().lower() not in SHOW_ANSWERS: + return answer + say(card_text(doc)) + if dry_run: say(f"Dry run: wrote {run_dir / 'public-seal.json'}. Nothing was uploaded.") return None @@ -616,6 +671,7 @@ def publish( "Response", "Transport", "build", + "card_summary", "card_text", "check_link", "consent", diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 7338bb09bf..be35696296 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -67,6 +67,13 @@ browser dialog is retried instead of failing the recording or run. - A click on a `