Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions openadapt/quickstart/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ def build(outcome: Outcome) -> NextSteps:
return NextSteps(
verify=verify,
verify_run=lambda run_dir: hint(f"verify {quote(display_path(run_dir))}"),
record=hint(
f"flow record --backend web --url {YOUR_APP_URL} --out my-task"
),
record=hint(f"record --backend web --url {YOUR_APP_URL} --out my-task"),
agent=agent,
keep=keep,
shadow=shadow() if shadow is not None else None,
Expand Down
14 changes: 13 additions & 1 deletion openadapt/quickstart/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,19 +428,28 @@ def __init__(self, root: Path, *, visible: bool, pace_s: float = 0.0) -> None:
self._base_url: Optional[str] = None
self._pool: Any = None
self._starter: Any = None
self._progress: Callable[[str, bool], None] = lambda _text, _milestone: None

# -- lifetime ---------------------------------------------------------

def __enter__(self) -> "FlowEngine":
def set_progress(self, progress: Callable[[str, bool], None]) -> None:
"""Report startup stages while the runtime and browser come up."""
self._progress = progress

def _start_runtime(self) -> "FlowEngine":
self._progress("[1/4] Loading OpenAdapt runtime", True)
from openadapt_flow import _prewarm
from openadapt_flow.backends._browser_process import shared_browser
from openadapt_flow.mockmed.fault_server import serve

# Load OCR while the browser starts; compiling and every run use it.
self._progress("[2/4] Prewarming OCR engine", True)
_prewarm.start()
self.root.mkdir(parents=True, exist_ok=True)
try:
self._progress("[3/4] Starting browser engine", True)
self._stack.enter_context(shared_browser(headless=not self.visible))
self._progress("[4/4] Starting synthetic clinic app", True)
base_url, _db, stop = serve()
self._stack.callback(stop)
except BaseException:
Expand All @@ -449,6 +458,9 @@ def __enter__(self) -> "FlowEngine":
self._base_url = base_url
return self

def __enter__(self) -> "FlowEngine":
return self._start_runtime()

def __exit__(self, *exc: object) -> None:
self._stack.close()

Expand Down
7 changes: 7 additions & 0 deletions openadapt/quickstart/story.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@

#: The placeholder app address in the "try it on your own app" command.
YOUR_APP_URL = "https://your-app.example"
#: One-line Python drop-in for Playwright/CUA agents via ``openadapt-verify``.
VERIFY_SNIPPET = (
'with checked_write("verify.yaml", values): ... # from openadapt_verify'
)
#: Where the finale points for Seals of real runs, after the person's own.
REAL_SEALS_URL = "https://openadapt.ai/seals"

Expand Down Expand Up @@ -102,6 +106,8 @@ class NextSteps:
verify: Optional[str]
record: str
agent: str
#: One-line drop-in snippet for Playwright/CUA scripts (``openadapt-verify``).
verify_snippet: str = VERIFY_SNIPPET
#: Under ``uvx`` only: the command that installs this version for good.
keep: Optional[str] = None
#: Under ``uvx`` only: a warning when the shell's ``openadapt`` is another
Expand Down Expand Up @@ -410,6 +416,7 @@ def _act1_subtitle(visible: bool, scene: Scene = MOCKMED) -> str:


__all__ = [
"VERIFY_SNIPPET",
"YOUR_APP_URL",
"display_path",
"Engine",
Expand Down
18 changes: 18 additions & 0 deletions openadapt/quickstart/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,15 @@ def next_step(steps: NextSteps) -> tuple[str, str, str]:
)


def bridge_lines(steps: NextSteps) -> list[tuple[str, str]]:
"""Bridge from the synthetic demo to the user's own app and agent scripts."""

lines = [("Your own app", steps.record)]
if steps.verify_snippet:
lines.append(("Playwright/CUA drop-in", steps.verify_snippet))
return lines


def failure_step(outcome: Outcome) -> tuple[str, str]:
"""When something didn't check out: the report to read first."""

Expand Down Expand Up @@ -434,6 +443,11 @@ def more_lines(steps: NextSteps, root: Path, seal_page: Optional[Path]) -> list[
f"{title} (any MCP client): {steps.agent}",
f"Try it on your own app: {steps.record}",
]
if steps.verify_snippet:
lines.append(
f"Verify Playwright/CUA writes (pip install openadapt-verify): "
f"{steps.verify_snippet}"
)
if steps.verify:
lines.append(f"Check every receipt again: {steps.verify}")
if seal_page is not None:
Expand Down Expand Up @@ -691,6 +705,8 @@ def finale(self, outcome: Outcome, steps: NextSteps) -> None:
self._say(f"Next: {title}")
self._say(f" {command}")
self._say(f" {other}")
for label, value in bridge_lines(steps):
self._say(f" {label}: {value}")
else:
title, path = failure_step(outcome)
self._say(f"Next: {title}")
Expand Down Expand Up @@ -1335,6 +1351,8 @@ def say(line: str) -> None:
soft_wrap=True,
)
self.console.print(f"[dim]{_escape(other)}[/]")
for label, value in bridge_lines(steps):
self.console.print(f"[dim]{_escape(label)}:[/] {_escape(value)}")
else:
title, path = failure_step(outcome)
self.console.print(f"[bold red]Next[/] [bold]{_escape(title)}[/]")
Expand Down
2 changes: 2 additions & 0 deletions tests/snapshots/quickstart_openemr_plain.snapshot
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,7 @@ Your receipt: Signed
Next: Give your agent this task as a tool
claude mcp add openadapt -- openadapt agent serve --bundles openadapt-quickstart/bundle
Any other MCP client: openadapt agent serve --bundles openadapt-quickstart/bundle
Your own app: openadapt record --backend web --url https://your-app.example --out my-task
Playwright/CUA drop-in: with checked_write("verify.yaml", values): ... # from openadapt_verify
More next steps: openadapt quickstart --more
Done in 2.5s. Reports: openadapt-quickstart, one REPORT.md per run
2 changes: 2 additions & 0 deletions tests/snapshots/quickstart_plain.snapshot
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,7 @@ Your receipt: Signed
Next: Give your agent this task as a tool
claude mcp add openadapt -- openadapt agent serve --allow-run
Any other MCP client: openadapt agent serve --allow-run
Your own app: openadapt record --backend web --url https://your-app.example --out my-task
Playwright/CUA drop-in: with checked_write("verify.yaml", values): ... # from openadapt_verify
More next steps: openadapt quickstart --more
Done in 2.5s. Reports: openadapt-quickstart, one REPORT.md per run; side by side: openadapt-quickstart/index.html
107 changes: 97 additions & 10 deletions tests/test_quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,14 @@ def test_finale_has_one_next_step_and_the_rest_behind_more(root):
" claude mcp add openadapt -- openadapt agent serve --allow-run"
)
assert sum(1 for line in finale if line.startswith("Next: ")) == 1
assert "flow record" not in output
assert (
" Your own app: openadapt record --backend web --url "
"https://your-app.example --out my-task" in finale
)
assert (
' Playwright/CUA drop-in: with checked_write("verify.yaml", values): ...'
" # from openadapt_verify" in finale
)
assert "More next steps: openadapt quickstart --more" in finale
assert sum(1 for line in finale if line.startswith("Done in ")) == 1

Expand All @@ -343,10 +350,9 @@ def test_more_lists_every_other_next_step(root):
"openadapt -- openadapt agent serve --allow-run"
)
joined = "\n".join(lines)
assert "Try it on your own app: openadapt flow record --backend web" in joined
assert (
"Check every receipt again: openadapt verify openadapt-quickstart" in joined
)
assert "Try it on your own app: openadapt record --backend web" in joined
assert 'checked_write("verify.yaml", values)' in joined
assert "Check every receipt again: openadapt verify openadapt-quickstart" in joined
assert "Open your receipt (offline): openadapt-quickstart/run-1/seal.html" in joined
assert "https://openadapt.ai/seals" in joined

Expand Down Expand Up @@ -503,7 +509,8 @@ def test_the_finale_names_the_persons_own_seal_then_the_real_ones(root):
"offline; nothing is uploaded"
)
assert (
finale[at + 2] == " Real receipts from OpenEMR runs: https://openadapt.ai/seals"
finale[at + 2]
== " Real receipts from OpenEMR runs: https://openadapt.ai/seals"
)
# The person's own Seal opens; the side-by-side page does not.
assert opened == [root / "run-1" / "seal.html"]
Expand Down Expand Up @@ -718,14 +725,14 @@ def test_terminal_finale_is_short_with_every_optional_line(root, monkeypatch):
outcome.runs = [_run(root, index) for index in range(1, 6)]
steps = NextSteps(
verify="openadapt seal verify qs",
record="openadapt flow record",
record="openadapt record --backend web --url https://your-app.example --out my-task",
agent="openadapt agent serve --allow-run",
keep="uv tool install --python 3.12 openadapt",
shadow="Your shell's openadapt is 1.5.1 at /opt/x; the commands above use uvx.",
)
RichView(stream, environ={}, width=110, animate=False).finale(outcome, steps)
lines = [line for line in _visible(stream.getvalue()).splitlines() if line.strip()]
assert len(lines) <= 20, lines
assert len(lines) <= 22, lines
assert lines[-1].startswith("Your shell's openadapt is 1.5.1")
assert "uv tool install" not in "\n".join(lines)

Expand All @@ -747,7 +754,8 @@ def test_terminal_view_tells_the_story_with_boxes_and_one_next_step(root):
assert "◆ Your receipt" in text and "●─●─●─●─●─◆" in text
assert "claude mcp add openadapt -- openadapt agent serve --allow-run" in text
assert text.count("Next ") == 1
assert "flow record" not in text
assert "Your own app: openadapt record --backend web" in text
assert 'Playwright/CUA drop-in: with checked_write("verify.yaml", values)' in text
assert "\x1b]1337;" not in output and "\x1b_G" not in output


Expand Down Expand Up @@ -952,7 +960,11 @@ def test_no_key_is_created_under_the_opt_out(root, monkeypatch, tmp_path):
({"LC_TERMINAL": "iTerm2"}, True, ITERM2),
# WezTerm drew blank rows for the iTerm2 protocol: text unless asked.
({"TERM_PROGRAM": "WezTerm"}, True, None),
({"TERM_PROGRAM": "WezTerm", "OPENADAPT_INLINE_IMAGES": "iterm2"}, True, ITERM2),
(
{"TERM_PROGRAM": "WezTerm", "OPENADAPT_INLINE_IMAGES": "iterm2"},
True,
ITERM2,
),
({"KITTY_WINDOW_ID": "3"}, True, KITTY),
({"TERM": "xterm-kitty"}, True, KITTY),
({"TERM_PROGRAM": "ghostty"}, True, KITTY),
Expand Down Expand Up @@ -1308,3 +1320,78 @@ def test_a_captured_stream_never_opens_the_seal_page():
assert quickstart._shown(io.StringIO(), lambda: True) is False
assert quickstart._shown(_Terminal(), lambda: True) is True
assert quickstart._shown(_Terminal(), lambda: False) is False


def test_flow_engine_reports_four_startup_stages(tmp_path, monkeypatch):
"""FlowEngine emits [1/4]..[4/4] startup milestones so cold starts stay transparent."""

import contextlib
import types

from openadapt.quickstart.engine import FlowEngine

stopped = []
prewarm_mod = types.ModuleType("openadapt_flow._prewarm")
prewarm_mod.start = lambda: None # type: ignore[attr-defined]
browser_mod = types.ModuleType("openadapt_flow.backends._browser_process")
browser_mod.shared_browser = ( # type: ignore[attr-defined]
lambda *, headless: contextlib.nullcontext()
)
fault_mod = types.ModuleType("openadapt_flow.mockmed.fault_server")
fault_mod.serve = lambda: ( # type: ignore[attr-defined]
"http://127.0.0.1:9999",
None,
lambda: stopped.append(True),
)

flow_pkg = types.ModuleType("openadapt_flow")
flow_pkg._prewarm = prewarm_mod # type: ignore[attr-defined]
backends_pkg = types.ModuleType("openadapt_flow.backends")
mockmed_pkg = types.ModuleType("openadapt_flow.mockmed")

for name, mod in (
("openadapt_flow", flow_pkg),
("openadapt_flow._prewarm", prewarm_mod),
("openadapt_flow.backends", backends_pkg),
("openadapt_flow.backends._browser_process", browser_mod),
("openadapt_flow.mockmed", mockmed_pkg),
("openadapt_flow.mockmed.fault_server", fault_mod),
):
monkeypatch.setitem(sys.modules, name, mod)

seen: list[tuple[str, bool]] = []
stream = io.StringIO()
view = PlainView(stream)

def record_progress(text: str, milestone: bool) -> None:
seen.append((text, milestone))
view.setup_progress(text, milestone)

engine = FlowEngine(tmp_path / "qs", visible=False)
engine.set_progress(record_progress)
engine._start_runtime()
try:
assert engine._base_url == "http://127.0.0.1:9999"
finally:
engine.__exit__(None, None, None)

assert [m for _, m in seen] == [True, True, True, True]
assert [t.split(" ", 1)[0] for t, _ in seen] == ["[1/4]", "[2/4]", "[3/4]", "[4/4]"]
rendered = stream.getvalue()
assert "[1/4] Loading OpenAdapt runtime" in rendered
assert "[4/4] Starting synthetic clinic app" in rendered
assert stopped == [True]


def test_next_steps_bridge_uses_record_and_checked_write(root):
uvx_steps = next_steps(
lambda rest: f"uvx --python 3.12 openadapt@latest {rest}",
cli._shell_quote,
True,
)(Outcome(root=root))
assert (
uvx_steps.record
== "uvx --python 3.12 openadapt@latest record --backend web --url "
"https://your-app.example --out my-task"
)
assert 'checked_write("verify.yaml", values)' in uvx_steps.verify_snippet