onboarding_flow.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. """First-run onboarding as data: the beats, the run record, and how each event moves the record.
  2. Pure: no I/O, no clock. ``apply(record, event, facts, now=...)`` returns the next record, the result
  3. the model reads, and the key of the reminder that rides on it (``agent/onboarding_text.py`` renders
  4. it). The record is stored by ``agent/onboarding_record.py``; ``tools/setup_beat_tool.py`` drives it.
  5. """
  6. from __future__ import annotations
  7. import copy
  8. from collections.abc import Callable, Mapping
  9. from dataclasses import asdict, dataclass, field
  10. from typing import Any
  11. from agent.onboarding_first_tasks import FIXED_ID, OWN_ID, card_options, pick_error
  12. PENDING, SHOWN, DONE, SKIPPED = "pending", "shown", "done", "skipped"
  13. ONBOARDING, COMPLETE, PHASE_SKIPPED = "onboarding", "complete", "skipped"
  14. CARD_TIMEOUT_S = 300
  15. MAX_PLUGINS = 5
  16. LAYOUT_OPTIONS = ({"id": "sidebar-left", "label": "Basic"}, {"id": "terminal-deck", "label": "Elite"})
  17. TOUR_OPTIONS = ({"id": "quick", "label": "Quick tour"}, {"id": "full", "label": "Show me everything"},
  18. {"id": "skip", "label": "Skip, let's build something"})
  19. @dataclass(frozen=True)
  20. class Facts:
  21. """The safe facts (class A) one run is built from. ``full_name`` reaches only the name card; it is
  22. never stored in the record or put in a result."""
  23. os: str # macos | windows | linux
  24. arch: str = ""
  25. machine_kind: str = "computer" # Mac | PC | Spark | computer
  26. nvidia_platform: str | None = None # rtx_spark | dgx_spark | discrete
  27. facts_source: str = "local" # local | remote: whose computer these facts describe
  28. locale: str | None = None
  29. plugins: tuple[str, ...] = () # onboarding catalog plugins this OS runs
  30. tours: bool = True
  31. full_name: str | None = field(default=None, compare=False)
  32. def stored(self) -> dict:
  33. data = asdict(self)
  34. data.pop("full_name")
  35. data["plugins"] = list(self.plugins)
  36. return data
  37. @classmethod
  38. def from_stored(cls, data: Mapping[str, Any]) -> Facts:
  39. known = {key: data[key] for key in cls.__dataclass_fields__ if key in data and key != "full_name"}
  40. return cls(**{**known, "plugins": tuple(known.get("plugins") or ())})
  41. # ── events ────────────────────────────────────────────────────────────────────────────────────
  42. @dataclass(frozen=True)
  43. class Shown:
  44. """``options``: the model's build picks, ``[{id, label}]``; empty brings back the card already shown.
  45. ``suggest``: the connector slugs the model pins after it looked around."""
  46. beat: str
  47. tool_call_id: str = ""
  48. options: Any = None
  49. suggest: Any = None
  50. @dataclass(frozen=True)
  51. class Answered:
  52. """``said``: the answer came as words in the composer (the name card), so the chat shows them as
  53. the user's bubble."""
  54. beat: str
  55. answer: Mapping[str, Any]
  56. said: str = ""
  57. # ``present`` on the events below: the beat's picks as this machine has them now (the apps connected,
  58. # the plugins installed), so a card closed without its own answer still reports them.
  59. @dataclass(frozen=True)
  60. class Wrote:
  61. """The user sent a message instead of answering the card. The message is their own next turn, so the
  62. result carries none of it."""
  63. beat: str
  64. present: Any = None
  65. @dataclass(frozen=True)
  66. class TimedOut:
  67. beat: str
  68. present: Any = None
  69. @dataclass(frozen=True)
  70. class Recorded:
  71. beat: str
  72. value: str
  73. present: Any = None
  74. @dataclass(frozen=True)
  75. class Skipped:
  76. beat: str
  77. present: Any = None
  78. @dataclass(frozen=True)
  79. class End:
  80. """The run ended outside the model: ``skipped`` (Skip setup), ``replaced`` (a rerun opened a new
  81. run) or ``deleted`` (its chat is being deleted)."""
  82. outcome: str = "skipped"
  83. @dataclass(frozen=True)
  84. class Done:
  85. pass
  86. @dataclass(frozen=True)
  87. class Applied:
  88. """A general tool's result during the run: ``set_theme``, ``manage_connections`` display, ``gui_tour``."""
  89. tool: str
  90. args: Mapping[str, Any]
  91. result: Mapping[str, Any]
  92. Event = Shown | Answered | Wrote | TimedOut | Recorded | Skipped | End | Done | Applied
  93. @dataclass(frozen=True)
  94. class Step:
  95. record: dict
  96. result: dict
  97. reminder: str = ""
  98. # ── beats ─────────────────────────────────────────────────────────────────────────────────────
  99. def build_values(facts: Facts, picks: Mapping[str, Any]) -> tuple[str, ...]:
  100. """Ids the build beat accepts: what its card showed, plus a task they named in words."""
  101. return (*_option_ids(picks.get("build_options") or ()), FIXED_ID, OWN_ID)
  102. def _option_ids(options) -> tuple[str, ...]:
  103. return tuple(option["id"] for option in options)
  104. @dataclass(frozen=True)
  105. class Beat:
  106. """``card`` is the beat's data for the desktop; ``when`` false skips the beat on this machine;
  107. ``picks`` are the answer keys recorded; ``value`` is the pick a ``value`` given in words sets
  108. (None: the beat takes no value, it is only marked done); ``values`` lists the accepted ids."""
  109. id: str
  110. card: Callable[[Facts, Mapping], dict]
  111. picks: tuple[str, ...]
  112. value: str | None = None
  113. values: Callable[[Facts, Mapping], tuple[str, ...]] | None = None
  114. when: Callable[[Facts, Mapping], bool] = lambda facts, picks: True
  115. def after(self, picks: Mapping[str, Any]) -> str:
  116. """Reminder key for the result that settles this beat."""
  117. if self.id in ("tour", "build") and picks.get(self.id):
  118. return f"{self.id}_{picks[self.id]}"
  119. return f"after_{self.id}"
  120. BEATS: tuple[Beat, ...] = (
  121. Beat("name", lambda facts, picks: {}, picks=("name",), value="name"),
  122. Beat("theme", lambda facts, picks: {"picker": "accent"}, picks=("accent", "mode"), value="accent"),
  123. Beat("layout", lambda facts, picks: {"options": list(LAYOUT_OPTIONS)}, picks=("layout",), value="layout",
  124. values=lambda facts, picks: _option_ids(LAYOUT_OPTIONS)),
  125. Beat("connectors", lambda facts, picks: {}, picks=("connected", "newly_connected")),
  126. Beat("plugins", lambda facts, picks: {"plugins": list(facts.plugins[:MAX_PLUGINS])}, picks=("installed",),
  127. when=lambda facts, picks: bool(facts.plugins)),
  128. Beat("tour", lambda facts, picks: {"options": list(TOUR_OPTIONS)}, picks=("tour",), value="tour",
  129. values=lambda facts, picks: _option_ids(TOUR_OPTIONS), when=lambda facts, picks: facts.tours),
  130. Beat("build", lambda facts, picks: {"options": card_options(picks.get("build_options"))}, picks=("build",),
  131. value="build", values=build_values),
  132. )
  133. BEAT_BY_ID = {beat.id: beat for beat in BEATS}
  134. BEAT_IDS = tuple(BEAT_BY_ID)
  135. def new_record(facts: Facts, *, now: float = 0.0, run_id: str = "") -> dict:
  136. record = {
  137. "run_id": run_id, "phase": ONBOARDING, "beats": {beat.id: PENDING for beat in BEATS}, "waiting": None,
  138. "picks": {"name": None, "accent": None, "mode": None, "layout": None, "connected": [],
  139. "newly_connected": [], "installed": [], "tour": None, "build": None,
  140. "build_options": []},
  141. "look_around": "not_offered", "facts": facts.stored(), "ended_by": None,
  142. "started_at": now, "updated_at": now,
  143. }
  144. return _settle_unfit(record, facts)
  145. def _settle_unfit(record: dict, facts: Facts) -> dict:
  146. for beat in BEATS:
  147. if record["beats"][beat.id] == PENDING and not beat.when(facts, record["picks"]):
  148. record["beats"][beat.id] = SKIPPED
  149. return record
  150. def next_beat(record: Mapping[str, Any]) -> str | None:
  151. """The first beat still pending or shown; None when every beat is settled."""
  152. return next((beat for beat in BEAT_IDS if record["beats"][beat] in (PENDING, SHOWN)), None)
  153. def is_active(record: Mapping[str, Any] | None) -> bool:
  154. return bool(record) and record.get("phase") == ONBOARDING
  155. # ── apply ─────────────────────────────────────────────────────────────────────────────────────
  156. def _next_field(record: Mapping[str, Any]) -> str:
  157. return next_beat(record) or "done"
  158. def _settle(record: dict, beat: str, patch: Mapping[str, Any]) -> None:
  159. record["beats"][beat] = DONE
  160. record["picks"].update({key: value for key, value in patch.items() if key in BEAT_BY_ID[beat].picks})
  161. def _build_picks_error(record: dict, event: Shown, facts: Facts) -> str | None:
  162. """Stores the model's build picks; a bring-back without picks reuses the ones already on the card."""
  163. if not event.options and record["picks"].get("build_options"):
  164. return None
  165. if error := pick_error(event.options, facts, record["picks"]):
  166. return error
  167. record["picks"]["build_options"] = [{"id": o["id"], "label": o["label"].strip()} for o in event.options]
  168. return None
  169. def _has_suggestions(suggest: Any) -> bool:
  170. return isinstance(suggest, list | tuple) and any(str(slug).strip() for slug in suggest)
  171. def _shown(record: dict, event: Shown, facts: Facts, now: float) -> Step:
  172. if not BEAT_BY_ID[event.beat].when(facts, record["picks"]):
  173. record["beats"][event.beat] = SKIPPED
  174. return Step(record, {"beat": event.beat, "skipped": True, "next": _next_field(record)}, "moved_on")
  175. if event.beat == "build" and (error := _build_picks_error(record, event, facts)):
  176. # No ``beat``: no card was shown, so the transcript draws nothing for this refusal.
  177. return Step(record, {"error": error})
  178. if event.beat == "connectors" and record["look_around"] == "not_offered":
  179. # The offer reaches the model only here, so it is offered now; suggestions mean it already looked.
  180. record["look_around"] = "offered"
  181. if not _has_suggestions(event.suggest):
  182. return Step(record, {"error": "offer first"}, "offer_first")
  183. # A later card on screen means the user moved on from an earlier card left open.
  184. for earlier in BEAT_IDS[:BEAT_IDS.index(event.beat)]:
  185. if record["beats"][earlier] == SHOWN:
  186. record["beats"][earlier] = DONE
  187. if record["beats"][event.beat] != DONE:
  188. record["beats"][event.beat] = SHOWN
  189. record["waiting"] = {"beat": event.beat, "tool_call_id": event.tool_call_id, "since": now}
  190. return Step(record, {})
  191. def _is_names(value: Any) -> bool:
  192. return isinstance(value, list) and all(isinstance(item, str) for item in value)
  193. def valid_answer(beat: str, answer: Mapping[str, Any], facts: Facts, picks: Mapping[str, Any]) -> bool:
  194. """A card answer carries only its beat's pick keys, with ids from the card's own options. ``label``
  195. is the text the card showed, kept for the transcript and never recorded."""
  196. spec = BEAT_BY_ID[beat]
  197. if not isinstance(answer.get("label", ""), str):
  198. return False
  199. answer = {key: value for key, value in answer.items() if key != "label"}
  200. if not answer or not set(answer) <= set(spec.picks):
  201. return False
  202. if spec.values is not None:
  203. return answer.get(spec.value) in spec.values(facts, picks)
  204. if beat == "name":
  205. return isinstance(answer.get("name"), str) and bool(answer["name"].strip())
  206. if beat == "theme":
  207. return all(value is None or isinstance(value, str) for value in answer.values())
  208. if beat == "plugins":
  209. return _is_names(answer.get("installed")) and set(answer["installed"]) <= set(facts.plugins)
  210. return "connected" in answer and all(_is_names(value) for value in answer.values())
  211. def _answered(record: dict, event: Answered, facts: Facts, now: float) -> Step:
  212. record["waiting"] = None
  213. if not valid_answer(event.beat, event.answer, facts, record["picks"]):
  214. return Step(record, {"beat": event.beat, "error": "The card sent an answer this beat does not accept. "
  215. f'Bring it back with setup_beat(beat="{event.beat}").'})
  216. _settle(record, event.beat, event.answer)
  217. said = {"said": event.said} if event.said else {}
  218. return Step(record, {"beat": event.beat, "answer": dict(event.answer), **said, "next": _next_field(record)},
  219. BEAT_BY_ID[event.beat].after(record["picks"]))
  220. def _note_present(record: dict, event: Wrote | TimedOut | Recorded | Skipped) -> dict:
  221. """Record the beat's picks as the machine has them now; returns them for the result."""
  222. present = {key: value for key, value in (event.present or {}).items() if key in BEAT_BY_ID[event.beat].picks}
  223. record["picks"].update(present)
  224. return present
  225. def _wrote(record: dict, event: Wrote, facts: Facts, now: float) -> Step:
  226. record["waiting"] = None
  227. return Step(record, {"beat": event.beat, "wrote_instead": True, **_note_present(record, event)}, "wrote")
  228. def _timed_out(record: dict, event: TimedOut, facts: Facts, now: float) -> Step:
  229. record["waiting"] = None
  230. return Step(record, {"beat": event.beat, "timed_out": True, **_note_present(record, event)}, "timed_out")
  231. # Beats a general tool applies; their result settles the beat, so a value given in words would only
  232. # record a pick that never reaches the screen.
  233. APPLIED_BY = {"theme": "set_theme", "layout": "set_theme"}
  234. def _recorded(record: dict, event: Recorded, facts: Facts, now: float) -> Step:
  235. beat = BEAT_BY_ID[event.beat]
  236. if tool := APPLIED_BY.get(event.beat):
  237. return Step(record, {"error": f"Apply the {event.beat} with {tool}; its result settles this beat.",
  238. "next": _next_field(record)})
  239. accepted = beat.values(facts, record["picks"]) if beat.values else None
  240. if accepted is not None and event.value not in accepted:
  241. return Step(record, {"error": f"value for {event.beat} must be one of: {', '.join(accepted)}.",
  242. "next": _next_field(record)})
  243. _settle(record, event.beat, {beat.value: event.value} if beat.value else {})
  244. present = _note_present(record, event)
  245. return Step(record, {"recorded": event.beat, **present, "next": _next_field(record)}, beat.after(record["picks"]))
  246. def _skipped(record: dict, event: Skipped, facts: Facts, now: float) -> Step:
  247. record["beats"][event.beat] = SKIPPED
  248. present = _note_present(record, event)
  249. return Step(record, {"recorded": event.beat, "skipped": True, **present, "next": _next_field(record)}, "moved_on")
  250. def _end(record: dict, event: End, facts: Facts, now: float) -> Step:
  251. record.update(phase=PHASE_SKIPPED, ended_by=event.outcome, waiting=None)
  252. for beat in BEAT_IDS:
  253. if record["beats"][beat] != DONE:
  254. record["beats"][beat] = SKIPPED
  255. return Step(record, {"skipped_all": True}, "skip_all")
  256. def _done(record: dict, event: Done, facts: Facts, now: float) -> Step:
  257. if record["beats"]["build"] == PENDING:
  258. return Step(record, {"error": "Onboarding ends after the first build is shown and its close card is "
  259. "answered. If they want to stop, tell them about the Skip setup button.",
  260. "next": _next_field(record)})
  261. record["beats"]["build"] = DONE
  262. return Step(record, {}, "complete")
  263. def _applied_beats(event: Applied) -> list[tuple[str, dict]]:
  264. """The beats a general tool's result settles, with the picks it recorded."""
  265. result, args = event.result, event.args
  266. if event.tool == "set_theme":
  267. values = result.get("applied") or result.get("picked") or {}
  268. theme = {key: values[key] for key in ("accent", "mode") if key in values}
  269. settled = [("theme", theme)] if theme else []
  270. return [*settled, ("layout", {"layout": values["layout"]})] if values.get("layout") else settled
  271. if event.tool == "manage_connections" and args.get("action") == "display" and "connected" in result:
  272. return [("connectors", {"connected": list(result.get("connected") or ()),
  273. "newly_connected": list(result.get("newly_connected") or ())})]
  274. if event.tool == "gui_tour" and args.get("action") == "start" and not result.get("error"):
  275. return [("tour", {"tour": args.get("preset") or "full"})]
  276. return []
  277. def _applied(record: dict, event: Applied, facts: Facts, now: float) -> Step:
  278. """The reminder names the last beat this result newly settled, so the model moves on instead of
  279. recording it again with setup_beat. ``after_<beat>``, not ``Beat.after``: the tour already started.
  280. A repeat apply of a theme or layout already settled gets ``already_<beat>``, so it stops re-applying."""
  281. settled, repeated = "", ""
  282. for beat, patch in _applied_beats(event):
  283. if record["beats"][beat] != DONE:
  284. settled = beat
  285. elif beat in APPLIED_BY:
  286. repeated = beat
  287. _settle(record, beat, patch)
  288. if (record["waiting"] or {}).get("beat") == beat:
  289. record["waiting"] = None
  290. return Step(record, {}, f"after_{settled}" if settled else f"already_{repeated}" if repeated else "")
  291. _HANDLERS: dict[type, Callable[[dict, Any, Facts, float], Step]] = {
  292. Shown: _shown, Answered: _answered, Wrote: _wrote, TimedOut: _timed_out, Recorded: _recorded,
  293. Skipped: _skipped, End: _end, Done: _done, Applied: _applied,
  294. }
  295. _ENDED = "Onboarding is over in this chat; it is a normal chat now."
  296. def _ended(record: dict, event: Event) -> Step:
  297. """An ended run ignores general tool results and refuses setup_beat, except a repeat of its own
  298. end: done on a completed run and any end on an ended run answer as if they had ended it."""
  299. if isinstance(event, Applied):
  300. return Step(record, {})
  301. if isinstance(event, Done) and record.get("phase") == COMPLETE:
  302. return Step(record, {"completed": True}, "complete")
  303. if isinstance(event, End):
  304. return Step(record, {"skipped_all": True})
  305. return Step(record, {"error": _ENDED})
  306. def apply(record: Mapping[str, Any], event: Event, facts: Facts, *, now: float = 0.0) -> Step:
  307. """The record after ``event``, the model-facing result, and the reminder key. The run completes
  308. when the build beat settles: the answer to the first-task card ends onboarding."""
  309. working = copy.deepcopy(dict(record))
  310. if not is_active(working):
  311. return _ended(working, event)
  312. step = _HANDLERS[type(event)](working, event, facts, now)
  313. if is_active(step.record) and step.record["beats"]["build"] == DONE:
  314. step.record.update(phase=COMPLETE, ended_by="done", waiting=None)
  315. step = Step(step.record, {**step.result, "completed": True}, step.reminder)
  316. if step.record != record:
  317. step.record["updated_at"] = now
  318. return step
  319. def applies_to(tool: str) -> bool:
  320. """Whether a general tool's result can settle a beat (the hook's cheap pre-check)."""
  321. return tool in ("set_theme", "manage_connections", "gui_tour")