Skip to content

The agent that grows with you

feat(onboarding): first-run onboarding beats, run record and words as pure modules

alt-glitchf854ebac2f37
diff --git a/agent/onboarding_flow.py b/agent/onboarding_flow.py
new file mode 100644
index 00000000000..a9edb9af435
--- /dev/null
+++ b/agent/onboarding_flow.py
@@ -0,0 +1,337 @@
+"""First-run onboarding as data: the beats, the run record, and how each event moves the record.
+
+Pure: no I/O, no clock. ``apply(record, event, facts, now=...)`` returns the next record, the result
+the model reads, and the key of the reminder that rides on it (``agent/onboarding_text.py`` renders
+it). The record is stored by ``agent/onboarding_record.py``; ``tools/setup_beat_tool.py`` drives it.
+"""
+
+from __future__ import annotations
+
+import copy
+from collections.abc import Callable, Mapping
+from dataclasses import asdict, dataclass, field
+from typing import Any
+
+PENDING, SHOWN, DONE, SKIPPED = "pending", "shown", "done", "skipped"
+ONBOARDING, COMPLETE, PHASE_SKIPPED = "onboarding", "complete", "skipped"
+CARD_TIMEOUT_S = 300
+# Fallback end: no onboarding change for this long after the build card was reached.
+QUIET_COMPLETE_S = 30 * 60
+MAX_PLUGINS = 5
+
+LAYOUT_OPTIONS = ({"id": "sidebar-left", "label": "Basic"}, {"id": "terminal-deck", "label": "Elite"})
+TOUR_OPTIONS = ({"id": "quick", "label": "Quick tour"}, {"id": "full", "label": "Show me everything"},
+ {"id": "skip", "label": "Skip, let's build something"})
+
+
+@dataclass(frozen=True)
+class Facts:
+ """The safe facts (class A) one run is built from. ``full_name`` reaches only the name card; it is
+ never stored in the record or put in a result."""
+
+ os: str # macos | windows | linux
+ arch: str = ""
+ machine_kind: str = "computer" # Mac | PC | Spark | computer
+ nvidia_platform: str | None = None # rtx_spark | dgx_spark | discrete
+ facts_source: str = "local" # local | remote: whose computer these facts describe
+ locale: str | None = None
+ plugins: tuple[str, ...] = () # onboarding catalog plugins this OS runs
+ tours: bool = True
+ full_name: str | None = field(default=None, compare=False)
+
+ def stored(self) -> dict:
+ data = asdict(self)
+ data.pop("full_name")
+ data["plugins"] = list(self.plugins)
+ return data
+
+ @classmethod
+ def from_stored(cls, data: Mapping[str, Any]) -> Facts:
+ known = {key: data[key] for key in cls.__dataclass_fields__ if key in data and key != "full_name"}
+ return cls(**{**known, "plugins": tuple(known.get("plugins") or ())})
+
+
+# ── events ────────────────────────────────────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class Shown:
+ beat: str
+ tool_call_id: str = ""
+
+
+@dataclass(frozen=True)
+class Answered:
+ beat: str
+ answer: Mapping[str, Any]
+
+
+@dataclass(frozen=True)
+class Said:
+ beat: str
+ text: str
+
+
+@dataclass(frozen=True)
+class TimedOut:
+ beat: str
+
+
+@dataclass(frozen=True)
+class Recorded:
+ beat: str
+ value: str
+
+
+@dataclass(frozen=True)
+class Skipped:
+ beat: str
+
+
+@dataclass(frozen=True)
+class SkipAll:
+ pass
+
+
+@dataclass(frozen=True)
+class Done:
+ pass
+
+
+@dataclass(frozen=True)
+class Applied:
+ """A general tool's result during the run: ``set_theme``, ``manage_connections`` display, ``gui_tour``."""
+
+ tool: str
+ args: Mapping[str, Any]
+ result: Mapping[str, Any]
+
+
+Event = Shown | Answered | Said | TimedOut | Recorded | Skipped | SkipAll | Done | Applied
+
+
+@dataclass(frozen=True)
+class Step:
+ record: dict
+ result: dict
+ reminder: str = ""
+
+
+# ── beats ─────────────────────────────────────────────────────────────────────────────────────
+
+
+def build_options(facts: Facts, picks: Mapping[str, Any]) -> list[dict]:
+ """Two tasks that fit the facts and picks, then the three fixed rows."""
+ installed, connected = set(picks.get("installed") or ()), list(picks.get("connected") or ())
+ tasks = [
+ ("games", "Set up my games and streaming", facts.os == "windows" and facts.nvidia_platform == "discrete"),
+ ("blender", "Help me make something in Blender", "blender" in installed),
+ ("brief", "A daily brief from my apps", bool(connected)),
+ ("week", "A summary of my week", True),
+ ("scan", f"Look around this {facts.machine_kind} and suggest something", True),
+ ]
+ rows = [{"id": task_id, "label": label} for task_id, label, fits in tasks if fits][:2]
+ return [*rows, {"id": "mind", "label": "I have something in mind"},
+ {"id": "machine", "label": f"Help me set up this {facts.machine_kind}"},
+ {"id": "together", "label": "Let's figure it out together"}]
+
+
+def _option_ids(options) -> tuple[str, ...]:
+ return tuple(option["id"] for option in options)
+
+
+@dataclass(frozen=True)
+class Beat:
+ """``card`` is the beat's data for the desktop; ``when`` false skips the beat on this machine;
+ ``picks`` are the answer keys recorded; ``value`` is the pick a ``value`` given in words sets
+ (None: the beat takes no value, it is only marked done); ``values`` lists the accepted ids."""
+
+ id: str
+ card: Callable[[Facts, Mapping], dict]
+ picks: tuple[str, ...]
+ value: str | None = None
+ values: Callable[[Facts, Mapping], tuple[str, ...]] | None = None
+ when: Callable[[Facts, Mapping], bool] = lambda facts, picks: True
+
+ def after(self, picks: Mapping[str, Any]) -> str:
+ """Reminder key for the result that settles this beat."""
+ if self.id in ("tour", "build") and picks.get(self.id):
+ return f"{self.id}_{picks[self.id]}"
+ return f"after_{self.id}"
+
+
+BEATS: tuple[Beat, ...] = (
+ Beat("name", lambda facts, picks: {}, picks=("name",), value="name"),
+ Beat("theme", lambda facts, picks: {"picker": "accent"}, picks=("accent", "mode"), value="accent"),
+ Beat("layout", lambda facts, picks: {"options": list(LAYOUT_OPTIONS)}, picks=("layout",), value="layout",
+ values=lambda facts, picks: _option_ids(LAYOUT_OPTIONS)),
+ Beat("connectors", lambda facts, picks: {}, picks=("connected", "newly_connected")),
+ Beat("plugins", lambda facts, picks: {"plugins": list(facts.plugins[:MAX_PLUGINS])}, picks=("installed",),
+ when=lambda facts, picks: bool(facts.plugins)),
+ Beat("tour", lambda facts, picks: {"options": list(TOUR_OPTIONS)}, picks=("tour",), value="tour",
+ values=lambda facts, picks: _option_ids(TOUR_OPTIONS), when=lambda facts, picks: facts.tours),
+ Beat("build", lambda facts, picks: {"options": build_options(facts, picks)}, picks=("build",), value="build",
+ values=lambda facts, picks: _option_ids(build_options(facts, picks))),
+)
+BEAT_BY_ID = {beat.id: beat for beat in BEATS}
+BEAT_IDS = tuple(BEAT_BY_ID)
+
+
+def new_record(facts: Facts, *, now: float = 0.0) -> dict:
+ record = {
+ "phase": ONBOARDING, "beats": {beat.id: PENDING for beat in BEATS}, "waiting": None,
+ "picks": {"name": None, "accent": None, "mode": None, "layout": None, "connected": [],
+ "newly_connected": [], "installed": [], "tour": None, "build": None},
+ "look_around": "not_offered", "facts": facts.stored(), "ended_by": None,
+ "started_at": now, "updated_at": now,
+ }
+ return _settle_unfit(record, facts)
+
+
+def _settle_unfit(record: dict, facts: Facts) -> dict:
+ for beat in BEATS:
+ if record["beats"][beat.id] == PENDING and not beat.when(facts, record["picks"]):
+ record["beats"][beat.id] = SKIPPED
+ return record
+
+
+def next_beat(record: Mapping[str, Any]) -> str | None:
+ """The first beat still pending or shown; None when every beat is settled."""
+ return next((beat for beat in BEAT_IDS if record["beats"][beat] in (PENDING, SHOWN)), None)
+
+
+def is_active(record: Mapping[str, Any] | None) -> bool:
+ return bool(record) and record.get("phase") == ONBOARDING
+
+
+def expire(record: dict, *, now: float) -> dict:
+ """The quiet-spell fallback: a run whose build card was reached and that has not changed for
+ ``QUIET_COMPLETE_S`` is complete."""
+ if is_active(record) and record["beats"]["build"] != PENDING and now - record["updated_at"] >= QUIET_COMPLETE_S:
+ record = copy.deepcopy(record)
+ record.update(phase=COMPLETE, ended_by="timeout", waiting=None, updated_at=now)
+ return record
+
+
+# ── apply ─────────────────────────────────────────────────────────────────────────────────────
+
+
+def _next_field(record: Mapping[str, Any]) -> str:
+ return next_beat(record) or "done"
+
+
+def _settle(record: dict, beat: str, patch: Mapping[str, Any]) -> None:
+ record["beats"][beat] = DONE
+ record["picks"].update({key: value for key, value in patch.items() if key in BEAT_BY_ID[beat].picks})
+
+
+def _shown(record: dict, event: Shown, facts: Facts, now: float) -> Step:
+ if not BEAT_BY_ID[event.beat].when(facts, record["picks"]):
+ record["beats"][event.beat] = SKIPPED
+ return Step(record, {"beat": event.beat, "skipped": True, "next": _next_field(record)},
+ f"after_{event.beat}")
+ # A later card on screen means the user moved on from an earlier card left open.
+ for earlier in BEAT_IDS[:BEAT_IDS.index(event.beat)]:
+ if record["beats"][earlier] == SHOWN:
+ record["beats"][earlier] = DONE
+ if record["beats"][event.beat] != DONE:
+ record["beats"][event.beat] = SHOWN
+ if event.beat == "connectors" and record["look_around"] == "not_offered":
+ record["look_around"] = "offered"
+ record["waiting"] = {"beat": event.beat, "tool_call_id": event.tool_call_id, "since": now}
+ return Step(record, {})
+
+
+def _answered(record: dict, event: Answered, facts: Facts, now: float) -> Step:
+ record["waiting"] = None
+ _settle(record, event.beat, event.answer)
+ return Step(record, {"beat": event.beat, "answer": dict(event.answer), "next": _next_field(record)},
+ BEAT_BY_ID[event.beat].after(record["picks"]))
+
+
+def _said(record: dict, event: Said, facts: Facts, now: float) -> Step:
+ record["waiting"] = None
+ return Step(record, {"beat": event.beat, "said": event.text}, "said")
+
+
+def _timed_out(record: dict, event: TimedOut, facts: Facts, now: float) -> Step:
+ record["waiting"] = None
+ return Step(record, {"beat": event.beat, "timed_out": True}, "timed_out")
+
+
+def _recorded(record: dict, event: Recorded, facts: Facts, now: float) -> Step:
+ beat = BEAT_BY_ID[event.beat]
+ accepted = beat.values(facts, record["picks"]) if beat.values else None
+ if accepted is not None and event.value not in accepted:
+ return Step(record, {"error": f"value for {event.beat} must be one of: {', '.join(accepted)}.",
+ "next": _next_field(record)})
+ _settle(record, event.beat, {beat.value: event.value} if beat.value else {})
+ return Step(record, {"recorded": event.beat, "next": _next_field(record)}, beat.after(record["picks"]))
+
+
+def _skipped(record: dict, event: Skipped, facts: Facts, now: float) -> Step:
+ record["beats"][event.beat] = SKIPPED
+ return Step(record, {"recorded": event.beat, "skipped": True, "next": _next_field(record)}, "moved_on")
+
+
+def _skip_all(record: dict, event: SkipAll, facts: Facts, now: float) -> Step:
+ record.update(phase=PHASE_SKIPPED, ended_by="skip", waiting=None)
+ for beat in BEAT_IDS:
+ if record["beats"][beat] != DONE:
+ record["beats"][beat] = SKIPPED
+ return Step(record, {"skipped_all": True}, "skip_all")
+
+
+def _done(record: dict, event: Done, facts: Facts, now: float) -> Step:
+ if record["beats"]["build"] == PENDING:
+ return Step(record, {"error": "Onboarding ends after the first build is shown and its close card is "
+ "answered.", "next": _next_field(record)})
+ record["beats"]["build"] = DONE
+ record.update(phase=COMPLETE, ended_by="done", waiting=None)
+ return Step(record, {"completed": True}, "complete")
+
+
+def _applied_beats(event: Applied) -> list[tuple[str, dict]]:
+ """The beats a general tool's result settles, with the picks it recorded."""
+ result, args = event.result, event.args
+ if event.tool == "set_theme":
+ values = result.get("applied") or result.get("picked") or {}
+ theme = {key: values[key] for key in ("accent", "mode") if key in values}
+ settled = [("theme", theme)] if theme else []
+ return [*settled, ("layout", {"layout": values["layout"]})] if values.get("layout") else settled
+ if event.tool == "manage_connections" and args.get("action") == "display" and "connected" in result:
+ return [("connectors", {"connected": list(result.get("connected") or ()),
+ "newly_connected": list(result.get("newly_connected") or ())})]
+ if event.tool == "gui_tour" and args.get("action") == "start" and not result.get("error"):
+ return [("tour", {"tour": args.get("preset") or "full"})]
+ return []
+
+
+def _applied(record: dict, event: Applied, facts: Facts, now: float) -> Step:
+ for beat, patch in _applied_beats(event):
+ _settle(record, beat, patch)
+ return Step(record, {})
+
+
+_HANDLERS: dict[type, Callable[[dict, Any, Facts, float], Step]] = {
+ Shown: _shown, Answered: _answered, Said: _said, TimedOut: _timed_out, Recorded: _recorded,
+ Skipped: _skipped, SkipAll: _skip_all, Done: _done, Applied: _applied,
+}
+_ENDED = "Onboarding is over in this chat; it is a normal chat now."
+
+
+def apply(record: Mapping[str, Any], event: Event, facts: Facts, *, now: float = 0.0) -> Step:
+ """The record after ``event``, the model-facing result, and the reminder key. A finished run
+ refuses every setup_beat event and ignores general tool results."""
+ working = copy.deepcopy(dict(record))
+ if not is_active(working):
+ return Step(working, {} if isinstance(event, Applied) else {"error": _ENDED})
+ step = _HANDLERS[type(event)](working, event, facts, now)
+ if step.record != record:
+ step.record["updated_at"] = now
+ return step
+
+
+def applies_to(tool: str) -> bool:
+ """Whether a general tool's result can settle a beat (the hook's cheap pre-check)."""
+ return tool in ("set_theme", "manage_connections", "gui_tour")
diff --git a/agent/onboarding_text.py b/agent/onboarding_text.py
new file mode 100644
index 00000000000..1b82e275e89
--- /dev/null
+++ b/agent/onboarding_text.py
@@ -0,0 +1,256 @@
+"""The words of first-run onboarding: the scripted greeting, the opening prompt, and the reminder
+that rides on every ``setup_beat`` result. Pure; ``reminder(key, record, facts)`` renders the key
+``agent/onboarding_flow.py::apply`` returns.
+
+The rules for the whole run live in the opening prompt (a hidden user turn, so the system prompt
+stays byte-stable); reminders say only what was picked and what comes next.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any
+
+from agent.onboarding_flow import Facts, next_beat
+
+CHAT_TITLE = "Getting started"
+GREETING = "Hi, I'm Hermes. Let's set things up for you. Then we'll get something cool done."
+
+QUESTIONS = {
+ "name": "What should I call you?",
+ "theme": "Pick a colour.",
+ "layout": "Which layout?",
+ "connectors": "Which apps should I work with?",
+ "plugins": "Want any of these?",
+ "tour": "Want a look around first?",
+ "build": "Know what you'd like me to make?",
+}
+
+_SET_THEME = 'tool_call {"calls":[{"name":"set_theme","arguments":{"accent":"Ultraviolet"}}]}'
+_TOUR_CALL = 'tool_call {"calls":[{"name":"gui_tour","arguments":{"action":"start","preset":"%s"}}]}'
+
+PROFILE_DIMENSIONS = (
+ ("agent experience", "new to AI apps / chat apps only / has used local agents / builds agents"),
+ ("technical depth", "non-developer / tinkerer / developer"),
+ ("creative work", "none / hobby / regular"),
+ ("gaming", "none / casual / enthusiast"),
+ ("local compute", "cloud only / small local models / strong local (Spark, large GPU or unified memory)"),
+ ("work context", "personal / work / mixed"),
+ ("machine role", "daily driver / dedicated AI box / remote server"),
+)
+
+_NVIDIA = {
+ "rtx_spark": "It is an NVIDIA RTX Spark (Windows on Arm), built to run local models.",
+ "dgx_spark": "It is an NVIDIA DGX Spark (Linux on Arm with a GB10), built to run local models.",
+ "discrete": "It has an NVIDIA GPU.",
+}
+
+
+def facts_block(facts: Facts) -> str:
+ whose = ("the computer running Hermes, which is not the one in front of the user"
+ if facts.facts_source == "remote" else "this computer")
+ lines = [f"What you know about {whose}: {facts.os} on {facts.arch or 'an unknown architecture'}, "
+ f"a {facts.machine_kind}."]
+ if facts.nvidia_platform in _NVIDIA:
+ lines.append(_NVIDIA[facts.nvidia_platform])
+ if facts.locale:
+ lines.append(f"Locale: {facts.locale}.")
+ lines.append("Never recite these. A fact that is missing is unknown. When the user says otherwise, "
+ "believe the user.")
+ return " ".join(lines)
+
+
+def opening_prompt(facts: Facts) -> str:
+ """The hidden first turn of the onboarding chat: every rule of the run."""
+ dimensions = "\n".join(f"- {name}: {buckets}" for name, buckets in PROFILE_DIMENSIONS)
+ return f"""[System note: This is the user's first time opening the Hermes desktop app. You run their first-run onboarding in this chat. The beats, in order: their name, the theme (accent colour; light or dark only if they ask), the layout, connectors, plugins, a tour, then the first thing you build for them.
+
+How it works:
+- setup_beat shows a beat's card and waits for the user. setup_beat(beat="next") shows the next beat. Its result carries their answer and a reminder of what to do next. Follow the reminder.
+- Before a card, acknowledge in a few words and at most one more sentence. The card asks its own question and shows its own options: never ask it yourself, never list the options in text.
+- After a pick, say it by its label in three words or fewer. No opinion, no praise, never the same words twice.
+- If they answer in words while a card waits, the card closes and you get their words. If the words answer the card, apply it yourself and move on. Otherwise answer them properly and briefly, then bring the card back in one line with setup_beat(beat=<that beat>). Never show a card again unless you are bringing it back.
+- If they ask you to pick (a colour, a layout), pick from what you know and say why in one line.
+- If they skip a beat in words, call setup_beat(beat=<that beat>, skip=true), take the default, and never ask it again in the same form. If they want to stop setup altogether, call setup_beat(beat="done", skip=true).
+- Off-script requests are done now, then you bring the card back.
+
+Voice: every word you write is spoken to the user. Never think out loud. Never mention beats, cards, tools, reminders or a script, and never call this setup or onboarding. One or two short, plain sentences per message: warm, like the front desk of somewhere good. No thanks, no praise, no stock lines, no em dashes, no exclamation marks. Write in the user's language when the locale is not English, labels included.
+
+{facts_block(facts)}
+If they ask what you know about them, answer truthfully: these machine basics and what they picked.
+
+Tools you reach through tool_call (their call shapes):
+- {_SET_THEME}. accent: a picker name or a hex colour; mode: light, dark or system; layout: sidebar-left (Basic) or terminal-deck (Elite).
+- {_TOUR_CALL % "quick"} (preset quick or full).
+
+Local models: the model picker chooses one. Explain the download and how it fits this hardware first, then point to Settings, Providers, Local Models. Never install a model runtime or download a model yourself.
+Ask before sending, deleting or scheduling anything. Never turn off a security setting.
+
+As you go, form a coarse read of them on these seven dimensions, from what they say and pick and from what you see when they let you look. Use it to choose suggestions and words; never say it out loud. Presence of an app is not use, and absence is unknown.
+{dimensions}
+
+The app has already greeted them and is asking their name.]"""
+
+
+# ── reminders ─────────────────────────────────────────────────────────────────────────────────
+
+_LOOK_AROUND = (
+ "Before the card, offer once to look around this computer and suggest what to connect. Only on yes, and "
+ "only installed apps, developer tools, the OS and the hardware; never personal files, documents, browser "
+ "data or messages without a specific ask. Then show the card with what you suggest: "
+ 'setup_beat(beat="connectors", suggest=[<connector slugs>]).')
+
+# How a typed answer settles each beat without the card.
+_TYPED_ANSWER = {
+ "name": 'setup_beat(beat="name", value="<their name>")',
+ "theme": _SET_THEME.replace('"accent":"Ultraviolet"', '"accent":"<colour>"'),
+ "layout": 'setup_beat(beat="layout", value="sidebar-left" or "terminal-deck")',
+ "connectors": 'setup_beat(beat="connectors", value="continue") for "done" or "continue", skip=true for "skip"',
+ "plugins": 'setup_beat(beat="plugins", value="continue") for "done" or "continue", skip=true for "skip"',
+ "tour": 'setup_beat(beat="tour", value="quick", "full" or "skip"), bucketing their words into one of the three',
+ "build": 'a task they name is setup_beat(beat="build", value="mind"), then build it',
+}
+
+_CLOSE = ('When the first thing is built and shown, ask with clarify: "How does this look?" with the choices '
+ '"Looks right", "Change something" and "Take it further", exactly. Put the next-step idea in your text. '
+ 'After they answer, call setup_beat(beat="done").')
+
+_BUILD_RULES = (
+ "Rules: real data only (connected apps, or tools signed in on this computer); never mock or invented data, "
+ "never route around a connector. Visible work within a minute, a first result within five. First reply: one "
+ "line and a tool call. At most two checks and one question before work. Connect or install once each, with "
+ "exact ids, no searching. Never search the whole disk. Save every file in ~/hermes-first-task/ and say where "
+ "it is; no test files. A page is one self-contained HTML file opened with desktop_preview.")
+
+_BUILD = {
+ "games": ("First move: install the NVIDIA App and NVIDIA Broadcast plugins with manage_catalog through "
+ "tool_call if they are not installed, then set up what they play and stream with them."),
+ "blender": "First move: make one small thing in Blender with its plugin, from a short script, and show it.",
+ "brief": ("First move: find the connected apps' tools with tool_search, then write today's brief from the real "
+ "data: what needs attention, what changed, what is next. Make it a page if it reads better. If "
+ "nothing answers, say so in one line, run one check (gh auth status) and brief from GitHub if it "
+ "is signed in; otherwise make a start page that needs no account."),
+ "week": ("First move: pull the past seven days from what is connected (find their tools with tool_search), then "
+ "build a one-page summary of their week: meetings, threads, work shipped, open loops. If nothing is "
+ "connected, say so in one line, run one check (gh auth status) and use GitHub if it is signed in; "
+ "otherwise offer to connect Calendar or Gmail and make a start page meanwhile."),
+ "scan": ("A deeper look: ask permission for each scope before reading it (installed apps, developer tools, "
+ "the home folder's top level). Never read personal files, browser data or messages. Then suggest "
+ "three things you could build and build the one they pick."),
+ "mind": ("They have something in mind. If you know what it is, start now: one line on the first slice, then "
+ "build it. If not, ask one short question (clarify with three concrete options is fine), then build. "
+ "Cut a big ask to a first slice and say so in one line."),
+ "machine": ("Machine setup: one clarify card with three to five everyday apps that fit them, multi-select. "
+ "Then one check of which are already installed, and install only the missing picks, one per "
+ "command. List anything that needs a password, licence or payment. Never install a model runtime: "
+ "local models live in the model picker."),
+ "together": ("Vague ask: one clarify card with three options, each makes a thing in five minutes. Name only apps "
+ "they connected. The first option always makes a page or a file. Never offer find, review, audit or "
+ "clean up. If they say \"surprise me\", start the first option now. A script goes in "
+ "~/hermes-first-task/, previews by default (--apply makes changes), and runs once on the real "
+ "folder."),
+}
+
+_OS_LINES = {
+ "macos": ("This Mac: check with `which brew` and `ls -d /Applications/<App>.app`; install with "
+ "`brew install --cask <app>`; on Apple silicon check `lipo -archs` for a binary's architecture."),
+ "windows": ("This PC: check with `winget list --accept-source-agreements`; install with `winget install <id> "
+ "--accept-source-agreements --accept-package-agreements` (without both flags a fresh profile hangs "
+ "on an agreements prompt)."),
+ "linux": ("This Linux machine: check with `which`, and `flatpak list` when flatpak is there; install with "
+ "`flatpak install -y flathub <id>`. Anything that needs sudo is listed for the user, never run."),
+}
+_ARM_WINDOWS = ("On Windows on Arm, read arm64 vs x64 from winget's install output, not the manifest, and say when "
+ "an app is x64 only.")
+_SPARK_LINE = "This machine is built for local models; say so once when it fits what they asked."
+
+
+def build_guidance(option: str, facts: Facts) -> str:
+ lines = [_BUILD.get(option, _BUILD["mind"]), _BUILD_RULES, _OS_LINES.get(facts.os, _OS_LINES["linux"])]
+ if facts.os == "windows" and facts.arch == "arm64":
+ lines.append(_ARM_WINDOWS)
+ if facts.nvidia_platform in ("rtx_spark", "dgx_spark"):
+ lines.append(_SPARK_LINE)
+ if facts.facts_source == "remote":
+ lines.append("Hermes runs on another computer than the user's: say which machine anything is installed on.")
+ return "\n".join([*lines, _CLOSE])
+
+
+def _names(values) -> str:
+ return ", ".join(values) if values else "none"
+
+
+def _next(record: Mapping[str, Any]) -> str:
+ beat = next_beat(record)
+ if beat is None:
+ return 'Every beat is settled; after the build is shown and its close card answered, call setup_beat(beat="done").'
+ return f'Next: setup_beat(beat="next") shows the {beat} card.'
+
+
+def _after_layout(record, facts) -> str:
+ label = {"sidebar-left": "Basic", "terminal-deck": "Elite"}.get(record["picks"]["layout"], record["picks"]["layout"])
+ offer = f" {_LOOK_AROUND}" if record["look_around"] == "not_offered" else ""
+ return f"Layout {label} is on. {_next(record)}{offer}"
+
+
+def _tour(preset: str):
+ return lambda record, facts: (
+ f'Say "Here\'s where things live." Then, in this same turn, call {_TOUR_CALL % preset} and then '
+ 'setup_beat(beat="next"): the build card waits under the tour. Never bring the tour up again.')
+
+
+def _waiting_beat(record) -> str:
+ return (record.get("waiting") or {}).get("beat") or next_beat(record) or "build"
+
+
+_REMINDERS = {
+ "after_name": lambda r, f: f"They go by {r['picks']['name']}. Greet them by name in a few words. {_next(r)}",
+ "after_theme": lambda r, f: f"Accent {r['picks']['accent'] or 'Nous blue'} is on. React in three words or fewer. {_next(r)}",
+ "after_layout": _after_layout,
+ "after_connectors": lambda r, f: (f"Connected: {_names(r['picks']['connected'])}; newly connected: "
+ f"{_names(r['picks']['newly_connected'])}. {_next(r)}"),
+ "after_plugins": lambda r, f: f"Installed plugins: {_names(r['picks']['installed'])}. {_next(r)}",
+ "after_tour": lambda r, f: _next(r),
+ "after_build": lambda r, f: _next(r),
+ "tour_quick": _tour("quick"),
+ "tour_full": _tour("full"),
+ "tour_skip": lambda r, f: 'No tour. In this same turn, setup_beat(beat="next") shows the build card.',
+ "moved_on": lambda r, f: f"That beat is skipped; take its default and do not ask it again. {_next(r)}",
+ "skip_all": lambda r, f: ("They ended setup. In one line, say they can ask you anything any time, then stop "
+ "guiding. The onboarding rules no longer apply; this is a normal chat."),
+ "complete": lambda r, f: ("Onboarding is complete. Its rules no longer apply; this is a normal chat. Close in "
+ "one short line: whenever they are stuck, they can just ask."),
+}
+
+
+def _said(record, facts, beat: str) -> str:
+ return (f"They typed this while the {beat} card waited; the card is closed. If their words answer it, apply it "
+ f"yourself ({_TYPED_ANSWER[beat]}) and move on. Otherwise answer them properly and briefly, then bring "
+ f'the card back in one line with setup_beat(beat="{beat}").')
+
+
+def _timed_out(record, facts, beat: str) -> str:
+ return (f"No answer to the {beat} card in five minutes; it is closed. Say one short line that they can pick up "
+ f'whenever they are back, then stop. When they return, bring it back with setup_beat(beat="{beat}").')
+
+
+def reminder(key: str, record: Mapping[str, Any], facts: Facts, beat: str | None = None) -> str:
+ """The text for a reminder key; ``beat`` names the card a ``said`` / ``timed_out`` result is about."""
+ if not key:
+ return ""
+ if key in ("said", "timed_out"):
+ return (_said if key == "said" else _timed_out)(record, facts, beat or _waiting_beat(record))
+ if key.startswith("build_"):
+ return build_guidance(key.removeprefix("build_"), facts)
+ return _REMINDERS[key](record, facts)
+
+
+def turn_note(record: Mapping[str, Any]) -> str:
+ """The note on a user turn while no card waits: which card is closed and how to bring it back."""
+ beat = _waiting_beat(record)
+ return (f"[System note: Onboarding continues; the {beat} card is closed. Answer their message first, then bring "
+ f'the card back in one line with setup_beat(beat="{beat}").]')
+
+
+def finish_reminder(record: Mapping[str, Any]) -> str:
+ return _next(record)
diff --git a/tests/agent/test_onboarding_flow.py b/tests/agent/test_onboarding_flow.py
new file mode 100644
index 00000000000..d752f45ff42
--- /dev/null
+++ b/tests/agent/test_onboarding_flow.py
@@ -0,0 +1,260 @@
+"""``agent/onboarding_flow.py``: the beats, the run record and every event, across machine fixtures.
+
+Sequences named after lab runs replay what those runs did; the lab bugs they showed are the
+assertions (``.scratch/onboarding-plan/NOTES-onboarding-flow.md``).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from agent import onboarding_flow as flow
+from agent.onboarding_flow import (
+ DONE, PENDING, SHOWN, SKIPPED, Answered, Applied, Done, Facts, Recorded, Said, Shown, SkipAll, Skipped,
+ TimedOut, apply, build_options, expire, new_record, next_beat,
+)
+from agent.onboarding_text import opening_prompt, reminder, turn_note
+
+MACHINES = {
+ "mac": Facts(os="macos", arch="arm64", machine_kind="Mac", plugins=("blender",)),
+ "windows_rtx": Facts(os="windows", arch="arm64", machine_kind="Spark", nvidia_platform="rtx_spark",
+ plugins=("nvidia-app", "nvidia-broadcast", "blender")),
+ "spark": Facts(os="linux", arch="arm64", machine_kind="Spark", nvidia_platform="dgx_spark", plugins=("blender",)),
+ "linux": Facts(os="linux", arch="amd64", machine_kind="computer", plugins=()),
+ "windows_laptop": Facts(os="windows", arch="amd64", machine_kind="PC", nvidia_platform="discrete",
+ plugins=("nvidia-app", "nvidia-broadcast", "blender")),
+ "remote": Facts(os="linux", arch="amd64", machine_kind="computer", facts_source="remote", tours=False),
+}
+
+
+def run(facts: Facts, *events):
+ """Apply events in order from a fresh record; returns every step."""
+ record, steps = new_record(facts, now=0), []
+ for clock, event in enumerate(events, start=1):
+ step = apply(record, event, facts, now=float(clock))
+ record = step.record
+ steps.append(step)
+ return steps
+
+
+def answer_all(facts: Facts) -> list:
+ """The happy path for a machine: every beat it gets, shown and answered on its card."""
+ answers = {"name": {"name": "Sid"}, "theme": {"accent": "Ultraviolet"}, "layout": {"layout": "terminal-deck"},
+ "connectors": {"connected": ["slack"], "newly_connected": ["slack"]},
+ "plugins": {"installed": ["blender"]}, "tour": {"tour": "quick"}, "build": {"build": "week"}}
+ record, events = new_record(facts), []
+ while (beat := next_beat(record)) is not None:
+ for event in (Shown(beat, f"call_{beat}"), Answered(beat, answers[beat])):
+ events.append(event)
+ record = apply(record, event, facts).record
+ return [*events, Done()]
+
+
[email protected]("machine", sorted(MACHINES))
+def test_happy_path_settles_every_beat_this_machine_gets_and_completes(machine):
+ facts = MACHINES[machine]
+ steps = run(facts, *answer_all(facts))
+
+ final = steps[-1]
+ assert final.result == {"completed": True} and final.reminder == "complete"
+ assert final.record["phase"] == flow.COMPLETE and final.record["ended_by"] == "done"
+ assert set(final.record["beats"].values()) <= {DONE, SKIPPED}
+ assert (final.record["beats"]["plugins"] == SKIPPED) is not bool(facts.plugins)
+ assert (final.record["beats"]["tour"] == SKIPPED) is not facts.tours
+ # Every answer names the next beat, and every reminder renders.
+ for step in steps:
+ assert ("next" in step.result) is isinstance(step.result.get("answer"), dict)
+ assert isinstance(reminder(step.reminder, step.record, facts), str)
+
+
[email protected]("machine", sorted(MACHINES))
+def test_the_full_name_never_reaches_the_record_or_the_opening(machine):
+ facts = Facts(**{**MACHINES[machine].__dict__, "full_name": "Ada Lovelace"})
+
+ assert "Ada Lovelace" not in repr(new_record(facts))
+ assert "Ada Lovelace" not in opening_prompt(facts)
+
+
+def test_run_hrs0_typed_answer_is_applied_and_never_reshows_the_card():
+ """hrs0: "elite sounds like my type ;)" got a second layout picker. Typed words close the card;
+ the model applies them with set_theme and the hook settles the beat."""
+ facts = MACHINES["mac"]
+ steps = run(facts, Shown("name"), Answered("name", {"name": "Sid"}), Shown("theme"),
+ Answered("theme", {"accent": "Ultraviolet"}), Shown("layout"),
+ Said("layout", "elite sounds like my type ;)"),
+ Applied("set_theme", {"layout": "terminal-deck"}, {"success": True, "applied": {"layout": "terminal-deck"}}))
+
+ said, applied = steps[-2], steps[-1]
+ assert said.result == {"beat": "layout", "said": "elite sounds like my type ;)"}
+ assert said.record["waiting"] is None and said.record["beats"]["layout"] == SHOWN
+ assert "apply it yourself" in reminder("said", said.record, facts, "layout")
+ assert applied.record["beats"]["layout"] == DONE and applied.record["picks"]["layout"] == "terminal-deck"
+ assert next_beat(applied.record) == "connectors"
+
+
+def test_run_hrs0_off_script_questions_keep_one_card_and_continue_settles_it():
+ """hrs0: each off-script question re-rendered the apps cards (four open copies), and a typed
+ "continue" left the beat shown. Bringing a card back is a new Shown of the same beat; a value
+ given in words settles it."""
+ facts = MACHINES["mac"]
+ events = [Shown("name"), Answered("name", {"name": "Sid"}), Skipped("theme"), Skipped("layout")]
+ for question in ("tell me about SpaceX first", "who runs it?"):
+ events += [Shown("connectors", question), Said("connectors", question)]
+ events += [Shown("connectors"), Said("connectors", "continue"), Recorded("connectors", "continue")]
+ steps = run(facts, *events)
+
+ assert all(step.record["waiting"] is None for step in steps if isinstance(step.result.get("said"), str))
+ assert steps[-1].result == {"recorded": "connectors", "next": "plugins"}
+ assert steps[-1].record["beats"]["connectors"] == DONE
+
+
+def test_run_3ofn_pick_for_me_applies_layout_and_offers_the_look_around_once():
+ """3ofn: "look around and pick one for me" ended in Elite through set_theme; the look-around
+ offer rides the layout result once."""
+ facts = MACHINES["mac"]
+ steps = run(facts, Shown("name"), Answered("name", {"name": "Sid"}), Shown("theme"),
+ Answered("theme", {"accent": "Ember"}), Shown("layout"),
+ Said("layout", "look around and pick one for me"),
+ Applied("set_theme", {"layout": "terminal-deck"}, {"success": True, "applied": {"layout": "terminal-deck"}}),
+ Shown("connectors"))
+
+ layout_done = steps[-2].record
+ assert "look around" in reminder("after_layout", layout_done, facts)
+ assert steps[-1].record["look_around"] == "offered"
+ assert "look around" not in reminder("after_layout", steps[-1].record, facts)
+
+
+def test_skip_setup_while_a_card_waits_ends_the_run_and_refuses_later_beats():
+ facts = MACHINES["windows_laptop"]
+ steps = run(facts, Shown("name"), Answered("name", {"name": "Sid"}), Shown("theme"), SkipAll(), Shown("theme"))
+
+ skipped, refused = steps[-2], steps[-1]
+ assert skipped.result == {"skipped_all": True} and skipped.reminder == "skip_all"
+ assert skipped.record["phase"] == flow.PHASE_SKIPPED and skipped.record["waiting"] is None
+ assert skipped.record["beats"]["name"] == DONE
+ assert all(skipped.record["beats"][beat] == SKIPPED for beat in flow.BEAT_IDS if beat != "name")
+ assert "error" in refused.result and refused.record == skipped.record
+
+
+def test_walks_away_closes_the_card_and_the_turn_note_brings_it_back():
+ facts = MACHINES["linux"]
+ step = run(facts, Shown("name"), Answered("name", {"name": "Sid"}), Shown("theme"), TimedOut("theme"))[-1]
+
+ assert step.result == {"beat": "theme", "timed_out": True}
+ assert step.record["beats"]["theme"] == SHOWN and step.record["waiting"] is None
+ assert 'setup_beat(beat="theme")' in turn_note(step.record)
+
+
+def test_out_of_order_card_leaves_earlier_pending_beats_for_next():
+ facts = MACHINES["mac"]
+ step = run(facts, Shown("connectors"), Answered("connectors", {"connected": [], "newly_connected": []}))[-1]
+
+ assert step.record["beats"]["name"] == PENDING
+ assert step.result["next"] == "name"
+
+
+def test_a_later_card_settles_an_earlier_card_left_open():
+ facts = MACHINES["mac"]
+ step = run(facts, Shown("name"), Said("name", "hi"), Shown("theme"))[-1]
+
+ assert step.record["beats"]["name"] == DONE and step.record["beats"]["theme"] == SHOWN
+
+
+def test_a_done_beat_shown_again_stays_done_and_records_the_new_pick():
+ facts = MACHINES["mac"]
+ step = run(facts, Shown("theme"), Answered("theme", {"accent": "Ember"}), Shown("theme"),
+ Answered("theme", {"accent": "Ultraviolet"}))[-1]
+
+ assert step.record["beats"]["theme"] == DONE and step.record["picks"]["accent"] == "Ultraviolet"
+
+
+def test_done_is_refused_before_the_build_card_was_reached():
+ step = run(MACHINES["mac"], Shown("name"), Answered("name", {"name": "Sid"}), Done())[-1]
+
+ assert "error" in step.result and step.result["next"] == "theme"
+ assert step.record["phase"] == flow.ONBOARDING
+
+
+def test_a_value_outside_the_cards_options_is_refused():
+ step = run(MACHINES["mac"], Recorded("tour", "everything"))[-1]
+
+ assert "quick" in step.result["error"] and step.record["beats"]["tour"] == PENDING
+
+
+def test_a_beat_this_machine_skips_is_never_carded():
+ step = run(MACHINES["linux"], Shown("plugins"))[-1]
+
+ assert step.result["skipped"] is True and step.record["waiting"] is None
+
+
[email protected](("tool", "args", "result", "beat", "pick"), [
+ ("set_theme", {"accent": "violet"}, {"success": True, "applied": {"accent": "custom:#8a2be2"}}, "theme",
+ ("accent", "custom:#8a2be2")),
+ ("set_theme", {"picker": "accent"}, {"success": True, "picked": {"accent": None, "mode": "dark"}}, "theme",
+ ("mode", "dark")),
+ ("manage_connections", {"action": "display"}, {"connected": ["gmail"], "newly_connected": [], "suggested": []},
+ "connectors", ("connected", ["gmail"])),
+ ("gui_tour", {"action": "start", "preset": "quick"}, {"success": True}, "tour", ("tour", "quick")),
+])
+def test_general_tool_results_settle_their_beat(tool, args, result, beat, pick):
+ step = run(MACHINES["mac"], Applied(tool, args, result))[-1]
+
+ assert step.record["beats"][beat] == DONE
+ assert step.record["picks"][pick[0]] == pick[1]
+
+
[email protected](("tool", "args", "result"), [
+ ("set_theme", {"accent": "nope"}, {"success": False, "error": "unknown", "available": []}),
+ ("set_theme", {"picker": "layout"}, {"said": "hmm"}),
+ ("manage_connections", {"action": "display"}, {"timed_out": True}),
+ ("manage_connections", {"action": "status"}, {"connected": ["gmail"]}),
+ ("gui_tour", {"action": "next"}, {"success": True}),
+])
+def test_results_that_pick_nothing_settle_nothing(tool, args, result):
+ step = run(MACHINES["mac"], Applied(tool, args, result))[-1]
+
+ assert set(step.record["beats"].values()) <= {PENDING, SKIPPED}
+
+
[email protected](("machine", "first_two", "machine_row"), [
+ ("windows_laptop", ["games", "week"], "Help me set up this PC"),
+ ("windows_rtx", ["week", "scan"], "Help me set up this Spark"),
+ ("spark", ["week", "scan"], "Help me set up this Spark"),
+ ("mac", ["week", "scan"], "Help me set up this Mac"),
+])
+def test_build_options_fit_the_machine(machine, first_two, machine_row):
+ options = build_options(MACHINES[machine], {"connected": [], "installed": []})
+
+ assert [row["id"] for row in options[:2]] == first_two
+ assert [row["id"] for row in options[2:]] == ["mind", "machine", "together"]
+ assert options[3]["label"] == machine_row
+
+
+def test_build_options_follow_the_picks():
+ options = build_options(MACHINES["mac"], {"connected": ["notion", "slack"], "installed": ["blender"]})
+
+ assert [row["id"] for row in options[:2]] == ["blender", "brief"]
+
+
[email protected](("machine", "present", "absent"), [
+ ("mac", "brew install --cask", "winget"),
+ ("windows_laptop", "--accept-package-agreements", "brew"),
+ ("windows_rtx", "x64 only", "brew"),
+ ("linux", "flatpak install", "winget"),
+ ("remote", "another computer", "brew"),
+])
+def test_build_guidance_carries_only_this_hosts_commands(machine, present, absent):
+ text = reminder("build_machine", new_record(MACHINES[machine]), MACHINES[machine])
+
+ assert present in text and absent not in text
+ assert 'setup_beat(beat="done")' in text
+
+
+def test_quiet_spell_after_the_build_card_completes_the_run():
+ facts = MACHINES["mac"]
+ record = run(facts, Shown("build"))[-1].record
+
+ assert expire(record, now=record["updated_at"] + flow.QUIET_COMPLETE_S - 1)["phase"] == flow.ONBOARDING
+ ended = expire(record, now=record["updated_at"] + flow.QUIET_COMPLETE_S)
+ assert ended["phase"] == flow.COMPLETE and ended["ended_by"] == "timeout"
+ assert expire(new_record(facts), now=10**9)["phase"] == flow.ONBOARDING