Skip to content

Self-improving AI Employees for everyone

feat(home): onboarding on Home: Welcome guide, setup card, first day, checklist

trohitg6de1662ac00f
diff --git a/CLAUDE.md b/CLAUDE.md
index 436b4173..03825a5e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -17,7 +17,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Node Allowlist](./docs-internal/node_allowlist.md)** | Single-config UI visibility — `server/config/node_allowlist.json` controls which nodes / credential categories / skill folders show in the UI. Five lists with two enforcement tiers (mode-gated allowlist + absolute blocklist). `useNodeAllowlist` hook exposes `isVisible` / `isBlocked` / `isAllowed` / `isCredentialCategoryDisabled` / `isSkillFolderDisabled`. Adding a new disabled domain = single JSON edit, no code change. |
| **[Normal Mode (Home)](./docs-internal/normal_mode.md)** | The owner-facing landing screen: describe a job, an LLM on the server drafts a setup screen (a JSON UI spec the client parses, normalises and renders from a fixed catalogue), and Hire builds, validates, saves and starts one workflow per AI employee (`services/employees/`, graph built from `config/employee_apps.json` plus the owner's skill library and a Canvas node, and checked against `node_allowlist.json` `enabled_nodes`). Covers the screen switch (`app/`, `shellMode` / `ui_shell_mode`, `VITE_NORMAL_MODE=false` kill switch, Home shows light/dark only), the employee page (the shared chat, `features/chat`, with the employee named in the header beside New conversation; Pause is in the Workspace header), deleting an employee from the team sidebar (stopped through Reset first, then gone from every tab), the live Ask first rule (`workflow_rules`, the chat's Ask first chip via `set_ask_first`; app replies wait in `approvalGate`, sending tool calls are held as drafts by `services/approvals/tool_calls.py` and sent after a 5 s Undo window by `ApprovedToolCallWorkflow`; cards in the chat; builder v3 gates every app reply, attaches every app tool and gives the talk agent `chatUi` and the registry's `talk_send` tools, with instructions identical whatever the rule; older employees are upgraded on Apply / Turn on Talk / Start by `services/employees/upgrade.py`), run records for "done today" (`machina-run-record-v1`), automatic-pause reasons, Settings (Profile fields; usage-only Billing via `get_employee_usage`; Skills, the user-skills library each new hire copies onto a Skills node; consumer Connectors with `publisher` / `verified`; Plugins, the starter bundles in `hire/starters.json`; the last three share one catalog page), the Workspace dock (an employee's Canvas board, named by the summary's `canvas_node_id`; a live Browser tab with user takeover, shared with Dev mode; Mobile shows the managed local Android phone), the "Web browser" app (attached whole, each call read-only while the owner asks first through its approval spec's `restrict_while_asking`; while the agent waits in `request_user` the summary's `browser_request` shows Needs you and Help in browser), Talk on the employee page (a thread over the chat session whose id is the workflow id, rows written through `services/chat_thread.py` and, for the owner's messages and their chat runs, `services/chat/ledger.py` (see [Chat Protocol](./docs-internal/chat_protocol.md)); the talk line is chatTrigger → an agent → `chatReply` "Reply in Chat": a chat hire's own agent is its talk agent, other hires get a "Talk with {name}" agent sharing the worker's tools and skills with its own Context, and schedule hires also "Post to Talk"), Turn on Talk (for talk `off`) and Apply (while the summary's `pending_changes` is true) via `enable_employee_talk` / `apply_employee_changes`, each a restart on the saved graph through `services/deployment/restart.py`, self-extension from Talk through the Agent Builder within the Hire rule (`services/employees/policy.py`), the 3D orb, the wire contract and the `employee_lifecycle` / `approval_lifecycle` / `chat.updated` broadcasts. |
| **[Chat Protocol](./docs-internal/chat_protocol.md)** | The wire contract between the chat runtime (`server/services/chat/`) and the shared chat UI: AG-UI's event model on the existing WebSocket, snake_case, in the CloudEvents envelope. A message a deployed chat trigger will answer starts a **chat run** admitted with it in one reserved write transaction (`Database.reserved_session`, SQLite `BEGIN IMMEDIATE`): one live run per session (the lane, also a partial unique index; a second send answers `run_in_progress`), idempotent `client_message_id`, claimed and finished by the MachinaWorkflow that answers it behind `machina-chat-run-v1` (the run id is trusted only from an event whose source is `opencompany://services/chat`; `run_scope` rides every node context; only the claimant finishes), the reply saved as `a_<run id>` by `chatReply`, every message appended after the session's active leaf (`chat_threads`) so concurrent writes never fork the thread. `chat_run_event` frames reach only sockets that passed `chat_subscribe`'s owner check (`services/chat/hub.py`: per-run `seq`, `hub_epoch`, bounded per-socket queues with a resync), never the status broadcast; a standalone worker sends its run events, `chat.updated` and `approval_lifecycle` to the backend over `/ws/internal` (`services/chat/relay.py`, `chat_run_publish`, ordered, dropped events resynced). A watchdog (`services/chat/watchdog.py`, started by `main.py`) ends runs nothing will finish (`not_delivered`, `timed_out`, `interrupted`). The agent wired into Reply in Chat (`answers_chat_run`) streams its answer as `text.*` events (`services/chat/stream.py`, activity input only, no workflow patch), its tool calls show as steps (`services/chat/steps.py`; label from the plugin's `chat_step`), and `stop_chat_run` stops a run cooperatively: its LLM step polls the run and returns what was shown, unstarted tools are skipped, the reply is saved `stopped`, and the watchdog cancels a run still stopping after `runs.stop_grace_s`. Generated UI: the `show_ui` tool (`chatUi`) is checked against `config/chat_genui_catalog.json` (`services/genui/spec.py`; refused with every reason so the model retries), saved as a run part, streamed as `activity.*` RFC 6902 patches and sealed into the reply (`services/chat/parts.py`); `chat_ui_state` keeps what the owner set, and a button press comes back as `send_chat_message{ui_event}` -> a `[ui-event]` turn. The answering agent's system prompt ends with a fixed guide (`services/chat/guide.py`), what the owner set reaches its next turn as a `[ui-state]` note (`chat_notes`, `services/chat/notes.py`: claimed by the payload, told when the run answered), a trailing `<followups>` block becomes `parts.followups`, and a `chat_sources` tool's results are numbered per conversation for `[n]` citations (`services/chat/sources.py`). Approvals (`services/approvals/`, its own section): a plugin's `approval` spec marks a tool call that sends; while the workflow asks first it is held as a `tool_call` draft, shown as a card on the reply that made it, sent once after the Undo window by `ApprovedToolCallWorkflow`, with the outcome told to the employee as an `[update]` note. Branches (`services/chat/branches.py`): `get_chat_messages` returns the path to the thread's active leaf, each message with its versions (`siblings`), `editable` and the owner's rating; `edit_chat_message` / `regenerate_chat_reply` / `switch_chat_branch` move the path in one reserved transaction under the conversation store's lock, taking each agent's stored conversation back to the cursor its run recorded at `prepare_payload` (`chat_runs.context_cursors`) or restoring the branch's kept copy (`chat_branch_snapshots`), refused on `revision_conflict`, `run_in_progress`, `cannot_rewind`, `branch_unavailable` or `older_generation`; `set_chat_feedback` keeps a rating and tells the next turn (`[feedback]` note). Attachments (`services/chat/attachments.py`): the chat uploads files under `uploads/` and sends only their paths, the server rebuilds each reference from the file (refusing anything else, at most six), the answering agent reads an `[attachments]` line and images ride the opening user message for a provider with `vision.user_images`; `options.web: false` drops the `search` tools for that run; `get_chat_context` gives slash commands (generic plus the apps' `commands`) and capabilities; dictation is the speech plugin's `dictation_status` / `transcribe_audio`. Lists every event, handler, part and error code (among them `engine_unavailable`: with Temporal not connected a workflow's chat saves nothing, since nothing could deliver it). |
-| **[Theme System](./docs-internal/theme_system.md)** | 12-way visual theme system — 2 base (light, dark) + 5 utopian (renaissance, greek, edo, steampunk, atomic) + 5 dystopian (cyber, wasteland, rot, plague, surveillance) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Token taxonomy (surface / fg / border / accent / typography / motion) in **hex + `color-mix()`**; `@theme inline` bridge maps `--color-X: var(--X)` (no `hsl()` wrapper); per-theme files own the colour hex, base.css owns the shared `--tint-*` alpha scale; action role tokens (incl. `-ink` readable text), **per-theme `--code-*` syntax tokens** (tier 6 — the code editor, console/output JSON viewers, and chat code blocks paint in each theme's own palette: keyword→trigger, string→success, number→agent, function→model, on an adaptive dark/light code surface; replaced the global dracula `--prism-*` block + dead `getPrismTokenCSS`; the `OutputPanel` JSON viewer reads the same vars), per-theme `--pulse-keyframe` animation system + `.opencompany-*` helpers in `animations.css`, decorative-layer wrappers (`.app-frame` / `.canvas-host` / `.modal-frame`), per-component decorative ornaments (panel textures + canvas decorations + node pseudo-element overlays + theme-specific keyframes), **canvas-node visual contract via `--node-color` CSS custom property** (no inline `background` / `border` on node components — base.css + per-theme CSS owns visuals; `NodeStyle` helper type at [types/NodeTypes.ts](./client/src/types/NodeTypes.ts) makes the inline custom-prop typecheck-clean), **`--node-pulse-color` separate from `--node-color`** so executing-node glow uses each theme's highest-contrast accent regardless of plugin accent (Cyber neon cyan, Surveillance REC red, Renaissance ultramarine, etc.), **`data-page-hidden` animation pause** (set by `app/usePageActivitySync.ts`, mounted in `AppShell` on both screens, while the tab is hidden or the window is blurred; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyph system** (290 inline SVG glyph strings across 29 keys × 10 themes via [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts) + theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **decorative HTML primitives** (`<SvgFilterDefs>` mounting `#ink-blot` / `#noise` / `#crt` filter IDs at app root, `<DropCap>` wrapper for Renaissance ornament rule), **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), **per-theme scrollbar webkit rules** in all 12 themes, 9-event WebAudio sound system (10 packs via `--sound-pack` token + `useSound()` hook + global hover delegate + sonner toast monkey-patch + `withSound()` HOC + `Sounds.unlock()` gesture-unlock for AudioContext autoplay-policy compliance), `@media (prefers-reduced-motion: reduce)` accessibility, 30 ms throttle on `type` / `hover`, migration recipe, anti-patterns. Read this before adding a new theme, migrating a component to the new contract, or adding a canvas-node component. |
+| **[Theme System](./docs-internal/theme_system.md)** | 12-way visual theme system — 2 base (light, dark) + 5 utopian (renaissance, greek, edo, steampunk, atomic) + 5 dystopian (cyber, wasteland, rot, plague, surveillance) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Token taxonomy (surface / fg / border / accent / typography / motion) in **hex + `color-mix()`**; `@theme inline` bridge maps `--color-X: var(--X)` (no `hsl()` wrapper); per-theme files own the colour hex, base.css owns the shared `--tint-*` alpha scale; action role tokens (incl. `-ink` readable text), **per-theme `--code-*` syntax tokens** (tier 6 — the code editor, console/output JSON viewers, and chat code blocks paint in each theme's own palette: keyword→trigger, string→success, number→agent, function→model, on an adaptive dark/light code surface; replaced the global dracula `--prism-*` block + dead `getPrismTokenCSS`; the `OutputPanel` JSON viewer reads the same vars), per-theme `--pulse-keyframe` animation system + `.opencompany-*` helpers in `animations.css`, decorative-layer wrappers (`.app-frame` / `.canvas-host` / `.modal-frame`), per-component decorative ornaments (panel textures + canvas decorations + node pseudo-element overlays + theme-specific keyframes), **canvas-node visual contract via `--node-color` CSS custom property** (no inline `background` / `border` on node components — base.css + per-theme CSS owns visuals; `NodeStyle` helper type at [types/NodeTypes.ts](./client/src/types/NodeTypes.ts) makes the inline custom-prop typecheck-clean), **`--node-pulse-color` separate from `--node-color`** so executing-node glow uses each theme's highest-contrast accent regardless of plugin accent (Cyber neon cyan, Surveillance REC red, Renaissance ultramarine, etc.), **`data-page-hidden` animation pause** (set by `app/usePageActivitySync.ts`, mounted in `App.tsx` above the sign-in gate so it covers every screen, while the tab is hidden or the window is blurred; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyph system** (290 inline SVG glyph strings across 29 keys × 10 themes via [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts) + theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **decorative HTML primitives** (`<SvgFilterDefs>` mounting `#ink-blot` / `#noise` / `#crt` filter IDs at app root, `<DropCap>` wrapper for Renaissance ornament rule), **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), **per-theme scrollbar webkit rules** in all 12 themes, 9-event WebAudio sound system (10 packs via `--sound-pack` token + `useSound()` hook + global hover delegate + sonner toast monkey-patch + `withSound()` HOC + `Sounds.unlock()` gesture-unlock for AudioContext autoplay-policy compliance), `@media (prefers-reduced-motion: reduce)` accessibility, 30 ms throttle on `type` / `hover`, migration recipe, anti-patterns. Read this before adding a new theme, migrating a component to the new contract, or adding a canvas-node component. |
| **[Design System Bundle](./docs-internal/design-system/IMPLEMENTATION.md)** | Canonical, vendored design-system reference (extracted from this repo; see its `IMPLEMENTATION.md` for the contract). Tokens are **hex + `color-mix()`** (`tokens/{colors,typography,spacing,motion,fonts,base}.css`) — the format the live codebase standardizes on. Includes 34 reference components (`components/`, inline-style reference only — recreate in Tailwind/shadcn idioms), full-app UI kit (`ui_kits/opencompany/index.html`), 12-theme docs (`guidelines/THEMES.md`), **the merged handoff brief (`HANDOFF.md` — glow-ladder traps, step-edge contract, toolbar layout traps, canvas-layer asymmetries, plus the recorded product amendments)**, and **the panel×theme fidelity target (`reference-mockup/Panel Theme Matrix.dc.html` — 17 panels × 12 themes, open in a browser)**. `reference/themes/` no longer vendors CSS snapshots — it points at the authoritative [client/src/themes/](./client/src/themes/). Copy token values verbatim; do not re-derive by eye. Pairs with [Theme System](./docs-internal/theme_system.md). |
| **[Schema Source of Truth RFC](./docs-internal/ARCHIVE/schema_source_of_truth_rfc.md)** | *Archived — shipped.* Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons; `VITE_NODESPEC_BACKEND` defaults on and the frontend node definitions are gone. Plugin pattern: one `BaseNode` subclass in `server/nodes/<group>/<plugin>/__init__.py`. Wire format: `asset:<key>` / `<lib>:<brand>` / URL / emoji. Endpoint: `/api/schemas/nodes/{type}/spec.json`. Current reference: [Plugin System](./docs-internal/plugin_system.md). |
| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern; `request()` supports `json` / `data` / `files` — the last for multipart uploads, threaded through the auth-retry rebuild). `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use); live count via `len(services.plugin.credential.CREDENTIAL_REGISTRY)` — do not hand-maintain a number here. `TaskQueue` constants route to Temporal worker pools. Plugins live across 9 queues (live plugin count via `len(services.node_registry.NODE_METADATA)`; a bare `__init__.py` glob overcounts by also matching group packages); handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `triggers.py` generic trigger-node handler, `todo.py` writeTodos shim — `google_auth.py` was retired into `nodes/google/_auth_helper.py`). **Wave 11.H added "self-contained plugin folders"** — generic registries (live list via `grep -rn '^def register_' server/services server/core`; the plugin-facing ones are `ws_handler_registry.{register_ws_handlers,register_router,register_option_loader,register_oauth_callback_path}`, `event_waiter.{register_filter_builder,register_trigger_precheck}`, `status_broadcaster.register_service_refresh`, `node_output_schemas.register_output_schema`, `edge_walker.{register_agent_context_builder,register_master_skill_expander}`, `register_webhook_source`, `register_canary_trigger_type`, `register_poll_coroutine_factory`, `register_social_send_handler`, `register_shutdown_hook`, `register_service_factory`, `register_log_source_tag`, `register_conversation_listener`) so rich plugins like telegram own their entire surface area without core-services edits. |
@@ -61,7 +61,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Skill Creation Guide](./server/skills/GUIDE.md)** | How to create new skills (folder structure, SKILL.md format, metadata, supporting files) |
| **[Known Errors & Troubleshooting](./docs-internal/errors.md)** | Documented root causes and fixes for common errors (SQLAlchemy Windows hang, Temporal issues, WhatsApp timeouts) |
| **[New Service Integration](./docs-internal/ARCHIVE/new_service_integration.md)** | *Archived* pre-Wave-11 guide; integrate a service as one plugin folder per [Node Creation Guide](./docs-internal/node_creation.md), with [server/nodes/google/](./server/nodes/google/) as the OAuth reference |
-| **[Onboarding Service](./docs-internal/onboarding.md)** | First-launch welcome wizard with 4 steps, database persistence, and replay from Settings |
+| **[Onboarding Service](./docs-internal/onboarding.md)** | The Welcome guide on Home (`features/home/onboarding/`): three steps (Welcome, Connect an AI model, Your first hire), opened on first launch and again from the header's Guide button or Settings → Help; progress saved on `UserSettings.onboarding_completed` / `onboarding_step`; the open state lives in `homeStore.guide`, so a remount never reopens it |
| **[CLI Services Integration](./docs-internal/cli_services_integration.md)** | Guide for integrating CLI-based services (Temporal, etc.) with proper lifecycle management |
| **[Temporal Architecture](./docs-internal/TEMPORAL_ARCHITECTURE.md)** | Distributed workflow execution: activities, FIRST_COMPLETED scheduling, horizontal scaling |
| **[Native LLM SDK](./docs-internal/native_llm_sdk.md)** | Native SDK layer in `services/llm/`: protocol-based providers, config-driven base URLs, and 14 registered providers (11 cloud, Ollama / LM Studio, and `openai_compatible`, which serves any number of user-named endpoints — llama.cpp, vLLM, a LiteLLM proxy — added in the Credentials Modal with no code; xAI is agent-selectable without a standalone chat-model node). A JSON-driven `supports_model_listing: false` flag covers endpoints that speak the OpenAI chat wire format but ship no `/v1/models` route (Sarvam) — `OpenAIProvider.fetch_models` then serves the curated list and probes the key with a one-token completion. `chat(on_event=...)` streams `StreamEvent`s only for providers whose block declares `"streaming": true` (Anthropic, OpenAI); the unifier replays the finished response into the sink for the rest, and the returned response never changes (`tests/llm/test_streaming.py`). Every provider is native; `tests/llm/test_langchain_removed.py` locks the retired-dependency end state. |
@@ -819,7 +819,7 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.
✅ **Authentication System**: n8n-style JWT authentication with HttpOnly cookies, single-owner and multi-user modes, rate-limited login. Note `AUTH_MODE=multi` authenticates but does NOT isolate data — see Known Limitations in [authentication.md](./docs-internal/authentication.md)
✅ **Cache System**: n8n-pattern cache with Redis (production) / SQLite (local dev) / Memory fallback hierarchy
✅ **AI Thinking/Reasoning**: Extended thinking for Claude, Gemini 2.5/3, OpenAI GPT-5/GPT-6/o-series, Groq Qwen3 with output available in Input Data & Variables for downstream nodes
-✅ **Onboarding Service**: 4-step welcome wizard with shadcn UI, database persistence, skip/resume/replay support
+✅ **Onboarding Service**: 3-step Welcome guide on Home with shadcn UI, database persistence, skip/resume/replay support
✅ **Proxy System**: Residential proxy provider management with template-based URL formatting, auto-selection by health score, transparent proxy injection on httpRequest/httpScraper nodes via `useProxy: true`
✅ **Markdown Formatter**: GFM markdown to platform-native formatting (Telegram HTML, WhatsApp syntax, plain text) using markdown-it-py
@@ -1372,7 +1372,7 @@ if "examples_loaded" not in columns:
## Onboarding Service
-Multi-step welcome wizard shown on first launch of the workflow editor (it lives in `Dashboard.tsx`, so with Normal mode on it first appears when Dev mode opens) — database-backed (`UserSettings.onboarding_completed` + `onboarding_step`), skippable, resumable, replayable from Settings, and auto-skipped for existing users (migration sets `onboarding_completed=1` where `examples_loaded=1`). Built with shadcn primitives (no antd). Full step list, key files, replay flow, and how to add a step are in **[Onboarding Service](./docs-internal/onboarding.md)**.
+The Welcome guide on Home ([features/home/onboarding/](./client/src/features/home/onboarding/), mounted by `HomeShell`): Welcome, Connect an AI model (the shared `CredentialsBrowser` cut to AI models) and Your first hire (Home's composer through genui's effect-free `useJobComposer`). It opens on first launch for an owner whose `UserSettings.onboarding_completed` is false, at the saved `onboarding_step`, and again from the header's Guide button or Settings → Help; skipping finishes it, and existing users were marked finished by the migration (`onboarding_completed=1` where `examples_loaded=1`). The open state and step live in `homeStore.guide` with a once-per-session `checked` flag, so a remount never reopens it. Once it is finished, a Get started checklist in Home's corner ticks off four first steps (two latched in `UserSettings`: `getting_started_said_hello`, `getting_started_approved_draft`). With `VITE_NORMAL_MODE=false` there is no Home and so no guide and no checklist. Steps, state, tests and key files are in **[Onboarding Service](./docs-internal/onboarding.md)**.
## AI Chat Model Development Guide
@@ -2758,7 +2758,7 @@ This function:
- **The sanitizer is client-only, and the backend depends on it without enforcing it.** There is no server-side sanitizer and no server-side export endpoint; the raw material is freely available to any caller via `handle_get_all_node_parameters` (`routers/websocket.py`), which returns stored parameters verbatim. So *any* export path built outside the React app is unsanitized by construction. This is deliberate but load-bearing: `server/tests/test_export_sanitizer_sync.py` reads `parameterSanitizer.ts` off disk and asserts its `RUNTIME_KEYS` covers everything `clear_agent_session_state` wipes — a cross-language invariant that exists because these two lists *already drifted once*, when the sanitizer held camelCase `memoryContent` against the real `memory_content` and every export carried full conversation histories into the shipped example workflows and from there into a public repo. Two consequences worth knowing before touching either side: adding a field to `clear_agent_session_state` fails that test until `RUNTIME_KEYS` matches, and adding a server-side export path silently bypasses stripping entirely. Known accepted hole: `sanitizeParameters` recurses into objects but passes arrays through untouched (documented in its own docstring and locked by `parameterSanitizer.test.ts`), so `{tasks: [{api_key: 'sk-1'}]}` exports the key.
- **Skill System Architecture**: Skills organized in `server/skills/<folder>/` subfolders. Each folder appears in Master Skill dropdown. DB/Master Skill customization is authoritative. Standard skills use progressive disclosure without modifying the agent system prompt: the dynamically connected `Skill` tool carries the bounded name/description catalogue, loads instructions, then separately reads/searches declared resources. Personality skills remain eager. Duplicate connected names block with `DUPLICATE_CONNECTED_SKILL_NAME`. Runtime state and sanitized `agent.skill.*` observability live in [`skill_runtime.py`](./server/services/skill_runtime.py); tool results persist in the current conversation while canvas badges clear at turn end. Icon resolution mirrors `BaseNode._metadata_dict`: per-plugin `<plugin>/icon.svg` (served as `/api/schemas/nodes/<type>/icon`) → `visuals.json` (emoji / `lobehub:<brand>`); color: per-plugin `<plugin>/meta.json` → `visuals.json`. Lives in [`skill_loader.py::_parse_skill_metadata`](./server/services/skill_loader.py). Native DOM keydown handler prevents React Flow from intercepting Ctrl shortcuts in skill editor. **Mutation broadcasts use the CloudEvents-typed `skill_lifecycle` wire key** with stages `created` / `updated` / `deleted` / `content_saved` — see "Plugin-folder location for plugin-specific CloudEvents factories" below.
- **Example Workflows**: Auto-load example workflow seeds from `<repo>/.opencompany/workflows/` on first use (git-tracked; the only non-ignored content under `<repo>/.opencompany/`). Path resolved by `core.paths.example_workflows_dir()` — fixed, NOT under `DATA_DIR`, preserved by `company clean` via `_OPENCOMPANY_KEEP`. Uses `UserSettings.examples_loaded` flag; supports anonymous users (`user_id="default"`); embedded `nodeParameters` saved to DB on import.
-- **Onboarding Service**: 4-step welcome wizard (Welcome, How it works, Connect your AI, Try it) using shadcn primitives + lucide icons. Database-backed via `UserSettings.onboarding_completed` + `onboarding_step`. Existing users auto-skip (migration marks `examples_loaded=1` as completed). Replayable from Settings "Help" section. No new WebSocket handlers needed. See [Onboarding Service](./docs-internal/onboarding.md) for details.
+- **Onboarding Service**: 3-step Welcome guide on Home (Welcome, Connect an AI model, Your first hire) using shadcn primitives + lucide icons. Database-backed via `UserSettings.onboarding_completed` + `onboarding_step`. Existing users auto-skip (migration marks `examples_loaded=1` as completed). Replayable from the Home header's Guide button and Settings → Help. No new WebSocket handlers needed. See [Onboarding Service](./docs-internal/onboarding.md) for details.
- **JS/TS Code Executor (bun sidecar)**: Persistent Express server on bun at `NODEJS_EXECUTOR_PORT` for JavaScript/TypeScript execution, replacing subprocess spawning per execution. `server/nodejs/` is bundled by `bun build src/index.ts --target=bun --outfile=dist/index.js` (express inlined) and spawned as `[bun, dist/index.js]` by `nodes/code/_runtime.py`, with bun resolved through `server/core/js_runtime.py` (`OPENCOMPANY_BUN_BIN`, else PATH) — no Node or npm anywhere shipped. The code executor plugins under `server/nodes/code/` call `NodeJSClient` which makes HTTP requests to the sidecar. All config via environment variables (`NODEJS_EXECUTOR_URL`, `NODEJS_EXECUTOR_PORT`, etc. — the names are unchanged).
- **writeTodos Tool Node**: Dedicated AI tool for task planning connecting to any agent's `input-tools` handle. `TodoService` singleton (`server/services/todo_service.py`) stores JSON-based per-session todo state keyed by workflow_id. Handler broadcasts `phase: "todo_update"` via WebSocket on each update for real-time UI. (The former checklist rendering — `formatTodoOutput()` — lived only in the legacy `ui/OutputDisplayPanel.tsx`, which was deleted as dead code; the active `components/output/OutputPanel.tsx` shows todo results as regular JSON.) Schema uses `TodoItem`/`TodoStatus` Pydantic enum. Skill at `server/skills/assistant/write-todos-skill/SKILL.md` teaches the plan-work-update loop.
- **Temporal Activity Heartbeats**: Activities send `activity.heartbeat()` on every non-matching WebSocket broadcast inside the read loop in `services/temporal/activities.py`. This keeps long-running browser and claude_code_agent operations alive past the 2-minute `heartbeat_timeout`. Start/end heartbeats alone were causing `TIMEOUT_TYPE_HEARTBEAT` failures on ops taking 5-10 minutes. Connection config: `heartbeat=30`, `receive_timeout=None` (each receive is bounded by a 30 s `asyncio.wait_for`; liveness comes from heartbeats, and per-node activities run under a 24 h `start_to_close_timeout`).
@@ -2781,7 +2781,7 @@ This function:
- **Telegram inbound content types**: `_format_message` extracts detail dicts for all 11 types via the `_CONTENT_PROBES` / `_DETAIL_EXTRACTORS` tables, plus a normalized `media` block (`kind` / `file_id` / `mime_type` / `file_name` / …) that downstream nodes read instead of branching per type; MIME and filename are synthesised where Telegram omits them. **Probe order is load-bearing**: Telegram sets `message.document` on animation messages too, so `animation` and `video_note` must be probed before `document` and `video` or every GIF classifies as a document. The trigger never downloads — media travels as a `file_id`, never bytes or base64, because node results are persisted, broadcast, and replayed into the LLM conversation every turn.
- **Google OAuth scope expansion**: Google's authorisation server legitimately returns a wider scope set than requested when the OAuth Client's "Data Access" page lists extra scopes (commonly `cloud-platform`) or when `include_granted_scopes` replays a previously-granted scope. `oauthlib` does strict set-equality and aborts with `Warning: Scope has changed`. As of 2026 (`google-auth-oauthlib` 1.2.4, `oauthlib` upstream issue #562 still open), no constructor flag, context manager, or `expected_scopes` argument exists — the documented relief is the env var. `server/nodes/google/_oauth.py` sets `OAUTHLIB_RELAX_TOKEN_SCOPE=1` via `os.environ.setdefault` BEFORE the `google_auth_oauthlib.flow` import (oauthlib reads it once at parameters-module import; request-time setting races under uvicorn workers), paired with `warnings.filterwarnings(message=r"Scope has changed.*")` to keep the operator log clean. Long-term root cause: audit the Cloud Console Data Access page and remove `cloud-platform` if no handler uses it.
- **Code-executor error mapping** (`pythonExecutor` / `javascriptExecutor` / `typescriptExecutor`): wrap user-code execution and sidecar calls in `try/except`. Python: detect `ImportError("__import__ not found")` (the LLM tried `import X` against the sandboxed builtins) and surface the pre-injected names list (`math, json, datetime, timedelta, re, random, Counter, defaultdict`) plus the suggestion to use `process_manager` for unsupported modules; other exceptions get formatted as `<ErrorName> at line N: <message>` (line N walked from `<string>` frame in the traceback) plus any captured stdout. JS/TS: detect `aiohttp.ClientConnectorError` / the spawn `RuntimeError` (bun missing or `dist/index.js` not built) and surface "JavaScript executor is unavailable (bun sidecar at <NODEJS_EXECUTOR_URL>). Fall back to python_executor for similar logic." All raise `NodeUserError` so the framework logs one WARN line — no aiohttp/CreateProcessW noise in the operator log.
-- **Workflow-scoped chat + console history**: chat messages persist with `chat_messages.session_id == <workflow_id>` (or `"default"` when no workflow is open); console logs persist with `console_logs.workflow_id`. Backend `database.get_console_logs(limit, workflow_id=None)` and `clear_console_logs(workflow_id=None)` filter by workflow when given. `handle_clear_console_logs` broadcasts `console_logs_cleared` carrying the `workflow_id` so the existing frontend filter in `WebSocketContext` keeps other workflows' panels intact. Frontend reads `currentWorkflow.id` via the documented Zustand escape hatch (`useAppStore.getState().currentWorkflow?.id`) at call time for `clearConsoleLogs` so the callback doesn't re-create on every workflow switch. A dedicated `useEffect([currentWorkflowId, isReady])` resets local `consoleLogs` and refetches them when the user opens / switches workflow. Incoming `console_log` broadcasts are filtered by `currentWorkflow.id` so a parallel run on another workflow never bleeds into the active panel. Legacy logs without `workflow_id` still surface (transition guard). `WebSocketContext` keeps no chat state: every reader (the console's Chat pane, Home's employee page, the get-started checklist in `hooks/useGetStarted.ts`) reads `get_chat_messages` through the shared thread query (`useChatThread` from `features/chat`), which `chat.updated`, a runtime reset and a reconnect invalidate.
+- **Workflow-scoped chat + console history**: chat messages persist with `chat_messages.session_id == <workflow_id>` (or `"default"` when no workflow is open); console logs persist with `console_logs.workflow_id`. Backend `database.get_console_logs(limit, workflow_id=None)` and `clear_console_logs(workflow_id=None)` filter by workflow when given. `handle_clear_console_logs` broadcasts `console_logs_cleared` carrying the `workflow_id` so the existing frontend filter in `WebSocketContext` keeps other workflows' panels intact. Frontend reads `currentWorkflow.id` via the documented Zustand escape hatch (`useAppStore.getState().currentWorkflow?.id`) at call time for `clearConsoleLogs` so the callback doesn't re-create on every workflow switch. A dedicated `useEffect([currentWorkflowId, isReady])` resets local `consoleLogs` and refetches them when the user opens / switches workflow. Incoming `console_log` broadcasts are filtered by `currentWorkflow.id` so a parallel run on another workflow never bleeds into the active panel. Legacy logs without `workflow_id` still surface (transition guard). `WebSocketContext` keeps no chat state: every reader (the console's Chat pane, Home's employee page, Home's Get started checklist in `features/home/onboarding/useGetStarted.ts`) reads `get_chat_messages` through the shared thread query (`useChatThread` from `features/chat`), which `chat.updated`, a runtime reset and a reconnect invalidate.
- **Auto-derived `isConfigNode` uiHint**: `_derive_auto_ui_hints(group)` in `services/plugin/base.py` automatically sets `uiHints.isConfigNode: True` on any plugin whose `group` tuple contains `memory` or `tool` (centralized as `_CONFIG_NODE_GROUPS = frozenset({"memory", "tool"})`). Explicit `cls.ui_hints` always wins (merge order: auto first, then `dict.update`). Frontend `InputSection.tsx` consumes the flag via `definition?.uiHints?.isConfigNode === true` — the old `groups.includes('memory') || groups.includes('tool')` heuristic is gone. Pytest invariant `test_ui_hints_only_carry_known_flags` locks the flag name. Adding a new auxiliary node type costs zero per-plugin code; opting out costs one line (`ui_hints = {"isConfigNode": False}`).
- **`isMasterSkillEditor` uiHint replaces `node.type === 'masterSkill'` checks**: the frontend callsites (`useAutoSkillEdges.ts` constant + edge filter, `MiddleSection.tsx` × 3; Dashboard's component-dispatch branch went with the unused `ToolkitNode`, because masterSkill declares `component_kind = "tool"` and renders through SquareNode) read `getCachedNodeSpec(type)?.uiHints?.isMasterSkillEditor === true` instead of comparing the type string. The `MasterSkillNode` plugin already declared the hint — no backend change. Renaming the plugin's `type` is now a single backend edit followed by a NodeSpec deploy; the frontend never needs to know the string.
- **`outputMode: "terminal"` uiHint — spec-driven CLI output rendering**: the output panel (`components/output/OutputPanel.tsx`, the active renderer — `ui/OutputDisplayPanel.tsx` is legacy/unimported) renders string responses through ReactMarkdown by default, which whitespace-collapses CLI text. CLI-wrapper plugins (`githubAction`, `vercelAction`, `shell`) declare `ui_hints = {"outputMode": "terminal"}`; the panel resolves the spec via `useNodeSpec(selectedNode?.type)` and renders their text in a `<pre>` on the per-theme `--code-*` surface, routes wholly-JSON strings to the JSON tree via the shared `tryParseJson` (`utils/formatters.ts`), and surfaces object/array `result` payloads (server-side-parsed CLI JSON; arrays survive `unwrap` un-peeled) in the Response section. Pair with the `_shape` convention: parsed JSON in `result` OR text in `stdout` — never both — empty keys omitted. Locked by `client/src/components/__tests__/OutputPanel.test.tsx` (render tests: real `\n`/`\t` preserved) + the uiHints known-set in `test_node_spec.py`. Cache note: nodeSpecs are session-sticky (`staleTime: FOREVER`, revision-busted at page load) — after a backend restart a hard browser reload is needed before new uiHints reach an open canvas.
diff --git a/client/src/App.tsx b/client/src/App.tsx
index 9bc4c35c..9366e61f 100644
--- a/client/src/App.tsx
+++ b/client/src/App.tsx
@@ -1,23 +1,33 @@
-import React from 'react';
+import React, { useEffect } from 'react';
import AppShell from './app/AppShell';
+import { usePageActivitySync } from './app/usePageActivitySync';
import ProtectedRoute from './components/auth/ProtectedRoute';
import SvgFilterDefs from './components/SvgFilterDefs';
import { Toaster } from '@/components/ui/sonner';
+import { disposeOrb } from './features/home/orb/orb';
import { PillToaster } from './features/home/ui/pillToast';
// `<html data-theme>` and the `.dark` flag are written by ThemeProvider
// (contexts/ThemeContext.tsx) and, before the first paint, by the script in
// index.html. Nothing else may write them.
-const App: React.FC = () => (
- <>
- <SvgFilterDefs />
- <ProtectedRoute>
- <AppShell />
- </ProtectedRoute>
- <Toaster position="top-right" richColors closeButton />
- {/* Normal mode's bottom-centre pill toasts; see features/home/ui/pillToast. */}
- <PillToaster />
- </>
-);
+const App: React.FC = () => {
+ // Above the sign-in gate, which draws the orb too: page activity pauses
+ // script-driven motion on every screen, and signing out must not free the
+ // orb the sign-in screen has just taken. The orb keeps its renderer across
+ // screens and goes with the app.
+ usePageActivitySync();
+ useEffect(() => disposeOrb, []);
+ return (
+ <>
+ <SvgFilterDefs />
+ <ProtectedRoute>
+ <AppShell />
+ </ProtectedRoute>
+ <Toaster position="top-right" richColors closeButton />
+ {/* Normal mode's bottom-centre pill toasts; see features/home/ui/pillToast. */}
+ <PillToaster />
+ </>
+ );
+};
export default App;
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index ab802701..1ba1beda 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -33,8 +33,6 @@ import ComponentPalette from './components/ui/ComponentPalette';
import TopToolbar from './components/ui/TopToolbar';
import WorkflowSidebar from './components/ui/WorkflowSidebar';
import AIResultModal from './components/ui/AIResultModal';
-import OnboardingWizard from './components/onboarding/OnboardingWizard';
-import GetStartedChecklist from './components/onboarding/GetStartedChecklist';
import { useShellDialogsStore } from './stores/shellDialogsStore';
import ErrorBoundary from './components/ui/ErrorBoundary';
import ConsolePanel from './components/ui/ConsolePanel';
@@ -166,12 +164,10 @@ const DashboardContent: React.FC = () => {
const setSelectedNode = useAppStore((s) => s.setSelectedNode);
const renamingNodeId = useAppStore((s) => s.renamingNodeId);
const setRenamingNodeId = useAppStore((s) => s.setRenamingNodeId);
- const openExampleAndChat = useAppStore((s) => s.openExampleAndChat);
// App-level dialogs live in the shell (app/AppShell) so either screen can
// open them.
const openSettings = useShellDialogsStore((s) => s.openSettings);
const openCredentials = useShellDialogsStore((s) => s.openCredentials);
- const onboardingReplay = useShellDialogsStore((s) => s.onboardingReplay);
// Per-workflow UI state (n8n pattern)
const setWorkflowExecuting = useAppStore((s) => s.setWorkflowExecuting);
const setWorkflowExecutionOrder = useAppStore((s) => s.setWorkflowExecutionOrder);
@@ -213,7 +209,7 @@ const DashboardContent: React.FC = () => {
} = useWorkflowManagement();
const { collapsedSections, searchQuery, setSearchQuery, toggleSection } = useComponentPalette();
- const { saveNodeParameters, getNodeParameters, getAllNodeParameters, executeWorkflow, nodeStatuses, deploymentStatus, workflowControlStatuses, workflowControlPending, startWorkflow, pauseWorkflow, resumeWorkflow, resetWorkflow, getWorkflowControlStatus, workflowLock, isReady, sendRequest, clearNodeStatus } = useWebSocket();
+ const { saveNodeParameters, getNodeParameters, getAllNodeParameters, executeWorkflow, nodeStatuses, deploymentStatus, workflowControlStatuses, workflowControlPending, startWorkflow, pauseWorkflow, resumeWorkflow, resetWorkflow, workflowLock, isReady, sendRequest, clearNodeStatus } = useWebSocket();
// Workflows list: server-owned data, cached by TanStack Query.
const queryClient = useQueryClient();
@@ -733,35 +729,6 @@ const DashboardContent: React.FC = () => {
}
};
- // Onboarding handoff: open the AI Assistant example, focus chat, and
- // deploy it so the chat trigger is live. Shared by the wizard's finish
- // button and the Get Started checklist.
- const handleRunExample = React.useCallback(async () => {
- if (!(await settleUnsavedWork())) return;
- const workflow = await openExampleAndChat('AI Assistant');
- if (!workflow) return;
-
- try {
- const status = await getWorkflowControlStatus(workflow.id);
- if (!status.can_start) return;
- const result = await startWorkflow(
- workflow.id,
- workflow.nodes,
- workflow.edges,
- 'default',
- status.revision,
- );
- applyAuthoritativeStartGraph(workflow.id, result);
- } catch {
- toast.error('Could not start the example — press Start on the toolbar.');
- }
- }, [
- applyAuthoritativeStartGraph,
- getWorkflowControlStatus,
- openExampleAndChat,
- startWorkflow,
- ]);
-
const handlePauseWorkflow = async () => {
const workflowId = currentWorkflow?.id;
if (!workflowId) return;
@@ -1389,23 +1356,6 @@ const DashboardContent: React.FC = () => {
result={executionResult}
/>
- {/* Onboarding Wizard (editor only; Settings and Credentials are
- shell dialogs, see app/AppShell). */}
- <OnboardingWizard
- onOpenCredentials={openCredentials}
- reopenTrigger={onboardingReplay}
- onFinish={() => void handleRunExample()}
- />
-
- {/* Get Started checklist (appears after onboarding completes) */}
- <GetStartedChecklist
- actions={{
- 'add-key': openCredentials,
- 'chat-example': () => void handleRunExample(),
- 'build-workflow': handleNew,
- }}
- />
-
{/* Node Context Menu (right-click) */}
{contextMenu && (
<NodeContextMenu
diff --git a/client/src/app/AppShell.tsx b/client/src/app/AppShell.tsx
index 627a6b30..f82ce28a 100644
--- a/client/src/app/AppShell.tsx
+++ b/client/src/app/AppShell.tsx
@@ -10,18 +10,15 @@
* changes on every console, chat and terminal line.
*/
-import { Suspense, lazy, useEffect, useState } from 'react';
+import { Suspense, lazy, useState } from 'react';
import { TooltipProvider } from '@/components/ui/tooltip';
-import { disposeOrb } from '../features/home/orb/orb';
import { useSoundSync } from '../hooks/useSound';
-import { useSaveUserSettingsMutation } from '../hooks/useUserSettingsQuery';
import { useSavedGraphSync } from '../hooks/useWorkflowOpsListener';
import { useShellDialogsStore } from '../stores/shellDialogsStore';
import { useWorkflowSettingsStore } from '../stores/workflowSettingsStore';
import { ShellModeSwitch } from './ShellModeSwitch';
import { useCurrentWorkflowSync } from './useCurrentWorkflowSync';
import { useModeShortcut } from './useModeShortcut';
-import { usePageActivitySync } from './usePageActivitySync';
import { useUIDefaultsOnce } from './useUIDefaultsOnce';
const SettingsPanel = lazy(() => import('../components/ui/SettingsPanel'));
@@ -31,14 +28,11 @@ function ShellEffects() {
// Mirror the sound preference into the WebAudio engine and re-read
// --sound-pack whenever the theme changes.
useSoundSync();
- usePageActivitySync();
useCurrentWorkflowSync();
// Server-saved canvas changes reach the editor's copy on either screen.
useSavedGraphSync();
useUIDefaultsOnce();
useModeShortcut();
- // Home's orb keeps its renderer across mode switches; free it with the app.
- useEffect(() => disposeOrb, []);
return null;
}
@@ -56,10 +50,8 @@ function ShellDialogs() {
const credentialsOpen = useShellDialogsStore((s) => s.credentialsOpen);
const closeSettings = useShellDialogsStore((s) => s.closeSettings);
const closeCredentials = useShellDialogsStore((s) => s.closeCredentials);
- const replayOnboarding = useShellDialogsStore((s) => s.replayOnboarding);
const settings = useWorkflowSettingsStore((s) => s.settings);
const setSettings = useWorkflowSettingsStore((s) => s.setSettings);
- const saveUserSettings = useSaveUserSettingsMutation();
const settingsMounted = useOpenedOnce(settingsOpen);
const credentialsMounted = useOpenedOnce(credentialsOpen);
@@ -71,11 +63,6 @@ function ShellDialogs() {
onClose={closeSettings}
settings={settings}
onSettingsChange={setSettings}
- onReplayOnboarding={replayOnboarding}
- onShowGetStarted={() => {
- saveUserSettings.mutate({ getting_started_dismissed: false });
- closeSettings();
- }}
/>
)}
{credentialsMounted && <CredentialsModal visible={credentialsOpen} onClose={closeCredentials} />}
diff --git a/client/src/components/__tests__/CredentialsModal.test.tsx b/client/src/components/__tests__/CredentialsModal.test.tsx
index 95a58acf..0c004fbb 100644
--- a/client/src/components/__tests__/CredentialsModal.test.tsx
+++ b/client/src/components/__tests__/CredentialsModal.test.tsx
@@ -153,7 +153,7 @@ describe('shared credentials host', () => {
it('keeps AI guidance and key links, and a refused save preserves the input and shows its reason', async () => {
mount({ categoryId: 'ai', intent: 'connect' }); await open();
- expect(await screen.findByText(/Your employees need an AI model/)).toBeVisible();
+ expect(await screen.findByRole('dialog', { name: 'Connect an AI model' })).toBeVisible();
expect(screen.queryByRole('button', { name: 'Manage Telegram' })).not.toBeInTheDocument();
await userEvent.click(await screen.findByRole('button', { name: 'Connect OpenAI' }));
expect(screen.getByRole('link', { name: 'Get a key from OpenAI' })).toHaveAttribute('href', 'https://platform.openai.com/api-keys');
diff --git a/client/src/components/catalog/CatalogLayout.tsx b/client/src/components/catalog/CatalogLayout.tsx
index e812460a..cab2e94c 100644
--- a/client/src/components/catalog/CatalogLayout.tsx
+++ b/client/src/components/catalog/CatalogLayout.tsx
@@ -9,7 +9,10 @@
* - the page supplies both lists, and Yours counts its own;
* - the category filter exists when there are categories, and starts open
* when the page is opened on one;
- * - Discover shows DISCOVER_LIMIT cards until "Show all";
+ * - Discover shows DISCOVER_LIMIT cards until "Show all" (`discoverLimit`
+ * changes the cap; null shows everything);
+ * - `variant="embedded"` fits a narrower host (the Welcome guide's step):
+ * a smaller title and a shorter search box;
* - a card offers remove only with `onRemove`, and a switch only with
* `onToggle`;
* - a card glows when its item turns 'added' while it is on screen, then
@@ -51,6 +54,12 @@ export interface CatalogLayoutProps {
onItemAdded?: (item: CatalogItem) => void;
/** A header button that opens an inline form above the list. */
primaryAction?: { label: string; form: (close: () => void) => ReactNode };
+ /** `page` in Settings; `embedded` inside a narrower host. */
+ variant?: 'page' | 'embedded';
+ /** Cards Discover shows before "Show all"; null shows every one. */
+ discoverLimit?: number | null;
+ /** The Yours / Discover switch's accessible name (default "{title} to show"). */
+ listLabel?: string;
}
const GRID = '-mt-2 grid grid-cols-[repeat(auto-fill,minmax(min(100%,300px),1fr))] gap-3';
@@ -70,6 +79,9 @@ export function CatalogLayout({
onToggle,
onItemAdded,
primaryAction,
+ variant = 'page',
+ discoverLimit = DISCOVER_LIMIT,
+ listLabel,
}: CatalogLayoutProps) {
const [view, setView] = useState<CatalogView>('discover');
const [category, setCategory] = useState(initialCategory);
@@ -90,8 +102,10 @@ export function CatalogLayout({
}, [view, category]);
const list = view === 'yours' ? yours.items : discover.items;
- const { shown, total } = catalogSlice(list, { category, query, cap: view === 'discover' && !showAll ? DISCOVER_LIMIT : null });
- const canShowAll = view === 'discover' && total > DISCOVER_LIMIT;
+ const cap = view === 'discover' && !showAll ? discoverLimit : null;
+ const { shown, total } = catalogSlice(list, { category, query, cap });
+ const canShowAll = view === 'discover' && discoverLimit !== null && total > discoverLimit;
+ const embedded = variant === 'embedded';
const q = query.trim();
const changeView = (next: CatalogView) => {
@@ -117,11 +131,11 @@ export function CatalogLayout({
return (
<div ref={rootRef} className="flex flex-col gap-5.5 px-4 pt-6.5 pb-8 sm:px-8">
<div data-stagger className="flex flex-wrap items-center gap-3.5 pr-10">
- <h2 className="text-xl font-semibold tracking-[-0.02em] text-fg-default">{title}</h2>
+ <h2 className={cn('font-semibold tracking-[-0.02em] text-fg-default', embedded ? 'text-lg' : 'text-xl')}>{title}</h2>
<ToggleGroup
type="single"
variant="segmented"
- aria-label={`${title} to show`}
+ aria-label={listLabel ?? `${title} to show`}
value={view}
onValueChange={(next) => next && changeView(next as CatalogView)}
>
@@ -133,8 +147,13 @@ export function CatalogLayout({
Discover
</ToggleGroupItem>
</ToggleGroup>
- <div className="ml-auto flex flex-[1_1_280px] items-center justify-end gap-2">
- <SearchField value={query} onChange={setQuery} placeholder={searchPlaceholder} className="max-w-75 flex-1" />
+ <div className={cn('ml-auto flex items-center justify-end gap-2', embedded ? 'flex-[1_1_180px]' : 'flex-[1_1_280px]')}>
+ <SearchField
+ value={query}
+ onChange={setQuery}
+ placeholder={searchPlaceholder}
+ className={cn('flex-1', embedded ? 'max-w-60' : 'max-w-75')}
+ />
{categories.length > 0 && (
<Toggle
variant="chips"
diff --git a/client/src/components/credentials/CredentialsBrowser.tsx b/client/src/components/credentials/CredentialsBrowser.tsx
index ff19878b..e10b585e 100644
--- a/client/src/components/credentials/CredentialsBrowser.tsx
+++ b/client/src/components/credentials/CredentialsBrowser.tsx
@@ -74,11 +74,36 @@ function toItem(provider: ConsumerProvider): CatalogItem {
};
}
+/** What the browser says. Settings > Connectors uses the defaults; the
+ * Welcome guide's Connect step speaks of AI models. */
+export interface CredentialsBrowserCopy {
+ title: string;
+ searchPlaceholder: string;
+ /** The Yours / Discover switch's accessible name. */
+ listLabel: string;
+ discoverTitle: string;
+ yoursEmpty: { title: string; detail: string };
+}
+
+const CONNECTORS_COPY: CredentialsBrowserCopy = {
+ title: 'Connectors',
+ searchPlaceholder: 'Search connectors',
+ listLabel: 'Connectors to show',
+ discoverTitle: 'Top connectors',
+ yoursEmpty: { title: 'No apps connected yet', detail: 'Connect the apps your employees should work in.' },
+};
+
export interface CredentialsBrowserProps {
onConnect: (providerId: string, intent?: 'connect' | 'manage') => void;
initialCategory?: string;
/** The host can share its query/visibility result without another hook. */
catalogue?: CredentialsCatalogue;
+ copy?: CredentialsBrowserCopy;
+ /** Passed to CatalogLayout (the Welcome guide embeds the browser). */
+ variant?: 'page' | 'embedded';
+ discoverLimit?: number | null;
+ /** A provider on screen turned connected (after its card's glow starts). */
+ onItemAdded?: (providerId: string) => void;
}
export function CredentialsBrowser(props: CredentialsBrowserProps) {
@@ -96,6 +121,10 @@ function CredentialsBrowserContent({
onConnect,
initialCategory = 'all',
catalogue,
+ copy = CONNECTORS_COPY,
+ variant,
+ discoverLimit,
+ onItemAdded,
}: CredentialsBrowserProps & { catalogue: CredentialsCatalogue }) {
const { providers, categories, isLoading, isError, refetch } = catalogue;
const { sendRequest } = useWebSocketActions();
@@ -130,21 +159,21 @@ function CredentialsBrowserContent({
return (
<>
<CatalogLayout
- title="Connectors"
- searchPlaceholder="Search connectors"
+ title={copy.title}
+ searchPlaceholder={copy.searchPlaceholder}
+ listLabel={copy.listLabel}
+ variant={variant}
+ discoverLimit={discoverLimit}
loading={isLoading}
categories={categories}
initialCategory={initialCategory}
- yours={{
- items: connected,
- sectionTitle: 'Connected',
- empty: { title: 'No apps connected yet', detail: 'Connect the apps your employees should work in.' },
- }}
- discover={{ items, sectionTitle: 'Top connectors' }}
+ yours={{ items: connected, sectionTitle: 'Connected', empty: copy.yoursEmpty }}
+ discover={{ items, sectionTitle: copy.discoverTitle }}
verbs={{ add: 'Connect', remove: 'Disconnect' }}
onAdd={(item) => onConnect(item.id, 'connect')}
onManage={(item) => onConnect(item.id, 'manage')}
onRemove={(item) => setConfirming(byId.get(item.id) ?? null)}
+ onItemAdded={onItemAdded && ((item) => onItemAdded(item.id))}
/>
<AlertDialog open={confirming !== null} onOpenChange={(open) => !open && setConfirming(null)}>
diff --git a/client/src/components/credentials/CredentialsModal.tsx b/client/src/components/credentials/CredentialsModal.tsx
index b132f1bc..55bda74d 100644
--- a/client/src/components/credentials/CredentialsModal.tsx
+++ b/client/src/components/credentials/CredentialsModal.tsx
@@ -1,19 +1,14 @@
-/** One app-level host for browsing, connecting and managing credentials. */
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { ArrowLeft, ExternalLink, ShieldCheck } from 'lucide-react';
+/** One app-level host for browsing, connecting and managing credentials.
+ * The Welcome guide's Connect step shows the same provider page inline
+ * (ProviderPage); every other entry point opens this dialog. */
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { ShieldCheck } from 'lucide-react';
import { toast } from 'sonner';
-import { useShellMode } from '@/app/ShellModeSwitch';
-import { FEATURED_AI_PROVIDERS } from '@/components/onboarding/aiProviderLinks';
import Modal from '@/components/ui/Modal';
-import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
-import { Badge } from '@/components/ui/badge';
-import { Button } from '@/components/ui/button';
-import { Skeleton } from '@/components/ui/skeleton';
import { useShellDialogsStore, type CredentialsIntent, type CredentialsOptions } from '@/stores/shellDialogsStore';
import CredentialsBrowser from './CredentialsBrowser';
import { isConnected, useCredentialsCatalogue } from './catalogue';
-import { rehydrateProvider } from './catalogueAdapter';
-import PanelRenderer from './PanelRenderer';
+import { ProviderPage } from './ProviderPage';
interface Props { visible: boolean; onClose: () => void }
@@ -26,7 +21,6 @@ export default function CredentialsModal(props: Props) {
function CredentialsSession({ visible, onClose, options }: Props & { options: CredentialsOptions }) {
const view = useCredentialsCatalogue();
- const showTechnicalSections = useShellMode() === 'dev';
const [browsing, setBrowsing] = useState(!options.providerId);
const [selection, setSelection] = useState<{ id: string; intent: CredentialsIntent } | null>(
options.providerId ? { id: options.providerId, intent: options.intent ?? 'manage' } : null,
@@ -35,8 +29,6 @@ function CredentialsSession({ visible, onClose, options }: Props & { options: Cr
const providerOpener = useRef<HTMLElement | null>(null);
const sessionOpener = useRef<HTMLElement | null>(null);
const provider = view.providers.find((p) => p.id === selection?.id) ?? null;
- const config = useMemo(() => provider ? rehydrateProvider(provider) : null, [provider]);
- const featured = FEATURED_AI_PROVIDERS.find((p) => p.id === provider?.id);
const connected = provider ? isConnected(provider) : false;
const seen = useRef({ id: selection?.id, known: false, connected: false });
@@ -58,7 +50,6 @@ function CredentialsSession({ visible, onClose, options }: Props & { options: Cr
const allProviders = () => { setBrowsing(true); setSelection(null); };
const aiSetup = options.categoryId === 'ai' && options.intent === 'connect';
- const hasData = Boolean(view.catalogue.data) && !view.isLoading;
return (
<>
@@ -81,14 +72,6 @@ function CredentialsSession({ visible, onClose, options }: Props & { options: Cr
}
}}
>
- {aiSetup && (
- <div className="px-5 pt-5 sm:px-8">
- <p className="text-sm text-fg-muted">
- Your employees need an AI model to think. Pick a provider, then connect with its API key,
- or choose a model that runs on this computer.
- </p>
- </div>
- )}
<CredentialsBrowser catalogue={view} initialCategory={options.categoryId}
onConnect={(id, intent = 'connect') => setSelection({ id, intent })} />
</Modal>
@@ -113,59 +96,16 @@ function CredentialsSession({ visible, onClose, options }: Props & { options: Cr
if (providerOpener.current?.isConnected) providerOpener.current.focus();
}}
>
- <div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-5 pt-4">
- <Button variant="quiet" size="sm" onClick={allProviders} className="-ml-2 gap-1">
- <ArrowLeft aria-hidden className="size-4" />
- {options.categoryId === 'ai' ? 'All AI models' : 'All connectors'}
- </Button>
- {featured && (
- <a href={featured.keyUrl} target="_blank" rel="noopener noreferrer"
- className="ml-auto inline-flex items-center gap-1 text-sm text-fg-default underline-offset-4 hover:underline">
- Get a key from {provider?.name}<ExternalLink aria-hidden className="size-3.5" />
- </a>
- )}
- </div>
- {!hasData ? (
- view.isError ? <CatalogueError onRetry={() => void view.refetch()} /> : (
- <div className="space-y-3 p-5" role="status" aria-label="Loading connector">
- <Skeleton className="h-6 w-48" /><Skeleton className="h-24 w-full" />
- </div>
- )
- ) : !provider ? (
- <div className="p-5">
- <Alert>
- <AlertTitle>Connector unavailable</AlertTitle>
- <AlertDescription>This connector is missing or disabled. Choose another connector from the catalogue.</AlertDescription>
- </Alert>
- </div>
- ) : (
- <>
- <div className="space-y-2 px-5 pt-3 text-sm text-fg-muted">
- {(provider.description || featured?.hint) && <p>{provider.description || featured?.hint}</p>}
- <div className="flex flex-wrap items-center gap-2">
- {provider.publisher && <span>by {provider.publisher}</span>}
- {provider.verified && <Badge variant="outline">Verified</Badge>}
- <Badge variant={connected ? 'success' : 'secondary'}>{connected ? 'Connected' : 'Not connected'}</Badge>
- {connected && provider.account_label && <span>{provider.account_label}</span>}
- {provider.runs_locally && <span>Runs on this computer</span>}
- </div>
- </div>
- <PanelRenderer config={config} visible={visible} showTechnicalSections={showTechnicalSections} />
- </>
+ {selection && (
+ <ProviderPage
+ view={view}
+ selection={selection}
+ backLabel={options.categoryId === 'ai' ? 'All AI models' : 'All connectors'}
+ onBack={allProviders}
+ visible={visible}
+ />
)}
</Modal>
</>
);
}
-
-function CatalogueError({ onRetry }: { onRetry: () => void }) {
- return (
- <div className="p-5">
- <Alert variant="destructive">
- <AlertTitle>Couldn't reach the credentials server</AlertTitle>
- <AlertDescription>Check your connection and try again.</AlertDescription>
- </Alert>
- <Button variant="outline" onClick={onRetry} className="mt-3">Try again</Button>
- </div>
- );
-}
diff --git a/client/src/components/credentials/ProviderPage.tsx b/client/src/components/credentials/ProviderPage.tsx
new file mode 100644
index 00000000..5d85d4f6
--- /dev/null
+++ b/client/src/components/credentials/ProviderPage.tsx
@@ -0,0 +1,130 @@
+/**
+ * One provider's page: back to the list, "Get a key from …" for the featured
+ * AI providers, what it is (description, publisher, Verified, connected or
+ * not, runs on this computer), and its panel (PanelRenderer). The
+ * credentials dialog shows it as its second layer, under its own title bar;
+ * the Welcome guide's Connect step shows it in place of the list, with its
+ * own heading (`showHeading`).
+ *
+ * Rows keep the panel's 20px inset (ApiKeyPanel pads itself by `p-5`), so
+ * a host adds only its outer margin.
+ */
+
+import { useEffect, useMemo, useRef } from 'react';
+import { ArrowLeft, ExternalLink } from 'lucide-react';
+import { useShellMode } from '@/app/ShellModeSwitch';
+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import type { CredentialsIntent } from '@/stores/shellDialogsStore';
+import { FEATURED_AI_PROVIDERS } from './aiProviderLinks';
+import { isConnected, type CredentialsCatalogue } from './catalogue';
+import { rehydrateProvider } from './catalogueAdapter';
+import PanelRenderer from './PanelRenderer';
+
+export interface ProviderSelection {
+ id: string;
+ intent: CredentialsIntent;
+}
+
+export interface ProviderPageProps {
+ view: CredentialsCatalogue;
+ selection: ProviderSelection;
+ backLabel: string;
+ onBack: () => void;
+ /** Whether the page is on screen (the panel's `visible`). */
+ visible: boolean;
+ /** "Connect {name}" / "Manage {name}" as the page's own heading. */
+ showHeading?: boolean;
+ /** Move focus to Back when the page appears (it replaced the list). */
+ autoFocusBack?: boolean;
+}
+
+export function ProviderPage({ view, selection, backLabel, onBack, visible, showHeading = false, autoFocusBack = false }: ProviderPageProps) {
+ const showTechnicalSections = useShellMode() === 'dev';
+ const provider = view.providers.find((p) => p.id === selection.id) ?? null;
+ const config = useMemo(() => (provider ? rehydrateProvider(provider) : null), [provider]);
+ const featured = FEATURED_AI_PROVIDERS.find((p) => p.id === provider?.id);
+ const connected = provider ? isConnected(provider) : false;
+ const hasData = Boolean(view.catalogue.data) && !view.isLoading;
+ const backRef = useRef<HTMLButtonElement>(null);
+
+ useEffect(() => {
+ if (autoFocusBack) backRef.current?.focus();
+ }, [autoFocusBack]);
+
+ return (
+ <>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-5 pt-4">
+ <Button ref={backRef} variant="quiet" size="sm" onClick={onBack} className="-ml-2 gap-1">
+ <ArrowLeft aria-hidden className="size-4" />
+ {backLabel}
+ </Button>
+ {featured && (
+ <a
+ href={featured.keyUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="ml-auto inline-flex items-center gap-1 text-sm text-fg-default underline-offset-4 hover:underline"
+ >
+ Get a key from {provider?.name}
+ <ExternalLink aria-hidden className="size-3.5" />
+ </a>
+ )}
+ </div>
+ {showHeading && provider && (
+ <h2 className="m-0 px-5 pt-2.5 text-lg font-semibold tracking-[-0.02em] text-fg-default">
+ {selection.intent === 'manage' ? 'Manage' : 'Connect'} {provider.name}
+ </h2>
+ )}
+ {!hasData ? (
+ view.isError ? (
+ <CatalogueError onRetry={() => void view.refetch()} />
+ ) : (
+ <div className="space-y-3 p-5" role="status" aria-label="Loading connector">
+ <Skeleton className="h-6 w-48" />
+ <Skeleton className="h-24 w-full" />
+ </div>
+ )
+ ) : !provider ? (
+ <div className="p-5">
+ <Alert>
+ <AlertTitle>Connector unavailable</AlertTitle>
+ <AlertDescription>This connector is missing or disabled. Choose another connector from the catalogue.</AlertDescription>
+ </Alert>
+ </div>
+ ) : (
+ <>
+ <div className="space-y-2 px-5 pt-3 text-sm text-fg-muted">
+ {(provider.description || featured?.hint) && <p>{provider.description || featured?.hint}</p>}
+ <div className="flex flex-wrap items-center gap-2">
+ {provider.publisher && <span>by {provider.publisher}</span>}
+ {provider.verified && <Badge variant="outline">Verified</Badge>}
+ <Badge variant={connected ? 'success' : 'secondary'}>{connected ? 'Connected' : 'Not connected'}</Badge>
+ {connected && provider.account_label && <span>{provider.account_label}</span>}
+ {provider.runs_locally && <span>Runs on this computer</span>}
+ </div>
+ </div>
+ <PanelRenderer config={config} visible={visible} showTechnicalSections={showTechnicalSections} />
+ </>
+ )}
+ </>
+ );
+}
+
+function CatalogueError({ onRetry }: { onRetry: () => void }) {
+ return (
+ <div className="p-5">
+ <Alert variant="destructive">
+ <AlertTitle>Couldn't reach the credentials server</AlertTitle>
+ <AlertDescription>Check your connection and try again.</AlertDescription>
+ </Alert>
+ <Button variant="outline" onClick={onRetry} className="mt-3">
+ Try again
+ </Button>
+ </div>
+ );
+}
+
+export default ProviderPage;
diff --git a/client/src/components/onboarding/aiProviderLinks.ts b/client/src/components/credentials/aiProviderLinks.ts
similarity index 62%
rename from client/src/components/onboarding/aiProviderLinks.ts
rename to client/src/components/credentials/aiProviderLinks.ts
index e90be02d..bb0354f8 100644
--- a/client/src/components/onboarding/aiProviderLinks.ts
+++ b/client/src/components/credentials/aiProviderLinks.ts
@@ -1,14 +1,14 @@
/**
- * Featured AI providers for onboarding surfaces (wizard + Get Started
- * checklist). Only marketing hints and key-page URLs live here — display
- * name, icon, and stored state come from the live credential catalogue
- * (`useCatalogueQuery`), which is the single source of truth.
+ * Featured AI providers: where to get a key, and a one-line hint. The
+ * provider page links "Get a key from {name}" for these. Only the hint and
+ * the key-page URL live here; the name, icon and connected state come from
+ * the live credential catalogue.
*/
export interface FeaturedAiProvider {
/** Catalogue provider id (`ServerProviderConfig.id`). */
id: string;
- /** One-line plain-language hint shown under the provider name. */
+ /** One-line plain-language hint, used when the catalogue has no description. */
hint: string;
/** Direct link to the page where the user generates an API key. */
keyUrl: string;
diff --git a/client/src/components/onboarding/GetStartedChecklist.tsx b/client/src/components/onboarding/GetStartedChecklist.tsx
deleted file mode 100644
index fc0b78de..00000000
--- a/client/src/components/onboarding/GetStartedChecklist.tsx
+++ /dev/null
@@ -1,142 +0,0 @@
-import React from 'react';
-import { Sparkles, Check, ChevronDown, ChevronUp, X } from 'lucide-react';
-import { toast } from 'sonner';
-
-import { Card, CardContent, CardHeader } from '@/components/ui/card';
-import { Progress } from '@/components/ui/progress';
-import { Button } from '@/components/ui/button';
-import { ActionButton } from '@/components/ui/action-button';
-import { cn } from '@/lib/utils';
-import { useGetStarted } from '../../hooks/useGetStarted';
-import { GET_STARTED_ITEMS, type GetStartedItemId } from './getStartedItems';
-
-interface GetStartedChecklistProps {
- /** Per-item click actions, wired by the Dashboard. Items without an
- * action (or already completed) render as plain rows. */
- actions?: Partial<Record<GetStartedItemId, () => void>>;
-}
-
-const GetStartedChecklist: React.FC<GetStartedChecklistProps> = ({ actions }) => {
- const { visible, items, completedCount, totalCount, dismiss } = useGetStarted();
- const [collapsed, setCollapsed] = React.useState(false);
-
- if (!visible) return null;
-
- const handleDismiss = () => {
- dismiss();
- toast.info('Get started hidden — reopen it anytime from Settings → Help.');
- };
-
- const allComplete = completedCount === totalCount;
- const completedById = new Map(items.map((item) => [item.id, item.completed]));
-
- if (collapsed) {
- return (
- <button
- type="button"
- onClick={() => setCollapsed(false)}
- className="fixed bottom-14 right-4 z-40 inline-flex h-8 items-center gap-1.5 rounded-full border border-border bg-card px-3 text-xs font-medium shadow-md hover:bg-accent"
- >
- <Sparkles className="h-3.5 w-3.5" />
- Get started · {completedCount}/{totalCount}
- <ChevronUp className="h-3.5 w-3.5 text-muted-foreground" />
- </button>
- );
- }
-
- return (
- <Card className="fixed bottom-14 right-4 z-40 w-80 shadow-md">
- <CardHeader className="flex flex-row items-center gap-2 space-y-0 px-4 pt-3 pb-2">
- <Sparkles className="h-4 w-4 shrink-0" />
- <div className="min-w-0 flex-1">
- <div className="text-sm font-semibold">
- {allComplete ? "You're all set!" : 'Get started'}
- </div>
- <div className="text-xs text-muted-foreground">
- {completedCount} of {totalCount} complete
- </div>
- </div>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6"
- onClick={() => setCollapsed(true)}
- aria-label="Collapse checklist"
- >
- <ChevronDown className="h-4 w-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6"
- onClick={handleDismiss}
- aria-label="Dismiss checklist"
- >
- <X className="h-4 w-4" />
- </Button>
- </CardHeader>
- <CardContent className="flex flex-col gap-1 px-2 pb-3">
- <div className="px-2 pb-2">
- <Progress value={(completedCount / totalCount) * 100} className="h-1.5" />
- </div>
-
- {GET_STARTED_ITEMS.map((item) => {
- const completed = completedById.get(item.id) ?? false;
- const action = actions?.[item.id];
- const clickable = !completed && item.actionable && action !== undefined;
- const row = (
- <>
- <span
- className={cn(
- 'flex h-6 w-6 shrink-0 items-center justify-center rounded-full border',
- completed
- ? 'border-primary bg-primary text-primary-foreground'
- : 'border-border text-muted-foreground',
- )}
- >
- {completed ? <Check className="h-3.5 w-3.5" /> : <item.icon className="h-3.5 w-3.5" />}
- </span>
- <span className="min-w-0 flex-1 text-left">
- <span
- className={cn(
- 'block text-sm font-medium',
- completed && 'text-muted-foreground line-through',
- )}
- >
- {item.label}
- </span>
- <span className="block text-xs text-muted-foreground">{item.sublabel}</span>
- </span>
- </>
- );
-
- return clickable ? (
- <button
- key={item.id}
- type="button"
- onClick={action}
- className="flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-accent"
- >
- {row}
- </button>
- ) : (
- <div key={item.id} className="flex items-center gap-2.5 rounded-md px-2 py-1.5">
- {row}
- </div>
- );
- })}
-
- {allComplete && (
- <div className="mt-1 px-2 text-center">
- <ActionButton intent="run" onClick={handleDismiss}>
- <Check className="h-4 w-4" />
- Done
- </ActionButton>
- </div>
- )}
- </CardContent>
- </Card>
- );
-};
-
-export default GetStartedChecklist;
diff --git a/client/src/components/onboarding/OnboardingWizard.tsx b/client/src/components/onboarding/OnboardingWizard.tsx
deleted file mode 100644
index eddf10e8..00000000
--- a/client/src/components/onboarding/OnboardingWizard.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import React from 'react';
-import { ArrowLeft, ArrowRight, Check, MessageCircle } from 'lucide-react';
-
-import { Button } from '@/components/ui/button';
-import { ActionButton } from '@/components/ui/action-button';
-import { cn } from '@/lib/utils';
-import Modal from '../ui/Modal';
-import { useOnboarding } from '../../hooks/useOnboarding';
-import WelcomeStep from './steps/WelcomeStep';
-import HowItWorksStep from './steps/HowItWorksStep';
-import ConnectAIStep from './steps/ConnectAIStep';
-import TryItStep from './steps/TryItStep';
-
-interface OnboardingWizardProps {
- onOpenCredentials: () => void;
- reopenTrigger?: number;
- /** Called after the final step's button completes the wizard — the
- * Dashboard uses it to open the AI Assistant example and focus chat.
- * Never called on skip or modal close. */
- onFinish?: () => void;
-}
-
-// Single source of truth for the wizard's step list. Length feeds the
-// hook's totalSteps and the progress indicator; renderer is dispatched
-// by index. Adding a step is a one-line edit here.
-const STEPS: { title: string; render: (props: { onOpenCredentials: () => void }) => React.ReactNode }[] = [
- { title: 'Welcome', render: () => <WelcomeStep /> },
- { title: 'How it works', render: () => <HowItWorksStep /> },
- { title: 'Connect your AI', render: ({ onOpenCredentials }) => <ConnectAIStep onOpenCredentials={onOpenCredentials} /> },
- { title: 'Try it', render: () => <TryItStep /> },
-];
-
-const OnboardingWizard: React.FC<OnboardingWizardProps> = ({ onOpenCredentials, reopenTrigger, onFinish }) => {
- const {
- isVisible,
- currentStep,
- isLoading,
- hasChecked,
- nextStep,
- prevStep,
- skip,
- complete,
- } = useOnboarding(reopenTrigger, STEPS.length);
-
- if (!isVisible || !hasChecked || isLoading) return null;
-
- const safeIndex = Math.min(Math.max(currentStep, 0), STEPS.length - 1);
- const isLastStep = safeIndex === STEPS.length - 1;
-
- const handleFinish = () => {
- complete();
- onFinish?.();
- };
-
- return (
- <Modal
- isOpen={isVisible}
- onClose={skip}
- title="Welcome Guide"
- maxWidth="95vw"
- maxHeight="95vh"
- >
- <div className="flex flex-col px-5 pt-4 pb-3">
- {/* Progress steps */}
- <ol className="mb-4 flex w-full items-center">
- {STEPS.map((item, idx) => {
- const status: 'completed' | 'active' | 'upcoming' =
- idx < safeIndex ? 'completed' : idx === safeIndex ? 'active' : 'upcoming';
- const isLast = idx === STEPS.length - 1;
- return (
- <li key={item.title} className="flex flex-1 items-center gap-2">
- <div
- className={cn(
- 'flex h-7 w-7 shrink-0 items-center justify-center rounded-full border text-xs font-medium transition-colors',
- status === 'completed' && 'border-primary bg-primary text-primary-foreground',
- status === 'active' && 'border-primary text-primary',
- status === 'upcoming' && 'border-border text-muted-foreground',
- )}
- >
- {status === 'completed' ? <Check className="h-4 w-4" /> : idx + 1}
- </div>
- <span
- className={cn(
- 'whitespace-nowrap text-xs',
- status === 'upcoming' ? 'text-muted-foreground' : 'text-foreground',
- )}
- >
- {item.title}
- </span>
- {!isLast && (
- <div
- className={cn(
- 'h-px flex-1',
- idx < safeIndex ? 'bg-primary' : 'bg-border',
- )}
- />
- )}
- </li>
- );
- })}
- </ol>
-
- {/* Step content */}
- <div className="overflow-y-auto pr-1 max-h-[calc(95vh-200px)]">
- {STEPS[safeIndex].render({ onOpenCredentials })}
- </div>
-
- {/* Footer navigation */}
- <div className="flex items-center justify-between border-t border-border pt-3 mt-3">
- <Button variant="ghost" size="sm" onClick={skip} className="text-muted-foreground">
- Skip for now
- </Button>
-
- <div className="flex items-center gap-2">
- {safeIndex > 0 && (
- <Button variant="outline" onClick={prevStep}>
- <ArrowLeft className="h-4 w-4" />
- Back
- </Button>
- )}
- {isLastStep ? (
- <ActionButton intent="run" onClick={handleFinish}>
- <MessageCircle className="h-4 w-4" />
- Open AI Assistant
- </ActionButton>
- ) : (
- <ActionButton intent="tools" onClick={nextStep}>
- Next
- <ArrowRight className="h-4 w-4" />
- </ActionButton>
- )}
- </div>
- </div>
- </div>
- </Modal>
- );
-};
-
-export default OnboardingWizard;
diff --git a/client/src/components/onboarding/__tests__/ConnectAIStep.test.tsx b/client/src/components/onboarding/__tests__/ConnectAIStep.test.tsx
deleted file mode 100644
index d4c032d2..00000000
--- a/client/src/components/onboarding/__tests__/ConnectAIStep.test.tsx
+++ /dev/null
@@ -1,189 +0,0 @@
-/**
- * ConnectAIStep behavioural tests.
- *
- * The catalogue hook is module-mocked (simpler and more robust than seeding
- * the TanStack Query cache + real WebSocket plumbing -- the component only
- * reads `catalogueQuery.data`). The WebSocketContext is also full-module
- * replaced defensively so no transitive import ever reaches the real
- * provider (the importActual+spread variant is documented broken under
- * React 19 -- see CredentialsModal.test.tsx).
- *
- * Locks in:
- * - only `category === 'ai'` providers render
- * - featured cards render in openai / anthropic / gemini order with the
- * correct "Get a key" hrefs + target/rel hardening
- * - stored provider flips: Connected badge, "You're connected" header,
- * "Manage AI accounts" CTA
- * - none stored: "Connect your AI" header, "Connect your AI account" CTA,
- * trust microcopy
- * - data undefined: skeletons render and the CTA stays usable
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { screen } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { renderWithProviders } from '../../../test/providers';
-
-import type {
- CatalogueResponse,
- ServerProviderConfig,
-} from '../../../hooks/useCatalogueQuery';
-
-// --- Mocks (declared BEFORE importing the component -- vi.mock is hoisted) --
-
-let catalogueData: CatalogueResponse | undefined;
-
-vi.mock('../../../hooks/useCatalogueQuery', () => ({
- useCatalogueQuery: () => ({ data: catalogueData }),
-}));
-
-// Defensive full-module replace: nothing in this render tree should touch
-// the real WebSocket provider.
-vi.mock('../../../contexts/WebSocketContext', () => ({
- useWebSocket: () => ({
- isConnected: true,
- isReady: true,
- sendRequest: vi.fn().mockResolvedValue({}),
- }),
-}));
-
-import ConnectAIStep from '../steps/ConnectAIStep';
-
-// --- Fixtures ---------------------------------------------------------------
-
-const makeProvider = (
- over: Partial<ServerProviderConfig> & { id: string; name: string },
-): ServerProviderConfig => ({
- category: 'ai',
- category_label: 'AI Providers',
- color: '#8be9fd',
- kind: 'apiKey',
- icon_ref: '\u{1F916}',
- stored: false,
- ...over,
-});
-
-const baseProviders = (): ServerProviderConfig[] => [
- makeProvider({ id: 'openai', name: 'OpenAI' }),
- makeProvider({ id: 'anthropic', name: 'Anthropic' }),
- makeProvider({ id: 'gemini', name: 'Gemini' }),
- // Non-featured ai provider -> renders in the "more providers" chip row.
- makeProvider({ id: 'groq', name: 'Groq' }),
- // Non-ai provider -> must never render on this step.
- makeProvider({
- id: 'google',
- name: 'Google Workspace',
- category: 'google',
- category_label: 'Google',
- kind: 'oauth',
- }),
-];
-
-const catalogue = (providers: ServerProviderConfig[]): CatalogueResponse => ({
- providers,
- categories: [],
- version: 'test-v1',
-});
-
-const renderStep = (onOpenCredentials: () => void = vi.fn()) =>
- renderWithProviders(<ConnectAIStep onOpenCredentials={onOpenCredentials} />);
-
-beforeEach(() => {
- vi.clearAllMocks();
- catalogueData = catalogue(baseProviders());
-});
-
-// --- Tests ------------------------------------------------------------------
-
-describe('ConnectAIStep provider filtering', () => {
- it('renders only ai-category providers', () => {
- renderStep();
- // Featured card.
- expect(screen.getByText('Gemini')).toBeInTheDocument();
- // Non-featured ai provider appears in the chip row.
- expect(screen.getByText('Groq')).toBeInTheDocument();
- // Non-ai category providers are filtered out entirely.
- expect(screen.queryByText('Google Workspace')).not.toBeInTheDocument();
- });
-});
-
-describe('ConnectAIStep featured cards', () => {
- it('renders featured cards in openai/anthropic/gemini order with hardened key links', () => {
- renderStep();
-
- const links = screen.getAllByRole('link', { name: /get a key/i });
- expect(links.map((l) => l.getAttribute('href'))).toEqual([
- 'https://platform.openai.com/api-keys',
- 'https://console.anthropic.com/settings/keys',
- 'https://aistudio.google.com/apikey',
- ]);
- for (const link of links) {
- expect(link).toHaveAttribute('target', '_blank');
- expect(link).toHaveAttribute('rel', 'noopener noreferrer');
- }
- });
-});
-
-describe('ConnectAIStep stored state', () => {
- it('shows Connected badge, connected header, and Manage CTA when anthropic is stored', () => {
- catalogueData = catalogue(
- baseProviders().map((p) => (p.id === 'anthropic' ? { ...p, stored: true } : p)),
- );
- renderStep();
-
- // Badge on the stored card.
- expect(screen.getByText('Connected')).toBeInTheDocument();
- // Header flips (curly apostrophe in the source -- match loosely).
- expect(screen.getByText(/You.re connected/)).toBeInTheDocument();
- expect(screen.queryByText('Connect your AI')).not.toBeInTheDocument();
- // CTA flips.
- expect(
- screen.getByRole('button', { name: 'Manage AI accounts' }),
- ).toBeInTheDocument();
- // Stored card no longer offers a "Get a key" link; the other two do.
- expect(screen.getAllByRole('link', { name: /get a key/i })).toHaveLength(2);
- });
-
- it('shows connect header, connect CTA, and trust microcopy when nothing is stored', () => {
- renderStep();
-
- expect(screen.getByText('Connect your AI')).toBeInTheDocument();
- expect(
- screen.getByRole('button', { name: 'Connect your AI account' }),
- ).toBeInTheDocument();
- expect(
- screen.getByText(/Your key is saved only on this device/),
- ).toBeInTheDocument();
- expect(screen.queryByText('Connected')).not.toBeInTheDocument();
- });
-});
-
-describe('ConnectAIStep loading state', () => {
- it('renders skeletons while the catalogue is loading and keeps the CTA usable', async () => {
- catalogueData = undefined;
- const onOpenCredentials = vi.fn();
- const { container } = renderStep(onOpenCredentials);
-
- // One skeleton per featured provider.
- expect(container.querySelectorAll('[data-slot="skeleton"]')).toHaveLength(3);
- // No provider cards yet.
- expect(screen.queryByText('OpenAI')).not.toBeInTheDocument();
-
- // CTA renders (loading counts as "not connected") and still fires.
- const cta = screen.getByRole('button', { name: 'Connect your AI account' });
- await userEvent.click(cta);
- expect(onOpenCredentials).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('ConnectAIStep CTA', () => {
- it('clicking the CTA calls onOpenCredentials exactly once', async () => {
- const onOpenCredentials = vi.fn();
- renderStep(onOpenCredentials);
-
- await userEvent.click(
- screen.getByRole('button', { name: 'Connect your AI account' }),
- );
- expect(onOpenCredentials).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/client/src/components/onboarding/__tests__/GetStartedChecklist.test.tsx b/client/src/components/onboarding/__tests__/GetStartedChecklist.test.tsx
deleted file mode 100644
index 6ff49ea5..00000000
--- a/client/src/components/onboarding/__tests__/GetStartedChecklist.test.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-/**
- * Tests for GetStartedChecklist — the floating Get Started card.
- *
- * The hook contract is exhaustively tested in
- * client/src/hooks/__tests__/useGetStarted.test.ts. This suite full-replace
- * mocks the hook and locks the rendering contract:
- * - renders null when not visible
- * - header math ("N of M complete")
- * - incomplete actionable items with a provided action render as buttons
- * firing exactly that action; completed rows are non-clickable
- * - collapse chevron -> pill ("Get started · N/M"); pill click re-expands
- * - all-complete -> "You're all set!" + Done button dismisses
- * - X dismisses (with toast)
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, fireEvent } from '@testing-library/react';
-
-// --- mocks (hoisted; closures dereference state at call time) ---------------
-
-const dismissMock = vi.fn();
-const restoreMock = vi.fn();
-
-const hookState = {
- visible: true,
- items: [] as Array<{ id: string; completed: boolean }>,
- completedCount: 0,
- totalCount: 5,
-};
-
-vi.mock('../../../hooks/useGetStarted', () => ({
- useGetStarted: () => ({
- visible: hookState.visible,
- items: hookState.items,
- completedCount: hookState.completedCount,
- totalCount: hookState.totalCount,
- dismiss: dismissMock,
- restore: restoreMock,
- }),
-}));
-
-const toastInfoMock = vi.fn();
-vi.mock('sonner', () => ({
- toast: {
- info: (...args: unknown[]) => toastInfoMock(...args),
- error: vi.fn(),
- success: vi.fn(),
- message: vi.fn(),
- warning: vi.fn(),
- },
-}));
-
-import GetStartedChecklist from '../GetStartedChecklist';
-import { GET_STARTED_ITEMS, type GetStartedItemId } from '../getStartedItems';
-
-// --- helpers -----------------------------------------------------------------
-
-function setItems(completedIds: GetStartedItemId[]) {
- hookState.items = GET_STARTED_ITEMS.map((item) => ({
- id: item.id,
- completed: completedIds.includes(item.id),
- }));
- hookState.completedCount = completedIds.length;
- hookState.totalCount = GET_STARTED_ITEMS.length;
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
- hookState.visible = true;
- setItems(['setup', 'add-key']); // default: 2 of 5 complete
-});
-
-// ---------------------------------------------------------------------------
-
-describe('GetStartedChecklist', () => {
- it('renders nothing when not visible', () => {
- hookState.visible = false;
- const { container } = render(<GetStartedChecklist />);
- expect(container).toBeEmptyDOMElement();
- });
-
- it('renders the header with completion math', () => {
- render(<GetStartedChecklist />);
- expect(screen.getByText('Get started')).toBeInTheDocument();
- expect(screen.getByText('2 of 5 complete')).toBeInTheDocument();
- // All five item labels render.
- for (const item of GET_STARTED_ITEMS) {
- expect(screen.getByText(item.label)).toBeInTheDocument();
- }
- });
-
- it('fires the matching action for an incomplete actionable item', () => {
- const chatAction = vi.fn();
- const buildAction = vi.fn();
- render(
- <GetStartedChecklist
- actions={{ 'chat-example': chatAction, 'build-workflow': buildAction }}
- />,
- );
-
- fireEvent.click(
- screen.getByRole('button', { name: /Chat with your AI Assistant/ }),
- );
- expect(chatAction).toHaveBeenCalledTimes(1);
- expect(buildAction).not.toHaveBeenCalled();
- });
-
- it('renders a completed item as a non-clickable row even when an action is provided', () => {
- setItems(['setup', 'chat-example']);
- const chatAction = vi.fn();
- render(<GetStartedChecklist actions={{ 'chat-example': chatAction }} />);
-
- const label = screen.getByText('Chat with your AI Assistant');
- expect(label.closest('button')).toBeNull();
- });
-
- it('renders an incomplete actionable item without a provided action as a plain row', () => {
- render(<GetStartedChecklist />); // no actions prop at all
- const label = screen.getByText('Add your AI key');
- expect(label.closest('button')).toBeNull();
- });
-
- it('collapses to a pill showing "Get started · N/M" and re-expands on pill click', () => {
- render(<GetStartedChecklist />);
-
- fireEvent.click(screen.getByLabelText('Collapse checklist'));
-
- // Collapsed view is a single pill button.
- expect(screen.queryByText('2 of 5 complete')).not.toBeInTheDocument();
- const pill = screen.getByRole('button');
- expect(pill).toHaveTextContent('Get started · 2/5');
-
- fireEvent.click(pill);
- expect(screen.getByText('2 of 5 complete')).toBeInTheDocument();
- });
-
- it('shows "You\'re all set!" and a Done button that dismisses when everything is complete', () => {
- setItems(['setup', 'add-key', 'chat-example', 'build-workflow', 'try-theme']);
- render(<GetStartedChecklist />);
-
- expect(screen.getByText("You're all set!")).toBeInTheDocument();
- expect(screen.getByText('5 of 5 complete')).toBeInTheDocument();
-
- fireEvent.click(screen.getByRole('button', { name: /Done/ }));
- expect(dismissMock).toHaveBeenCalledTimes(1);
- });
-
- it('does not show the Done affordance while incomplete', () => {
- render(<GetStartedChecklist />);
- expect(screen.queryByText("You're all set!")).not.toBeInTheDocument();
- expect(screen.queryByRole('button', { name: /Done/ })).not.toBeInTheDocument();
- });
-
- it('X dismisses the checklist and toasts', () => {
- render(<GetStartedChecklist />);
- fireEvent.click(screen.getByLabelText('Dismiss checklist'));
- expect(dismissMock).toHaveBeenCalledTimes(1);
- expect(toastInfoMock).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/client/src/components/onboarding/__tests__/HowItWorksStep.test.tsx b/client/src/components/onboarding/__tests__/HowItWorksStep.test.tsx
deleted file mode 100644
index c44df982..00000000
--- a/client/src/components/onboarding/__tests__/HowItWorksStep.test.tsx
+++ /dev/null
@@ -1,96 +0,0 @@
-/**
- * HowItWorksStep behavioural tests.
- *
- * useNodeGroups is module-mocked (full replace) so the step renders against
- * a controlled groups payload without WebSocket / TanStack plumbing.
- *
- * Locks in:
- * - Badge chips render ONLY for groups with visibility 'normal' or 'all'
- * ('dev' groups are filtered out)
- * - when groups data is undefined, the sentence renders without chips and
- * the three concept cards still render
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { screen } from '@testing-library/react';
-import { renderWithProviders } from '../../../test/providers';
-
-import type { NodeGroupEntry } from '../../../lib/nodeSpec';
-
-// --- Mocks (declared BEFORE importing the component -- vi.mock is hoisted) --
-
-let groupsData: Record<string, NodeGroupEntry> | undefined;
-
-vi.mock('../../../lib/nodeSpec', () => ({
- useNodeGroups: () => ({ data: groupsData }),
-}));
-
-import HowItWorksStep from '../steps/HowItWorksStep';
-
-// --- Fixtures ---------------------------------------------------------------
-
-const entry = (
- label: string,
- visibility: NodeGroupEntry['visibility'],
-): NodeGroupEntry => ({
- types: [],
- label,
- icon: '\u{1F916}',
- color: '#bd93f9',
- visibility,
-});
-
-const CONCEPT_TITLES = [
- 'Snap blocks together',
- 'Agents do the thinking',
- 'Chat to make it go',
-];
-
-beforeEach(() => {
- groupsData = undefined;
-});
-
-// --- Tests ------------------------------------------------------------------
-
-describe('HowItWorksStep group chips', () => {
- it('renders chips for normal + all visibility groups and filters out dev groups', () => {
- groupsData = {
- agent: entry('AI Agents', 'normal'),
- model: entry('AI Models', 'all'),
- android: entry('Android', 'dev'),
- };
- renderWithProviders(<HowItWorksStep />);
-
- expect(screen.getByText('AI Agents')).toBeInTheDocument();
- expect(screen.getByText('AI Models')).toBeInTheDocument();
- expect(screen.queryByText('Android')).not.toBeInTheDocument();
- });
-
- it('renders the toolbar sentence without chips when groups data is undefined', () => {
- groupsData = undefined;
- const { container } = renderWithProviders(<HowItWorksStep />);
-
- expect(container.querySelectorAll('[data-slot="badge"]')).toHaveLength(0);
- expect(
- screen.getByText(/Normal shows just the AI blocks/),
- ).toBeInTheDocument();
- });
-});
-
-describe('HowItWorksStep concept cards', () => {
- it('always renders the three concept cards (with groups data)', () => {
- groupsData = { agent: entry('AI Agents', 'normal') };
- renderWithProviders(<HowItWorksStep />);
- for (const title of CONCEPT_TITLES) {
- expect(screen.getByText(title)).toBeInTheDocument();
- }
- });
-
- it('always renders the three concept cards (without groups data)', () => {
- groupsData = undefined;
- renderWithProviders(<HowItWorksStep />);
- for (const title of CONCEPT_TITLES) {
- expect(screen.getByText(title)).toBeInTheDocument();
- }
- });
-});
diff --git a/client/src/components/onboarding/__tests__/OnboardingWizard.test.tsx b/client/src/components/onboarding/__tests__/OnboardingWizard.test.tsx
deleted file mode 100644
index 9f4636c4..00000000
--- a/client/src/components/onboarding/__tests__/OnboardingWizard.test.tsx
+++ /dev/null
@@ -1,227 +0,0 @@
-/**
- * OnboardingWizard behavioural tests.
- *
- * The wizard's state machine lives in useOnboarding (tested separately in
- * src/hooks/__tests__/useOnboarding.steps.test.ts). Here the hook is fully
- * mocked so each test pins the wizard at a known step and asserts:
- * - the 4-step rail renders every step title
- * - step dispatch by index (ConnectAI stub at index 2, with
- * onOpenCredentials passed through)
- * - footer nav wiring: Back hidden on step 0, Next -> nextStep,
- * final "Open AI Assistant" -> complete() then onFinish() (in order),
- * "Skip for now" / modal close -> skip() and NEVER onFinish()
- * - visibility gate: renders nothing unless isVisible && hasChecked
- * && !isLoading
- *
- * Step children that consume live hooks (catalogue / node groups) are
- * stubbed; the pure steps (Welcome, TryIt) render for real.
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { screen } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import type { ComponentProps } from 'react';
-import { renderWithProviders } from '../../../test/providers';
-
-// --- Mocks (declared BEFORE importing the wizard -- vi.mock is hoisted) -----
-
-const nextStep = vi.fn();
-const prevStep = vi.fn();
-const skip = vi.fn();
-const complete = vi.fn();
-
-interface HookState {
- isVisible: boolean;
- currentStep: number;
- isCompleted: boolean;
- isLoading: boolean;
- hasChecked: boolean;
- totalSteps: number;
-}
-
-let hookState: HookState;
-
-// Full-module replace (the importActual+spread variant is documented broken
-// under React 19 for context-backed modules; full replace is the canonical
-// pattern -- see CredentialsModal.test.tsx).
-vi.mock('../../../hooks/useOnboarding', () => ({
- useOnboarding: () => ({
- ...hookState,
- nextStep,
- prevStep,
- skip,
- complete,
- }),
-}));
-
-// Stub the step children that consume live hooks (useCatalogueQuery /
-// useNodeGroups). They have their own dedicated suites.
-vi.mock('../steps/ConnectAIStep', () => ({
- default: ({ onOpenCredentials }: { onOpenCredentials: () => void }) => (
- <button type="button" data-testid="connect-ai-stub" onClick={onOpenCredentials}>
- ConnectAIStep stub
- </button>
- ),
-}));
-
-vi.mock('../steps/HowItWorksStep', () => ({
- default: () => <div data-testid="how-it-works-stub" />,
-}));
-
-import OnboardingWizard from '../OnboardingWizard';
-
-const RAIL_LABELS = ['Welcome', 'How it works', 'Connect your AI', 'Try it'];
-
-const renderWizard = (
- props: Partial<ComponentProps<typeof OnboardingWizard>> = {},
-) =>
- renderWithProviders(
- <OnboardingWizard onOpenCredentials={props.onOpenCredentials ?? vi.fn()} {...props} />,
- );
-
-beforeEach(() => {
- vi.clearAllMocks();
- hookState = {
- isVisible: true,
- currentStep: 0,
- isCompleted: false,
- isLoading: false,
- hasChecked: true,
- totalSteps: 4,
- };
-});
-
-describe('OnboardingWizard progress rail', () => {
- it('renders all four step rail labels', () => {
- renderWizard();
- for (const label of RAIL_LABELS) {
- expect(screen.getByText(label)).toBeInTheDocument();
- }
- });
-});
-
-describe('OnboardingWizard step dispatch', () => {
- it('renders the ConnectAI step at index 2 and passes onOpenCredentials through', async () => {
- hookState.currentStep = 2;
- const onOpenCredentials = vi.fn();
- renderWizard({ onOpenCredentials });
-
- const stub = screen.getByTestId('connect-ai-stub');
- expect(stub).toBeInTheDocument();
- // Steps for other indices are not mounted.
- expect(screen.queryByTestId('how-it-works-stub')).not.toBeInTheDocument();
-
- await userEvent.click(stub);
- expect(onOpenCredentials).toHaveBeenCalledTimes(1);
- });
-
- it('renders the HowItWorks step at index 1', () => {
- hookState.currentStep = 1;
- renderWizard();
- expect(screen.getByTestId('how-it-works-stub')).toBeInTheDocument();
- expect(screen.queryByTestId('connect-ai-stub')).not.toBeInTheDocument();
- });
-});
-
-describe('OnboardingWizard footer navigation', () => {
- it('hides the Back button on the first step', () => {
- renderWizard();
- expect(screen.queryByRole('button', { name: /back/i })).not.toBeInTheDocument();
- });
-
- it('shows Back from step 1 onward and clicking it calls prevStep', async () => {
- hookState.currentStep = 1;
- renderWizard();
- const back = screen.getByRole('button', { name: /back/i });
- await userEvent.click(back);
- expect(prevStep).toHaveBeenCalledTimes(1);
- });
-
- it('clicking Next calls nextStep', async () => {
- renderWizard();
- await userEvent.click(screen.getByRole('button', { name: /next/i }));
- expect(nextStep).toHaveBeenCalledTimes(1);
- });
-
- it('shows "Open AI Assistant" instead of Next on the last step', () => {
- hookState.currentStep = 3;
- renderWizard();
- expect(screen.getByRole('button', { name: 'Open AI Assistant' })).toBeInTheDocument();
- expect(screen.queryByRole('button', { name: /next/i })).not.toBeInTheDocument();
- });
-
- it('final button calls complete then onFinish, each exactly once, complete first', async () => {
- hookState.currentStep = 3;
- const onFinish = vi.fn();
- renderWizard({ onFinish });
-
- await userEvent.click(screen.getByRole('button', { name: 'Open AI Assistant' }));
-
- expect(complete).toHaveBeenCalledTimes(1);
- expect(onFinish).toHaveBeenCalledTimes(1);
- // complete() must run before onFinish() (handleFinish contract).
- expect(complete.mock.invocationCallOrder[0]).toBeLessThan(
- onFinish.mock.invocationCallOrder[0],
- );
- // Skipping paths untouched.
- expect(skip).not.toHaveBeenCalled();
- });
-
- it('final button does not throw when onFinish is omitted', async () => {
- hookState.currentStep = 3;
- renderWizard(); // no onFinish prop
- await userEvent.click(screen.getByRole('button', { name: 'Open AI Assistant' }));
- expect(complete).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('OnboardingWizard skip paths never call onFinish', () => {
- it('"Skip for now" calls skip and never onFinish/complete', async () => {
- const onFinish = vi.fn();
- renderWizard({ onFinish });
-
- await userEvent.click(screen.getByRole('button', { name: /skip for now/i }));
-
- expect(skip).toHaveBeenCalledTimes(1);
- expect(onFinish).not.toHaveBeenCalled();
- expect(complete).not.toHaveBeenCalled();
- });
-
- it('modal close (X) calls skip and never onFinish/complete', async () => {
- const onFinish = vi.fn();
- renderWizard({ onFinish });
-
- // Modal's DialogClose carries aria-label="Close". Radix may fire both the
- // explicit onClick and onOpenChange(false), so assert >= 1 call rather
- // than an exact count -- the contract under test is "skip, not finish".
- await userEvent.click(screen.getByRole('button', { name: /close/i }));
-
- expect(skip.mock.calls.length).toBeGreaterThanOrEqual(1);
- expect(onFinish).not.toHaveBeenCalled();
- expect(complete).not.toHaveBeenCalled();
- });
-});
-
-describe('OnboardingWizard visibility gate', () => {
- it('renders nothing when isVisible is false', () => {
- hookState.isVisible = false;
- const { container } = renderWizard();
- expect(container).toBeEmptyDOMElement();
- // Portal content absent too.
- expect(screen.queryByText('Welcome Guide')).not.toBeInTheDocument();
- });
-
- it('renders nothing before the settings check completes (hasChecked false)', () => {
- hookState.hasChecked = false;
- hookState.isLoading = true;
- const { container } = renderWizard();
- expect(container).toBeEmptyDOMElement();
- expect(screen.queryByText('Welcome Guide')).not.toBeInTheDocument();
- });
-
- it('renders nothing while isLoading is true', () => {
- hookState.isLoading = true;
- const { container } = renderWizard();
- expect(container).toBeEmptyDOMElement();
- });
-});
diff --git a/client/src/components/onboarding/getStartedItems.ts b/client/src/components/onboarding/getStartedItems.ts
deleted file mode 100644
index 47fd1937..00000000
--- a/client/src/components/onboarding/getStartedItems.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import type { LucideIcon } from 'lucide-react';
-import { Sparkles, KeyRound, MessageCircle, Workflow, Palette } from 'lucide-react';
-
-export type GetStartedItemId =
- | 'setup'
- | 'add-key'
- | 'chat-example'
- | 'build-workflow'
- | 'try-theme';
-
-export interface GetStartedItemDef {
- id: GetStartedItemId;
- /** Verb-first label. */
- label: string;
- sublabel: string;
- icon: LucideIcon;
- /** Whether clicking the row performs an action (wired by Dashboard). */
- actionable: boolean;
-}
-
-/** The three seeded example workflow names — used to tell "built your own
- * workflow" apart from editing a shipped example. */
-export const EXAMPLE_WORKFLOW_NAMES = ['AI Assistant', 'AI Employee', 'Claude Assistant'];
-
-export const GET_STARTED_ITEMS: GetStartedItemDef[] = [
- {
- id: 'setup',
- label: 'Set up your workspace',
- sublabel: 'OpenCompany is installed and running',
- icon: Sparkles,
- actionable: false,
- },
- {
- id: 'add-key',
- label: 'Add your AI key',
- sublabel: 'Connect OpenAI, Anthropic, or another provider',
- icon: KeyRound,
- actionable: true,
- },
- {
- id: 'chat-example',
- label: 'Chat with your AI Assistant',
- sublabel: 'Say hello to the ready-made example',
- icon: MessageCircle,
- actionable: true,
- },
- {
- id: 'build-workflow',
- label: 'Build your own workflow',
- sublabel: 'Start from a blank canvas and save it',
- icon: Workflow,
- actionable: true,
- },
- {
- id: 'try-theme',
- label: 'Try a new look',
- sublabel: 'Pick one of 12 visual themes',
- icon: Palette,
- actionable: false,
- },
-];
diff --git a/client/src/components/onboarding/nodeRoleClasses.ts b/client/src/components/onboarding/nodeRoleClasses.ts
deleted file mode 100644
index dfc57875..00000000
--- a/client/src/components/onboarding/nodeRoleClasses.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- * Shared role-to-Tailwind-classes map for the onboarding step cards.
- * Each role keys into the existing `--node-X` triplet (soft bg + border
- * + accent text). Co-located with the onboarding folder because all
- * consumers (the wizard steps) live here.
- */
-
-export type NodeRole = 'model' | 'skill' | 'agent' | 'workflow' | 'trigger';
-
-export interface NodeRoleClasses {
- /** Tinted background + border for the card surface. */
- card: string;
- /** Accent text colour matching the card's role. */
- text: string;
-}
-
-export const NODE_ROLE_CLASSES: Record<NodeRole, NodeRoleClasses> = {
- model: { card: 'bg-node-model-soft border-node-model-border', text: 'text-node-model' },
- skill: { card: 'bg-node-skill-soft border-node-skill-border', text: 'text-node-skill' },
- agent: { card: 'bg-node-agent-soft border-node-agent-border', text: 'text-node-agent' },
- workflow: { card: 'bg-node-workflow-soft border-node-workflow-border', text: 'text-node-workflow' },
- trigger: { card: 'bg-node-trigger-soft border-node-trigger-border', text: 'text-node-trigger' },
-};
diff --git a/client/src/components/onboarding/steps/ConnectAIStep.tsx b/client/src/components/onboarding/steps/ConnectAIStep.tsx
deleted file mode 100644
index 373a1334..00000000
--- a/client/src/components/onboarding/steps/ConnectAIStep.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-import React from 'react';
-import { KeyRound, Check, ExternalLink, ShieldCheck } from 'lucide-react';
-
-import { Button } from '@/components/ui/button';
-import { Alert, AlertDescription } from '@/components/ui/alert';
-import { Badge } from '@/components/ui/badge';
-import { Skeleton } from '@/components/ui/skeleton';
-import { NodeIcon } from '../../../assets/icons';
-import { theme } from '../../../styles/theme';
-import { useCatalogueQuery, type ServerProviderConfig } from '../../../hooks/useCatalogueQuery';
-import { FEATURED_AI_PROVIDERS } from '../aiProviderLinks';
-
-interface ConnectAIStepProps {
- onOpenCredentials: () => void;
-}
-
-const ConnectAIStep: React.FC<ConnectAIStepProps> = ({ onOpenCredentials }) => {
- const catalogueQuery = useCatalogueQuery();
- const providers = catalogueQuery.data?.providers;
-
- const aiProviders = React.useMemo(
- () => (providers ?? []).filter((p) => p.category === 'ai'),
- [providers],
- );
- const featured = FEATURED_AI_PROVIDERS
- .map((entry) => {
- const provider = aiProviders.find((p) => p.id === entry.id);
- return provider ? { ...entry, provider } : null;
- })
- .filter((entry): entry is { id: string; hint: string; keyUrl: string; provider: ServerProviderConfig } => entry !== null);
- const featuredIds = new Set(FEATURED_AI_PROVIDERS.map((entry) => entry.id));
- const moreProviders = aiProviders.filter((p) => !featuredIds.has(p.id));
- const connected = aiProviders.some((p) => p.stored);
- const isLoading = providers === undefined;
-
- return (
- <div className="py-1">
- <div className="mb-4 text-center">
- <h4 className="m-0 mb-1 flex items-center justify-center gap-2 text-lg font-semibold">
- {connected ? (
- <>
- <Check className="h-4 w-4 text-success" />
- You&apos;re connected
- </>
- ) : (
- <>
- <KeyRound className="h-4 w-4 text-warning" />
- Connect your AI
- </>
- )}
- </h4>
- <p className="text-xs text-muted-foreground">
- {connected
- ? 'Nice — your AI is ready to think.'
- : 'Your agents need an AI account to think. Paste one key — it takes about a minute.'}
- </p>
- </div>
-
- {isLoading ? (
- <div className="grid grid-cols-3 gap-2">
- {FEATURED_AI_PROVIDERS.map((entry) => (
- <Skeleton key={entry.id} className="h-24 w-full" />
- ))}
- </div>
- ) : (
- <>
- <div className="grid grid-cols-3 gap-2">
- {featured.map(({ id, hint, keyUrl, provider }) => (
- <div
- key={id}
- className="flex flex-col items-center gap-1 rounded-md border border-border bg-muted/50 px-3 py-3 text-center"
- >
- <NodeIcon icon={provider.icon_ref} size={theme.iconSize.md} className="shrink-0" />
- <span className="text-sm font-semibold">{provider.name}</span>
- <span className="text-xs text-muted-foreground">{hint}</span>
- {provider.stored ? (
- <Badge variant="success" className="mt-1">
- <Check className="h-3 w-3" />
- Connected
- </Badge>
- ) : (
- <a
- href={keyUrl}
- target="_blank"
- rel="noopener noreferrer"
- className="mt-1 inline-flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground"
- >
- <ExternalLink className="h-3 w-3" /> Get a key
- </a>
- )}
- </div>
- ))}
- </div>
-
- {moreProviders.length > 0 && (
- <div className="mt-3 text-center">
- <div className="flex flex-wrap items-center justify-center gap-1.5">
- {moreProviders.map((p) => (
- <span
- key={p.id}
- className="inline-flex items-center gap-1 rounded-full border border-border bg-muted/50 px-2 py-0.5 text-xs"
- >
- <NodeIcon icon={p.icon_ref} size={theme.iconSize.xs} className="shrink-0" />
- {p.name}
- {p.stored && <Check className="h-3 w-3 text-success" />}
- </span>
- ))}
- </div>
- <p className="mt-2 text-xs text-muted-foreground">
- No account yet? Ollama and LM Studio run free models right on your computer — pick
- one from the list.
- </p>
- </div>
- )}
- </>
- )}
-
- <div className="mt-5 text-center">
- <Button
- variant={connected ? 'outline' : 'default'}
- onClick={onOpenCredentials}
- className="gap-2"
- >
- <KeyRound className="h-4 w-4" />
- {connected ? 'Manage AI accounts' : 'Connect your AI account'}
- </Button>
- </div>
-
- {connected ? (
- <Alert variant="success" className="mt-4">
- <AlertDescription className="text-xs">
- You can add another AI account or change your key anytime — click the key button in the
- toolbar.
- </AlertDescription>
- </Alert>
- ) : (
- <p className="mt-4 flex items-center justify-center gap-1.5 text-xs text-muted-foreground">
- <ShieldCheck className="h-3.5 w-3.5" />
- Your key is saved only on this device. It&apos;s never shared with anyone except the AI you
- choose.
- </p>
- )}
- </div>
- );
-};
-
-export default ConnectAIStep;
diff --git a/client/src/components/onboarding/steps/HowItWorksStep.tsx b/client/src/components/onboarding/steps/HowItWorksStep.tsx
deleted file mode 100644
index 7f5c2956..00000000
--- a/client/src/components/onboarding/steps/HowItWorksStep.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-import React from 'react';
-import { LayoutGrid, Bot, MessageCircle } from 'lucide-react';
-import { Badge } from '@/components/ui/badge';
-import { useNodeGroups } from '../../../lib/nodeSpec';
-import { NODE_ROLE_CLASSES, type NodeRole } from '../nodeRoleClasses';
-
-const concepts: { Icon: typeof LayoutGrid; title: string; desc: string; role: NodeRole }[] = [
- {
- Icon: LayoutGrid,
- title: 'Snap blocks together',
- desc: 'Every project is made of simple blocks — a chat window, an AI brain, a web search. Drag them in from the right-hand panel and draw lines to connect them.',
- role: 'model',
- },
- {
- Icon: Bot,
- title: 'Agents do the thinking',
- desc: 'An agent is a block with a brain. Tell it what you want in plain English and it plans the steps, using the blocks connected to it.',
- role: 'agent',
- },
- {
- Icon: MessageCircle,
- title: 'Chat to make it go',
- desc: 'Press the green Start button at the top, then type in the chat panel at the bottom. Your agent answers right there.',
- role: 'trigger',
- },
-];
-
-const HowItWorksStep: React.FC = () => {
- const groupsQuery = useNodeGroups();
- const normalGroupLabels = Object.values(groupsQuery.data ?? {})
- .filter((group) => group.visibility === 'normal' || group.visibility === 'all')
- .map((group) => group.label);
-
- return (
- <div className="py-1">
- <div className="mb-4 text-center">
- <h4 className="m-0 mb-1 text-lg font-semibold">See how it works</h4>
- <p className="text-xs text-muted-foreground">Three ideas are all you need.</p>
- </div>
-
- <div className="flex w-full flex-col gap-2.5">
- {concepts.map((c) => {
- const classes = NODE_ROLE_CLASSES[c.role];
- return (
- <div
- key={c.title}
- className={`flex items-start gap-3 rounded-md border p-3 ${classes.card}`}
- >
- <div className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-md ${classes.card}`}>
- <c.Icon className={`h-4 w-4 ${classes.text}`} />
- </div>
- <div className="min-w-0 flex-1">
- <div className={`mb-0.5 text-sm font-semibold ${classes.text}`}>{c.title}</div>
- <p className="m-0 text-xs leading-relaxed text-muted-foreground">{c.desc}</p>
- </div>
- </div>
- );
- })}
- </div>
-
- <div className="mt-4 text-center text-xs text-muted-foreground">
- <span>
- The Normal / Dev switch in the toolbar keeps things simple. Normal shows just the AI blocks
- </span>
- {normalGroupLabels.length > 0 && (
- <span className="mx-1 inline-flex flex-wrap items-center justify-center gap-1 align-middle">
- {normalGroupLabels.map((label) => (
- <Badge key={label} variant="outline" className="text-[10px]">
- {label}
- </Badge>
- ))}
- </span>
- )}
- <span> — flip to Dev when you want everything else.</span>
- </div>
- </div>
- );
-};
-
-export default HowItWorksStep;
diff --git a/client/src/components/onboarding/steps/TryItStep.tsx b/client/src/components/onboarding/steps/TryItStep.tsx
deleted file mode 100644
index cac3920e..00000000
--- a/client/src/components/onboarding/steps/TryItStep.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-import React from 'react';
-import { FolderOpen, Play, MessageCircle, Code, Users } from 'lucide-react';
-import { NODE_ROLE_CLASSES, type NodeRole } from '../nodeRoleClasses';
-
-const recipe: { Icon: typeof FolderOpen; title: string; desc: string; role: NodeRole }[] = [
- {
- Icon: FolderOpen,
- title: 'Open AI Assistant',
- desc: 'Find it in the sidebar on the left — a friendly helper that can search the web and manage files.',
- role: 'skill',
- },
- {
- Icon: Play,
- title: 'Press the green Start button',
- desc: "It's in the toolbar at the top. This wakes your agent up.",
- role: 'agent',
- },
- {
- Icon: MessageCircle,
- title: 'Say hello',
- desc: 'Type anything in the chat panel at the bottom of the screen. Your agent replies right there.',
- role: 'trigger',
- },
-];
-
-const explore: { Icon: typeof Code; title: string; desc: string; role: NodeRole }[] = [
- {
- Icon: Code,
- title: 'Claude Assistant',
- desc: 'An agent powered by Claude Code — great for coding help. Works best with an Anthropic key.',
- role: 'model',
- },
- {
- Icon: Users,
- title: 'AI Employee',
- desc: "A whole team of agents working together. Explore it once you're comfortable.",
- role: 'workflow',
- },
-];
-
-const TryItStep: React.FC = () => {
- return (
- <div className="py-1">
- <div className="mb-4 text-center">
- <h4 className="m-0 mb-1 text-lg font-semibold">Say hello to your first agent</h4>
- <p className="text-xs text-muted-foreground">
- Three examples are already waiting in your sidebar. Here&apos;s the fastest way in.
- </p>
- </div>
-
- <div className="flex w-full flex-col gap-2.5">
- {recipe.map((step, index) => {
- const classes = NODE_ROLE_CLASSES[step.role];
- return (
- <div
- key={step.title}
- className={`flex items-start gap-3 rounded-md border p-3 ${classes.card}`}
- >
- <div className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full ${classes.card}`}>
- <span className={`text-sm font-semibold ${classes.text}`}>{index + 1}</span>
- </div>
- <div className="min-w-0 flex-1">
- <div className={`mb-0.5 flex items-center gap-1.5 text-sm font-semibold ${classes.text}`}>
- <step.Icon className="h-4 w-4" />
- {step.title}
- </div>
- <p className="m-0 text-xs leading-relaxed text-muted-foreground">{step.desc}</p>
- </div>
- </div>
- );
- })}
- </div>
-
- <div className="mt-4 mb-2 text-center text-xs font-semibold text-muted-foreground">
- More to explore
- </div>
- <div className="grid grid-cols-2 gap-2.5">
- {explore.map((item) => {
- const classes = NODE_ROLE_CLASSES[item.role];
- return (
- <div key={item.title} className={`rounded-md border p-3 ${classes.card}`}>
- <div className={`mb-0.5 flex items-center gap-1.5 text-sm font-semibold ${classes.text}`}>
- <item.Icon className="h-4 w-4" />
- {item.title}
- </div>
- <p className="m-0 text-xs leading-relaxed text-muted-foreground">{item.desc}</p>
- </div>
- );
- })}
- </div>
-
- <p className="mt-4 text-center text-xs text-muted-foreground">
- You can replay this guide anytime from Settings.
- </p>
- </div>
- );
-};
-
-export default TryItStep;
diff --git a/client/src/components/onboarding/steps/WelcomeStep.tsx b/client/src/components/onboarding/steps/WelcomeStep.tsx
deleted file mode 100644
index 7bf67686..00000000
--- a/client/src/components/onboarding/steps/WelcomeStep.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import React from 'react';
-import { Rocket, Bot, Blocks, Plug, ShieldCheck } from 'lucide-react';
-import { Card, CardContent } from '@/components/ui/card';
-import { NODE_ROLE_CLASSES, type NodeRole } from '../nodeRoleClasses';
-
-const features: { Icon: typeof Bot; label: string; desc: string; role: NodeRole }[] = [
- { Icon: Bot, label: 'Agents that work for you', desc: 'Give them a goal; they figure out the steps.', role: 'agent' },
- { Icon: Blocks, label: 'Build by dragging', desc: 'Snap blocks together — no code, no setup scripts.', role: 'model' },
- { Icon: Plug, label: 'Bring your favorite AI', desc: 'Works with OpenAI, Claude, Gemini and more.', role: 'skill' },
- { Icon: ShieldCheck, label: 'Yours and private', desc: 'Everything runs and stays on this device.', role: 'workflow' },
-];
-
-const WelcomeStep: React.FC = () => {
- return (
- <div className="py-2 text-center">
- <Rocket className="mx-auto mb-2 h-10 w-10 text-node-agent" />
-
- <h3 className="m-0 mb-1 text-xl font-semibold">Build your own AI team</h3>
-
- <p className="text-[15px] font-semibold text-node-agent">
- Helpful AI agents that chat with you and get real work done
- </p>
-
- <p className="mx-auto mt-4 mb-6 max-w-[480px] text-sm text-muted-foreground">
- OpenCompany runs on your own computer. Snap building blocks together on
- a visual canvas, connect your favorite AI, and watch your agents get to
- work. No coding needed.
- </p>
-
- <div className="mx-auto grid max-w-[440px] grid-cols-2 gap-3">
- {features.map(({ Icon, label, desc, role }) => {
- const classes = NODE_ROLE_CLASSES[role];
- return (
- <Card key={label} className={`text-center ${classes.card}`}>
- <CardContent className="flex flex-col items-center gap-1 p-3">
- <Icon className={`h-5 w-5 ${classes.text}`} />
- <span className="block text-sm font-semibold">{label}</span>
- <span className="text-xs text-muted-foreground">{desc}</span>
- </CardContent>
- </Card>
- );
- })}
- </div>
- </div>
- );
-};
-
-export default WelcomeStep;
diff --git a/client/src/components/ui/ApiKeyInput.tsx b/client/src/components/ui/ApiKeyInput.tsx
index c773dc49..fe3a5e02 100644
--- a/client/src/components/ui/ApiKeyInput.tsx
+++ b/client/src/components/ui/ApiKeyInput.tsx
@@ -77,6 +77,8 @@ const ApiKeyInput: React.FC<ApiKeyInputProps> = ({
size="icon"
onClick={onDelete}
disabled={disabled}
+ aria-label="Remove key"
+ title="Remove key"
>
<Trash2 className="h-4 w-4" />
</Button>
diff --git a/client/src/components/ui/Modal.tsx b/client/src/components/ui/Modal.tsx
index fc567fef..c5fa79fc 100644
--- a/client/src/components/ui/Modal.tsx
+++ b/client/src/components/ui/Modal.tsx
@@ -67,6 +67,9 @@ interface ModalProps {
/** Focus lifecycle for programmatically opened dialogs without a DialogTrigger. */
onOpenAutoFocus?: React.ComponentProps<typeof DialogPrimitive.Content>['onOpenAutoFocus'];
onCloseAutoFocus?: React.ComponentProps<typeof DialogPrimitive.Content>['onCloseAutoFocus'];
+ /** Esc reaches this first; `event.preventDefault()` keeps the dialog open
+ * (the Welcome guide steps back from a provider page instead). */
+ onEscapeKeyDown?: React.ComponentProps<typeof DialogPrimitive.Content>['onEscapeKeyDown'];
}
const DEFAULT_TITLE_ICON = <Settings className="h-4 w-4 opacity-70" />;
@@ -100,6 +103,7 @@ const Modal: React.FC<ModalProps> = ({
motion = 'default',
onOpenAutoFocus,
onCloseAutoFocus,
+ onEscapeKeyDown,
}) => {
const showHeader = !hideHeader && Boolean(title || headerActions);
@@ -125,6 +129,7 @@ const Modal: React.FC<ModalProps> = ({
<DialogPrimitive.Content
onOpenAutoFocus={onOpenAutoFocus}
onCloseAutoFocus={onCloseAutoFocus}
+ onEscapeKeyDown={onEscapeKeyDown}
data-slot="dialog-content"
className={cn(
// bg-bg-app + border-border-default consume the new-contract
diff --git a/client/src/components/ui/SettingsPanel.tsx b/client/src/components/ui/SettingsPanel.tsx
index 9661bc56..a57c42d6 100644
--- a/client/src/components/ui/SettingsPanel.tsx
+++ b/client/src/components/ui/SettingsPanel.tsx
@@ -7,15 +7,12 @@ import {
Save,
Brain,
Cpu,
- HelpCircle,
RotateCcw,
X,
Volume2,
- ListChecks,
} from 'lucide-react';
import { useAppStore } from '../../store/useAppStore';
-import { Button } from '@/components/ui/button';
import { ActionButton } from '@/components/ui/action-button';
import { Switch } from '@/components/ui/switch';
import { Slider } from '@/components/ui/slider';
@@ -42,8 +39,6 @@ interface SettingsPanelProps {
onClose: () => void;
settings: WorkflowSettings;
onSettingsChange: (settings: WorkflowSettings) => void;
- onReplayOnboarding?: () => void;
- onShowGetStarted?: () => void;
}
// ---------------------------------------------------------------------------
@@ -111,8 +106,6 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({
onClose,
settings,
onSettingsChange,
- onReplayOnboarding,
- onShowGetStarted,
}) => {
const settingsQuery = useUserSettingsQuery();
const saveMutation = useSaveUserSettingsMutation();
@@ -447,38 +440,6 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({
/>
</Row>
</Section>
-
- {/* Help */}
- <Section title="Help" Icon={HelpCircle} tone="model">
- <Row
- label="Replay Welcome Guide"
- description="Show the onboarding wizard again to review platform features"
- >
- <Button
- size="sm"
- variant="default"
- onClick={onReplayOnboarding}
- disabled={!onReplayOnboarding}
- >
- <HelpCircle className="h-3.5 w-3.5" />
- Replay
- </Button>
- </Row>
- <Row
- label="Get Started Checklist"
- description="Show the getting-started checklist on the canvas"
- >
- <Button
- size="sm"
- variant="default"
- onClick={onShowGetStarted}
- disabled={!onShowGetStarted}
- >
- <ListChecks className="h-3.5 w-3.5" />
- Show
- </Button>
- </Row>
- </Section>
</div>
</div>
</Modal>
diff --git a/client/src/components/ui/ring-spinner.tsx b/client/src/components/ui/ring-spinner.tsx
new file mode 100644
index 00000000..c43e5329
--- /dev/null
+++ b/client/src/components/ui/ring-spinner.tsx
@@ -0,0 +1,22 @@
+/**
+ * A thin ring that spins: a chat step at work, a new employee starting up,
+ * a server being dialled. Colour the track with a `border-*` class and the
+ * moving head with `border-t-*`; size it with `size-*`. `slow` turns at the
+ * live-ring pace (1200 ms) instead of the spinner's 800 ms. Reduced motion
+ * stops it (themes/animations.css).
+ */
+
+import { cn } from '@/lib/utils';
+
+export function RingSpinner({ slow = false, className }: { slow?: boolean; className?: string }) {
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ slow ? 'opencompany-spinner-slow' : 'opencompany-spinner',
+ 'block shrink-0 rounded-full border-2 border-action-tools-soft border-t-action-tools-ink',
+ className,
+ )}
+ />
+ );
+}
diff --git a/client/src/features/chat/ChatPane.tsx b/client/src/features/chat/ChatPane.tsx
index d39bc943..2e0ff199 100644
--- a/client/src/features/chat/ChatPane.tsx
+++ b/client/src/features/chat/ChatPane.tsx
@@ -19,8 +19,10 @@
* Files go with a message where the chat allows them: Attach, a paste, or
* a drop anywhere on the chat (DropOverlay), all through one
* `addAttachments` (composer/attachments.ts). The box also dictates, offers
- * slash commands and, in an empty chat, suggestions (data/chatContext.ts),
- * and the Web chip keeps the employee off web search for the next messages.
+ * slash commands and, in an empty chat, the host's greetings or else
+ * suggestions (data/chatContext.ts), and the Web chip keeps the employee off
+ * web search for the next messages. In the host's `wait` the box shows but
+ * takes nothing yet.
*
* The owner can change the conversation (data/branches.ts, TurnActions):
* edit one of their messages in place (ArrowUp in an empty box edits the
@@ -46,6 +48,7 @@ import { StandaloneApprovals } from './approval/StandaloneApprovals';
import { AskFirstChip } from './composer/AskFirstChip';
import { addAttachments } from './composer/attachments';
import { DropOverlay } from './composer/DropOverlay';
+import { Greetings } from './composer/Greetings';
import { Suggestions } from './composer/Suggestions';
import { WebChip } from './composer/WebChip';
import { canRecord, useChatContext, useDictation, type ChatCommand } from './data/chatContext';
@@ -275,8 +278,8 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
.filter((id) => !linked.has(id) && isOpenApproval(approvals.byId.get(id)!, now));
}, [approvals, linked]);
const approvalsValue = useMemo<ApprovalsValue>(
- () => ({ approvals, name: persona.name, askFirst: askFirstQuery.data?.askFirst ?? null, compact, decide, deciding }),
- [approvals, persona.name, askFirstQuery.data?.askFirst, compact, decide, deciding],
+ () => ({ approvals, name: persona.name, compact, decide, deciding }),
+ [approvals, persona.name, compact, decide, deciding],
);
// Ctrl/Cmd+Enter sends the newest draft still waiting for the owner.
@@ -313,25 +316,32 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
},
[sessionId, workflowId, notify],
);
- const filesAllowed = Boolean(workflowId && chatContext?.attachments && composer !== 'closed');
- const fillBox = useCallback(
- (command: ChatCommand) => {
- useComposerStore.getState().setText(sessionId, command.fill);
+ const filesAllowed = Boolean(workflowId && chatContext?.attachments && (composer === 'send' || composer === 'queue'));
+ const fill = useCallback(
+ (text: string) => {
+ useComposerStore.getState().setText(sessionId, text);
requestAnimationFrame(() => {
const box = boxRef.current;
if (!box) return;
box.focus();
- box.setSelectionRange(command.fill.length, command.fill.length);
+ box.setSelectionRange(text.length, text.length);
});
},
[sessionId],
);
+ const fillBox = useCallback((command: ChatCommand) => fill(command.fill), [fill]);
// Home only: the editor's chat is a console for trying chat triggers, where
// a card about the employee in an empty chat read as something a Reset left.
const suggestions = useMemo(
() => (host.kind === 'home' ? (chatContext?.commands ?? []).filter((command) => command.suggest) : []),
[chatContext, host.kind],
);
+ // What to say first, under the empty state, once a message can go.
+ const starters =
+ composer !== 'send' ? null
+ : host.greetings?.length ? <Greetings items={host.greetings} onPick={fill} />
+ : suggestions.length > 0 ? <Suggestions items={suggestions} onPick={fillBox} />
+ : null;
// A drop anywhere on the chat adds the files, as Attach does.
const [dragging, setDragging] = useState(false);
@@ -417,10 +427,10 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
) : null
}
emptyState={
- composer === 'send' && suggestions.length > 0 ? (
+ starters ? (
<div className="flex flex-col items-center gap-4">
{host.emptyState}
- <Suggestions items={suggestions} onPick={fillBox} />
+ {starters}
</div>
) : (
host.emptyState
@@ -456,6 +466,8 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
onAddFiles={filesAllowed ? addFiles : undefined}
dictation={workflowId && dictationQuery.data ? { workflowId, notify } : null}
commands={chatContext?.commands}
+ disabled={composer === 'wait'}
+ placeholder={host.placeholder}
/>
)}
{host.footnote && <p className="m-0 text-center text-xs text-fg-muted">{host.footnote}</p>}
diff --git a/client/src/features/chat/__tests__/approvals.test.tsx b/client/src/features/chat/__tests__/approvals.test.tsx
index 77b4542e..03ff4249 100644
--- a/client/src/features/chat/__tests__/approvals.test.tsx
+++ b/client/src/features/chat/__tests__/approvals.test.tsx
@@ -174,7 +174,7 @@ describe('a draft in the chat', () => {
const card = (await screen.findByText('Maya wants to send a WhatsApp message')).closest('[data-approval]') as HTMLElement;
const reply = screen.getByText('I drafted a WhatsApp to Ana.').closest('[data-turn="assistant"]') as HTMLElement;
expect(reply.contains(card)).toBe(true);
- expect(within(card).getByText('Ask first is on, so nothing goes out until you send it.')).toBeInTheDocument();
+ expect(within(card).queryByText(/goes out until you send it/)).not.toBeInTheDocument();
fireEvent.click(within(card).getByRole('button', { name: /^Send$/ }));
await waitFor(() => expect(server.decisions).toHaveLength(1));
diff --git a/client/src/features/chat/__tests__/composer.test.tsx b/client/src/features/chat/__tests__/composer.test.tsx
index bd294e51..76ed2be6 100644
--- a/client/src/features/chat/__tests__/composer.test.tsx
+++ b/client/src/features/chat/__tests__/composer.test.tsx
@@ -220,6 +220,23 @@ describe('commands, Web and suggestions', () => {
expect(box()).toHaveValue('What does tomorrow look like?');
});
+ it('says hello in place of the suggestions, filling the box', async () => {
+ renderPane(host({ greetings: ['Hi! What can you do?', 'Walk me through your routine'] }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Hi! What can you do?' }));
+ expect(box()).toHaveValue('Hi! What can you do?');
+ expect(screen.queryByRole('button', { name: /Check a day in the calendar/ })).not.toBeInTheDocument();
+ });
+
+ it('shows a box that takes nothing yet while the host waits, and no greetings', async () => {
+ renderPane(host({ composer: 'wait', placeholder: 'Maya is starting…', greetings: ['Hi! What can you do?'] }));
+ expect(await screen.findByPlaceholderText('Maya is starting…')).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();
+ await waitFor(() => expect(requests('get_chat_context')).toHaveLength(1));
+ await act(async () => {});
+ expect(screen.queryByRole('button', { name: 'Attach files' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Hi! What can you do?' })).not.toBeInTheDocument();
+ });
+
it('suggests nothing in the editor’s chat, a console for trying chat triggers', async () => {
renderPane(host({ kind: 'dev', compact: true }));
// Attach shows once the chat's context has arrived, commands included.
diff --git a/client/src/features/chat/approval/ApprovalCard.tsx b/client/src/features/chat/approval/ApprovalCard.tsx
index 572d8758..00496c38 100644
--- a/client/src/features/chat/approval/ApprovalCard.tsx
+++ b/client/src/features/chat/approval/ApprovalCard.tsx
@@ -10,7 +10,7 @@
* only the edit in progress. `chat-approval` is the theme hook.
*/
-import { Check, Link2, Loader2, MessageCircle, Pause, Pencil, RotateCcw, Send, ShieldCheck, Undo2 } from 'lucide-react';
+import { Check, Link2, Loader2, MessageCircle, Pause, Pencil, RotateCcw, Send, Undo2 } from 'lucide-react';
import { useContext, useEffect, useId, useLayoutEffect, useState, type KeyboardEvent } from 'react';
import { ActionButton } from '@/components/ui/action-button';
import { Button } from '@/components/ui/button';
@@ -80,7 +80,7 @@ export function ApprovalCard({ approvalId, className }: { approvalId: string; cl
function Card({ approval, className }: { approval: ChatApproval; className?: string }) {
const shared = useContext(ApprovalsContext)!;
- const { approvals, name, askFirst, compact, decide, deciding } = shared;
+ const { approvals, name, compact, decide, deciding } = shared;
const [editing, setEditing] = useState(false);
const [text, setText] = useState(approval.body);
const [subject, setSubject] = useState(approval.subject ?? '');
@@ -229,13 +229,6 @@ function Card({ approval, className }: { approval: ChatApproval; className?: str
))}
</dl>
)}
-
- {view.reassure && (
- <span className="flex items-center gap-1.5 text-xs text-fg-faint">
- <ShieldCheck aria-hidden className="size-3" strokeWidth={2} />
- {askFirst ? 'Ask first is on, so nothing goes out until you send it.' : 'Nothing goes out until you send it.'}
- </span>
- )}
</div>
<Footer view={view} approval={approval} busy={busy} editing={editing} canSend={canSend} onSend={send} onToggleEdit={() => setEditing((on) => !on)} />
diff --git a/client/src/features/chat/approval/context.ts b/client/src/features/chat/approval/context.ts
index d4e1ecce..4962d710 100644
--- a/client/src/features/chat/approval/context.ts
+++ b/client/src/features/chat/approval/context.ts
@@ -1,7 +1,7 @@
/**
* What a chat's approval cards share (set by ChatPane): the session's drafts,
- * who answers, the Ask first rule, and how to decide a draft. A card outside
- * a chat renders nothing.
+ * who answers, and how to decide a draft. A card outside a chat renders
+ * nothing.
*/
import { createContext } from 'react';
@@ -11,8 +11,6 @@ export interface ApprovalsValue {
approvals: ChatApprovals;
/** Who drafted them ("Maya wants to send ..."). */
name: string;
- /** The workflow's live rule; null when it has none. */
- askFirst: boolean | null;
compact: boolean;
decide: (input: DecideInput) => void;
/** Drafts with a decision on its way to the server. */
diff --git a/client/src/features/chat/approval/view.ts b/client/src/features/chat/approval/view.ts
index 67eead82..56bfe5cb 100644
--- a/client/src/features/chat/approval/view.ts
+++ b/client/src/features/chat/approval/view.ts
@@ -42,8 +42,6 @@ export interface CardView {
/** The small line inside the preview. */
when: string;
footer: CardFooter;
- /** "Ask first is on, so nothing goes out until you send it." */
- reassure: boolean;
}
function lowerFirst(text: string): string {
@@ -84,7 +82,6 @@ export function approvalView(approval: ChatApproval, { name, nowMs, offsetMs, ed
bubble: 'draft',
when: 'Draft',
footer: { kind: 'decide' },
- reassure: true,
};
case 'approved': {
if (approval.consumedAt === null) {
@@ -100,7 +97,6 @@ export function approvalView(approval: ChatApproval, { name, nowMs, offsetMs, ed
bubble: 'draft',
when: 'Sending',
footer,
- reassure: false,
};
}
const at = timeLabel(approval.consumedAt, now);
@@ -115,7 +111,6 @@ export function approvalView(approval: ChatApproval, { name, nowMs, offsetMs, ed
bubble: 'draft',
when: 'Sending',
footer: { kind: 'sending' },
- reassure: false,
};
case 'sent':
return sentView(approval, noun.sent, sub, to, channel, timeLabel(approval.outcome?.at ?? approval.consumedAt, now));
@@ -130,7 +125,6 @@ export function approvalView(approval: ChatApproval, { name, nowMs, offsetMs, ed
bubble: 'struck',
when: 'Not sent',
footer: { kind: 'discarded', text: `Discarded. ${name} won’t send this.`, restoreSeconds, canRestore },
- reassure: false,
};
}
case 'failed': {
@@ -144,7 +138,6 @@ export function approvalView(approval: ChatApproval, { name, nowMs, offsetMs, ed
bubble: 'draft',
when: 'Not sent',
footer: { kind: 'failed', text: unknown ? `It may have gone out${why}` : `It didn’t go out${why}`, unknown },
- reassure: false,
};
}
case 'expired':
@@ -165,7 +158,6 @@ function sentView(approval: ChatApproval, title: string, sub: string, to: string
bubble: 'sent',
when: at || 'Sent',
footer: { kind: 'sent', text: `Sent to ${to} on ${channel}${when}${auto}.` },
- reassure: false,
};
}
@@ -178,7 +170,6 @@ function endedView(title: string, label: string, sub: string, text: string): Car
bubble: 'struck',
when: 'Not sent',
footer: { kind: 'ended', text },
- reassure: false,
};
}
diff --git a/client/src/features/chat/composer/Composer.tsx b/client/src/features/chat/composer/Composer.tsx
index f46729fe..8a955ce3 100644
--- a/client/src/features/chat/composer/Composer.tsx
+++ b/client/src/features/chat/composer/Composer.tsx
@@ -65,6 +65,10 @@ export interface ComposerProps {
dictation?: { workflowId: string; notify: (message: string, tone: NotifyTone) => void } | null;
/** The slash commands the box offers. */
commands?: readonly ChatCommand[];
+ /** The box takes nothing yet (the host's `wait`). */
+ disabled?: boolean;
+ /** In place of "Message {name}…". */
+ placeholder?: string;
}
export function Composer({
@@ -84,6 +88,8 @@ export function Composer({
onAddFiles,
dictation = null,
commands = NO_COMMANDS,
+ disabled = false,
+ placeholder,
}: ComposerProps) {
const draft = useComposerDraft(sessionId);
const setText = useComposerStore((state) => state.setText);
@@ -95,7 +101,7 @@ export function Composer({
const uploading = attachments.some((item) => item.state === 'uploading');
const finished = attachments.some((item) => item.state === 'ready');
- const canSend = ready && !busy && !uploading && (draft.text.trim().length > 0 || finished);
+ const canSend = ready && !disabled && !busy && !uploading && (draft.text.trim().length > 0 || finished);
// The slash list: open while the box is one word starting with `/` that
// begins a command, until Esc (for that text) or a pick.
@@ -244,12 +250,13 @@ export function Composer({
variant="bare"
rows={1}
value={draft.text}
+ disabled={disabled}
onChange={(event) => setText(sessionId, event.target.value)}
onKeyDown={onKeyDown}
onPaste={onPaste}
aria-label={`Message ${name}`}
aria-autocomplete={commands.length ? 'list' : undefined}
- placeholder={commands.length ? `Message ${name}… Type / for commands` : `Message ${name}…`}
+ placeholder={placeholder ?? (commands.length ? `Message ${name}… Type / for commands` : `Message ${name}…`)}
className={cn(
'max-h-(--h-chat-composer-max) overflow-hidden text-fg-default field-sizing-fixed',
compact ? 'py-1 text-sm leading-normal' : 'py-1.5 text-md leading-normal',
diff --git a/client/src/features/chat/composer/Greetings.tsx b/client/src/features/chat/composer/Greetings.tsx
new file mode 100644
index 00000000..30776980
--- /dev/null
+++ b/client/src/features/chat/composer/Greetings.tsx
@@ -0,0 +1,30 @@
+/**
+ * Things to say first, in an empty chat that can take a message (a new
+ * hire's first day, onboarding handoff C): chips that put their words in the
+ * message box for the owner to send or change. They rise in a moment after
+ * the chat can take them.
+ */
+
+import { useLayoutEffect, useRef } from 'react';
+import { Button } from '@/components/ui/button';
+import { rise } from '@/lib/motion';
+
+export function Greetings({ items, onPick }: { items: readonly string[]; onPick: (text: string) => void }) {
+ const ref = useRef<HTMLUListElement>(null);
+ useLayoutEffect(() => {
+ rise(ref.current, { delay: 200 });
+ }, []);
+ return (
+ <ul ref={ref} aria-label="Say hello" className="m-0 flex list-none flex-wrap justify-center gap-2 p-0">
+ {items.map((text) => (
+ <li key={text}>
+ <Button variant="chip" size="chip" onClick={() => onPick(text)} className="bg-bg-elevated font-medium">
+ {text}
+ </Button>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+export default Greetings;
diff --git a/client/src/features/chat/host.ts b/client/src/features/chat/host.ts
index 1b2aa265..672340b2 100644
--- a/client/src/features/chat/host.ts
+++ b/client/src/features/chat/host.ts
@@ -24,10 +24,12 @@ export interface ChatPersona {
* The message box:
* - `send`: a message goes to them now;
* - `queue`: it waits until they are resumed;
+ * - `wait`: the box shows but takes nothing yet (a new hire still
+ * starting; the host's `placeholder` says so);
* - `closed`: nothing can read it, so there is no box (the host's notices
* say why and offer what to do).
*/
-export type ComposerMode = 'send' | 'queue' | 'closed';
+export type ComposerMode = 'send' | 'queue' | 'wait' | 'closed';
export type NotifyTone = 'info' | 'success' | 'error';
@@ -48,6 +50,11 @@ export interface ChatHost {
afterThread?: ReactNode;
/** In place of the conversation while it has no message. */
emptyState?: ReactNode;
+ /** Under the empty state while a message can go: things to say first,
+ * each putting its words in the box. In place of the suggested commands. */
+ greetings?: readonly string[];
+ /** The box's placeholder, in place of "Message {name}…". */
+ placeholder?: string;
/** One line under the box. */
footnote?: ReactNode;
/** A short message for the owner (Home: the pill toast; Dev: a toast). */
diff --git a/client/src/features/chat/turns/StepsDisclosure.tsx b/client/src/features/chat/turns/StepsDisclosure.tsx
index 437bd116..f383f262 100644
--- a/client/src/features/chat/turns/StepsDisclosure.tsx
+++ b/client/src/features/chat/turns/StepsDisclosure.tsx
@@ -9,22 +9,14 @@
import { Check, ChevronDown, Minus, X } from 'lucide-react';
import { useState } from 'react';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
+import { RingSpinner } from '@/components/ui/ring-spinner';
import type { RunStep } from '@/lib/agui/reduceRun';
import { cn } from '@/lib/utils';
import type { TurnWork } from '../thread/model';
import { stepDetail, workLabel } from './runCopy';
-function Spinner({ className }: { className?: string }) {
- return (
- <span
- aria-hidden
- className={cn('opencompany-spinner block shrink-0 rounded-full border-2 border-action-tools-soft border-t-action-tools-ink', className)}
- />
- );
-}
-
function StepIcon({ step }: { step: RunStep }) {
- if (step.state === 'running') return <Spinner className="size-2.5 border-border-default" />;
+ if (step.state === 'running') return <RingSpinner className="size-2.5 border-border-default" />;
if (step.state === 'failed') return <X aria-hidden className="size-3 text-action-stop-ink" strokeWidth={2.2} />;
if (step.state === 'skipped') return <Minus aria-hidden className="size-3 text-fg-faint" strokeWidth={2.2} />;
return <Check aria-hidden className="size-3 text-action-run-ink" strokeWidth={2.2} />;
@@ -65,7 +57,7 @@ export function StepsDisclosure({ work, compact = false }: { work: TurnWork; com
)}
>
{work.live ? (
- <Spinner className="size-3" />
+ <RingSpinner className="size-3" />
) : (
<Check aria-hidden className="size-3.25 text-action-run-ink" strokeWidth={2.4} />
)}
diff --git a/client/src/features/home/HomeShell.tsx b/client/src/features/home/HomeShell.tsx
index 51797dce..0d5e772b 100644
--- a/client/src/features/home/HomeShell.tsx
+++ b/client/src/features/home/HomeShell.tsx
@@ -6,7 +6,9 @@
*
* The shell owns what spans views: the employee broadcasts that keep the
* team current, the orb behind the content, the Workspace dock on the
- * right, and the Settings dialog. Connection actions open the app shell's
+ * right, the Settings dialog, the Welcome guide (onboarding/, which
+ * opens over the hire view on first launch) and, once the guide is
+ * finished, the Get started checklist. Connection actions open the app shell's
* shared credentials dialog. Switching views scrolls to the top and plays
* the view swap.
*
@@ -25,6 +27,8 @@ import type { EmployeeSummary } from './data/schemas';
import { EmployeeView } from './employee/EmployeeView';
import { HomeHeader } from './header/HomeHeader';
import { HireView } from './hire/HireView';
+import { GetStartedChecklist } from './onboarding/GetStartedChecklist';
+import { WelcomeGuide } from './onboarding/WelcomeGuide';
import { SPIKE, spikeOrb } from './orb/orb';
import { OrbStage } from './orb/OrbStage';
import { HomeSettings } from './settings/HomeSettings';
@@ -107,6 +111,8 @@ export default function HomeShell() {
</main>
<WorkspaceDock onConnect={openConnect} />
<HomeSettings onConnect={openConnect} />
+ <WelcomeGuide />
+ <GetStartedChecklist />
</div>
);
}
diff --git a/client/src/features/home/__tests__/catalogLayout.test.tsx b/client/src/features/home/__tests__/catalogLayout.test.tsx
index 71379de2..18a5d24c 100644
--- a/client/src/features/home/__tests__/catalogLayout.test.tsx
+++ b/client/src/features/home/__tests__/catalogLayout.test.tsx
@@ -49,6 +49,18 @@ describe('CatalogLayout', () => {
expect(screen.getByRole('button', { name: /Show less/ })).toBeInTheDocument();
});
+ it('shows every card with no cap, and names the list switch when asked', () => {
+ renderLayout({
+ discover: { items: Array.from({ length: 14 }, (_, i) => item(String(i))), sectionTitle: 'Top things' },
+ discoverLimit: null,
+ listLabel: 'AI models to show',
+ variant: 'embedded',
+ });
+ expect(cards()).toHaveLength(14);
+ expect(screen.queryByRole('button', { name: /Show all/ })).not.toBeInTheDocument();
+ expect(screen.getByLabelText('AI models to show')).toBeInTheDocument();
+ });
+
it('reveals the category chips, and closing the filter clears the category', () => {
renderLayout({
categories: [
diff --git a/client/src/features/home/__tests__/composer.test.tsx b/client/src/features/home/__tests__/composer.test.tsx
index 5c662fba..282f0055 100644
--- a/client/src/features/home/__tests__/composer.test.tsx
+++ b/client/src/features/home/__tests__/composer.test.tsx
@@ -70,6 +70,20 @@ describe('Composer', () => {
expect(createLabel(true, false)).toBe('Creating…');
expect(createLabel(false, true)).toBe('Update');
expect(createLabel(false, false)).toBe('Create employee');
+ expect(createLabel(false, false, 'Create their setup')).toBe('Create their setup');
+ expect(createLabel(true, false, 'Create their setup')).toBe('Creating…');
+ });
+
+ it('takes the guide’s label, and drops the float shadow when flat', () => {
+ setup({ idleLabel: 'Create their setup', flat: true });
+ const create = screen.getByRole('button', { name: /Create their setup/ });
+ expect(create).toBeEnabled();
+ expect(create.closest('[data-intro]')).not.toHaveClass('shadow-float');
+ });
+
+ it('floats on the hire view', () => {
+ setup();
+ expect(screen.getByRole('button', { name: /Create employee/ }).closest('[data-intro]')).toHaveClass('shadow-float');
});
it('counts the connected apps and opens Connectors', () => {
@@ -119,6 +133,17 @@ describe('TemplateChips', () => {
fireEvent.click(screen.getByRole('button', { name: 'Hire now' }));
expect(onHireNow).toHaveBeenCalledWith(receptionist);
});
+
+ it('shows the chips alone without Hire now (the Welcome guide)', () => {
+ render(
+ <ThemeProvider>
+ <TemplateChips picked={receptionist} onPick={vi.fn()} className="justify-start" />
+ </ThemeProvider>,
+ );
+ expect(screen.getByRole('button', { name: receptionist.label })).toHaveAttribute('aria-pressed', 'true');
+ expect(screen.queryByRole('button', { name: 'Hire now' })).not.toBeInTheDocument();
+ expect(screen.queryByText(receptionist.summary)).not.toBeInTheDocument();
+ });
});
describe('HireNotice', () => {
diff --git a/client/src/features/home/__tests__/getStarted.test.tsx b/client/src/features/home/__tests__/getStarted.test.tsx
new file mode 100644
index 00000000..b369059d
--- /dev/null
+++ b/client/src/features/home/__tests__/getStarted.test.tsx
@@ -0,0 +1,172 @@
+/**
+ * The Get started checklist on Home (onboarding/GetStartedChecklist): it
+ * shows once the Welcome guide is finished and stays out of the way while
+ * the guide is open; Connect an AI model and Hire your first employee
+ * follow the team as it is now, and their rows take the owner there; Say
+ * hello and Approve a first draft are latched in the owner's settings,
+ * each written once; it folds to a pill; hiding it says where it comes back.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+
+const sendRequest = vi.fn();
+const listeners = new Map<string, Set<(data: unknown) => void>>();
+
+vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),
+ useWebSocketActions: () => ({
+ sendRequest,
+ isReady: true,
+ addEventListener: (type: string, listener: (data: unknown) => void) => {
+ const set = listeners.get(type) ?? new Set();
+ set.add(listener);
+ listeners.set(type, set);
+ return () => set.delete(listener);
+ },
+ }),
+}));
+
+let ai: { id: string; name: string; consumer_category: string; connected: boolean }[] = [];
+
+vi.mock('../data/connectors', () => ({
+ useConnectors: () => ({ providers: ai, categories: [], connectedApps: [], hasAi: ai.some((p) => p.connected), isLoading: false }),
+ isConnected: (provider: { connected?: boolean }) => Boolean(provider.connected),
+}));
+
+vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));
+
+import { GetStartedChecklist } from '../onboarding/GetStartedChecklist';
+import { useHomeStore } from '../state/homeStore';
+import { pillToast } from '../ui/pillToast';
+
+type Wire = Record<string, unknown>;
+
+let server: { settings: Wire; employees: Wire[]; messages: Wire[] };
+
+const MAYA = {
+ workflow_id: 'w1',
+ name: 'Maya',
+ role: 'Receptionist',
+ derived: false,
+ hired_at: '2026-10-08T09:00:00+00:00',
+ pending_approvals: 0,
+ control: { state: 'running' },
+};
+
+function saves(): Wire[] {
+ return sendRequest.mock.calls.filter(([type]) => type === 'save_user_settings').map(([, data]) => (data as Wire).settings as Wire);
+}
+
+function renderChecklist() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+ <QueryClientProvider client={client}>
+ <GetStartedChecklist />
+ </QueryClientProvider>,
+ );
+}
+
+function emit(type: string, data: unknown) {
+ act(() => {
+ for (const listener of listeners.get(type) ?? []) listener(data);
+ });
+}
+
+const step = (name: RegExp) => screen.getByRole('button', { name });
+
+beforeEach(() => {
+ listeners.clear();
+ ai = [];
+ vi.mocked(pillToast).mockClear();
+ useHomeStore.setState((state) => ({ view: { kind: 'hire' }, guide: { ...state.guide, open: false } }));
+ server = { settings: { onboarding_completed: true }, employees: [], messages: [] };
+ sendRequest.mockReset().mockImplementation(async (type: string, data: Wire) => {
+ if (type === 'get_user_settings') return { settings: server.settings };
+ if (type === 'save_user_settings') {
+ server.settings = { ...server.settings, ...(data.settings as Wire) };
+ return { success: true };
+ }
+ if (type === 'list_employees') return { success: true, employees: server.employees };
+ if (type === 'get_chat_messages') return { success: true, messages: server.messages };
+ return { success: true };
+ });
+});
+
+describe('Get started on Home', () => {
+ it('waits for the Welcome guide to be finished, and for it to close', async () => {
+ server.settings = { onboarding_completed: false };
+ renderChecklist();
+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('get_user_settings', {}));
+ expect(screen.queryByRole('region', { name: 'Get started' })).not.toBeInTheDocument();
+ });
+
+ it('stays hidden while the guide is open', async () => {
+ useHomeStore.setState((state) => ({ guide: { ...state.guide, open: true } }));
+ renderChecklist();
+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('list_employees', {}));
+ expect(screen.queryByRole('region', { name: 'Get started' })).not.toBeInTheDocument();
+ });
+
+ it('offers the first steps, each taking the owner there', async () => {
+ renderChecklist();
+ const card = await screen.findByRole('region', { name: 'Get started' });
+ expect(within(card).getByText('0 of 4 done')).toBeInTheDocument();
+ expect(within(card).getByText('OpenAI, Anthropic, Gemini or a local model')).toBeInTheDocument();
+ fireEvent.click(step(/Connect an AI model/));
+ expect(useHomeStore.getState().guide).toMatchObject({ open: true, step: 'connect' });
+ act(() => useHomeStore.setState((state) => ({ guide: { ...state.guide, open: false }, view: { kind: 'employee', workflowId: 'x' } })));
+ fireEvent.click(await screen.findByRole('button', { name: /Hire your first employee/ }));
+ expect(useHomeStore.getState().view).toEqual({ kind: 'hire' });
+ });
+
+ it('ticks what is done now: a model connected, someone hired', async () => {
+ ai = [{ id: 'openai', name: 'OpenAI', consumer_category: 'ai', connected: true }];
+ server.employees = [MAYA];
+ renderChecklist();
+ expect(await screen.findByText('Maya, Receptionist')).toBeInTheDocument();
+ expect(screen.getByText('OpenAI is connected')).toBeInTheDocument();
+ expect(screen.getByText('2 of 4 done')).toBeInTheDocument();
+ fireEvent.click(step(/Say hello/));
+ expect(useHomeStore.getState().view).toEqual({ kind: 'employee', workflowId: 'w1' });
+ });
+
+ it('latches Say hello once the owner has written to their first hire', async () => {
+ server.employees = [MAYA];
+ server.messages = [{ id: 1, role: 'user', message: 'Hi!', timestamp: '2026-10-08T09:05:00+00:00', run_key: 'g1' }];
+ renderChecklist();
+ await waitFor(() => expect(saves()).toEqual([{ getting_started_said_hello: true }]));
+ expect(await screen.findByText('2 of 4 done')).toBeInTheDocument();
+ });
+
+ it('latches Approve a first draft when the owner sends one, and not for a discard', async () => {
+ server.employees = [MAYA];
+ renderChecklist();
+ await screen.findByRole('region', { name: 'Get started' });
+ emit('approval_lifecycle', { type: 'com.opencompany.approval.decided', data: { approval_id: 'a1', workflow_id: 'w1', status: 'discarded' } });
+ expect(saves()).toEqual([]);
+ emit('approval_lifecycle', { type: 'com.opencompany.approval.decided', data: { approval_id: 'a2', workflow_id: 'w1', status: 'approved' } });
+ await waitFor(() => expect(saves()).toEqual([{ getting_started_approved_draft: true }]));
+ // Latched: the next one writes nothing.
+ emit('approval_lifecycle', { type: 'com.opencompany.approval.decided', data: { approval_id: 'a3', workflow_id: 'w1', status: 'approved' } });
+ expect(saves()).toHaveLength(1);
+ });
+
+ it('folds to a pill and opens again', async () => {
+ renderChecklist();
+ await screen.findByRole('region', { name: 'Get started' });
+ fireEvent.click(screen.getByRole('button', { name: 'Fold the checklist' }));
+ fireEvent.click(screen.getByRole('button', { name: /Get started · 0\/4/ }));
+ expect(screen.getByRole('region', { name: 'Get started' })).toBeInTheDocument();
+ });
+
+ it('says where it comes back when hidden', async () => {
+ renderChecklist();
+ await screen.findByRole('region', { name: 'Get started' });
+ fireEvent.click(screen.getByRole('button', { name: 'Hide the checklist' }));
+ await waitFor(() => expect(saves()).toEqual([{ getting_started_dismissed: true }]));
+ expect(pillToast).toHaveBeenCalledWith('Get started hidden. Reopen it from Settings → Help.');
+ await waitFor(() => expect(screen.queryByRole('region', { name: 'Get started' })).not.toBeInTheDocument());
+ });
+});
diff --git a/client/src/features/home/__tests__/guideStore.test.ts b/client/src/features/home/__tests__/guideStore.test.ts
new file mode 100644
index 00000000..461b1b99
--- /dev/null
+++ b/client/src/features/home/__tests__/guideStore.test.ts
@@ -0,0 +1,70 @@
+/**
+ * The Welcome guide's state in homeStore: the first-launch check runs once
+ * per session and only opens the guide for an owner who has not finished
+ * it; opening and moving remember the furthest step visited; moving leaves
+ * a provider's page; closing keeps the step but not a job waiting for a
+ * model.
+ */
+
+import { beforeEach, describe, expect, it } from 'vitest';
+import { useHomeStore, type GuideState } from '../state/homeStore';
+
+const guide = () => useHomeStore.getState().guide;
+const fresh = (patch: Partial<GuideState> = {}): GuideState => ({
+ open: false,
+ step: 'welcome',
+ furthest: 0,
+ checked: false,
+ provider: null,
+ pendingDraft: false,
+ ...patch,
+});
+
+beforeEach(() => {
+ useHomeStore.setState({ guide: fresh() });
+});
+
+describe('the guide state', () => {
+ it('opens at the saved step once, and never for a finished owner', () => {
+ useHomeStore.getState().checkGuide({ onboarding_completed: false, onboarding_step: 1 });
+ expect(guide()).toEqual(fresh({ open: true, step: 'connect', furthest: 1, checked: true }));
+ useHomeStore.getState().closeGuide();
+ useHomeStore.getState().checkGuide({ onboarding_completed: false, onboarding_step: 2 });
+ expect(guide()).toMatchObject({ open: false, step: 'connect' });
+
+ useHomeStore.setState({ guide: fresh() });
+ useHomeStore.getState().checkGuide({ onboarding_completed: true, onboarding_step: 1 });
+ expect(guide()).toMatchObject({ open: false, checked: true });
+ });
+
+ it('starts on Welcome for a saved step that is not one of its steps', () => {
+ for (const saved of [-1, 3, 1.5, 'two', null]) {
+ useHomeStore.setState({ guide: fresh({ step: 'connect' }) });
+ useHomeStore.getState().checkGuide({ onboarding_completed: false, onboarding_step: saved });
+ expect(guide().step).toBe('welcome');
+ }
+ });
+
+ it('remembers the furthest step, and keeps the step while closing', () => {
+ useHomeStore.getState().openGuide('first-hire');
+ useHomeStore.getState().goToGuideStep('welcome');
+ expect(guide()).toMatchObject({ open: true, step: 'welcome', furthest: 2 });
+ useHomeStore.getState().closeGuide();
+ expect(guide()).toMatchObject({ open: false, step: 'welcome', furthest: 2 });
+ useHomeStore.getState().openGuide();
+ expect(guide()).toMatchObject({ open: true, step: 'welcome', furthest: 2 });
+ });
+
+ it('leaves a provider’s page on a move, and drops a waiting job when it closes', () => {
+ useHomeStore.getState().openGuide('connect');
+ useHomeStore.getState().setGuideProvider({ id: 'openai', intent: 'connect' });
+ useHomeStore.getState().setGuidePendingDraft(true);
+ useHomeStore.getState().goToGuideStep('connect');
+ expect(guide()).toMatchObject({ provider: null, pendingDraft: true });
+ useHomeStore.getState().closeGuide();
+ expect(guide().pendingDraft).toBe(false);
+ useHomeStore.getState().setGuideProvider({ id: 'openai', intent: 'manage' });
+ useHomeStore.getState().openGuide('welcome');
+ expect(guide().provider).toBeNull();
+ });
+});
diff --git a/client/src/features/home/__tests__/homeHeader.test.tsx b/client/src/features/home/__tests__/homeHeader.test.tsx
index 08c189bc..769776b2 100644
--- a/client/src/features/home/__tests__/homeHeader.test.tsx
+++ b/client/src/features/home/__tests__/homeHeader.test.tsx
@@ -27,6 +27,7 @@ vi.mock('@/lib/workspaceUpload', () => ({ uploadToWorkspace: vi.fn() }));
import { normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';
import { uploadToWorkspace } from '@/lib/workspaceUpload';
+import { useNodeStatusStore } from '@/stores/nodeStatusStore';
import { enterDev } from '../../../app/useShellActions';
import { parseEmployee } from '../data/schemas';
import { HomeHeader } from '../header/HomeHeader';
@@ -56,6 +57,7 @@ describe('HomeHeader', () => {
vi.mocked(enterDev).mockClear();
sendRequest.mockReset().mockResolvedValue({ success: true });
useHomeStore.setState({ sidebarOpen: true });
+ useNodeStatusStore.setState({ allStatuses: {} });
});
it('says who is on screen', () => {
@@ -63,7 +65,16 @@ describe('HomeHeader', () => {
wrap(<HomeHeader title="Maya" employee={maya} scrolled={false} />);
expect(screen.getByRole('heading', { name: 'Maya' })).toBeInTheDocument();
expect(screen.getByText('Receptionist · WhatsApp, Google Calendar')).toBeInTheDocument();
+ // Running with nothing to do: Ready.
+ expect(screen.getByText('Ready')).toBeInTheDocument();
+ });
+
+ it('says Working while their talk agent answers', () => {
+ useHomeStore.setState({ view: { kind: 'employee', workflowId: 'w1' } });
+ useNodeStatusStore.setState({ allStatuses: { w1: { 'w1:talk': { status: 'executing' } } } });
+ wrap(<HomeHeader title="Maya" employee={maya} scrolled={false} />);
expect(screen.getByText('Working')).toBeInTheDocument();
+ expect(screen.queryByText('Ready')).not.toBeInTheDocument();
});
it('starts a new conversation once the owner confirms', async () => {
@@ -164,6 +175,16 @@ describe('HomeHeader', () => {
expect(screen.queryByRole('button', { name: 'Change Maya’s photo' })).not.toBeInTheDocument();
});
+ it('opens the Welcome guide at its first step', () => {
+ useHomeStore.setState({
+ view: { kind: 'hire' },
+ guide: { open: false, step: 'connect', furthest: 1, checked: true, provider: null, pendingDraft: false },
+ });
+ wrap(<HomeHeader title="New employee" employee={null} scrolled={false} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Guide' }));
+ expect(useHomeStore.getState().guide).toMatchObject({ open: true, step: 'welcome', furthest: 1 });
+ });
+
it('opens what the editor last had from the hire view', () => {
useHomeStore.setState({ view: { kind: 'hire' } });
wrap(<HomeHeader title="New employee" employee={null} scrolled={false} />);
diff --git a/client/src/features/home/__tests__/homeSettings.test.tsx b/client/src/features/home/__tests__/homeSettings.test.tsx
index fff9a49f..8592f558 100644
--- a/client/src/features/home/__tests__/homeSettings.test.tsx
+++ b/client/src/features/home/__tests__/homeSettings.test.tsx
@@ -77,4 +77,29 @@ describe('HomeSettings', () => {
renderSettings();
expect(await screen.findByText('—')).toBeInTheDocument();
});
+
+ it('replays the Welcome guide from Help, closing Settings', async () => {
+ useHomeStore.setState({ guide: { open: false, step: 'first-hire', furthest: 2, checked: true, provider: null, pendingDraft: false } });
+ useHomeStore.getState().openSettings('help');
+ renderSettings();
+ await userEvent.click(screen.getByRole('button', { name: 'Replay' }));
+ expect(useHomeStore.getState().settingsOpen).toBe(false);
+ expect(useHomeStore.getState().guide).toMatchObject({ open: true, step: 'welcome', furthest: 2 });
+ });
+
+ it('shows the hidden Get started checklist again from Help, closing Settings', async () => {
+ useHomeStore.getState().openSettings('help');
+ renderSettings();
+ await userEvent.click(screen.getByRole('button', { name: 'Show' }));
+ expect(useHomeStore.getState().settingsOpen).toBe(false);
+ expect(sendRequest).toHaveBeenCalledWith('save_user_settings', { settings: { getting_started_dismissed: false } });
+ });
+
+ it('finds Help by searching for the guide', () => {
+ useHomeStore.getState().openSettings();
+ renderSettings();
+ fireEvent.change(screen.getByRole('textbox', { name: 'Search settings' }), { target: { value: 'guide' } });
+ expect(screen.getByRole('tab', { name: 'Help' })).toBeInTheDocument();
+ expect(screen.queryByRole('tab', { name: 'Billing' })).not.toBeInTheDocument();
+ });
});
diff --git a/client/src/features/home/__tests__/homeSidebar.test.tsx b/client/src/features/home/__tests__/homeSidebar.test.tsx
index c92eca41..3ca2cf63 100644
--- a/client/src/features/home/__tests__/homeSidebar.test.tsx
+++ b/client/src/features/home/__tests__/homeSidebar.test.tsx
@@ -13,10 +13,12 @@ vi.mock('@/components/brand/Logo', () => ({ OcLogo: () => null }));
vi.mock('../data/profile', () => ({ useOwnerSettings: () => ({ data: { profile_full_name: 'Owner' } }) }));
vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));
+import { normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';
import { ThemeProvider } from '@/contexts/ThemeContext';
import { queryClient } from '@/lib/queryClient';
import { workflowApi } from '@/services/workflowApi';
import { useAppStore } from '@/store/useAppStore';
+import { useNodeStatusStore } from '@/stores/nodeStatusStore';
import { EMPLOYEES_QUERY_KEY } from '../data/employeeCache';
import { parseEmployee } from '../data/schemas';
import { HomeSidebar } from '../sidebar/HomeSidebar';
@@ -117,3 +119,32 @@ describe('HomeSidebar employee deletion', () => {
expect(workflowApi.deleteWorkflow).toHaveBeenCalledTimes(2);
});
});
+
+describe('HomeSidebar status pip', () => {
+ afterEach(() => {
+ useNodeStatusStore.setState({ allStatuses: {} });
+ });
+
+ it('pulses only while a running employee is answering', () => {
+ queryClient.setQueryData(EMPLOYEES_QUERY_KEY, [
+ parseEmployee({
+ workflow_id: 'a',
+ name: 'Maya',
+ role: 'Receptionist',
+ status: 'working',
+ watch_node_ids: ['a:aiAgent:1'],
+ control: normalizeWorkflowControlStatus({ state: 'running' }, 'a'),
+ })!,
+ ]);
+ const { container } = mountSidebar();
+ expect(container.querySelector('[data-pip="on"]')).toBeNull();
+ act(() => {
+ useNodeStatusStore.setState({ allStatuses: { a: { 'a:aiAgent:1': { status: 'executing' } } } });
+ });
+ expect(container.querySelector('[data-pip="on"]')).not.toBeNull();
+ act(() => {
+ useNodeStatusStore.setState({ allStatuses: { a: { 'a:aiAgent:1': { status: 'success' } } } });
+ });
+ expect(container.querySelector('[data-pip="on"]')).toBeNull();
+ });
+});
diff --git a/client/src/features/home/__tests__/liveTask.test.ts b/client/src/features/home/__tests__/liveTask.test.ts
new file mode 100644
index 00000000..81d163cc
--- /dev/null
+++ b/client/src/features/home/__tests__/liveTask.test.ts
@@ -0,0 +1,66 @@
+/**
+ * "Answering": one of an employee's nodes is executing right now, the
+ * watched ones or the agent that answers the owner in Talk. It decides
+ * Working versus Ready (data/presentation) and the hire view's count.
+ */
+
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it } from 'vitest';
+import { normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';
+import { useNodeStatusStore } from '@/stores/nodeStatusStore';
+import { isAnswering, useAnsweringCount, workingNodeIds } from '../data/liveTask';
+import { parseEmployee, type EmployeeSummary } from '../data/schemas';
+
+function employee(id: string, patch: Record<string, unknown> = {}): EmployeeSummary {
+ return parseEmployee({
+ workflow_id: id,
+ name: id,
+ status: 'working',
+ watch_node_ids: [`${id}:aiAgent:1`],
+ talk: { state: 'on', agent_node_id: `${id}:talk` },
+ control: normalizeWorkflowControlStatus({ state: 'running' }, id),
+ ...patch,
+ })!;
+}
+
+afterEach(() => {
+ useNodeStatusStore.setState({ allStatuses: {} });
+});
+
+describe('workingNodeIds', () => {
+ it('adds the talk agent to the watched nodes once', () => {
+ expect(workingNodeIds(employee('a'))).toEqual(['a:aiAgent:1', 'a:talk']);
+ expect(workingNodeIds(employee('a', { watch_node_ids: ['a:talk'] }))).toEqual(['a:talk']);
+ expect(workingNodeIds(employee('a', { talk: { state: 'off', agent_node_id: null } }))).toEqual(['a:aiAgent:1']);
+ });
+});
+
+describe('isAnswering', () => {
+ it('is true only while one of the nodes executes', () => {
+ const ids = ['a:aiAgent:1', 'a:talk'];
+ expect(isAnswering(undefined, ids)).toBe(false);
+ expect(isAnswering({ 'a:talk': { status: 'executing' } }, ids)).toBe(true);
+ expect(isAnswering({ 'a:aiAgent:1': { status: 'success' } }, ids)).toBe(false);
+ // Another node of theirs that is not watched does not count.
+ expect(isAnswering({ 'a:other:1': { status: 'executing' } }, ids)).toBe(false);
+ });
+});
+
+describe('useAnsweringCount', () => {
+ it('counts the running employees who are answering, in their own workflow only', () => {
+ const team = [employee('a'), employee('b'), employee('c', { status: 'ready' })];
+ const { result } = renderHook(() => useAnsweringCount(team));
+ expect(result.current).toBe(0);
+ act(() => {
+ useNodeStatusStore.setState({
+ allStatuses: {
+ a: { 'a:talk': { status: 'executing' } },
+ // b's id under another workflow is someone else's node.
+ c: { 'b:aiAgent:1': { status: 'executing' }, 'c:aiAgent:1': { status: 'executing' } },
+ },
+ });
+ });
+ // c is not running, so its executing node does not make it count.
+ expect(result.current).toBe(1);
+ });
+});
diff --git a/client/src/features/home/__tests__/presentation.test.ts b/client/src/features/home/__tests__/presentation.test.ts
index c505c129..e2240ec3 100644
--- a/client/src/features/home/__tests__/presentation.test.ts
+++ b/client/src/features/home/__tests__/presentation.test.ts
@@ -8,6 +8,8 @@ import { describe, expect, it } from 'vitest';
import { normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';
import {
busyLabelFor,
+ firstDayNote,
+ firstDayPhase,
initialOf,
presentEmployee,
primaryActionLabel,
@@ -30,17 +32,34 @@ const whatsapp = { app_id: 'whatsapp', provider_id: 'whatsapp', name: 'WhatsApp'
describe('presentEmployee', () => {
it.each([
- ['working', { state: 'running' }, 'Working', 'working', 'pause'],
- ['paused', { state: 'paused' }, 'Stopped', 'paused', 'resume'],
- ['attention', { state: 'paused' }, 'Needs attention', 'attention', 'resume'],
- ['attention', { state: 'failed', can_resume: false }, 'Needs attention', 'attention', 'start'],
- ['attention', { state: 'pausing', can_resume: false }, 'Needs attention', 'attention', 'open_workflow'],
- ['ready', { state: 'never_started' }, 'Ready', 'ready', 'start'],
- ])('%s (%o) shows %s and offers %s', (status, control, label, tone, action) => {
- const view = presentEmployee(employee({ status }, control));
+ ['working', { state: 'running' }, true, 'Working', 'working', 'pause'],
+ ['working', { state: 'running' }, false, 'Ready', 'ready', 'pause'],
+ ['paused', { state: 'paused' }, false, 'Stopped', 'paused', 'resume'],
+ ['attention', { state: 'paused' }, false, 'Needs attention', 'attention', 'resume'],
+ ['attention', { state: 'failed', can_resume: false }, false, 'Needs attention', 'attention', 'start'],
+ ['attention', { state: 'pausing', can_resume: false }, false, 'Needs attention', 'attention', 'open_workflow'],
+ ['ready', { state: 'never_started' }, false, 'Not started', 'paused', 'start'],
+ ])('%s (%o, answering: %s) shows %s and offers %s', (status, control, answering, label, tone, action) => {
+ const view = presentEmployee(employee({ status }, control), undefined, answering);
expect(view.pill).toEqual({ label, tone });
expect(view.primary.kind).toBe(action);
- expect(view.pulse).toBe(status === 'working');
+ // Only Working pulses, and only while they answer.
+ expect(view.pulse).toBe(tone === 'working');
+ });
+
+ it('says Starting… from the Start press until they run, and Resuming… on the way back', () => {
+ expect(presentEmployee(employee({ status: 'ready' }), { action: 'start', state: 'starting' }).pill).toEqual({
+ label: 'Starting…',
+ tone: 'ready',
+ });
+ expect(presentEmployee(employee({ status: 'working' }, { state: 'starting' }), undefined, true).pill).toEqual({
+ label: 'Starting…',
+ tone: 'ready',
+ });
+ expect(presentEmployee(employee({ status: 'working' }, { state: 'resuming' })).pill).toEqual({
+ label: 'Resuming…',
+ tone: 'ready',
+ });
});
// start_employee resets a failed employee before starting it again.
@@ -124,6 +143,31 @@ describe('the message box', () => {
});
});
+describe('a new hire’s first day', () => {
+ it.each([
+ [{ state: 'running' }, {}, true, 'ready'],
+ [{ state: 'starting' }, {}, true, 'starting'],
+ // Hired and started by the hire: no control row yet.
+ [{ state: 'never_started' }, { activation_state: 'saved' }, true, 'starting'],
+ // The start was held for something to connect, or failed.
+ [{ state: 'never_started' }, { activation_state: 'blocked' }, true, 'stopped'],
+ [{ state: 'never_started' }, { activation_state: 'failed' }, true, 'stopped'],
+ // The hire did not start them (something was missing).
+ [{ state: 'never_started' }, { activation_state: 'saved' }, false, 'stopped'],
+ [{ state: 'failed' }, {}, true, 'stopped'],
+ ])('control %o with %o (started: %s) is %s', (control, patch, started, phase) => {
+ expect(firstDayPhase(employee(patch, control), started)).toBe(phase);
+ });
+
+ it('says why they are not running', () => {
+ expect(firstDayNote(employee({ missing_apps: [whatsapp] }))).toBe('WhatsApp isn’t connected yet.');
+ expect(firstDayNote(employee({ needs_ai: true }))).toBe('Connect an AI model first.');
+ expect(firstDayNote(employee({ activation_state: 'failed' }))).toBe('Maya couldn’t start.');
+ expect(firstDayNote(employee({}, { state: 'failed' }))).toBe('Maya couldn’t start.');
+ expect(firstDayNote(employee({}))).toBe('Maya isn’t running.');
+ });
+});
+
describe('parseEmployee', () => {
it('drops an entry without its identity and repairs odd fields', () => {
expect(parseEmployee({ name: 'No id' })).toBeNull();
diff --git a/client/src/features/home/__tests__/welcomeDemo.test.tsx b/client/src/features/home/__tests__/welcomeDemo.test.tsx
new file mode 100644
index 00000000..b7b3ec0c
--- /dev/null
+++ b/client/src/features/home/__tests__/welcomeDemo.test.tsx
@@ -0,0 +1,80 @@
+/**
+ * The Welcome step's demo plays on its own clock (80 ms a tick): the job
+ * types itself, then each beat follows the last and the demo goes round;
+ * clicking a beat starts it; under reduced motion it holds the
+ * conversation still, with no clock and no progress bar, and a click shows
+ * another beat.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import { setReducedMotion } from '@/test/waapi';
+import { WelcomeDemo } from '../onboarding/steps/WelcomeDemo';
+
+const JOB = 'Answer WhatsApp messages and take bookings';
+
+const beat = (name: string) => screen.getByRole('button', { name: new RegExp(name) });
+const playing = () => screen.getAllByRole('button').find((button) => button.getAttribute('aria-current') === 'step')?.textContent;
+
+function ticks(count: number) {
+ act(() => {
+ vi.advanceTimersByTime(count * 80);
+ });
+}
+
+let restoreMotion: () => void = () => {};
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+});
+
+afterEach(() => {
+ restoreMotion();
+ restoreMotion = () => {};
+ vi.useRealTimers();
+});
+
+describe('the Welcome demo', () => {
+ it('types the job a character a tick, then moves on to the setup and the conversation, and round again', () => {
+ const { container } = render(<WelcomeDemo name="Jordan" />);
+ expect(playing()).toContain('Describe the job');
+ ticks(6);
+ expect(screen.getByText('Answer')).toBeInTheDocument();
+ ticks(JOB.length - 6);
+ expect(screen.getByText(JOB)).toBeInTheDocument();
+ // The job is written, then a pause before the setup.
+ ticks(16);
+ expect(playing()).toContain('Check and hire');
+ expect(screen.getByText('Receptionist · WhatsApp')).toBeInTheDocument();
+ ticks(48);
+ expect(playing()).toContain('Talk to them');
+ expect(screen.getByText(/Hi Jordan! Here’s a reply for Priya/)).toBeInTheDocument();
+ ticks(56);
+ expect(playing()).toContain('Describe the job');
+ expect(container.querySelector('[data-beat-progress]')).not.toBeNull();
+ });
+
+ it('starts a beat when it is clicked', () => {
+ render(<WelcomeDemo name="" />);
+ ticks(10);
+ fireEvent.click(beat('Talk to them'));
+ expect(playing()).toContain('Talk to them');
+ expect(screen.getByText('Hi Maya!')).toBeInTheDocument();
+ // From its start: the whole beat still to play.
+ ticks(55);
+ expect(playing()).toContain('Talk to them');
+ ticks(1);
+ expect(playing()).toContain('Describe the job');
+ });
+
+ it('holds the conversation still under reduced motion, and shows another beat on a click', () => {
+ restoreMotion = setReducedMotion(true);
+ const { container } = render(<WelcomeDemo name="Jordan" />);
+ expect(playing()).toContain('Talk to them');
+ ticks(200);
+ expect(playing()).toContain('Talk to them');
+ expect(container.querySelector('[data-beat-progress]')).toBeNull();
+ fireEvent.click(beat('Describe the job'));
+ expect(screen.getByText(JOB)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/features/home/__tests__/welcomeGuide.test.tsx b/client/src/features/home/__tests__/welcomeGuide.test.tsx
new file mode 100644
index 00000000..5140c270
--- /dev/null
+++ b/client/src/features/home/__tests__/welcomeGuide.test.tsx
@@ -0,0 +1,266 @@
+/**
+ * The Welcome guide on Home: it opens by itself once, at the saved step, for
+ * an owner who has not finished it, and a remount never reopens it; the nav
+ * reaches the steps already visited and Connect; the footer offers the next
+ * move each step allows; every way out saves the step reached; Connect lists
+ * every AI model and nothing else, opens a provider's page in place of the
+ * list (Back and Esc return to it), and returns to the list when the model
+ * connects; the last step creates the setup, or, with no AI model, sends
+ * nothing until one is connected on step 2, which then finishes the guide.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { ServerProviderConfig } from '@/hooks/useCatalogueQuery';
+
+const sendRequest = vi.fn();
+let settingsRow: Record<string, unknown> = {};
+let persistSaves = true;
+let providers: (ServerProviderConfig & { consumer_category: string })[] = [];
+const job = { value: '', working: false, onChange: vi.fn(), pick: vi.fn(), submit: vi.fn() };
+
+vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),
+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),
+}));
+
+vi.mock('@/components/credentials/catalogue', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/components/credentials/catalogue')>();
+ return {
+ ...actual,
+ useCredentialsCatalogue: () => ({
+ catalogue: { data: {} },
+ providers,
+ categories: [],
+ isLoading: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ }),
+ useConnectors: () => ({
+ providers,
+ categories: [],
+ connectedApps: [],
+ hasAi: providers.some((p) => p.consumer_category === 'ai' && actual.isConnected(p)),
+ isLoading: false,
+ }),
+ };
+});
+
+// The draft pipeline has its own tests; here the guide only hands it a job.
+vi.mock('../genui', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../genui')>()),
+ useJobComposer: () => job,
+}));
+// A provider's panel (the key field) has its own tests.
+vi.mock('@/components/credentials/PanelRenderer', () => ({ default: () => <p>The provider’s panel</p> }));
+vi.mock('../../../app/ShellModeSwitch', () => ({ useShellMode: () => 'normal' }));
+vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));
+
+import { ThemeProvider } from '@/contexts/ThemeContext';
+import { WelcomeGuide } from '../onboarding/WelcomeGuide';
+import { useHomeStore } from '../state/homeStore';
+import { pillToast } from '../ui/pillToast';
+
+function provider(id: string, consumer: string, connected = false) {
+ return { id, name: id, kind: 'apiKey', category: 'x', category_label: 'X', color: '', consumer_category: consumer, connected } as ServerProviderConfig & {
+ consumer_category: string;
+ };
+}
+
+function renderGuide() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const tree = () => (
+ <ThemeProvider>
+ <QueryClientProvider client={client}>
+ <WelcomeGuide />
+ </QueryClientProvider>
+ </ThemeProvider>
+ );
+ const utils = render(tree());
+ /** Render again: the catalogue mock reads `providers` anew. */
+ return { ...utils, refresh: () => utils.rerender(tree()) };
+}
+
+const saves = () =>
+ sendRequest.mock.calls.filter(([type]) => type === 'save_user_settings').map(([, data]) => (data as { settings: unknown }).settings);
+
+beforeEach(() => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 0 };
+ persistSaves = true;
+ providers = [provider('openai', 'ai'), provider('anthropic', 'ai'), provider('whatsapp', 'messages')];
+ Object.assign(job, { value: '', working: false });
+ job.submit.mockReset();
+ job.pick.mockReset();
+ job.onChange.mockReset();
+ vi.mocked(pillToast).mockClear();
+ sendRequest.mockReset().mockImplementation(async (type: string, data?: { settings?: Record<string, unknown> }) => {
+ if (type === 'get_user_settings') return { settings: { ...settingsRow } };
+ if (type === 'save_user_settings' && persistSaves) Object.assign(settingsRow, data?.settings);
+ return { success: true };
+ });
+ useHomeStore.setState({
+ view: { kind: 'employee', workflowId: 'w1' },
+ guide: { open: false, step: 'welcome', furthest: 0, checked: false, provider: null, pendingDraft: false },
+ });
+});
+
+describe('WelcomeGuide opening', () => {
+ it('opens for an owner who has not finished it, at the step they left', async () => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 2 };
+ renderGuide();
+ expect(await screen.findByRole('heading', { name: 'Who should we hire first?' })).toBeInTheDocument();
+ expect(screen.getByText('3 / 3')).toBeInTheDocument();
+ });
+
+ it('starts on Welcome when the saved step is not one of its steps', async () => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 7 };
+ renderGuide();
+ expect(await screen.findByRole('heading', { name: 'Your AI team, hired in plain words.' })).toBeInTheDocument();
+ });
+
+ it('never opens by itself for an owner who finished it', async () => {
+ settingsRow = { onboarding_completed: true, onboarding_step: 4 };
+ renderGuide();
+ await waitFor(() => expect(useHomeStore.getState().guide.checked).toBe(true));
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ });
+
+ it('does not reopen when Home mounts again, even before its save lands', async () => {
+ persistSaves = false;
+ const first = renderGuide();
+ await screen.findByRole('dialog');
+ fireEvent.click(screen.getByRole('button', { name: 'Skip for now' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ first.unmount();
+ renderGuide();
+ await waitFor(() => expect(sendRequest.mock.calls.filter(([type]) => type === 'get_user_settings')).toHaveLength(2));
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ });
+});
+
+describe('WelcomeGuide steps', () => {
+ it('greets the owner by name, and reaches only the visited steps and Connect', async () => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 0, profile_call_name: 'Jordan' };
+ renderGuide();
+ expect(await screen.findByText('Welcome, Jordan')).toBeInTheDocument();
+ expect(screen.getByRole('tab', { name: 'Your first hire' })).toBeDisabled();
+ expect(screen.getByRole('tab', { name: 'Connect an AI model' })).toBeEnabled();
+ expect(screen.queryByRole('button', { name: 'Back' })).not.toBeInTheDocument();
+ expect(screen.getByText('1 / 3')).toBeInTheDocument();
+ });
+
+ it('shows the beat the owner picks', async () => {
+ renderGuide();
+ fireEvent.click(await screen.findByRole('button', { name: /Check and hire/ }));
+ expect(screen.getByRole('button', { name: /Check and hire/ })).toHaveAttribute('aria-current', 'step');
+ expect(screen.getByText('Ask before sending')).toBeInTheDocument();
+ });
+
+ it('moves on with Next and saves each step', async () => {
+ renderGuide();
+ fireEvent.click(await screen.findByRole('button', { name: /Next/ }));
+ expect(useHomeStore.getState().guide.step).toBe('connect');
+ await waitFor(() => expect(saves()).toContainEqual({ onboarding_step: 1 }));
+ expect(screen.getByRole('button', { name: 'Back' })).toBeInTheDocument();
+ });
+
+ it('lists every AI model and no apps on Connect, and lets the owner do it later', async () => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 1 };
+ providers = [...Array.from({ length: 10 }, (_, i) => provider(`ai${i}`, 'ai')), provider('whatsapp', 'messages')];
+ renderGuide();
+ expect(await screen.findByRole('heading', { name: 'Connect an AI model' })).toBeInTheDocument();
+ expect(document.querySelectorAll('[data-catalog-item]')).toHaveLength(10);
+ expect(document.querySelector('[data-catalog-item="whatsapp"]')).toBeNull();
+ expect(screen.queryByRole('button', { name: /Next/ })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'I’ll do this later' }));
+ expect(useHomeStore.getState().guide.step).toBe('first-hire');
+ });
+
+ it('opens a provider’s page in place of the list, and goes back with Back or Esc', async () => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 1 };
+ renderGuide();
+ fireEvent.click(await screen.findByRole('button', { name: 'Connect openai' }));
+ expect(screen.getByRole('heading', { name: 'Connect openai' })).toBeInTheDocument();
+ expect(screen.getByText('The provider’s panel')).toBeInTheDocument();
+ // The page carries its own way back; the footer's moves step aside.
+ expect(screen.queryByRole('button', { name: 'I’ll do this later' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Back' })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'All AI models' }));
+ expect(screen.queryByRole('heading', { name: 'Connect openai' })).not.toBeInTheDocument();
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Connect openai' })).toHaveFocus());
+
+ fireEvent.click(screen.getByRole('button', { name: 'Connect anthropic' }));
+ fireEvent.keyDown(screen.getByRole('button', { name: 'All AI models' }), { key: 'Escape' });
+ expect(screen.queryByRole('heading', { name: 'Connect anthropic' })).not.toBeInTheDocument();
+ expect(useHomeStore.getState().guide.open).toBe(true);
+ });
+
+ it('says so when the model connects, and returns to the list', async () => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 1 };
+ const { refresh } = renderGuide();
+ fireEvent.click(await screen.findByRole('button', { name: 'Connect openai' }));
+ providers = [provider('openai', 'ai', true), provider('anthropic', 'ai')];
+ refresh();
+ expect(pillToast).toHaveBeenCalledWith('openai is connected');
+ expect(screen.queryByRole('heading', { name: 'Connect openai' })).not.toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'You’re connected' })).toBeInTheDocument();
+ expect(useHomeStore.getState().guide.open).toBe(true);
+ });
+
+ it('says so once an AI model is connected, and offers Next', async () => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 1 };
+ providers = [provider('openai', 'ai', true)];
+ renderGuide();
+ expect(await screen.findByRole('heading', { name: 'You’re connected' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Next/ })).toBeInTheDocument();
+ });
+
+ it('saves the step reached when the owner closes it', async () => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 1 };
+ renderGuide();
+ fireEvent.click(await screen.findByRole('button', { name: 'Close guide' }));
+ await waitFor(() => expect(saves()).toContainEqual({ onboarding_completed: true, onboarding_step: 1 }));
+ expect(useHomeStore.getState().guide.open).toBe(false);
+ });
+});
+
+describe('WelcomeGuide first hire', () => {
+ it('finishes the guide, shows the hire view and sends the job when there is a model', async () => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 2 };
+ providers = [provider('openai', 'ai', true)];
+ job.value = 'Answer my WhatsApp';
+ renderGuide();
+ fireEvent.click(await screen.findByRole('button', { name: /Create their setup/ }));
+ expect(job.submit).toHaveBeenCalledTimes(1);
+ expect(useHomeStore.getState().view).toEqual({ kind: 'hire' });
+ expect(useHomeStore.getState().guide.open).toBe(false);
+ await waitFor(() => expect(saves()).toContainEqual({ onboarding_completed: true, onboarding_step: 3 }));
+ });
+
+ it('sends nothing without an AI model, then finishes and sends once one is connected', async () => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 2 };
+ job.value = 'Answer my WhatsApp';
+ const { refresh } = renderGuide();
+ expect(await screen.findByText('Connect an AI model first.')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: /Create their setup/ }));
+ expect(job.submit).not.toHaveBeenCalled();
+ expect(useHomeStore.getState().guide).toMatchObject({ step: 'connect', pendingDraft: true });
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Connect openai' }));
+ providers = [provider('openai', 'ai', true), provider('anthropic', 'ai')];
+ refresh();
+ expect(job.submit).toHaveBeenCalledTimes(1);
+ expect(useHomeStore.getState().view).toEqual({ kind: 'hire' });
+ expect(useHomeStore.getState().guide.open).toBe(false);
+ await waitFor(() => expect(saves()).toContainEqual({ onboarding_completed: true, onboarding_step: 3 }));
+ });
+
+ it('carries no job to Connect when the box is empty', async () => {
+ settingsRow = { onboarding_completed: false, onboarding_step: 2 };
+ renderGuide();
+ fireEvent.click(await screen.findByRole('button', { name: 'Connect an AI model' }));
+ expect(useHomeStore.getState().guide).toMatchObject({ step: 'connect', pendingDraft: false });
+ });
+});
diff --git a/client/src/features/home/data/employeeCache.ts b/client/src/features/home/data/employeeCache.ts
index 714694da..bf278834 100644
--- a/client/src/features/home/data/employeeCache.ts
+++ b/client/src/features/home/data/employeeCache.ts
@@ -24,6 +24,7 @@ export function removeEmployee(queryClient: QueryClient, workflowId: string): vo
hireNotice: state.hireNotice?.workflowId === workflowId ? null : state.hireNotice,
glow: state.glow?.workflowId === workflowId ? null : state.glow,
}));
+ useHomeStore.getState().endFirstDay(workflowId);
// Refresh anything else the canceled list request would have brought in.
void queryClient.invalidateQueries({ queryKey: EMPLOYEES_QUERY_KEY, exact: true });
diff --git a/client/src/features/home/data/liveTask.ts b/client/src/features/home/data/liveTask.ts
index e4f7121b..c112c325 100644
--- a/client/src/features/home/data/liveTask.ts
+++ b/client/src/features/home/data/liveTask.ts
@@ -14,7 +14,8 @@
*/
import { useQuery } from '@tanstack/react-query';
-import { useCallback } from 'react';
+import { useCallback, useMemo } from 'react';
+import type { NodeStatus } from '@/contexts/WebSocketContext';
import { todoQueryKey } from '@/lib/todoQuery';
import { useNodeStatusStore } from '@/stores/nodeStatusStore';
import type { EmployeeSummary } from './schemas';
@@ -33,6 +34,40 @@ export function currentTodo(todos: unknown): string | null {
return text || null;
}
+/** The nodes whose work makes an employee "Working": the ones the summary
+ * watches, and the agent that answers the owner in Talk. */
+export function workingNodeIds(employee: EmployeeSummary): readonly string[] {
+ const talkAgent = employee.talk.agent_node_id;
+ return talkAgent && !employee.watch_node_ids.includes(talkAgent)
+ ? [...employee.watch_node_ids, talkAgent]
+ : employee.watch_node_ids;
+}
+
+/** True while one of these nodes is executing in this workflow's statuses. */
+export function isAnswering(statuses: Record<string, NodeStatus> | undefined, nodeIds: readonly string[]): boolean {
+ return Boolean(statuses) && nodeIds.some((id) => statuses?.[id]?.status === 'executing');
+}
+
+/** Whether the employee is answering or doing a job right now: the pill says
+ * "Working" only then, "Ready" while they run idle (data/presentation). */
+export function useAnswering(employee: EmployeeSummary): boolean {
+ const ids = useMemo(() => workingNodeIds(employee), [employee]);
+ return useNodeStatusStore(
+ useCallback((state) => isAnswering(state.allStatuses[employee.workflow_id], ids), [employee.workflow_id, ids]),
+ );
+}
+
+/** How many running employees are answering or working right now. */
+export function useAnsweringCount(employees: readonly EmployeeSummary[] | undefined): number {
+ const running = useMemo(
+ () => (employees ?? []).filter((e) => e.status === 'working').map((e) => ({ workflowId: e.workflow_id, ids: workingNodeIds(e) })),
+ [employees],
+ );
+ return useNodeStatusStore(
+ useCallback((state) => running.filter((e) => isAnswering(state.allStatuses[e.workflowId], e.ids)).length, [running]),
+ );
+}
+
export function useLiveTask(employee: EmployeeSummary): { label: 'Now'; text: string } | null {
const todoNodeId = employee.watch_node_ids.find((id) => id.includes(TODO_ID_MARK)) ?? null;
const { data: todos } = useQuery<unknown>({
diff --git a/client/src/features/home/data/presentation.ts b/client/src/features/home/data/presentation.ts
index 995246e2..3f3abc95 100644
--- a/client/src/features/home/data/presentation.ts
+++ b/client/src/features/home/data/presentation.ts
@@ -4,16 +4,28 @@
* A table over server-decided fields: the server owns `status`, the task
* text, `missing_apps`, `needs_ai` and the control capabilities; this only
* picks labels, colours and the primary action from them. It derives no new
- * rules.
+ * rules. `answering` is the one live input: one of the employee's nodes is
+ * executing right now (data/liveTask `useAnswering`).
*
- * | Server state | Pill (status tone) | Primary action |
- * |-----------------------|---------------------------|---------------------------------|
- * | working | Working | Pause |
- * | ready | Ready | Connect {App} / Connect AI / Start |
- * | paused | Paused | Resume |
- * | attention | Needs attention | Resume when possible; after a failure Start again (the server resets first); else Open in Dev mode |
- * | pending_approvals > 0 | Needs you (overrides pill) | (the drafts are the action) |
- * | browser_request | Needs you (overrides pill) | (Help in browser opens the Workspace) |
+ * The pill, first match wins:
+ *
+ * | State | Pill (status tone) |
+ * |-----------------------------------------|-------------------------|
+ * | pending_approvals > 0 or browser_request | Needs you (waiting) |
+ * | Start pressed, or control starting | Starting… (ready) |
+ * | control resuming | Resuming… (ready) |
+ * | working and answering | Working (working, pulses) |
+ * | working (running, idle) | Ready (ready) |
+ * | ready (never started, or reset) | Not started (paused) |
+ * | paused | Stopped (paused) |
+ * | attention | Needs attention |
+ *
+ * | Server state | Primary action |
+ * |--------------|------------------------------------------------------|
+ * | working | Pause |
+ * | ready | Connect {App} / Connect AI / Start |
+ * | paused | Resume |
+ * | attention | Resume when possible; after a failure Start again (the server resets first); else Open in Dev mode |
*
* The message box follows the control state the way the server's
* `send_chat_message` does (its `delivery`): a message goes now while the
@@ -49,13 +61,6 @@ export interface EmployeePresentation {
busyLabel: string | null;
}
-const PILL: Record<EmployeeSummary['status'], { label: string; tone: StatusTone }> = {
- working: { label: 'Working', tone: 'working' },
- ready: { label: 'Ready', tone: 'ready' },
- paused: { label: 'Stopped', tone: 'paused' },
- attention: { label: 'Needs attention', tone: 'attention' },
-};
-
const BUSY: Record<WorkflowControlPendingMutation['action'], string> = {
start: 'Starting…',
pause: 'Stopping…',
@@ -63,6 +68,29 @@ const BUSY: Record<WorkflowControlPendingMutation['action'], string> = {
reset: 'Resetting…',
};
+/** The pill: the first row of the table above that matches. */
+function pillOf(
+ employee: EmployeeSummary,
+ pending: WorkflowControlPendingMutation | undefined,
+ answering: boolean,
+): { label: string; tone: StatusTone } {
+ if (employee.pending_approvals > 0 || employee.browser_request !== null) return { label: 'Needs you', tone: 'waiting' };
+ const { state } = employee.control;
+ if (pending?.action === 'start' || state === 'starting') return { label: BUSY.start, tone: 'ready' };
+ if (state === 'resuming') return { label: BUSY.resume, tone: 'ready' };
+ switch (employee.status) {
+ case 'working':
+ return answering ? { label: 'Working', tone: 'working' } : { label: 'Ready', tone: 'ready' };
+ case 'paused':
+ return { label: 'Stopped', tone: 'paused' };
+ case 'attention':
+ return { label: 'Needs attention', tone: 'attention' };
+ case 'ready':
+ default:
+ return { label: 'Not started', tone: 'paused' };
+ }
+}
+
/** What starting needs first: an app to connect, or an AI model. */
function startBlocker(employee: EmployeeSummary): PrimaryAction | null {
if (employee.missing_apps.length > 0) return { kind: 'connect_app', app: employee.missing_apps[0] };
@@ -92,12 +120,12 @@ function primaryAction(employee: EmployeeSummary): PrimaryAction {
export function presentEmployee(
employee: EmployeeSummary,
pending?: WorkflowControlPendingMutation,
+ answering = false,
): EmployeePresentation {
- const needsYou = employee.pending_approvals > 0 || employee.browser_request !== null;
- const pill = needsYou ? { label: 'Needs you', tone: 'waiting' as const } : PILL[employee.status];
+ const pill = pillOf(employee, pending, answering);
return {
pill,
- // Only a green working dot pulses (its ring is green).
+ // Only a green working dot pulses (its ring is green), so only while answering.
pulse: pill.tone === 'working',
primary: primaryAction(employee),
busyLabel: pending ? BUSY[pending.action]
@@ -180,6 +208,30 @@ export function stateNoticeText(mode: TalkMode, name: string): string | null {
}
}
+// ----- a new hire's first day -----
+
+/** Where a new hire's start is (employee/FirstDay): `ready` once they run,
+ * `starting` while the start is under way (the hire started them, and it
+ * has neither been held for something to connect nor failed), `stopped`
+ * when it did not go ahead. */
+export type FirstDayPhase = 'starting' | 'ready' | 'stopped';
+
+export function firstDayPhase(employee: EmployeeSummary, started: boolean): FirstDayPhase {
+ const { state } = employee.control;
+ if (state === 'running') return 'ready';
+ if (state === 'starting' || state === 'resuming') return 'starting';
+ const held = employee.activation_state === 'blocked' || employee.activation_state === 'failed';
+ return started && !held && (state === 'never_started' || state === 'ready') ? 'starting' : 'stopped';
+}
+
+/** Why a new hire is not running, beside their main action. */
+export function firstDayNote(employee: EmployeeSummary): string | null {
+ if (employee.missing_apps.length > 0) return `${employee.missing_apps[0].name} isn’t connected yet.`;
+ if (employee.needs_ai) return 'Connect an AI model first.';
+ if (employee.activation_state === 'failed' || employee.control.state === 'failed') return `${employee.name} couldn’t start.`;
+ return stateNoticeText(talkMode(employee.control), employee.name);
+}
+
/** Said before anything that restarts an employee (Turn on Talk, Apply): a
* restart cancels the drafts waiting for the owner. */
export function restartDraftsWarning(name: string, drafts: number): string {
diff --git a/client/src/features/home/data/schemas.ts b/client/src/features/home/data/schemas.ts
index 76eec77c..2436c8d8 100644
--- a/client/src/features/home/data/schemas.ts
+++ b/client/src/features/home/data/schemas.ts
@@ -23,6 +23,10 @@ export const TASK_LABELS = ['Now', 'Next', 'Paused', 'Waiting'] as const;
* line that replies), `off` (one click adds it) or `unsupported`. */
export const TALK_STATES = ['on', 'off', 'unsupported'] as const;
+/** How a hire's own start went: `saved` until it is tried, then `blocked`
+ * (something to connect first), `running` or `failed`. */
+export const ACTIVATION_STATES = ['saved', 'blocked', 'starting', 'running', 'failed'] as const;
+
export const appRefSchema = z.object({
app_id: z.string(),
provider_id: z.string(),
@@ -72,6 +76,8 @@ export const employeeSummarySchema = z.object({
.catch(null),
revision: z.number().catch(0),
hired_at: z.string().nullable().catch(null),
+ /** Null for a workflow built in the editor. */
+ activation_state: z.enum(ACTIVATION_STATES).nullable().catch(null),
/** The talk line; `agent_node_id` is the agent that answers the owner. */
talk: z
.object({ state: z.enum(TALK_STATES).catch('unsupported'), agent_node_id: z.string().nullable().catch(null) })
diff --git a/client/src/features/home/employee/EmployeeChat.tsx b/client/src/features/home/employee/EmployeeChat.tsx
index d4eb6d34..fb67f6c3 100644
--- a/client/src/features/home/employee/EmployeeChat.tsx
+++ b/client/src/features/home/employee/EmployeeChat.tsx
@@ -15,6 +15,10 @@
* why a run of failures paused them.
* - Without a talk line, Turn on Talk offers to add one; an employee whose
* setup cannot answer gets a note instead of the box.
+ * - A new hire's page opens on their first day (FirstDay) until their first
+ * conversation begins: the box waits while they start, then offers
+ * something to say, and the card says why when the start did not go ahead
+ * (so the line above the box does not say it twice).
* - A document they wrote opens from its card in the reply on the
* Workspace's Canvas tab, at that version.
* - Cmd/Ctrl+K puts the cursor in the message box.
@@ -25,9 +29,9 @@ import { useEffect, useRef } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { ActionButton } from '@/components/ui/action-button';
import { Alert, AlertDescription } from '@/components/ui/alert';
-import { ChatPane, useLaneRun, type ChatPaneHandle, type ComposerMode } from '@/features/chat';
+import { ChatPane, useChatThread, useLaneRun, type ChatPaneHandle, type ComposerMode } from '@/features/chat';
import { invalidateEmployees } from '../data/employees';
-import { stateNoticeText, talkMode, talkNoticeText } from '../data/presentation';
+import { firstDayPhase, stateNoticeText, talkMode, talkNoticeText } from '../data/presentation';
import type { EmployeeSummary } from '../data/schemas';
import { useRetryNote } from '../data/talk';
import { HireNotice } from '../hire/HireNotice';
@@ -40,8 +44,12 @@ import { TurnOnTalk } from './TurnOnTalk';
import { EmployeeAccess } from './EmployeeAccess';
import { GiveTeam } from './GiveTeam';
import { EmployeeWork } from './EmployeeWork';
+import { FirstDay } from './FirstDay';
import type { EmployeeControl } from './useEmployeeControl';
+/** What to say first, on a new hire's first day. */
+const GREETINGS = ['Hi! What can you do?', 'Walk me through your routine'] as const;
+
/** The agent is waiting for the owner in the browser (it called `request_user`). */
function BrowserNotice({ employee }: { employee: EmployeeSummary }) {
const openWorkspace = useHomeStore((s) => s.openWorkspace);
@@ -70,12 +78,23 @@ function failurePauseText(employee: EmployeeSummary): string | null {
return employee.control.pause_detail || (employee.task?.label === 'Paused' ? employee.task.text : null) || null;
}
-function Notices({ employee, control, queued }: { employee: EmployeeSummary; control: EmployeeControl; queued: boolean }) {
+function Notices({
+ employee,
+ control,
+ queued,
+ firstDay,
+}: {
+ employee: EmployeeSummary;
+ control: EmployeeControl;
+ queued: boolean;
+ /** Their first day's card says their state and offers their main action. */
+ firstDay: boolean;
+}) {
const { name } = employee;
const mode = talkMode(employee.control);
const failure = mode === 'queue' ? failurePauseText(employee) : null;
// Their main action shows whether or not they can take messages here.
- const notice = employee.talk.state === 'on' ? talkNoticeText(mode, name, queued) : stateNoticeText(mode, name);
+ const notice = firstDay ? null : employee.talk.state === 'on' ? talkNoticeText(mode, name, queued) : stateNoticeText(mode, name);
return (
<>
{failure && (
@@ -118,7 +137,19 @@ export function EmployeeChat({
const lane = useLaneRun(workflowId);
const liveNote = useRetryNote(workflowId, employee.talk.agent_node_id, lane !== null && lane.state !== 'queued');
const mode = talkMode(employee.control);
- const composer: ComposerMode = employee.talk.state !== 'on' || mode === 'start' ? 'closed' : mode;
+
+ // Their first day lasts until their first conversation begins: a Reset
+ // that empties the thread later does not bring it back.
+ const firstDay = useHomeStore((s) => s.firstDays[workflowId]);
+ const endFirstDay = useHomeStore((s) => s.endFirstDay);
+ const spoken = (useChatThread(workflowId, 'all').data?.messages.length ?? 0) > 0;
+ useEffect(() => {
+ if (firstDay && spoken) endFirstDay(workflowId);
+ }, [endFirstDay, firstDay, spoken, workflowId]);
+ const phase = firstDay ? firstDayPhase(employee, firstDay.started) : null;
+
+ const composer: ComposerMode =
+ employee.talk.state !== 'on' ? 'closed' : phase === 'starting' ? 'wait' : mode === 'start' ? 'closed' : mode;
// Cmd/Ctrl+K puts the cursor in the message box (on Home only: in the
// editor it opens the command palette, which has Focus Chat).
@@ -155,13 +186,16 @@ export function EmployeeChat({
scope: 'all',
persona: { name, colorRole: employee.color_role, photo: employee.photo_url },
composer,
- notices: <Notices employee={employee} control={control} queued={lane?.state === 'queued'} />,
+ placeholder: composer === 'wait' ? `${name} is starting…` : undefined,
+ notices: <Notices employee={employee} control={control} queued={lane?.state === 'queued'} firstDay={Boolean(firstDay)} />,
top: (
<div className="flex flex-col items-center gap-4">
<OrbSlot size="employee" />
<HireNotice workflowId={workflowId} />
</div>
),
+ emptyState: firstDay && phase ? <FirstDay employee={employee} firstDay={firstDay} phase={phase} control={control} /> : undefined,
+ greetings: firstDay ? GREETINGS : undefined,
footnote: employee.asks_first
? `${name} asks before sending anything on your behalf.`
: `${name} doesn’t ask before sending anything on your behalf.`,
diff --git a/client/src/features/home/employee/FirstDay.tsx b/client/src/features/home/employee/FirstDay.tsx
new file mode 100644
index 00000000..08cc16d8
--- /dev/null
+++ b/client/src/features/home/employee/FirstDay.tsx
@@ -0,0 +1,211 @@
+/**
+ * A new hire's first day (onboarding handoff C): what their page shows in
+ * place of the empty conversation, from the hire until the owner's first
+ * message, for a hire made in this session (homeStore.firstDays).
+ *
+ * - Arrival: their avatar, with a ring turning while they start, then the
+ * hire glow and a ready pip; "{Name} joined your team".
+ * - Getting them ready: four rows driven by what really happened, never by
+ * timers. The hire saved their setup and built their workflow, so those
+ * two are done; their start follows the control state, and their
+ * conversation is ready once they run with Talk on. A start that did not
+ * go ahead says why, with their main action (connect what is missing, or
+ * Start).
+ * - What they do: their routine, from the hire's plan.
+ *
+ * The chat around it keeps the box waiting while they start and says hello
+ * once they can read messages (EmployeeChat).
+ */
+
+import { Check, Plug } from 'lucide-react';
+import { useLayoutEffect, useRef } from 'react';
+import { RingSpinner } from '@/components/ui/ring-spinner';
+import { RISE, animate, rise, stagger } from '@/lib/motion';
+import { cn } from '@/lib/utils';
+import { useEmployeeDetailQuery } from '../data/employees';
+import { firstDayNote, type FirstDayPhase } from '../data/presentation';
+import type { EmployeeSummary } from '../data/schemas';
+import type { FirstDay as FirstDayEntry } from '../state/homeStore';
+import { Avatar, MicroLabel, StatusPill } from '../ui/primitives';
+import { RoutineRow, RoutineTimeline } from '../ui/routine';
+import { PrimaryActionButton } from './PrimaryActionButton';
+import type { EmployeeControl } from './useEmployeeControl';
+
+type RowState = 'pending' | 'active' | 'done';
+
+const POP: Keyframe[] = [
+ { transform: 'scale(0.4)', opacity: 0 },
+ { transform: 'none', opacity: 1 },
+];
+
+/** A row's done mark, popping in when it arrives. */
+function DoneMark() {
+ const ref = useRef<HTMLSpanElement>(null);
+ useLayoutEffect(() => {
+ animate(ref.current, POP, { duration: 'chip-pop', easing: 'overshoot' });
+ }, []);
+ return (
+ <span
+ ref={ref}
+ className="grid size-5.5 place-items-center rounded-full border border-action-run-border bg-action-run-soft text-action-run-ink"
+ >
+ <Check aria-hidden className="size-3" strokeWidth={2.5} />
+ </span>
+ );
+}
+
+function ReadyRow({ state, label, done }: { state: RowState; label: string; done: string }) {
+ return (
+ <li className={cn('grid grid-cols-[22px_minmax(0,1fr)] items-center gap-2.5 py-1.75', state === 'pending' && 'opacity-50')}>
+ <span className="grid size-5.5 place-items-center">
+ {state === 'done' ? (
+ <DoneMark />
+ ) : state === 'active' ? (
+ <RingSpinner className="size-3 border-status-ready-border border-t-status-ready-dot" />
+ ) : (
+ <span aria-hidden className="size-1.25 rounded-full bg-fg-faint" />
+ )}
+ </span>
+ <span className={cn('truncate text-row', state === 'done' ? 'text-fg-default' : 'text-fg-muted')}>
+ {state === 'done' ? done : label}
+ </span>
+ </li>
+ );
+}
+
+/** The ready pip on their avatar, popping in once they run. */
+function ReadyPip() {
+ const ref = useRef<HTMLSpanElement>(null);
+ useLayoutEffect(() => {
+ animate(ref.current, [{ transform: 'scale(0)' }, { transform: 'none' }], { duration: 'chip-pop', easing: 'overshoot' });
+ }, []);
+ return (
+ <span
+ ref={ref}
+ aria-hidden
+ className="absolute right-0 bottom-0 box-content size-3.25 rounded-full border-3 border-bg-app bg-status-ready-dot"
+ />
+ );
+}
+
+function TheirRoutine({ workflowId, name }: { workflowId: string; name: string }) {
+ const plan = useEmployeeDetailQuery(workflowId).data?.plan ?? [];
+ const rowsRef = useRef<HTMLDivElement>(null);
+ const count = plan.length;
+ useLayoutEffect(() => {
+ const rows = rowsRef.current?.querySelectorAll('[data-routine-row]');
+ if (count > 0 && rows) stagger(rows, RISE, { base: 300, step: 140, duration: 'follow-in', easing: 'spring' });
+ }, [count]);
+ if (count === 0) return null;
+ return (
+ <section className="flex w-full flex-col gap-2 rounded-card border border-border-default bg-bg-panel px-4 py-3.5">
+ <div className="flex items-baseline gap-2">
+ <h3 className="m-0 flex-1 text-row font-semibold text-fg-default">What {name} does</h3>
+ <span className="font-mono text-2xs text-fg-faint">
+ {count} {count === 1 ? 'step' : 'steps'}
+ </span>
+ </div>
+ <RoutineTimeline ref={rowsRef}>
+ {plan.map((step, index) => (
+ <RoutineRow key={index} role={step.role} title={step.title} detail={step.detail} size="sm" />
+ ))}
+ </RoutineTimeline>
+ </section>
+ );
+}
+
+export function FirstDay({
+ employee,
+ firstDay,
+ phase,
+ control,
+}: {
+ employee: EmployeeSummary;
+ firstDay: FirstDayEntry;
+ phase: FirstDayPhase;
+ control: EmployeeControl;
+}) {
+ const { name } = employee;
+ const rootRef = useRef<HTMLDivElement>(null);
+ const avatarRef = useRef<HTMLSpanElement>(null);
+
+ useLayoutEffect(() => {
+ rise(rootRef.current);
+ }, []);
+ // They are ready: the hire glow, once.
+ useLayoutEffect(() => {
+ if (phase !== 'ready') return;
+ animate(
+ avatarRef.current,
+ [
+ { transform: 'scale(1.06)', boxShadow: 'var(--glow-hire)' },
+ { transform: 'none', boxShadow: '0 0 0 0 transparent' },
+ ],
+ { duration: 'glow', easing: 'spring' },
+ );
+ }, [phase]);
+
+ const start: RowState = phase === 'ready' ? 'done' : phase === 'starting' ? 'active' : 'pending';
+ const talk: RowState = phase === 'ready' && employee.talk.state === 'on' ? 'done' : 'pending';
+ const note = phase === 'stopped' ? firstDayNote(employee) : null;
+
+ return (
+ <div ref={rootRef} className="mx-auto flex w-full max-w-135 flex-col items-center gap-5.5">
+ <div className="flex flex-col items-center gap-3">
+ <div className="relative">
+ <span ref={avatarRef} className="block rounded-full">
+ <Avatar name={name} colorRole={employee.color_role} photo={employee.photo_url} size="xl" />
+ </span>
+ {phase === 'starting' && (
+ <RingSpinner slow className="absolute -inset-1.5 border-status-ready-border border-t-status-ready-dot" />
+ )}
+ {phase === 'ready' && <ReadyPip />}
+ </div>
+ <div className="flex flex-col items-center gap-1.5 text-center">
+ <MicroLabel className="text-node-agent-ink">New hire</MicroLabel>
+ <h2 className="m-0 text-headline leading-hero font-semibold tracking-hero text-balance text-fg-default">
+ {name} joined your team
+ </h2>
+ </div>
+ </div>
+
+ <section className="w-full overflow-hidden rounded-card border border-border-default bg-bg-elevated shadow-float">
+ <div className="flex flex-col gap-1 px-4 pt-3.5 pb-2.5">
+ <div className="flex items-center gap-2.5">
+ <h3 aria-live="polite" className="m-0 flex-1 truncate text-row font-semibold text-fg-default">
+ {phase === 'ready' ? `${name} is ready` : `Getting ${name} ready`}
+ </h3>
+ {phase === 'ready' ? (
+ <StatusPill tone="ready" label="Ready" size="compact" />
+ ) : phase === 'starting' ? (
+ <StatusPill tone="ready" label="Starting…" size="compact" />
+ ) : (
+ <StatusPill tone="paused" label="Not started" size="compact" />
+ )}
+ </div>
+ <ul className="m-0 list-none p-0">
+ <ReadyRow state="done" label="Saving their setup" done="Setup saved" />
+ <ReadyRow
+ state="done"
+ label="Building their workflow"
+ done={firstDay.nodeCount === null ? 'Workflow built' : `Workflow built · ${firstDay.nodeCount} blocks`}
+ />
+ <ReadyRow state={start} label={`Starting ${name}`} done={`${name} is running`} />
+ <ReadyRow state={talk} label="Opening their conversation" done="Ready to talk" />
+ </ul>
+ </div>
+ {note && (
+ <div className="flex flex-wrap items-center gap-3 border-t border-border-default bg-bg-panel px-4 py-3">
+ <Plug aria-hidden className="size-3.75 shrink-0 text-node-trigger-ink" />
+ <p className="m-0 min-w-40 flex-1 text-sm text-fg-muted">{note}</p>
+ <PrimaryActionButton control={control} className="h-7.5 px-3.5" />
+ </div>
+ )}
+ </section>
+
+ <TheirRoutine workflowId={employee.workflow_id} name={name} />
+ </div>
+ );
+}
+
+export default FirstDay;
diff --git a/client/src/features/home/employee/__tests__/FirstDay.test.tsx b/client/src/features/home/employee/__tests__/FirstDay.test.tsx
new file mode 100644
index 00000000..72e0de7c
--- /dev/null
+++ b/client/src/features/home/employee/__tests__/FirstDay.test.tsx
@@ -0,0 +1,165 @@
+/**
+ * A new hire's first day on their page (EmployeeChat with FirstDay): the
+ * card follows their real start (starting, ready, held for an app, failed),
+ * the box waits while they start and the greetings come once they can read
+ * messages, the card says why a start did not go ahead without the line
+ * above the box saying it again, their routine shows from the hire's plan,
+ * and the first day ends with their first conversation.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+
+const sendRequest = vi.fn();
+
+vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),
+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),
+}));
+
+vi.mock('../../../../app/useShellActions', () => ({ enterDev: vi.fn() }));
+vi.mock('../../ui/pillToast', () => ({ pillToast: vi.fn() }));
+
+import { normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';
+import { useComposerStore } from '@/features/chat/state/composerStore';
+import { resetChatRunStore } from '@/stores/chatRunStore';
+import { useNodeStatusStore } from '@/stores/nodeStatusStore';
+import { EMPLOYEES_QUERY_KEY } from '../../data/employees';
+import { presentEmployee, primaryActionLabel } from '../../data/presentation';
+import { parseEmployee, type EmployeeSummary } from '../../data/schemas';
+import { useHomeStore } from '../../state/homeStore';
+import { EmployeeChat } from '../EmployeeChat';
+import type { EmployeeControl } from '../useEmployeeControl';
+// Loaded up front so the turns' lazy markdown resolves from the module cache.
+import '@/features/chat/markdown/ReplyMarkdown';
+
+type Wire = Record<string, unknown>;
+
+const PLAN = [
+ { title: 'When a message arrives', detail: 'On WhatsApp', role: 'trigger', app: 'WhatsApp' },
+ { title: 'Answer the question', role: 'agent' },
+ { title: 'Book the visit', detail: 'In your calendar', role: 'tool' },
+];
+
+const whatsapp = { app_id: 'whatsapp', provider_id: 'whatsapp', name: 'WhatsApp', connected: false, supported: true };
+
+function employee(state: string, patch: Wire = {}): EmployeeSummary {
+ return parseEmployee({
+ workflow_id: 'w1',
+ name: 'Maya',
+ role: 'Receptionist',
+ status: state === 'running' || state === 'starting' ? 'working' : 'ready',
+ talk: { state: 'on', agent_node_id: 'w1:talk' },
+ control: normalizeWorkflowControlStatus({ generation: 1, revision: 4, state }, 'w1'),
+ activation_state: 'saved',
+ ...patch,
+ })!;
+}
+
+function controlFor(summary: EmployeeSummary): EmployeeControl {
+ const view = presentEmployee(summary);
+ return { view, label: primaryActionLabel(view.primary), busy: false, act: vi.fn() };
+}
+
+let server: { messages: Wire[] };
+
+function renderPage(summary: EmployeeSummary) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ client.setQueryData(EMPLOYEES_QUERY_KEY, [summary]);
+ const view = (next: EmployeeSummary) => (
+ <QueryClientProvider client={client}>
+ <EmployeeChat employee={next} control={controlFor(next)} />
+ </QueryClientProvider>
+ );
+ const utils = render(view(summary));
+ return { rerender: (next: EmployeeSummary) => utils.rerender(view(next)) };
+}
+
+beforeEach(() => {
+ resetChatRunStore();
+ useComposerStore.setState({ drafts: {} });
+ useNodeStatusStore.setState({ allStatuses: {} });
+ useHomeStore.setState({ firstDays: { w1: { started: true, nodeCount: 9 } }, hireNotice: null });
+ server = { messages: [] };
+ sendRequest.mockReset().mockImplementation(async (type: string) => {
+ if (type === 'chat_subscribe') return { success: true, hub_epoch: 'e1', active_runs: [] };
+ if (type === 'get_chat_messages') return { success: true, messages: server.messages };
+ if (type === 'get_employee') return { success: true, employee: { ...employee('starting'), plan: PLAN } };
+ return { success: true };
+ });
+});
+
+describe('a new hire’s first day', () => {
+ it('shows them starting, with the box waiting and no greetings yet', async () => {
+ renderPage(employee('starting'));
+ expect(await screen.findByText('Maya joined your team')).toBeInTheDocument();
+ expect(screen.getByText('Getting Maya ready')).toBeInTheDocument();
+ expect(screen.getByText('Starting…')).toBeInTheDocument();
+ expect(screen.getByText('Setup saved')).toBeInTheDocument();
+ expect(screen.getByText('Workflow built · 9 blocks')).toBeInTheDocument();
+ expect(screen.getByText('Starting Maya')).toBeInTheDocument();
+ expect(screen.getByText('Opening their conversation')).toBeInTheDocument();
+ expect(screen.getByPlaceholderText('Maya is starting…')).toBeDisabled();
+ expect(screen.queryByRole('button', { name: 'Hi! What can you do?' })).not.toBeInTheDocument();
+ });
+
+ it('counts a hire that started them as starting before Start made a control row', async () => {
+ renderPage(employee('never_started'));
+ expect(await screen.findByText('Starting Maya')).toBeInTheDocument();
+ expect(screen.getByPlaceholderText('Maya is starting…')).toBeDisabled();
+ });
+
+ it('says they are ready once they run, then offers something to say', async () => {
+ const page = renderPage(employee('starting'));
+ await screen.findByText('Getting Maya ready');
+ page.rerender(employee('running'));
+ expect(await screen.findByText('Maya is ready')).toBeInTheDocument();
+ expect(screen.getByText('Maya is running')).toBeInTheDocument();
+ expect(screen.getByText('Ready to talk')).toBeInTheDocument();
+ fireEvent.click(await screen.findByRole('button', { name: 'Hi! What can you do?' }));
+ expect(screen.getByRole('textbox', { name: 'Message Maya' })).toHaveValue('Hi! What can you do?');
+ });
+
+ it('says what to connect when the hire could not start them, and only once', async () => {
+ useHomeStore.setState({ firstDays: { w1: { started: false, nodeCount: 9 } } });
+ renderPage(employee('never_started', { status: 'ready', missing_apps: [whatsapp], activation_state: 'blocked' }));
+ expect(await screen.findByText('WhatsApp isn’t connected yet.')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Connect WhatsApp' })).toBeInTheDocument();
+ expect(screen.getByText('Not started')).toBeInTheDocument();
+ // The card says it, so the line above the box does not.
+ expect(screen.queryByText('Maya isn’t running.')).not.toBeInTheDocument();
+ expect(screen.queryByText(/isn’t running, so they can’t read messages/)).not.toBeInTheDocument();
+ });
+
+ it('says a start that failed did not go ahead, never spinning', async () => {
+ renderPage(employee('never_started', { activation_state: 'failed' }));
+ expect(await screen.findByText('Maya couldn’t start.')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Start' })).toBeInTheDocument();
+ expect(screen.getByText('Starting Maya')).toBeInTheDocument();
+ expect(screen.queryByPlaceholderText('Maya is starting…')).not.toBeInTheDocument();
+ });
+
+ it('shows what they do, from the hire’s plan', async () => {
+ renderPage(employee('starting'));
+ expect(await screen.findByText('What Maya does')).toBeInTheDocument();
+ expect(screen.getByText('3 steps')).toBeInTheDocument();
+ expect(screen.getByText('Answer the question')).toBeInTheDocument();
+ expect(screen.getByText('When')).toBeInTheDocument();
+ });
+
+ it('ends with their first conversation', async () => {
+ server.messages = [{ id: 1, role: 'user', message: 'Morning!', timestamp: new Date(2026, 9, 9, 9).toISOString(), run_key: 'g1' }];
+ renderPage(employee('running'));
+ expect(await screen.findByText('Morning!')).toBeInTheDocument();
+ await waitFor(() => expect(useHomeStore.getState().firstDays.w1).toBeUndefined());
+ expect(screen.queryByText('Maya joined your team')).not.toBeInTheDocument();
+ });
+
+ it('is not shown for an employee hired before this session', async () => {
+ useHomeStore.setState({ firstDays: {} });
+ renderPage(employee('running'));
+ expect(await screen.findByRole('textbox', { name: 'Message Maya' })).toBeEnabled();
+ expect(screen.queryByText('Maya joined your team')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/features/home/genui/HireDraftPanel.tsx b/client/src/features/home/genui/HireDraftPanel.tsx
index 95de010f..6341e368 100644
--- a/client/src/features/home/genui/HireDraftPanel.tsx
+++ b/client/src/features/home/genui/HireDraftPanel.tsx
@@ -2,7 +2,11 @@
* The new employee's setup screen under the composer (design handoff
* "Draft"): while the model writes it, a line saying so with the time it
* has taken so far and Cancel; the screen itself when it arrives; or what
- * went wrong with a way to try again.
+ * went wrong with a way to try again. The header (what they were asked to
+ * do, and Discard) shows while the setup is written or has failed; a ready
+ * card says who they are in its identity row instead, with Discard beside
+ * it (onboarding handoff R2). Their team, when the server suggests one,
+ * sits in the card above its footer strip.
*
* The screen is drawn by json-render (HireScreen, loaded lazily the first
* time one shows: json-render is not part of Home's first chunk). Its
@@ -17,6 +21,7 @@ import { X } from 'lucide-react';
import { Suspense, lazy, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { ActionButton } from '@/components/ui/action-button';
import { Button } from '@/components/ui/button';
+import { RingSpinner } from '@/components/ui/ring-spinner';
import { animate, finished } from '@/lib/motion';
import { isConnected, useConnectors } from '../data/connectors';
import { useHomeStore } from '../state/homeStore';
@@ -65,10 +70,7 @@ function WorkingLine({ token, onCancel }: { token: string | null; onCancel: () =
return (
<div className="flex flex-col gap-1.5 px-0.5 py-1">
<div className="flex items-center gap-2.5">
- <span
- aria-hidden
- className="mx-0.5 size-3.5 shrink-0 animate-[spin_700ms_linear_infinite] rounded-full border-2 border-node-agent-border border-t-node-agent motion-reduce:animate-none"
- />
+ <RingSpinner className="mx-0.5 size-3.5 border-node-agent-border border-t-node-agent" />
<span role="status" className="text-base text-fg-default">
Writing their setup…
</span>
@@ -137,7 +139,6 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)
const token = useDraftStore((s) => s.token);
const failure = useDraftStore((s) => s.failure);
const spec = useDraftStore((s) => s.spec);
- const intro = useDraftStore((s) => s.intro);
const apps = useDraftStore((s) => s.apps);
const team = useDraftStore((s) => s.team);
const version = useDraftStore((s) => s.version);
@@ -147,10 +148,10 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)
const openConnectAI = useHomeStore((s) => s.openConnectAI);
const { providers } = useConnectors();
const sectionRef = useRef<HTMLElement>(null);
- const introRef = useRef<HTMLParagraphElement>(null);
const visible = status !== 'idle';
const showSpec = Boolean(spec) && (status === 'ready' || (status === 'failed' && failure?.refine));
+ const showHeader = status !== 'ready' || !spec?.layout.identity;
const triggerApps = useMemo(() => triggerAppNames(apps), [apps]);
// Fetch the screen's code while the model writes, so it is there when the reply lands.
@@ -174,14 +175,6 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)
wasVisible.current = visible;
}, [visible]);
- // The introduction fades up when a new version arrives.
- useLayoutEffect(() => {
- if (status !== 'ready') return;
- animate(introRef.current, [{ opacity: 0, transform: 'translateY(6px)' }, { opacity: 1, transform: 'none' }], {
- duration: 420,
- });
- }, [status, version]);
-
const collapse = useCallback(async () => {
const section = sectionRef.current;
if (!section) return;
@@ -234,6 +227,18 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)
await collapse();
actions.discard();
};
+ const discardButton = (
+ <Button
+ variant="quiet"
+ size="icon-sm"
+ onClick={() => void discard()}
+ title="Discard draft"
+ aria-label="Discard draft"
+ className="rounded-lg"
+ >
+ <X className="size-3.5" />
+ </Button>
+ );
if (!visible) return null;
return (
@@ -244,20 +249,13 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)
className="mt-5.5 w-full max-w-(--w-composer) overflow-hidden"
>
<div className="flex flex-col gap-3.5 rounded-draft border border-border-default bg-bg-panel p-4.5 shadow-float">
- <div className="flex items-center gap-2.5">
- <MicroLabel className="shrink-0 text-node-agent-ink">New employee</MicroLabel>
- <span className="min-w-0 flex-1 truncate text-sm text-fg-muted">{job}</span>
- <Button
- variant="quiet"
- size="icon-sm"
- onClick={() => void discard()}
- title="Discard draft"
- aria-label="Discard draft"
- className="rounded-lg"
- >
- <X className="size-3.5" />
- </Button>
- </div>
+ {showHeader && (
+ <div className="flex items-center gap-2.5">
+ <MicroLabel className="shrink-0 text-node-agent-ink">New employee</MicroLabel>
+ <span className="min-w-0 flex-1 truncate text-sm text-fg-muted">{job}</span>
+ {discardButton}
+ </div>
+ )}
{status === 'working' && <WorkingLine token={token} onCancel={actions.cancel} />}
{hiring && (
@@ -268,11 +266,6 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)
{status === 'failed' && failure && (
<FailureNotice failure={failure} onRetry={() => void actions.retry()} onConnectAi={openConnectAI} />
)}
- {status === 'ready' && intro && (
- <p ref={introRef} className="m-0 text-lead leading-relaxed text-pretty text-fg-default">
- {intro}
- </p>
- )}
{showSpec && spec && (
<Suspense fallback={null}>
<HireScreen
@@ -282,19 +275,21 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)
busy={hiring}
triggerApps={triggerApps}
actions={actionContext}
- />
+ discard={showHeader ? null : discardButton}
+ >
+ {team.length > 0 && (
+ <details className="rounded-row border border-border-default px-3.5 py-3 text-sm text-fg-muted">
+ <summary className="cursor-pointer font-semibold text-fg-default">Their team</summary>
+ <p className="mt-2 mb-2">They can ask these helpers to do parts of the job, then check the result for you.</p>
+ <ul className="m-0 list-disc space-y-1 pl-5">
+ {team.map(({ responsibility }) => <li key={responsibility}>{responsibility}</li>)}
+ </ul>
+ <p className="mt-2 mb-0">Use Change something to adjust their responsibilities.</p>
+ </details>
+ )}
+ </HireScreen>
</Suspense>
)}
- {showSpec && team.length > 0 && (
- <details className="rounded-card border border-border-default px-3.5 py-3 text-sm text-fg-muted">
- <summary className="cursor-pointer font-semibold text-fg-default">Their team</summary>
- <p className="mt-2 mb-2">They can ask these helpers to do parts of the job, then check the result for you.</p>
- <ul className="m-0 list-disc space-y-1 pl-5">
- {team.map(({ responsibility }) => <li key={responsibility}>{responsibility}</li>)}
- </ul>
- <p className="mt-2 mb-0">Use Change something to adjust their responsibilities.</p>
- </details>
- )}
</div>
</section>
);
diff --git a/client/src/features/home/genui/HireScreen.tsx b/client/src/features/home/genui/HireScreen.tsx
index 89fdd957..570ad3c5 100644
--- a/client/src/features/home/genui/HireScreen.tsx
+++ b/client/src/features/home/genui/HireScreen.tsx
@@ -4,6 +4,14 @@
* shows, so json-render stays out of Home's first chunk; it renders one per
* version of the draft (keyed by it), so a new version starts afresh.
*
+ * The card (onboarding handoff R2) is drawn in the places the normaliser
+ * names (`spec.layout`), each a Renderer over the same spec under one
+ * provider, so all of them share the screen's state and handlers: the
+ * identity row with Discard beside it, the body (the routine, then the
+ * rest), the panel's own `children` (their team), then the footer strip,
+ * which bleeds to the card's edges, with Ask first on the left and the
+ * buttons on the right, both in the strip's look (HireSpecContext.inFooter).
+ *
* The screen keeps its own state store (lib/jsonRender/uiState.ts), seeded
* from the draft (what the model wrote, plus anything the owner already
* changed on this version), and every change goes back to the draft
@@ -13,7 +21,7 @@
* Development builds also show the spec and its patch stream.
*/
-import { useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import type { Spec } from '@json-render/core';
import { JSONUIProvider, Renderer } from '@json-render/react';
import { LiveUiContext, SpecInspector, createUiStateStore, useSpecReveal } from '@/lib/jsonRender';
@@ -34,6 +42,10 @@ export interface HireScreenProps {
triggerApps: Readonly<Record<string, string>>;
/** What the buttons reach on Home; read at each press. */
actions: HireActionContext;
+ /** Drawn at the end of the identity row (the panel's Discard), or nothing. */
+ discard: ReactNode;
+ /** Drawn after the body, above the footer strip. */
+ children?: ReactNode;
}
/** Unknown types are dropped by the normaliser; anything else renders nothing. */
@@ -41,7 +53,7 @@ function NoElement() {
return null;
}
-export default function HireScreen({ spec, version, busy, triggerApps, actions }: HireScreenProps) {
+export default function HireScreen({ spec, version, busy, triggerApps, actions, discard, children }: HireScreenProps) {
const devMode = useAppStore((state) => state.shellMode === 'dev');
const uiSpec = useMemo<Spec>(() => ({ root: spec.root, state: spec.state, elements: spec.elements }), [spec]);
const { spec: shown, revealing } = useSpecReveal(uiSpec, version);
@@ -56,19 +68,36 @@ export default function HireScreen({ spec, version, busy, triggerApps, actions }
});
const [handlers] = useState(() => hireActionHandlers(() => latest.current));
const context = useMemo(() => ({ writtenState: spec.state, triggerApps }), [spec.state, triggerApps]);
+ const footer = useMemo(() => ({ ...context, inFooter: true }), [context]);
+ const { layout } = spec;
+
+ /** The spec drawn from one element, once the reveal has reached it. */
+ const part = (root: string) =>
+ shown && <Renderer key={root} spec={{ ...shown, root }} registry={hireRegistry} loading={revealing} fallback={NoElement} />;
return (
- <>
- <div className={cn('flex min-w-0 flex-col gap-3', busy && 'pointer-events-none opacity-60')}>
- <HireSpecContext.Provider value={context}>
- <LiveUiContext.Provider value>
- <JSONUIProvider registry={hireRegistry} store={store} handlers={handlers}>
- <Renderer spec={shown} registry={hireRegistry} loading={revealing} fallback={NoElement} />
- </JSONUIProvider>
- </LiveUiContext.Provider>
- </HireSpecContext.Provider>
- </div>
- {import.meta.env.DEV && devMode && <SpecInspector spec={uiSpec} />}
- </>
+ <div className={cn('flex min-w-0 flex-col gap-3.5', busy && 'pointer-events-none opacity-60')}>
+ <HireSpecContext.Provider value={context}>
+ <LiveUiContext.Provider value>
+ <JSONUIProvider registry={hireRegistry} store={store} handlers={handlers}>
+ {layout.identity && (
+ <div className="flex items-start gap-3">
+ <div className="min-w-0 flex-1">{part(layout.identity)}</div>
+ {discard}
+ </div>
+ )}
+ {layout.body.map((id) => part(id))}
+ {children}
+ {import.meta.env.DEV && devMode && <SpecInspector spec={uiSpec} />}
+ <HireSpecContext.Provider value={footer}>
+ <div className="-mx-4.5 -mb-4.5 flex flex-wrap items-center gap-x-4 gap-y-2.5 rounded-b-draft border-t border-border-default bg-bg-app px-4.5 py-3.5">
+ {part(layout.askFirst)}
+ <div className="ml-auto">{part(layout.actions)}</div>
+ </div>
+ </HireSpecContext.Provider>
+ </JSONUIProvider>
+ </LiveUiContext.Provider>
+ </HireSpecContext.Provider>
+ </div>
);
}
diff --git a/client/src/features/home/genui/__fixtures__/replies.json b/client/src/features/home/genui/__fixtures__/replies.json
index 9a7372a5..cbc6bd33 100644
--- a/client/src/features/home/genui/__fixtures__/replies.json
+++ b/client/src/features/home/genui/__fixtures__/replies.json
@@ -65,7 +65,7 @@
"hireButtons": 1,
"refineButtons": 1,
"askFirstToggles": 1,
- "togglesInRulesCard": 2
+ "togglesInRulesCard": 1
}
},
{
diff --git a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
index 124fd942..34dd7a99 100644
--- a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
+++ b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
@@ -1,6 +1,8 @@
/**
* The draft panel end to end: the screen renders through json-render (its
- * code loads lazily, so the first look waits for it), a double-clicked Hire
+ * code loads lazily, so the first look waits for it) as the setup card (who
+ * they are with Discard beside it, the routine with Change on its When row,
+ * the model's rules, then the footer strip), a double-clicked Hire
* sends one request, a finished hire clears the draft and opens the new
* employee's page (with what the hire said, and the AI connect dialog when
* there is no model), "Change something" hands the composer the draft,
@@ -60,7 +62,6 @@ function seedReadyDraft(text = reply) {
job: 'Answer WhatsApp',
turns: [{ change: null, reply: text }],
spec,
- intro: parsed.text,
uiState: spec.state,
version: 1,
});
@@ -81,6 +82,7 @@ function hired(patch: Record<string, unknown> = {}) {
return {
success: true,
started: true,
+ node_count: 14,
warnings: [],
needs_ai: false,
employee: { workflow_id: 'w1', name: 'Maya', role: 'Receptionist', status: 'working', control: {}, revision: 1 },
@@ -107,7 +109,7 @@ beforeEach(() => {
vi.mocked(pillToast).mockClear();
resetDraftForTests();
seedReadyDraft();
- useHomeStore.setState({ view: { kind: 'hire' }, hireNotice: null });
+ useHomeStore.setState({ view: { kind: 'hire' }, hireNotice: null, firstDays: {} });
useShellDialogsStore.setState({ credentialsOpen: false });
useAppStore.setState({ shellMode: 'normal' });
});
@@ -134,14 +136,50 @@ describe('HireDraftPanel', () => {
expect(screen.queryByRole('combobox', { name: /specialist/i })).not.toBeInTheDocument();
});
- it('shows the introduction and the setup screen', async () => {
+ it('shows the setup card: who they are, their routine, their rules, then the footer', async () => {
renderPanel();
- expect(screen.getByText('Meet Maya, your new receptionist.')).toBeInTheDocument();
- expect(await screen.findByText('Their routine')).toBeInTheDocument();
- expect(screen.getByText('When something new arrives in WhatsApp')).toBeInTheDocument();
- expect(screen.getByRole('switch', { name: 'Ask me before sending anything' })).toBeChecked();
+ expect(await screen.findByText('Maya')).toBeInTheDocument();
+ expect(screen.getByText('Receptionist · WhatsApp, Google Calendar')).toBeInTheDocument();
+ expect(screen.getByText('Answers WhatsApp and books visits.')).toBeInTheDocument();
+ // The card says who they are, so the header, the model's introduction
+ // and the routine's own title stay out of it.
+ expect(screen.queryByText('New employee')).not.toBeInTheDocument();
+ expect(screen.queryByText('Meet Maya, your new receptionist.')).not.toBeInTheDocument();
+ expect(screen.queryByText('Their routine')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Discard draft' })).toBeInTheDocument();
+ // The routine, its When row first, with Change.
+ expect(screen.getByText('When a message arrives')).toBeInTheDocument();
+ expect(screen.getByText('Book the visit')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Change' })).toHaveAttribute('aria-expanded', 'false');
+ // The model's own rules stay in view.
expect(screen.getByRole('switch', { name: 'Only reply 9 to 6' })).not.toBeChecked();
expect(screen.getByRole('radio', { name: 'Daily' })).toBeChecked();
+ // The footer: Ask first, then Change something before Hire.
+ expect(screen.getByRole('switch', { name: 'Ask before sending' })).toBeChecked();
+ const change = screen.getByRole('button', { name: 'Change something' });
+ const hire = screen.getByRole('button', { name: 'Hire Maya' });
+ expect(change.compareDocumentPosition(hire) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ });
+
+ it('keeps the header for a card with no one to introduce', async () => {
+ const setup = JSON.parse(reply);
+ delete setup.spec.elements.b;
+ setup.spec.elements.a.children = ['c', 'd', 'e'];
+ seedReadyDraft(JSON.stringify(setup));
+ renderPanel();
+ expect(await hireButton()).toBeInTheDocument();
+ expect(screen.getByText('New employee')).toBeInTheDocument();
+ expect(screen.getByText('Answer WhatsApp')).toBeInTheDocument();
+ expect(screen.getAllByRole('button', { name: 'Discard draft' })).toHaveLength(1);
+ });
+
+ it('discards the draft from beside their name', async () => {
+ renderPanel();
+ await hireButton();
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Discard draft' }));
+ });
+ await waitFor(() => expect(useDraftStore.getState().status).toBe('idle'));
});
it('sends one hire for a double click, then clears the draft and opens the employee', async () => {
@@ -169,6 +207,8 @@ describe('HireDraftPanel', () => {
expect(useHomeStore.getState().glow?.workflowId).toBe('w1');
expect(useHomeStore.getState().view).toEqual({ kind: 'employee', workflowId: 'w1' });
expect(useHomeStore.getState().hireNotice).toBeNull();
+ // Their page opens on their first day, which knows the hire started them.
+ expect(useHomeStore.getState().firstDays.w1).toEqual({ started: true, nodeCount: 14 });
expect(screen.queryByText('Hiring your employee…')).not.toBeInTheDocument();
});
@@ -203,6 +243,8 @@ describe('HireDraftPanel', () => {
await act(async () => { fireEvent.click(hire); });
await waitFor(() => expect(useHomeStore.getState().view).toEqual({ kind: 'employee', workflowId: 'arjun-workflow' }));
expect(useDraftStore.getState()).toMatchObject({ status: 'idle', hiring: false });
+ // A hire held for WhatsApp did not start them; the first day says why.
+ expect(useHomeStore.getState().firstDays['arjun-workflow']).toEqual({ started: false, nodeCount: 14 });
expect(sendRequest).toHaveBeenCalledWith('hire_employee', expect.objectContaining({
name: 'Arjun', trigger: { kind: 'schedule', every: 'day', at: '08:00' }, rules: expect.objectContaining({ ask_first: true }),
}), expect.any(Number));
@@ -268,11 +310,13 @@ describe('HireDraftPanel', () => {
it('hires on the schedule the owner picked, and the routine follows it', async () => {
sendRequest.mockResolvedValue(hired());
renderPanel();
- fireEvent.click(await screen.findByRole('button', { name: 'Edit' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Change' }));
+ expect(screen.getByRole('button', { name: 'Done' })).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(screen.getByRole('radio', { name: 'On a schedule' }));
fireEvent.click(screen.getByRole('radio', { name: 'Weekdays' }));
- // The sentence and the routine's first step both say it.
- expect(screen.getAllByText('Every weekday at 09:00')).toHaveLength(2);
+ // The routine's When row says it.
+ expect(screen.getByText('Every weekday at 09:00')).toBeInTheDocument();
+ expect(screen.queryByText('When a message arrives')).not.toBeInTheDocument();
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Hire Maya' }));
});
@@ -286,8 +330,8 @@ describe('HireDraftPanel', () => {
seedReadyDraft(replies.find((c) => c.name === 'json-render shape: on.press and checked')!.reply);
sendRequest.mockResolvedValue(hired());
renderPanel();
- expect(await screen.findByRole('switch', { name: 'Ask me before sending anything' })).toBeChecked();
- fireEvent.click(screen.getByRole('switch', { name: 'Ask me before sending anything' }));
+ expect(await screen.findByRole('switch', { name: 'Ask before sending' })).toBeChecked();
+ fireEvent.click(screen.getByRole('switch', { name: 'Ask before sending' }));
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Hire Maya' }));
});
diff --git a/client/src/features/home/genui/__tests__/draftStore.test.ts b/client/src/features/home/genui/__tests__/draftStore.test.ts
index 3adfb77e..8dc3f12b 100644
--- a/client/src/features/home/genui/__tests__/draftStore.test.ts
+++ b/client/src/features/home/genui/__tests__/draftStore.test.ts
@@ -65,7 +65,6 @@ describe('submitDraft', () => {
expect(timeout).toBe(SETUP_TIMEOUT_MS);
const state = useDraftStore.getState();
expect(state.status).toBe('ready');
- expect(state.intro).toBe('Meet Maya, your new receptionist.');
expect(state.spec).not.toBeNull();
expect(state.uiState).toMatchObject({ rules: { askFirst: true } });
expect(state.source).toEqual({ provider: 'openai', model: 'gpt-x' });
diff --git a/client/src/features/home/genui/__tests__/normalize.test.ts b/client/src/features/home/genui/__tests__/normalize.test.ts
index 9fddb171..f65ca50a 100644
--- a/client/src/features/home/genui/__tests__/normalize.test.ts
+++ b/client/src/features/home/genui/__tests__/normalize.test.ts
@@ -5,11 +5,16 @@
* props), a Toggle binds `checked` (older replies say `value`), and every
* expression whose path reaches a prototype is dropped.
*
- * When they work, as the normalizer sets it up: one Schedule after the
- * routine, bound to /trigger, which starts as the hire button's trigger
- * (else the app the routine's first "When" step names, else the owner
- * messaging them), snapped to a trigger the server builds as it reads,
- * and kept however long the screen is.
+ * The card it lays out (onboarding handoff R2): the agent card, the
+ * routine, everything else as written, then the footer strip's ask-first
+ * toggle and its row of the change button and the hire button, each named
+ * in `layout` and kept however long the screen is.
+ *
+ * When they work, as the normalizer sets it up: the Plan's When row bound
+ * to /trigger (no Schedule beside it), else one Schedule bound there.
+ * /trigger starts as the hire button's trigger (else the app the routine's
+ * first "When" step names, else the owner messaging them), snapped to a
+ * trigger the server builds as it reads.
*/
import { describe, expect, it } from 'vitest';
@@ -47,6 +52,10 @@ function schedules(spec: NormalizedSpec): string[] {
return spec.order.filter((id) => spec.elements[id].type === 'Schedule');
}
+function actionsOf(spec: NormalizedSpec): (string | undefined)[] {
+ return spec.elements[spec.layout.actions].children.map((id) => spec.elements[id].on?.press.action);
+}
+
describe('json-render shape', () => {
const hireParams = { name: 'Maya', trigger: { kind: 'manual' } };
@@ -60,7 +69,7 @@ describe('json-render shape', () => {
for (const button of shapes) {
const spec = only({ h: button });
expect(spec.elements.h.on).toEqual({ press: { action: 'hire_employee', params: hireParams } });
- expect(spec.elements.h.props).toEqual({ label: 'Hire Maya' });
+ expect(spec.elements.h.props).toEqual({ label: 'Hire Maya', variant: 'primary' });
}
});
@@ -136,14 +145,90 @@ describe('json-render shape', () => {
});
});
+describe('the card', () => {
+ it('lays out who they are, the routine, the rest as written, then the footer', () => {
+ const spec = screen({ kind: 'manual' }, { note: { type: 'Text', props: { text: 'Hello' } } });
+ const { layout } = spec;
+ expect(spec.elements.r.children).toEqual(['a', 'p', 'note', layout.askFirst, layout.actions]);
+ expect(layout).toMatchObject({ identity: 'a', body: ['p', 'note'] });
+ expect(bindingPath(spec.elements[layout.askFirst].props.checked)).toBe(STATE_PATHS.askFirst);
+ expect(spec.elements[layout.actions]).toMatchObject({ type: 'Stack', props: { direction: 'horizontal' } });
+ expect(actionsOf(spec)).toEqual(['refine', 'hire_employee']);
+ // The model's own button row is left empty, so it goes.
+ expect(spec.elements.row).toBeUndefined();
+ });
+
+ it('takes the agent card, the routine, the toggle and the buttons out of the containers they were in', () => {
+ const spec = only({
+ who: { type: 'Card', props: { title: 'Meet Maya' }, children: ['a', 'p'] },
+ a: { type: 'AgentCard', props: { name: 'Maya', role: 'Receptionist' } },
+ p: { type: 'Plan', props: { steps: [{ title: 'Answer', role: 'agent' }] } },
+ rules: { type: 'Card', props: { title: 'Ground rules' }, children: ['ask', 'hours', 'h'] },
+ ask: { type: 'Toggle', props: { label: 'Ask me first', checked: { $bindState: '/rules/askFirst' } } },
+ hours: { type: 'Toggle', props: { label: 'Only 9 to 6', checked: { $bindState: '/rules/hours' } } },
+ h: { type: 'Button', props: { label: 'Hire Maya' }, on: { press: { action: 'hire_employee' } } },
+ });
+ expect(spec.elements.r.children).toEqual(['a', 'p', 'rules', 'ask', spec.layout.actions]);
+ expect(spec.elements.rules.children).toEqual(['hours']);
+ // A card left with nothing in it goes.
+ expect(spec.elements.who).toBeUndefined();
+ expect(spec.layout.askFirst).toBe('ask');
+ });
+
+ it('keeps one agent card and one Plan, the first of each', () => {
+ const spec = only({
+ a: { type: 'AgentCard', props: { name: 'Maya', role: 'Receptionist' } },
+ a2: { type: 'AgentCard', props: { name: 'Ivy', role: 'Diary keeper' } },
+ p: { type: 'Plan', props: { steps: [{ title: 'Answer', role: 'agent' }] } },
+ p2: { type: 'Plan', props: { steps: [{ title: 'Book', role: 'tool' }] } },
+ });
+ expect(spec.elements.a2).toBeUndefined();
+ expect(spec.elements.p2).toBeUndefined();
+ expect(spec.layout).toMatchObject({ identity: 'a', body: ['p'] });
+ });
+
+ it('makes the hire button primary and the change button secondary, whatever the model said', () => {
+ const spec = only({
+ h: { type: 'Button', props: { label: 'Hire Maya', variant: 'secondary' }, on: { press: { action: 'hire_employee' } } },
+ c: { type: 'Button', props: { label: 'Change something', variant: 'primary' }, on: { press: { action: 'refine' } } },
+ });
+ expect(spec.elements.h.props.variant).toBe('primary');
+ expect(spec.elements.c.props.variant).toBe('secondary');
+ });
+
+ it('adds the toggle and both buttons when the model left them out', () => {
+ const spec = only({ a: { type: 'AgentCard', props: { name: 'Sam', role: 'Social media helper' } } });
+ expect(spec.elements[spec.layout.askFirst].props.label).toBe('Ask me before sending anything');
+ expect(getPath(spec.state, STATE_PATHS.askFirst)).toBe(true);
+ expect(actionsOf(spec)).toEqual(['refine', 'hire_employee']);
+ const [, hire] = spec.elements[spec.layout.actions].children;
+ expect(spec.elements[hire].props).toEqual({ label: 'Hire Sam', variant: 'primary' });
+ });
+
+ it('has no identity without an agent card, and the routine comes first', () => {
+ const spec = only({ note: { type: 'Text', props: { text: 'Hello' } } });
+ const [schedule] = schedules(spec);
+ expect(spec.layout).toMatchObject({ identity: null, body: [schedule, 'note'] });
+ });
+});
+
describe('when they work', () => {
- it('is one Schedule right after the routine, bound to /trigger', () => {
+ it('is the routine’s When row, bound to /trigger, with no Schedule beside it', () => {
const spec = screen({ kind: 'app_event', app: 'WhatsApp' });
+ expect(schedules(spec)).toHaveLength(0);
+ expect(bindingPath(spec.elements.p.props.trigger)).toBe(STATE_PATHS.trigger);
+ expect(getPath(spec.state, STATE_PATHS.trigger)).toEqual({ kind: 'app_event', app: 'WhatsApp' });
+ });
+
+ it('is one Schedule after the agent card when there is no routine', () => {
+ const spec = only({
+ a: { type: 'AgentCard', props: { name: 'Maya', role: 'Receptionist' } },
+ note: { type: 'Text', props: { text: 'Hello' } },
+ });
const [schedule] = schedules(spec);
expect(schedules(spec)).toHaveLength(1);
expect(bindingPath(spec.elements[schedule].props.value)).toBe(STATE_PATHS.trigger);
- expect(spec.elements.r.children.indexOf(schedule)).toBe(spec.elements.r.children.indexOf('p') + 1);
- expect(getPath(spec.state, STATE_PATHS.trigger)).toEqual({ kind: 'app_event', app: 'WhatsApp' });
+ expect(spec.elements.r.children.slice(0, 3)).toEqual(['a', schedule, 'note']);
});
it('starts as the hire button’s trigger, snapped to what can run', () => {
@@ -174,21 +259,27 @@ describe('when they work', () => {
expect(getPath(screen({ kind: 'manual' }, {}, steps).state, STATE_PATHS.trigger)).toEqual({ kind: 'manual' });
});
- it('keeps one Schedule the model wrote, rebound, and drops the rest', () => {
- const spec = screen(
- { kind: 'manual' },
- { s1: { type: 'Schedule', props: { value: 'whenever' } }, s2: { type: 'Schedule', props: {} } },
- );
+ it('keeps one Schedule the model wrote when there is no routine, rebound, and drops the rest', () => {
+ const spec = only({ s1: { type: 'Schedule', props: { value: 'whenever' } }, s2: { type: 'Schedule', props: {} } });
expect(schedules(spec)).toEqual(['s1']);
expect(bindingPath(spec.elements.s1.props.value)).toBe(STATE_PATHS.trigger);
});
- it('survives the size cap', () => {
+ it('drops every Schedule the model wrote beside a routine', () => {
+ const spec = screen({ kind: 'manual' }, { s1: { type: 'Schedule', props: { value: 'whenever' } } });
+ expect(schedules(spec)).toEqual([]);
+ expect(bindingPath(spec.elements.p.props.trigger)).toBe(STATE_PATHS.trigger);
+ });
+
+ it('survives the size cap, with the rest of the card', () => {
const texts = Object.fromEntries(
Array.from({ length: 30 }, (_, i) => [`t${i}`, { type: 'Text', props: { text: `Line ${i}` } }]),
);
const spec = screen({ kind: 'manual' }, texts);
expect(spec.order.length).toBeLessThanOrEqual(16);
- expect(schedules(spec)).toHaveLength(1);
+ expect(spec.elements.p).toBeDefined();
+ expect(spec.layout.identity).toBe('a');
+ expect(spec.elements[spec.layout.askFirst]).toBeDefined();
+ expect(actionsOf(spec)).toEqual(['refine', 'hire_employee']);
});
});
diff --git a/client/src/features/home/genui/__tests__/replies.test.ts b/client/src/features/home/genui/__tests__/replies.test.ts
index 537c6e06..cff28bc4 100644
--- a/client/src/features/home/genui/__tests__/replies.test.ts
+++ b/client/src/features/home/genui/__tests__/replies.test.ts
@@ -2,7 +2,9 @@
* The shared corpus of model replies (genui/__fixtures__/replies.json):
* each one parses and normalizes to a renderable screen exactly when it is
* marked salvageable, and every such screen is in json-render's shape, can
- * be hired and changed, asks first by default and says when they work.
+ * be hired and changed, asks first by default, says when they work and is
+ * laid out as the setup card (who they are, the routine, the rest, then the
+ * footer strip).
* Replies come in both shapes a model writes: the older one (a Toggle's
* `value`, a Button's `action` / `actionParams` props) and json-render's
* (`checked`, `on.press`). The server's salvage check runs the same corpus
@@ -93,13 +95,32 @@ describe('model reply corpus', () => {
);
expect(askFirst).toHaveLength(1);
expect(typeof getPath(spec.state, STATE_PATHS.askFirst)).toBe('boolean');
- // And says when they work.
+ // And says when they work: the routine's When row, else one Schedule.
+ const plan = elements(spec).find(([, element]) => element.type === 'Plan');
const schedule = elements(spec).filter(([, element]) => element.type === 'Schedule');
- expect(schedule).toHaveLength(1);
- expect(bindingPath(schedule[0][1].props.value)).toBe(STATE_PATHS.trigger);
+ if (plan) {
+ expect(schedule).toHaveLength(0);
+ expect(bindingPath(plan[1].props.trigger)).toBe(STATE_PATHS.trigger);
+ } else {
+ expect(schedule).toHaveLength(1);
+ expect(bindingPath(schedule[0][1].props.value)).toBe(STATE_PATHS.trigger);
+ }
expect(getPath(spec.state, STATE_PATHS.trigger)).toMatchObject({ kind: expect.any(String) });
expect(Object.keys(spec.elements).length).toBeLessThanOrEqual(16);
+ // Laid out as the card: who they are, the routine, the rest, the footer.
+ const { layout } = spec;
+ expect(spec.elements[spec.root].children).toEqual([
+ ...(layout.identity ? [layout.identity] : []),
+ ...layout.body,
+ layout.askFirst,
+ layout.actions,
+ ]);
+ expect(['Plan', 'Schedule']).toContain(spec.elements[layout.body[0]].type);
+ expect(layout.askFirst).toBe(askFirst[0][0]);
+ const footer = spec.elements[layout.actions].children.map((id) => spec.elements[id].on?.press.action);
+ expect(footer).toEqual(['refine', 'hire_employee']);
+
if ('hasAgent' in want) {
const agent = elements(spec).find(([, element]) => element.type === 'AgentCard');
expect(agent?.[1].props.name).toBe(want.hasAgent);
@@ -143,12 +164,11 @@ describe('model reply corpus', () => {
expect(spec!.elements.c.children).toEqual(['d']);
});
- it('files unlisted controls into the rules card and buttons into one row', () => {
+ it('files unlisted controls into the rules card and the buttons into the footer row', () => {
const { spec } = read(cases.find((c) => c.name === 'nothing lists its children')!.reply);
- const row = elements(spec!).find(
- ([, element]) => element.type === 'Stack' && element.props.direction === 'horizontal',
- );
- expect(row?.[1].children.map((child) => spec!.elements[child].on?.press.action)).toEqual(['hire_employee', 'refine']);
+ const rules = elements(spec!).find(([, element]) => element.type === 'Card');
+ expect(rules?.[1].children).toEqual(['t1']);
+ expect(spec!.elements[spec!.layout.actions].children).toEqual(['edit', 'hire']);
});
it('keeps the model order when capping a long screen', () => {
diff --git a/client/src/features/home/genui/__tests__/useHireComposer.test.tsx b/client/src/features/home/genui/__tests__/useHireComposer.test.tsx
index 6e3c25cb..9ed29ee5 100644
--- a/client/src/features/home/genui/__tests__/useHireComposer.test.tsx
+++ b/client/src/features/home/genui/__tests__/useHireComposer.test.tsx
@@ -24,7 +24,7 @@ import corpus from '../__fixtures__/replies.json';
import { useHomeStore } from '../../state/homeStore';
import { useShellDialogsStore } from '@/stores/shellDialogsStore';
import { resetDraftForTests, useDraftStore } from '../draftStore';
-import { useHireComposer } from '../useHireComposer';
+import { useHireComposer, useJobComposer } from '../useHireComposer';
const GOOD_REPLY = (corpus as unknown as { name: string; reply: string }[]).find((c) => c.name === 'clean minified reply')!.reply;
@@ -79,3 +79,35 @@ describe('useHireComposer', () => {
expect(useDraftStore.getState().failure?.code).toBe('no_ai_provider');
});
});
+
+describe('useJobComposer (the Welcome guide’s box)', () => {
+ it('puts a chip’s job in the box without taking Home’s focus', () => {
+ const { result } = renderHook(() => useJobComposer());
+ act(() => result.current.pick('A receptionist who answers WhatsApp'));
+ expect(useDraftStore.getState().input).toBe('A receptionist who answers WhatsApp');
+ expect(useHomeStore.getState().composerFocus).toBe(0);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('sends the box as a new job, never as a change to the current draft', async () => {
+ sendRequest.mockResolvedValue({ success: true, reply: GOOD_REPLY });
+ const { result } = renderHook(() => useJobComposer());
+ useDraftStore.setState({ refining: true });
+ act(() => result.current.onChange('Answer my WhatsApp'));
+ await act(async () => {
+ await result.current.submit();
+ });
+ expect(sendRequest).toHaveBeenCalledWith('generate_employee_setup', expect.not.objectContaining({ refine: expect.anything() }), expect.any(Number));
+ expect(sendRequest.mock.calls[0][1]).toMatchObject({ job: 'Answer my WhatsApp' });
+ });
+
+ it('opens nothing on its own when there is no AI model', async () => {
+ sendRequest.mockResolvedValue({ success: false, error: 'no_ai_provider' });
+ const { result } = renderHook(() => useJobComposer());
+ act(() => result.current.onChange('Answer my WhatsApp'));
+ await act(async () => {
+ await result.current.submit();
+ });
+ expect(useShellDialogsStore.getState().credentialsOpen).toBe(false);
+ });
+});
diff --git a/client/src/features/home/genui/__tests__/useStarterHire.test.tsx b/client/src/features/home/genui/__tests__/useStarterHire.test.tsx
index d3c61dd2..0817a910 100644
--- a/client/src/features/home/genui/__tests__/useStarterHire.test.tsx
+++ b/client/src/features/home/genui/__tests__/useStarterHire.test.tsx
@@ -80,12 +80,13 @@ beforeEach(() => {
sendRequest.mockClear();
vi.mocked(pillToast).mockClear();
resetDraftForTests();
- useHomeStore.setState({ view: { kind: 'hire' }, hireNotice: null });
+ useHomeStore.setState({ view: { kind: 'hire' }, hireNotice: null, firstDays: {} });
library = [row('write-like-a-person', { is_active: false })];
builtIns = receptionist.skills.map((name) => ({ name, description: `Use for ${name}.`, metadata: { title: name } }));
hireResponse = {
success: true,
started: true,
+ node_count: 12,
warnings: [],
employee: { workflow_id: 'w1', name: 'Rosa', role: 'Receptionist', status: 'working', control: {}, revision: 1 },
};
@@ -108,6 +109,8 @@ describe('useStarterHire', () => {
});
expect(typeof payload.idempotency_key).toBe('string');
expect(useHomeStore.getState().view).toEqual({ kind: 'employee', workflowId: 'w1' });
+ // Their page opens on their first day.
+ expect(useHomeStore.getState().firstDays.w1).toEqual({ started: true, nodeCount: 12 });
// The composer held this job, which is now on the team.
expect(useDraftStore.getState()).toMatchObject({ hiring: false, input: '', hireKey: null });
});
diff --git a/client/src/features/home/genui/catalog.ts b/client/src/features/home/genui/catalog.ts
index 887ba47e..a9ea0972 100644
--- a/client/src/features/home/genui/catalog.ts
+++ b/client/src/features/home/genui/catalog.ts
@@ -143,7 +143,8 @@ export const PROP_SCHEMAS = {
Text: z.object({ text: block(LIMITS.maxText), muted: z.boolean().catch(false) }),
Metric: z.object({ label: line(60), value: line(40), hint: optionalLine(), tone }),
Badge: z.object({ label: line(40), tone }),
- Plan: z.object({ title: optionalLine(60), steps: listOf(planStep, LIMITS.maxSteps) }),
+ // `trigger`: bound to /trigger by the normaliser (the When row's Change); the model never writes it.
+ Plan: z.object({ title: optionalLine(60), steps: listOf(planStep, LIMITS.maxSteps), trigger: z.unknown().optional() }),
// What starts the work (the state at /trigger), read through hirePayload's snapTrigger.
Schedule: z.object({ value: z.unknown().optional() }),
AgentCard: z.object({
diff --git a/client/src/features/home/genui/draftStore.ts b/client/src/features/home/genui/draftStore.ts
index c6e99b81..5cc47187 100644
--- a/client/src/features/home/genui/draftStore.ts
+++ b/client/src/features/home/genui/draftStore.ts
@@ -103,8 +103,6 @@ export interface DraftState {
source: DraftSource | null;
/** The latest reply, read and made safe to render. */
spec: NormalizedSpec | null;
- /** The model's one-sentence introduction of the new employee. */
- intro: string;
/** What the owner has set on the setup screen (toggles, choices, inputs). */
uiState: UiState;
/** Apps the reply names, as the server resolved them: lower-cased name -> ref. */
@@ -131,7 +129,6 @@ const INITIAL: DraftState = {
failure: null,
source: null,
spec: null,
- intro: '',
uiState: {},
apps: {},
team: [],
@@ -264,7 +261,6 @@ export function acceptReply(token: string, response: SetupResponse, request: Pen
failure: null,
source: { provider: response.provider ?? null, model: response.model ?? null },
spec,
- intro: parsed.text.trim(),
uiState: fitTrigger(spec.state, apps),
apps,
team: parseTeam(response.team),
diff --git a/client/src/features/home/genui/hireSpecContext.ts b/client/src/features/home/genui/hireSpecContext.ts
index d711155b..4b177735 100644
--- a/client/src/features/home/genui/hireSpecContext.ts
+++ b/client/src/features/home/genui/hireSpecContext.ts
@@ -1,8 +1,9 @@
/**
* What the setup screen's components need beyond their own props: the
* state the screen was written with (the routine's "When" step is
- * rewritten only once the owner changes when they work) and the apps that
- * can start the work (Schedule offers only those). HireScreen provides it.
+ * rewritten only once the owner changes when they work), the apps that
+ * can start the work (the schedule editor offers only those), and whether
+ * they sit in the footer strip. HireScreen provides it.
*/
import { createContext } from 'react';
@@ -13,6 +14,9 @@ export interface HireSpecContextValue {
writtenState: UiState;
/** Apps that can start the work: any name the reply used -> the app's own name. */
triggerApps: Readonly<Record<string, string>>;
+ /** Drawn in the card's footer strip (Ask first, Change something, Hire),
+ * which styles the toggle and the buttons its own way. */
+ inFooter?: boolean;
}
export const HireSpecContext = createContext<HireSpecContextValue>({ writtenState: {}, triggerApps: {} });
diff --git a/client/src/features/home/genui/index.ts b/client/src/features/home/genui/index.ts
index 5a3c7f44..219d5127 100644
--- a/client/src/features/home/genui/index.ts
+++ b/client/src/features/home/genui/index.ts
@@ -9,5 +9,5 @@
export { HIRE_LIMITS } from './hirePayload';
export { HireDraftPanel } from './HireDraftPanel';
export { MessagePreview as DraftMessagePreview } from './MessagePreview';
-export { useHireComposer } from './useHireComposer';
+export { useHireComposer, useJobComposer } from './useHireComposer';
export { useStarterHire } from './useStarterHire';
diff --git a/client/src/features/home/genui/normalize.ts b/client/src/features/home/genui/normalize.ts
index b3839bc4..ebdedf4f 100644
--- a/client/src/features/home/genui/normalize.ts
+++ b/client/src/features/home/genui/normalize.ts
@@ -12,18 +12,23 @@
* Stack / Grid / Card keep children;
* - loses nothing a model placed badly: elements nobody lists are attached
* where they belong (controls into the rules card, connect buttons into
- * the apps card, the hire and change buttons into the button row);
+ * the apps card, anything else under the root);
* - gives every Button its action as `on.press` ({action, params}), whether
* the model wrote that or the older `action` / `actionParams` props, and
* every Toggle its value as `checked` (older replies say `value`);
- * - always has "Ask me before sending anything" bound to /rules/askFirst,
- * defaulting to on, and exactly one hire button and one change button;
- * - always says when they work: one Schedule, after the routine, bound to
- * /trigger, which starts as the hire button's trigger (else the app the
- * routine's first "When" step names, else the owner messaging them),
- * snapped to one the server builds exactly as it reads;
- * - has at most LIMITS.maxElements elements (the buttons, that toggle and
- * the Schedule are always kept);
+ * - is laid out as the setup card (onboarding handoff R2), the root's
+ * children in this order, named in `layout`: the agent card (the first
+ * one: who they are), the routine, everything else in the order written,
+ * then the footer strip's two: "Ask me before sending anything" bound to
+ * /rules/askFirst (on by default) and a row of one change button and one
+ * hire button;
+ * - always says when they work: the routine is the first Plan, its When row
+ * bound to /trigger, else one Schedule bound to it. /trigger starts as
+ * the hire button's trigger (else the app the routine's first "When" step
+ * names, else the owner messaging them), snapped to one the server builds
+ * exactly as it reads;
+ * - has at most LIMITS.maxElements elements (the card's own pieces are
+ * always kept);
* - cannot reach an object prototype: ids, prop keys and state keys named
* `__proto__`, `constructor` or `prototype` are dropped, and so is any
* expression whose path goes through one; `watch`, `repeat`, `slots`,
@@ -78,12 +83,25 @@ export interface SpecElement {
on?: { press: PressBinding };
}
+/** Where the card draws the root's children (HireScreen). */
+export interface CardLayout {
+ /** The agent card, the identity row; null when the model wrote none. */
+ identity: string | null;
+ /** The routine, then everything else, in order. */
+ body: string[];
+ /** The footer strip: the ask-first toggle on the left... */
+ askFirst: string;
+ /** ...and on the right a row of the change button, then the hire button. */
+ actions: string;
+}
+
export interface NormalizedSpec {
root: string;
state: UiState;
elements: Record<string, SpecElement>;
/** Element ids in render order (depth first), for the reveal. */
order: string[];
+ layout: CardLayout;
}
/** Element keys that are never props (everything else beside `props` is
@@ -197,10 +215,6 @@ function isVerticalStack(element: SpecElement): boolean {
return element.type === 'Stack' && element.props.direction !== 'horizontal';
}
-function isHorizontalStack(element: SpecElement): boolean {
- return element.type === 'Stack' && element.props.direction === 'horizontal';
-}
-
function buttonAction(element: SpecElement | undefined): ActionType | null {
return element?.type === 'Button' ? (element.on?.press.action ?? null) : null;
}
@@ -235,24 +249,26 @@ function depthFirst(elements: Elements, root: string): string[] {
return order;
}
-function removeEverywhere(elements: Elements, id: string): void {
- elements.delete(id);
+/** Take `id` out of its parent's children; the element itself stays. */
+function detach(elements: Elements, id: string): void {
for (const element of elements.values()) {
const index = element.children.indexOf(id);
if (index !== -1) element.children.splice(index, 1);
}
}
+function removeEverywhere(elements: Elements, id: string): void {
+ elements.delete(id);
+ detach(elements, id);
+}
+
/** When they work, as the screen first says it: the hire button's trigger,
* else the app the routine's first "When" step names, else the owner
* messaging them. */
-function seedTrigger(elements: Elements, root: string, state: UiState): HireTrigger {
- const tree = depthFirst(elements, root).map((id) => elements.get(id)!);
- const hire = tree.find((element) => buttonAction(element) === 'hire_employee');
- const params = resolveValue(hire?.on?.press.params, state);
+function seedTrigger(hire: SpecElement, plan: SpecElement | undefined, state: UiState): HireTrigger {
+ const params = resolveValue(hire.on?.press.params, state);
const given = readTrigger(isRecord(params) ? params.trigger : undefined);
if (given && (given.kind !== 'app_event' || given.app)) return given;
- const plan = tree.find((element) => element.type === 'Plan');
const parsed = plan ? PROP_SCHEMAS.Plan.safeParse(resolveValue(plan.props, state) ?? {}) : null;
const app = parsed?.success ? parsed.data.steps.find((step) => step.role === 'trigger')?.app : undefined;
return snapTrigger(app ? { kind: 'app_event', app } : { kind: 'manual' });
@@ -308,17 +324,14 @@ export function normalizeSpec(spec: unknown): NormalizedSpec | null {
};
tops.forEach(carry);
const cyclic = orphans.filter((id) => !carried.has(id));
- const sorted = { actions: [] as string[], controls: [] as string[], connects: [] as string[], others: [] as string[] };
+ const sorted = { controls: [] as string[], connects: [] as string[], others: [] as string[] };
const sort = (id: string) => {
const element = elements.get(id)!;
- const action = buttonAction(element);
- if (action === 'hire_employee' || action === 'refine') sorted.actions.push(id);
- else if (isControl(element.type)) sorted.controls.push(id);
- else if (action === 'connect_app') sorted.connects.push(id);
+ if (isControl(element.type)) sorted.controls.push(id);
+ else if (buttonAction(element) === 'connect_app') sorted.connects.push(id);
else sorted.others.push(id);
};
const attach = (host: string, ids: string[]) => {
- if (ids.length === 0) return;
for (const id of ids) {
if (placed.has(id)) continue;
elements.get(host)!.children.push(id);
@@ -335,27 +348,20 @@ export function normalizeSpec(spec: unknown): NormalizedSpec | null {
attach(root, sorted.others);
attach(titled(cards(), RULES_TITLE) ?? emptyCard() ?? root, sorted.controls);
attach(titled(cards(), APPS_TITLE) ?? emptyCard() ?? root, sorted.connects);
- if (sorted.actions.length > 0) {
- const row = depthFirst(elements, root).find((id) => {
- const element = elements.get(id)!;
- return isHorizontalStack(element) && element.children.length === 0;
- });
- let host = row;
- if (!host) {
- host = freshId(elements, '__acts');
- elements.set(host, { type: 'Stack', props: { direction: 'horizontal', gap: 'md' }, children: [] });
- attach(root, [host]);
- }
- attach(host, sorted.actions);
- }
for (const id of [...elements.keys()]) if (!placed.has(id)) elements.delete(id);
- // One hire button and one change button: the first of each, depth first.
- for (const action of ['hire_employee', 'refine']) {
- const buttons = depthFirst(elements, root).filter((id) => buttonAction(elements.get(id)) === action);
- buttons.slice(1).forEach((id) => removeEverywhere(elements, id));
- }
+ // One agent card, one Plan, one hire button and one change button: the
+ // first of each, depth first.
+ const firstOf = (match: (element: SpecElement) => boolean): string | undefined => {
+ const ids = depthFirst(elements, root).filter((id) => match(elements.get(id)!));
+ ids.slice(1).forEach((id) => removeEverywhere(elements, id));
+ return ids[0];
+ };
+ const agent = firstOf((element) => element.type === 'AgentCard');
+ const plan = firstOf((element) => element.type === 'Plan');
+ let hire = firstOf((element) => buttonAction(element) === 'hire_employee');
+ let change = firstOf((element) => buttonAction(element) === 'refine');
// "Ask me before sending anything" is always there, on by default.
const order = depthFirst(elements, root);
@@ -377,92 +383,57 @@ export function normalizeSpec(spec: unknown): NormalizedSpec | null {
}
}
if (typeof getPath(state, STATE_PATHS.askFirst) !== 'boolean') state = setPath(state, STATE_PATHS.askFirst, true);
-
- const agent = order.map((id) => elements.get(id)!).find((element) => element.type === 'AgentCard');
- const hasHire = order.some((id) => buttonAction(elements.get(id)) === 'hire_employee');
- const hasChange = order.some((id) => buttonAction(elements.get(id)) === 'refine');
- const actionRow = () =>
- depthFirst(elements, root).find((id) => {
- const element = elements.get(id)!;
- return isHorizontalStack(element) && element.children.some((child) => elements.get(child)?.type === 'Button');
- });
- if (!hasHire || !hasChange) {
- const added: string[] = [];
- if (!hasHire) {
- const id = freshId(elements, '__hire');
- elements.set(id, hireButton(agent));
- added.push(id);
- }
- if (!hasChange) {
- const id = freshId(elements, '__edit');
- elements.set(id, {
- type: 'Button',
- props: { label: 'Change something', variant: 'secondary' },
- on: { press: { action: 'refine' } },
- children: [],
- });
- added.push(id);
- }
- let host = actionRow();
- if (!host) {
- host = freshId(elements, '__acts');
- elements.set(host, { type: 'Stack', props: { direction: 'horizontal', gap: 'md' }, children: [] });
- attach(root, [host]);
- }
- attach(host, added);
- }
-
if (!askFirst) {
- const cardsNow = depthFirst(elements, root).filter((id) => elements.get(id)!.type === 'Card');
- let host = titled(cardsNow, /rule/i);
- if (!host) {
- host = freshId(elements, '__rules');
- elements.set(host, { type: 'Card', props: { title: 'Ground rules' }, children: [] });
- // Before the button row, which stays last.
- const rootChildren = elements.get(root)!.children;
- const row = actionRow();
- const at = row ? rootChildren.indexOf(row) : -1;
- rootChildren.splice(at === -1 ? rootChildren.length : at, 0, host);
- placed.add(host);
- }
askFirst = freshId(elements, '__askFirst');
elements.set(askFirst, {
type: 'Toggle',
props: { label: ASK_FIRST_LABEL, checked: { $bindState: STATE_PATHS.askFirst } },
children: [],
});
- attach(host, [askFirst]);
}
- // When they work: one Schedule bound to /trigger, after the routine (else
- // the agent card, else first). Hire reads /trigger before the button.
- state = setPath(state, STATE_PATHS.trigger, seedTrigger(elements, root, state));
+ // The hire button (primary) and the change button (secondary).
+ if (!hire) {
+ hire = freshId(elements, '__hire');
+ elements.set(hire, hireButton(agent ? elements.get(agent) : undefined));
+ }
+ if (!change) {
+ change = freshId(elements, '__edit');
+ elements.set(change, { type: 'Button', props: { label: 'Change something' }, on: { press: { action: 'refine' } }, children: [] });
+ }
+ elements.get(hire)!.props.variant = 'primary';
+ elements.get(change)!.props.variant = 'secondary';
+
+ // When they work, bound to /trigger: the Plan's When row, else one
+ // Schedule. Hire reads /trigger before the button.
+ state = setPath(state, STATE_PATHS.trigger, seedTrigger(elements.get(hire)!, plan ? elements.get(plan) : undefined, state));
const schedules = depthFirst(elements, root).filter((id) => elements.get(id)!.type === 'Schedule');
- schedules.slice(1).forEach((id) => removeEverywhere(elements, id));
- let schedule = schedules[0];
- if (!schedule) {
- schedule = freshId(elements, '__schedule');
- const tree = depthFirst(elements, root);
- const anchor =
- tree.find((id) => elements.get(id)!.type === 'Plan') ?? tree.find((id) => elements.get(id)!.type === 'AgentCard');
- const parent = (anchor && tree.find((id) => elements.get(id)!.children.includes(anchor))) || root;
- const siblings = elements.get(parent)!.children;
- siblings.splice(anchor ? siblings.indexOf(anchor) + 1 : 0, 0, schedule);
+ let routine: string;
+ if (plan) {
+ schedules.forEach((id) => removeEverywhere(elements, id));
+ elements.get(plan)!.props.trigger = { $bindState: STATE_PATHS.trigger };
+ routine = plan;
+ } else {
+ schedules.slice(1).forEach((id) => removeEverywhere(elements, id));
+ routine = schedules[0] ?? freshId(elements, '__schedule');
+ elements.set(routine, { type: 'Schedule', props: { value: { $bindState: STATE_PATHS.trigger } }, children: [] });
}
- elements.set(schedule, { type: 'Schedule', props: { value: { $bindState: STATE_PATHS.trigger } }, children: [] });
- // Cap the size, always keeping the buttons, the toggle, the Schedule and
- // their parents.
+ // The card: who they are, the routine, everything else as written, then
+ // the footer strip's toggle and buttons. All of these are leaves, so
+ // moving one never takes anything with it.
+ const pieces = [agent, routine, askFirst, change, hire].filter((id) => id !== undefined);
+ pieces.forEach((id) => detach(elements, id));
+ const actions = freshId(elements, '__actions');
+ elements.set(actions, { type: 'Stack', props: { direction: 'horizontal', gap: 'sm' }, children: [change, hire] });
+ const top = elements.get(root)!;
+ top.children = [...(agent ? [agent] : []), routine, ...top.children, askFirst, actions];
+
+ // Cap the size, always keeping the root and the card's own pieces.
const full = depthFirst(elements, root);
const parentOf = new Map<string, string>();
for (const id of full) for (const child of elements.get(id)!.children) parentOf.set(child, id);
- const mustKeep = new Set<string>([root]);
- const keepWithAncestors = (id: string | undefined) => {
- for (let at = id; at !== undefined; at = parentOf.get(at)) mustKeep.add(at);
- };
- keepWithAncestors(askFirst);
- keepWithAncestors(schedule);
- full.filter((id) => ['hire_employee', 'refine'].includes(buttonAction(elements.get(id)) ?? '')).forEach(keepWithAncestors);
+ const mustKeep = new Set<string>([root, actions, ...pieces]);
let budget = LIMITS.maxElements - mustKeep.size;
const kept = new Set<string>();
for (const id of full) {
@@ -488,5 +459,11 @@ export function normalizeSpec(spec: unknown): NormalizedSpec | null {
// No prototype: ids are looked up here as keys.
const record: Record<string, SpecElement> = Object.create(null);
for (const [id, element] of elements) record[id] = element;
- return { root, state, elements: record, order: depthFirst(elements, root) };
+ const layout: CardLayout = {
+ identity: agent ?? null,
+ body: elements.get(root)!.children.filter((id) => id !== agent && id !== askFirst && id !== actions),
+ askFirst,
+ actions,
+ };
+ return { root, state, elements: record, order: depthFirst(elements, root), layout };
}
diff --git a/client/src/features/home/genui/useHire.ts b/client/src/features/home/genui/useHire.ts
index 912a2579..81ded4e2 100644
--- a/client/src/features/home/genui/useHire.ts
+++ b/client/src/features/home/genui/useHire.ts
@@ -54,6 +54,8 @@ export interface HireResponse {
error?: string;
employee?: unknown;
started?: boolean;
+ /** Blocks in the workflow the hire built (the first day's "Workflow built"). */
+ node_count?: number;
needs_ai?: boolean;
warnings?: unknown;
activation_state?: string;
@@ -76,10 +78,14 @@ export function hireFailureMessage(error: unknown): string {
}
/** The new employee joins the team: a glow, the logo, a toast, and their
- * page, with what the hire said. */
+ * page on its first day, with what the hire said. */
export function welcomeHire(queryClient: QueryClient, employee: EmployeeSummary, response: HireResponse): void {
refreshEmployee(queryClient, employee.workflow_id);
const home = useHomeStore.getState();
+ home.beginFirstDay(employee.workflow_id, {
+ started: response.started === true,
+ nodeCount: typeof response.node_count === 'number' ? response.node_count : null,
+ });
home.glowRow(employee.workflow_id);
home.pulseLogo();
spikeOrb(SPIKE.hire);
diff --git a/client/src/features/home/genui/useHireComposer.ts b/client/src/features/home/genui/useHireComposer.ts
index 69e14f38..3e937de0 100644
--- a/client/src/features/home/genui/useHireComposer.ts
+++ b/client/src/features/home/genui/useHireComposer.ts
@@ -14,11 +14,36 @@ import { useConnectors } from '../data/connectors';
import { useHomeStore } from '../state/homeStore';
import { useDraftActions, useDraftStore } from './draftStore';
-export function useHireComposer() {
+/**
+ * The job box alone, with no side effects: its text, whether a setup is
+ * being written, picking a starter's job, and sending a new job. The
+ * Welcome guide's composer uses it, so the effects below stay mounted once
+ * (in the hire view) and picking a starter there takes no focus from Home.
+ */
+export function useJobComposer() {
const value = useDraftStore((s) => s.input);
- const refining = useDraftStore((s) => s.refining);
const status = useDraftStore((s) => s.status);
const hiring = useDraftStore((s) => s.hiring);
+ const actions = useDraftActions();
+ return {
+ value,
+ onChange: actions.setInput,
+ working: status === 'working' || hiring,
+ pick: useCallback(
+ (job: string) => {
+ actions.setRefining(false);
+ actions.setInput(job);
+ },
+ [actions],
+ ),
+ /** Send the box as a new job (never a change to the current draft). */
+ submit: useCallback(() => actions.submit(useDraftStore.getState().input, { refine: false }), [actions]),
+ };
+}
+
+export function useHireComposer() {
+ const job = useJobComposer();
+ const refining = useDraftStore((s) => s.refining);
const failure = useDraftStore((s) => s.failure);
const actions = useDraftActions();
const { hasAi, isLoading } = useConnectors();
@@ -42,22 +67,22 @@ export function useHireComposer() {
}, [hasAi, isLoading, actions]);
const send = useCallback((text: string, options?: { refine?: boolean }) => void actions.submit(text, options), [actions]);
+ const pickJob = job.pick;
return {
- value,
- onChange: actions.setInput,
+ value: job.value,
+ onChange: job.onChange,
onSubmit: useCallback(() => send(useDraftStore.getState().input), [send]),
refining,
onStopRefining: useCallback(() => actions.setRefining(false), [actions]),
- working: status === 'working' || hiring,
+ working: job.working,
/** A template: its job replaces whatever is in the box, ready to send. */
pick: useCallback(
- (job: string) => {
- actions.setRefining(false);
- actions.setInput(job);
+ (text: string) => {
+ pickJob(text);
useHomeStore.getState().showHire({ focus: true });
},
- [actions],
+ [pickJob],
),
};
}
diff --git a/client/src/features/home/genui/views.tsx b/client/src/features/home/genui/views.tsx
index c73d43e8..1d9573db 100644
--- a/client/src/features/home/genui/views.tsx
+++ b/client/src/features/home/genui/views.tsx
@@ -7,18 +7,24 @@
* loaded only with the screen (HireScreen).
*
* Controls write through json-render's bindings: a Toggle's `checked`, a
- * Choice's and an Input's `value`, the Schedule's `value` (`/trigger`).
- * A Button presses its `on.press` binding (emit), which json-render
- * resolves against the screen's state and runs (actions.ts).
+ * Choice's and an Input's `value`, the Schedule's `value` and the Plan's
+ * `trigger` (both `/trigger`). A Button presses its `on.press` binding
+ * (emit), which json-render resolves against the screen's state and runs
+ * (actions.ts).
*
- * When they work (Schedule) reads as one plain sentence; Edit offers only
- * what the hire can build: the owner messaging them, a schedule at the
- * times it can run, or a new message in one of the apps the server says can
- * start the work. Once the owner changes it, the routine's "When" step
- * follows (Plan reads the state at /trigger itself, beside its own props).
+ * The card (onboarding handoff R2): the AgentCard is the identity row, the
+ * Plan the routine as a timeline (ui/routine), and Ask first with the two
+ * buttons sit in the footer strip, where they take its look
+ * (HireSpecContext.inFooter). When they work is the routine's When row;
+ * its Change opens the editor under it, offering only what the hire can
+ * build: the owner messaging them, a schedule at the times it can run, or a
+ * new message in one of the apps the server says can start the work. Once
+ * the owner changes it, the When row says the new trigger. Without a Plan,
+ * a Schedule draws that one row.
*/
-import { Fragment, useContext, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
+import { Fragment, useContext, useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
+import { ArrowRight } from 'lucide-react';
import { useBoundProp, useStateValue } from '@json-render/react';
import { ActionButton } from '@/components/ui/action-button';
import { Button } from '@/components/ui/button';
@@ -26,10 +32,11 @@ import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
-import { useEntrance, type GuardedComponentProps } from '@/lib/jsonRender';
-import { animate } from '@/lib/motion';
+import { LiveUiContext, type GuardedComponentProps } from '@/lib/jsonRender';
+import { animate, RISE, stagger } from '@/lib/motion';
import { cn } from '@/lib/utils';
-import { MicroLabel } from '../ui/primitives';
+import { Avatar, MicroLabel } from '../ui/primitives';
+import { RoutineRow, RoutineTimeline } from '../ui/routine';
import { STATE_PATHS, type PROP_SCHEMAS, type PropsOf, type StepRole, type Tone } from './catalog';
import { getPath } from './expressions';
import { HireSpecContext } from './hireSpecContext';
@@ -85,17 +92,6 @@ const TONE_BADGE: Record<Tone, string> = {
neutral: 'border-border-default bg-bg-hover text-fg-default',
};
-const STEP_TONE: Record<StepRole, string> = {
- trigger:
- 'border-node-trigger-edge bg-linear-135/srgb from-node-trigger-fill to-bg-elevated shadow-[0_0_18px_var(--node-trigger-soft)]',
- agent: 'border-node-agent-edge bg-linear-135/srgb from-node-agent-fill to-bg-elevated shadow-[0_0_18px_var(--node-agent-soft)]',
- tool: 'border-node-tool-edge bg-linear-135/srgb from-node-tool-fill to-bg-elevated shadow-[0_0_18px_var(--node-tool-soft)]',
- workflow:
- 'border-node-workflow-edge bg-linear-135/srgb from-node-workflow-fill to-bg-elevated shadow-[0_0_18px_var(--node-workflow-soft)]',
-};
-
-const STEP_LABEL: Record<StepRole, string> = { trigger: 'When', agent: 'They', tool: 'Using', workflow: 'Then' };
-
const EVERY_LABEL: Record<NonNullable<HireTrigger['every']>, string> = {
hour: 'Every hour',
day: 'Every day',
@@ -108,20 +104,6 @@ const MONTH_DAYS = Array.from({ length: LAST_MONTH_DAY }, (_, index) => String(i
const STACK_GAP = { sm: 'gap-2', md: 'gap-3', lg: 'gap-4.5' } as const;
-const AGENT_STATUS = {
- ready: {
- label: 'Ready',
- dot: 'bg-status-working-dot shadow-[0_0_8px_var(--status-working-dot)]',
- ink: 'text-status-working-ink',
- },
- working: {
- label: 'Working',
- dot: 'bg-status-ready-dot shadow-[0_0_8px_var(--status-ready-dot)]',
- ink: 'text-status-ready-ink',
- },
- paused: { label: 'Stopped', dot: 'bg-status-paused-dot', ink: 'text-status-paused-ink' },
-} as const;
-
function Pip({ className }: { className?: string }) {
return <span aria-hidden className={cn('size-1.75 shrink-0 rounded-full', className)} />;
}
@@ -154,12 +136,14 @@ export function GridView({ props, children, enterRef }: ViewProps<'Grid'>) {
);
}
+/** A compact section of the card: the model's own rules, choices and
+ * notes, kept in view so nothing is hired unseen. */
export function CardView({ props, children, enterRef }: ViewProps<'Card'>) {
return (
- <div ref={enterRef} className={cn('flex flex-col gap-3 rounded-card border p-4', TONE_CARD[props.tone ?? 'neutral'])}>
+ <div ref={enterRef} className={cn('flex flex-col gap-2.5 rounded-row border px-3.5 py-3', TONE_CARD[props.tone ?? 'neutral'])}>
{(props.title || props.subtitle) && (
- <div className="flex flex-col gap-0.75">
- {props.title && <span className="text-lead font-semibold text-fg-default">{props.title}</span>}
+ <div className="flex flex-col gap-0.5">
+ {props.title && <MicroLabel>{props.title}</MicroLabel>}
{props.subtitle && <span className="text-sm text-fg-muted">{props.subtitle}</span>}
</div>
)}
@@ -212,58 +196,94 @@ export function DividerView({ enterRef }: ViewProps<'Divider'>) {
return <div ref={enterRef} className="h-px bg-border-default" />;
}
-function PlanStep({ step }: { step: PropsOf<'Plan'>['steps'][number] }) {
- const enter = useEntrance<HTMLDivElement>();
- return (
- <div
- ref={enter}
- className={cn('flex max-w-60 min-w-0 flex-[1_0_150px] flex-col gap-1.25 rounded-row border-2 p-3', STEP_TONE[step.role])}
- >
- <span className={cn('flex items-center gap-1.5 font-mono text-2xs font-medium tracking-label uppercase', TONE_INK[step.role])}>
- <Pip className={TONE_DOT[step.role]} />
- {STEP_LABEL[step.role]}
- {step.app && <span className="truncate normal-case tracking-normal text-fg-muted">· {step.app}</span>}
- </span>
- <span className="text-row font-semibold text-fg-default">{step.title}</span>
- {step.detail && <span className="text-meta leading-snug text-fg-muted">{step.detail}</span>}
- </div>
- );
-}
-
/** The app's own name, when the reply's name for it is one that can start the work. */
function appNameOf(trigger: HireTrigger, triggerApps: Readonly<Record<string, string>>): string | undefined {
return trigger.app ? (triggerApps[trigger.app.toLowerCase()] ?? trigger.app) : undefined;
}
-export function PlanView({ props, enterRef }: ViewProps<'Plan'>) {
- const { writtenState, triggerApps } = useContext(HireSpecContext);
- const current = snapTrigger(useStateValue<unknown>(STATE_PATHS.trigger));
- const written = snapTrigger(getPath(writtenState, STATE_PATHS.trigger));
- const steps = routineSteps(props.steps, written, current, appNameOf(current, triggerApps));
+interface RoutineStepProps {
+ title: string;
+ detail?: string;
+ role: StepRole;
+}
+
+/** The routine as a timeline. The When row (the first trigger step) ends in
+ * Change while `onChange` is given, which opens the editor under it. Rows
+ * rise in one after another when the screen arrives live: that is the
+ * routine's entrance, so the element's own is not played. */
+function Routine({
+ steps,
+ trigger,
+ appName,
+ onChange,
+}: {
+ steps: readonly RoutineStepProps[];
+ trigger: HireTrigger;
+ appName: string | undefined;
+ /** Null when nothing is bound to /trigger: no Change. */
+ onChange: ((next: HireTrigger) => void) | null;
+}) {
+ const live = useContext(LiveUiContext);
+ const rowsRef = useRef<HTMLDivElement>(null);
+ const [editing, setEditing] = useState(false);
+ const whenAt = steps.findIndex((step) => step.role === 'trigger');
+
+ useLayoutEffect(() => {
+ const rows = rowsRef.current?.querySelectorAll('[data-routine-row]');
+ if (live && rows) stagger(rows, RISE, { base: 120, step: 90, duration: 'follow-in', easing: 'spring' });
+ }, [live]);
+
return (
- <div ref={enterRef} className="flex min-w-0 flex-col gap-3.5 rounded-card border border-border-default bg-bg-elevated p-4">
- <div className="flex items-center gap-2">
- <span className="text-lead font-semibold text-fg-default">{props.title || 'Their routine'}</span>
- <span className="ml-auto font-mono text-2xs text-fg-faint">
- {steps.length} {steps.length === 1 ? 'step' : 'steps'}
- </span>
- </div>
- <div className="flex min-w-0 items-stretch overflow-x-auto overflow-y-hidden pb-1 [scrollbar-width:thin]">
+ <div className="min-w-0">
+ <RoutineTimeline ref={rowsRef}>
{steps.map((step, index) => (
<Fragment key={index}>
- {index > 0 && (
- <div aria-hidden className="flex w-5.5 shrink-0 items-center">
- <div className="h-0.5 w-full rounded-full bg-border-strong" />
- </div>
- )}
- <PlanStep step={step} />
+ <RoutineRow
+ role={step.role}
+ title={step.title}
+ detail={step.detail}
+ action={
+ index === whenAt && onChange ? (
+ <Button
+ variant="quiet"
+ aria-expanded={editing}
+ onClick={() => setEditing((on) => !on)}
+ className="h-6.5 rounded-pill border-border-default px-2.5 text-xs"
+ >
+ {editing ? 'Done' : 'Change'}
+ </Button>
+ ) : undefined
+ }
+ />
+ {index === whenAt && onChange && editing && <ScheduleEditor trigger={trigger} appName={appName} onChange={onChange} />}
</Fragment>
))}
- </div>
+ </RoutineTimeline>
</div>
);
}
+export function PlanView({ props, bindings }: ViewProps<'Plan'>) {
+ const { writtenState, triggerApps } = useContext(HireSpecContext);
+ const [, setTrigger] = useBoundProp<unknown>(props.trigger, bindings?.trigger);
+ const current = snapTrigger(useStateValue<unknown>(STATE_PATHS.trigger));
+ const written = snapTrigger(getPath(writtenState, STATE_PATHS.trigger));
+ const appName = appNameOf(current, triggerApps);
+ const steps = routineSteps(props.steps, written, current, appName);
+ // A routine with no "When" step still says when they work, first.
+ const shown = steps.some((step) => step.role === 'trigger')
+ ? steps
+ : [{ title: triggerSentence(current, appName), role: 'trigger' as const }, ...steps];
+ return (
+ <Routine
+ steps={shown}
+ trigger={current}
+ appName={appName}
+ onChange={bindings?.trigger ? (next) => setTrigger(snapTrigger(next)) : null}
+ />
+ );
+}
+
function ScheduleField({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="flex flex-col gap-1.5">
@@ -300,148 +320,129 @@ function SchedulePicker({
);
}
-export function ScheduleView({ props, bindings, enterRef }: ViewProps<'Schedule'>) {
+/** When they work, edited: what starts the work, and for a schedule how
+ * often, on which day and at what time. Opens under the routine's When
+ * row, in line with its text. */
+function ScheduleEditor({
+ trigger,
+ appName,
+ onChange,
+}: {
+ trigger: HireTrigger;
+ appName: string | undefined;
+ onChange: (next: HireTrigger) => void;
+}) {
const { triggerApps } = useContext(HireSpecContext);
- const [editing, setEditing] = useState(false);
- const [, setValue] = useBoundProp<unknown>(props.value, bindings?.value);
- const bound = Boolean(bindings?.value);
- const trigger = snapTrigger(props.value);
- const appName = appNameOf(trigger, triggerApps);
const apps = [...new Set(Object.values(triggerApps))];
- const change = (next: HireTrigger) => setValue(snapTrigger(next));
+ const change = (next: HireTrigger) => onChange(snapTrigger(next));
const starts = trigger.kind === 'app_event' ? `app:${appName ?? ''}` : trigger.kind;
const pickStart = (value: string) => {
if (value === 'manual' || value === 'schedule') change({ kind: value });
else change({ kind: 'app_event', app: value.slice('app:'.length) });
};
return (
- <div ref={enterRef} className="flex flex-col gap-3 rounded-card border border-border-default bg-bg-elevated p-4">
- <div className="flex items-center gap-3">
- <div className="flex min-w-0 flex-1 flex-col gap-1">
- <MicroLabel>When they work</MicroLabel>
- <span className="text-base font-medium text-fg-default">{triggerSentence(trigger, appName)}</span>
- </div>
- {bound && (
- <Button
- variant="quiet"
- aria-expanded={editing}
- onClick={() => setEditing((on) => !on)}
- className="h-8 rounded-lg border-border-strong px-3 font-semibold text-fg-default"
- >
- {editing ? 'Done' : 'Edit'}
- </Button>
- )}
- </div>
- {editing && bound && (
- <div className="flex flex-col gap-3 border-t border-border-default pt-3">
- <ScheduleField label="What starts their work">
+ <div className="mt-1 mb-2 ml-21 flex flex-col gap-3 rounded-row border border-border-default bg-bg-elevated p-3">
+ <ScheduleField label="What starts their work">
+ <ToggleGroup
+ type="single"
+ variant="chips"
+ aria-label="What starts their work"
+ value={starts}
+ onValueChange={(next) => next && pickStart(next)}
+ className="flex-wrap gap-1.5"
+ >
+ <ToggleGroupItem value="manual">When you message them</ToggleGroupItem>
+ <ToggleGroupItem value="schedule">On a schedule</ToggleGroupItem>
+ {apps.map((app) => (
+ <ToggleGroupItem key={app} value={`app:${app}`}>
+ When something new arrives in {app}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ </ScheduleField>
+ {trigger.kind === 'schedule' && (
+ <>
+ <ScheduleField label="How often">
<ToggleGroup
type="single"
- variant="chips"
- aria-label="What starts their work"
- value={starts}
- onValueChange={(next) => next && pickStart(next)}
- className="flex-wrap gap-1.5"
+ variant="segmented"
+ aria-label="How often"
+ value={trigger.every ?? ''}
+ onValueChange={(next) => next && change({ ...trigger, every: next as HireTrigger['every'] })}
+ className="flex-wrap self-start"
>
- <ToggleGroupItem value="manual">When you message them</ToggleGroupItem>
- <ToggleGroupItem value="schedule">On a schedule</ToggleGroupItem>
- {apps.map((app) => (
- <ToggleGroupItem key={app} value={`app:${app}`}>
- When something new arrives in {app}
+ {SCHEDULE_EVERY.map((every) => (
+ <ToggleGroupItem key={every} value={every} className="border-0">
+ {EVERY_LABEL[every]}
</ToggleGroupItem>
))}
</ToggleGroup>
</ScheduleField>
- {trigger.kind === 'schedule' && (
- <>
- <ScheduleField label="How often">
- <ToggleGroup
- type="single"
- variant="segmented"
- aria-label="How often"
- value={trigger.every ?? ''}
- onValueChange={(next) => next && change({ ...trigger, every: next as HireTrigger['every'] })}
- className="flex-wrap self-start"
- >
- {SCHEDULE_EVERY.map((every) => (
- <ToggleGroupItem key={every} value={every} className="border-0">
- {EVERY_LABEL[every]}
- </ToggleGroupItem>
- ))}
- </ToggleGroup>
- </ScheduleField>
- {trigger.every !== 'hour' && (
- <div className="flex flex-wrap gap-4">
- {trigger.every === 'week' && (
- <ScheduleField label="On">
- <SchedulePicker
- label="Day of the week"
- value={trigger.day}
- options={WEEKDAYS.map((day) => ({ value: day, label: `${day.charAt(0).toUpperCase()}${day.slice(1)}` }))}
- onChange={(day) => change({ ...trigger, day })}
- />
- </ScheduleField>
- )}
- {trigger.every === 'month' && (
- <ScheduleField label="On day">
- <SchedulePicker
- label="Day of the month"
- value={trigger.day}
- options={MONTH_DAYS.map((day) => ({ value: day, label: day }))}
- onChange={(day) => change({ ...trigger, day })}
- />
- </ScheduleField>
- )}
- <ScheduleField label="At">
- <SchedulePicker
- label="Time"
- value={trigger.at}
- options={SCHEDULE_TIMES.map((time) => ({ value: time, label: time }))}
- onChange={(at) => change({ ...trigger, at })}
- />
- </ScheduleField>
- </div>
+ {trigger.every !== 'hour' && (
+ <div className="flex flex-wrap gap-4">
+ {trigger.every === 'week' && (
+ <ScheduleField label="On">
+ <SchedulePicker
+ label="Day of the week"
+ value={trigger.day}
+ options={WEEKDAYS.map((day) => ({ value: day, label: `${day.charAt(0).toUpperCase()}${day.slice(1)}` }))}
+ onChange={(day) => change({ ...trigger, day })}
+ />
+ </ScheduleField>
+ )}
+ {trigger.every === 'month' && (
+ <ScheduleField label="On day">
+ <SchedulePicker
+ label="Day of the month"
+ value={trigger.day}
+ options={MONTH_DAYS.map((day) => ({ value: day, label: day }))}
+ onChange={(day) => change({ ...trigger, day })}
+ />
+ </ScheduleField>
)}
- </>
+ <ScheduleField label="At">
+ <SchedulePicker
+ label="Time"
+ value={trigger.at}
+ options={SCHEDULE_TIMES.map((time) => ({ value: time, label: time }))}
+ onChange={(at) => change({ ...trigger, at })}
+ />
+ </ScheduleField>
+ </div>
)}
- </div>
+ </>
)}
</div>
);
}
+/** When they work, for a screen without a routine: its one When row. */
+export function ScheduleView({ props, bindings }: ViewProps<'Schedule'>) {
+ const { triggerApps } = useContext(HireSpecContext);
+ const [, setValue] = useBoundProp<unknown>(props.value, bindings?.value);
+ const trigger = snapTrigger(props.value);
+ const appName = appNameOf(trigger, triggerApps);
+ return (
+ <Routine
+ steps={[{ title: triggerSentence(trigger, appName), role: 'trigger' }]}
+ trigger={trigger}
+ appName={appName}
+ onChange={bindings?.value ? (next) => setValue(snapTrigger(next)) : null}
+ />
+ );
+}
+
+/** Who they are: the setup card's identity row. The description goes into
+ * their instructions, so it shows too, kept to two lines. */
export function AgentCardView({ props, enterRef }: ViewProps<'AgentCard'>) {
- const status = AGENT_STATUS[props.status];
+ const sub = [props.role, props.apps.join(', ')].filter(Boolean).join(' · ');
return (
- <div ref={enterRef} className={cn('flex gap-3.5 rounded-card border p-4', TONE_CARD.agent)}>
- <span
- aria-hidden
- className="grid size-10.5 shrink-0 place-items-center rounded-full border-2 border-node-agent-edge bg-node-agent-fill text-md font-semibold text-node-agent-ink"
- >
- {Array.from(props.name)[0]?.toLocaleUpperCase() ?? 'A'}
- </span>
- <div className="flex min-w-0 flex-1 flex-col gap-1.25">
- <div className="flex flex-wrap items-center gap-2">
- <span className="text-lead font-semibold text-fg-default">{props.name}</span>
- <span className="text-meta text-fg-muted">{props.role}</span>
- <span className={cn('ml-auto flex items-center gap-1.5 text-xs', status.ink)}>
- <Pip className={status.dot} />
- {status.label}
- </span>
- </div>
- {props.description && <span className="text-row leading-normal text-fg-muted">{props.description}</span>}
- {props.apps.length > 0 && (
- <div className="mt-1 flex flex-wrap gap-1.5">
- {props.apps.map((app) => (
- <span
- key={app}
- className="inline-flex h-5.5 items-center rounded-md border border-border-default bg-bg-hover px-2 text-xs text-fg-default"
- >
- {app}
- </span>
- ))}
- </div>
- )}
+ <div ref={enterRef} className="flex min-w-0 items-center gap-3.5">
+ <Avatar name={props.name} colorRole="agent" size="card" />
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate text-lg leading-tight font-semibold tracking-[-0.02em] text-fg-default">{props.name}</span>
+ {sub && <span className="truncate text-sm text-fg-muted">{sub}</span>}
+ {props.description && <span className="line-clamp-2 text-sm text-pretty text-fg-muted">{props.description}</span>}
</div>
</div>
);
@@ -498,15 +499,30 @@ export function ProgressView({ props, enterRef }: ViewProps<'Progress'>) {
);
}
+/** In the footer strip it is Ask first, said shortly beside its switch. */
+const FOOTER_TOGGLE_LABEL = 'Ask before sending';
+
export function ToggleView({ props, bindings, enterRef }: ViewProps<'Toggle'>) {
+ const { inFooter } = useContext(HireSpecContext);
const [, setChecked] = useBoundProp<boolean>(props.checked, bindings?.checked);
+ const id = useId();
+ if (inFooter) {
+ return (
+ <div ref={enterRef} className="flex items-center gap-2.5">
+ <Switch id={id} tone="run" checked={props.checked} onCheckedChange={setChecked} />
+ <label htmlFor={id} className="cursor-pointer text-sm text-fg-muted">
+ {FOOTER_TOGGLE_LABEL}
+ </label>
+ </div>
+ );
+ }
return (
- <div ref={enterRef} className="flex items-center gap-3.5 py-1">
+ <div ref={enterRef} className="flex items-center gap-3.5 py-0.5">
<div className="flex flex-1 flex-col gap-0.5">
- <span className="text-base font-medium text-fg-default">{props.label}</span>
+ <span className="text-row font-medium text-fg-default">{props.label}</span>
{props.description && <span className="text-meta text-fg-muted">{props.description}</span>}
</div>
- <Switch size="md" tone="run" aria-label={props.label} checked={props.checked} onCheckedChange={setChecked} />
+ <Switch tone="run" aria-label={props.label} checked={props.checked} onCheckedChange={setChecked} />
</div>
);
}
@@ -553,7 +569,22 @@ export function InputView({ props, bindings, enterRef }: ViewProps<'Input'>) {
}
export function ButtonView({ props, emit, enterRef }: ViewProps<'Button'>) {
+ const { inFooter } = useContext(HireSpecContext);
const press = () => emit('press');
+ // The footer's pair: a quiet "Change something", then the one strong
+ // control on the card, "Hire {name} →".
+ if (inFooter) {
+ return props.variant === 'primary' ? (
+ <Button ref={enterRef} variant="invert" size="pill" onClick={press}>
+ {props.label}
+ <ArrowRight aria-hidden strokeWidth={2.25} />
+ </Button>
+ ) : (
+ <Button ref={enterRef} variant="quiet" size="pill" onClick={press} className="px-3.5">
+ {props.label}
+ </Button>
+ );
+ }
if (props.variant === 'primary') {
return (
<ActionButton
diff --git a/client/src/features/home/header/GuideButton.tsx b/client/src/features/home/header/GuideButton.tsx
new file mode 100644
index 00000000..11e486a5
--- /dev/null
+++ b/client/src/features/home/header/GuideButton.tsx
@@ -0,0 +1,25 @@
+/**
+ * The header's Guide pill: opens the Welcome guide again at its first step.
+ * Styled as the Workspace pill at rest.
+ */
+
+import { CircleHelp } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { useHomeStore } from '../state/homeStore';
+
+export function GuideButton() {
+ const openGuide = useHomeStore((s) => s.openGuide);
+ return (
+ <Button
+ variant="quiet"
+ title="Welcome guide: connect an AI model and hire your first employee"
+ onClick={() => openGuide('welcome')}
+ className="h-8.5 gap-1.75 rounded-pill border-border-default px-3 text-sm text-fg-default hover:border-border-strong"
+ >
+ <CircleHelp aria-hidden className="size-3.75" strokeWidth={1.75} />
+ Guide
+ </Button>
+ );
+}
+
+export default GuideButton;
diff --git a/client/src/features/home/header/HomeHeader.tsx b/client/src/features/home/header/HomeHeader.tsx
index 955a58c7..9f521276 100644
--- a/client/src/features/home/header/HomeHeader.tsx
+++ b/client/src/features/home/header/HomeHeader.tsx
@@ -21,6 +21,7 @@ import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import { useWorkflowControlPending } from '@/stores/workflowControlStore';
import { PHOTO_TYPES, useRenameEmployee, useSetEmployeePhoto } from '../data/identity';
+import { useAnswering } from '../data/liveTask';
import { presentEmployee } from '../data/presentation';
import type { EmployeeSummary } from '../data/schemas';
import { HIRE_LIMITS } from '../genui';
@@ -28,6 +29,7 @@ import { useHomeStore } from '../state/homeStore';
import { Avatar, StatusPill } from '../ui/primitives';
import { pillToast } from '../ui/pillToast';
import { WorkspaceButton } from '../workspace/WorkspaceButton';
+import { GuideButton } from './GuideButton';
import { NewConversationButton } from './NewConversationButton';
import { ThemeButton } from './ThemeButton';
@@ -146,7 +148,8 @@ function Name({ employee }: { employee: EmployeeSummary }) {
function Identity({ employee }: { employee: EmployeeSummary }) {
const pending = useWorkflowControlPending(employee.workflow_id);
- const { pill, pulse } = presentEmployee(employee, pending);
+ const answering = useAnswering(employee);
+ const { pill, pulse } = presentEmployee(employee, pending, answering);
const subtitle = subtitleOf(employee);
return (
<div className="flex min-w-0 items-center gap-2.5 px-1">
@@ -185,6 +188,7 @@ export function HomeHeader({ title, employee, scrolled }: { title: string; emplo
{employee ? <Identity employee={employee} /> : <h2 className="truncate px-1.5 text-lead font-semibold text-fg-default">{title}</h2>}
<div className="ml-auto flex shrink-0 items-center gap-2">
{employee && employee.talk.state === 'on' && <NewConversationButton employee={employee} />}
+ <GuideButton />
<WorkspaceButton />
<ModeToggle workflowId={employeeId} />
<ThemeButton />
diff --git a/client/src/features/home/hire/Composer.tsx b/client/src/features/home/hire/Composer.tsx
index 93b166c6..dd7a5420 100644
--- a/client/src/features/home/hire/Composer.tsx
+++ b/client/src/features/home/hire/Composer.tsx
@@ -46,6 +46,10 @@ export interface ComposerProps {
/** Told when the box gains or loses focus. */
onFocusChange?: (focused: boolean) => void;
maxLength?: number;
+ /** Create's label while idle (default "Create employee"). */
+ idleLabel?: string;
+ /** No float shadow: the box sits inside a dialog (the Welcome guide). */
+ flat?: boolean;
}
const APP_STACK = 3;
@@ -63,6 +67,8 @@ export function Composer({
onFocusTaken,
onFocusChange,
maxLength,
+ idleLabel,
+ flat = false,
}: ComposerProps) {
const boxRef = useRef<HTMLTextAreaElement>(null);
const surfaceRef = useRef<HTMLDivElement>(null);
@@ -119,7 +125,8 @@ export function Composer({
ref={surfaceRef}
data-intro
className={cn(
- 'relative flex w-full max-w-(--w-composer) shrink-0 scroll-mt-4 flex-col gap-2 rounded-composer border bg-bg-panel pt-3 pr-3 pb-2.5 pl-4 shadow-float transition-colors duration-(--dur-slow)',
+ 'relative flex w-full max-w-(--w-composer) shrink-0 scroll-mt-4 flex-col gap-2 rounded-composer border bg-bg-panel pt-3 pr-3 pb-2.5 pl-4 transition-colors duration-(--dur-slow)',
+ !flat && 'shadow-float',
refining ? 'border-node-agent-edge' : 'border-border-default focus-within:border-border-strong',
)}
>
@@ -174,7 +181,7 @@ export function Composer({
onClick={submit}
className="ml-auto"
>
- {createLabel(working, refining)}
+ {createLabel(working, refining, idleLabel)}
<ArrowRight aria-hidden strokeWidth={2.25} />
</Button>
</div>
diff --git a/client/src/features/home/hire/HireView.tsx b/client/src/features/home/hire/HireView.tsx
index c53f0edc..94bf5a03 100644
--- a/client/src/features/home/hire/HireView.tsx
+++ b/client/src/features/home/hire/HireView.tsx
@@ -11,6 +11,7 @@ import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { stagger } from '@/lib/motion';
import { useConnectors } from '../data/connectors';
import { useEmployeesQuery } from '../data/employees';
+import { useAnsweringCount } from '../data/liveTask';
import { callName, useOwnerSettings } from '../data/profile';
import { HireDraftPanel, useHireComposer, useStarterHire } from '../genui';
import { ENERGY, setEnergyTarget } from '../orb/orb';
@@ -53,7 +54,7 @@ export function HireView({ onConnect }: { onConnect: (providerId: string) => voi
}, [composer.working, hasText, focused]);
useEffect(() => () => setEnergyTarget(ENERGY.idle), []);
- const working = employees?.filter((employee) => employee.status === 'working').length ?? 0;
+ const working = useAnsweringCount(employees);
const name = callName(settings);
const apps = connectedApps.map((provider) => ({ id: provider.id, name: provider.name, icon_ref: provider.icon_ref }));
const picked = HIRE_TEMPLATES.find((template) => template.job === composer.value.trim()) ?? null;
@@ -66,7 +67,7 @@ export function HireView({ onConnect }: { onConnect: (providerId: string) => voi
data-intro
className="m-0 flex items-center gap-2 font-mono text-xs font-medium tracking-label text-fg-muted uppercase"
>
- <span aria-hidden className="size-1.5 rounded-full bg-status-working-dot shadow-[0_0_8px_var(--status-working-dot)]" />
+ <span aria-hidden className="size-1.5 rounded-full bg-current text-status-working-dot shadow-pip" />
{greetingFor(new Date())}
{name ? `, ${name}` : ''} · {working} working now
</p>
@@ -100,6 +101,7 @@ export function HireView({ onConnect }: { onConnect: (providerId: string) => voi
onPick={(template) => composer.pick(template.job)}
onHireNow={(template) => void starterHire.hire(template)}
disabled={composer.working}
+ className="mt-4"
/>
<HireDraftPanel onConnect={onConnect} />
</div>
diff --git a/client/src/features/home/hire/TemplateChips.tsx b/client/src/features/home/hire/TemplateChips.tsx
index c2487f6b..c5ae3966 100644
--- a/client/src/features/home/hire/TemplateChips.tsx
+++ b/client/src/features/home/hire/TemplateChips.tsx
@@ -2,8 +2,9 @@
* Starter jobs under the composer (design handoff "Template chips"). A chip
* puts its job in the composer for the owner to read, change and send;
* while the composer still holds that job as written, the chip shows as
- * picked and offers to hire the starter as it stands ("Hire now").
- * Coloured by node role, the same palette the employee avatars use.
+ * picked and, given `onHireNow`, offers to hire the starter as it stands
+ * ("Hire now"). The Welcome guide shows the chips alone. Coloured by node
+ * role, the same palette the employee avatars use.
*/
import { ActionButton } from '@/components/ui/action-button';
@@ -41,16 +42,20 @@ export function TemplateChips({
onPick,
onHireNow,
disabled = false,
+ className,
}: {
/** The starter whose job the composer holds, untouched. */
picked: HireTemplate | null;
onPick: (template: HireTemplate) => void;
- onHireNow: (template: HireTemplate) => void;
+ /** Without it the chips only fill the composer (no "Hire now" row). */
+ onHireNow?: (template: HireTemplate) => void;
disabled?: boolean;
+ /** The chip row's spacing and alignment (centred by default). */
+ className?: string;
}) {
return (
<>
- <div data-intro className="mt-4 flex max-w-(--w-composer) flex-wrap justify-center gap-2">
+ <div data-intro className={cn('flex max-w-(--w-composer) flex-wrap justify-center gap-2', className)}>
{HIRE_TEMPLATES.map((template) => (
<Button
key={template.id}
@@ -66,7 +71,7 @@ export function TemplateChips({
</Button>
))}
</div>
- {picked && (
+ {picked && onHireNow && (
<div className="mt-3 flex max-w-(--w-composer) flex-wrap items-center justify-center gap-x-3 gap-y-2 text-center">
<span className="text-sm text-pretty text-fg-muted">{picked.summary}</span>
<ActionButton intent="run" disabled={disabled} onClick={() => onHireNow(picked)} className="rounded-pill">
diff --git a/client/src/features/home/hire/composerKeys.ts b/client/src/features/home/hire/composerKeys.ts
index 84488b09..00ace24c 100644
--- a/client/src/features/home/hire/composerKeys.ts
+++ b/client/src/features/home/hire/composerKeys.ts
@@ -4,7 +4,9 @@
* testable on its own. Which Enter sends is lib/composerKeys.ts.
*/
-export function createLabel(working: boolean, refining: boolean): string {
+/** Create's label: busy, editing the draft, or `idle` (the Welcome guide
+ * says "Create their setup"). */
+export function createLabel(working: boolean, refining: boolean, idle = 'Create employee'): string {
if (working) return 'Creating…';
- return refining ? 'Update' : 'Create employee';
+ return refining ? 'Update' : idle;
}
diff --git a/client/src/features/home/onboarding/GetStartedChecklist.tsx b/client/src/features/home/onboarding/GetStartedChecklist.tsx
new file mode 100644
index 00000000..23e3b9c2
--- /dev/null
+++ b/client/src/features/home/onboarding/GetStartedChecklist.tsx
@@ -0,0 +1,120 @@
+/**
+ * The Get started checklist (onboarding handoff D): a card in Home's
+ * bottom-right corner once the Welcome guide is finished, whose four steps
+ * tick themselves as the owner gets going (useGetStarted). A step not done
+ * yet takes the owner there. The card folds to a "Get started · n/4" pill,
+ * and hiding it says where it comes back (Settings > Help). It stays out of
+ * the way while the guide is open.
+ */
+
+import { Check, ChevronDown, ChevronUp, Sparkles, X } from 'lucide-react';
+import { useState } from 'react';
+import { ActionButton } from '@/components/ui/action-button';
+import { Button } from '@/components/ui/button';
+import { Progress } from '@/components/ui/progress';
+import { cn } from '@/lib/utils';
+import { useHomeStore } from '../state/homeStore';
+import { pillToast } from '../ui/pillToast';
+import { useGetStarted, type GetStartedRow } from './useGetStarted';
+
+function Step({ row }: { row: GetStartedRow }) {
+ const body = (
+ <>
+ <span
+ className={cn(
+ 'grid size-6 shrink-0 place-items-center rounded-full border',
+ row.done ? 'border-action-run-border bg-action-run-soft text-action-run-ink' : 'border-border-default text-fg-muted',
+ )}
+ >
+ {row.done ? <Check aria-hidden className="size-3.5" strokeWidth={2.5} /> : <row.icon aria-hidden className="size-3.5" />}
+ </span>
+ <span className="min-w-0 flex-1 text-left">
+ <span className={cn('block text-sm font-medium', row.done ? 'text-fg-muted line-through' : 'text-fg-default')}>
+ {row.label}
+ </span>
+ <span className="block truncate text-xs text-fg-muted">{row.sub}</span>
+ </span>
+ </>
+ );
+ if (row.done || !row.act) return <div className="flex items-center gap-2.5 px-2 py-1.5">{body}</div>;
+ return (
+ <button
+ type="button"
+ onClick={row.act}
+ className="flex w-full items-center gap-2.5 rounded-row px-2 py-1.5 transition-colors hover:bg-bg-hover"
+ >
+ {body}
+ </button>
+ );
+}
+
+export function GetStartedChecklist() {
+ const guideOpen = useHomeStore((s) => s.guide.open);
+ const { visible, rows, doneCount, dismiss } = useGetStarted();
+ const [folded, setFolded] = useState(false);
+ if (!visible || guideOpen) return null;
+
+ const total = rows.length;
+ const allDone = doneCount === total;
+ const hide = () => {
+ dismiss();
+ pillToast('Get started hidden. Reopen it from Settings → Help.');
+ };
+
+ if (folded) {
+ return (
+ <Button
+ variant="quiet"
+ onClick={() => setFolded(false)}
+ className="fixed right-4 bottom-4 z-40 h-8 gap-1.5 rounded-pill border-border-default bg-bg-panel px-3 text-xs font-medium text-fg-default shadow-popover"
+ >
+ <Sparkles aria-hidden className="size-3.5" />
+ Get started · {doneCount}/{total}
+ <ChevronUp aria-hidden className="size-3.5 text-fg-muted" />
+ </Button>
+ );
+ }
+
+ return (
+ <section
+ aria-label="Get started"
+ className="fixed right-4 bottom-4 z-40 flex w-80 flex-col gap-1 rounded-card border border-border-default bg-bg-panel p-2 shadow-popover"
+ >
+ <div className="flex items-center gap-2 px-2 pt-1">
+ <Sparkles aria-hidden className="size-4 shrink-0 text-node-agent-ink" />
+ <div className="min-w-0 flex-1">
+ <h2 className="m-0 text-sm font-semibold text-fg-default">{allDone ? 'You’re all set!' : 'Get started'}</h2>
+ <p className="m-0 text-xs text-fg-muted">
+ {doneCount} of {total} done
+ </p>
+ </div>
+ <Button variant="quiet" size="icon-sm" onClick={() => setFolded(true)} aria-label="Fold the checklist" className="rounded-lg">
+ <ChevronDown className="size-4" />
+ </Button>
+ <Button variant="quiet" size="icon-sm" onClick={hide} aria-label="Hide the checklist" className="rounded-lg">
+ <X className="size-4" />
+ </Button>
+ </div>
+ <div className="px-2 pb-1.5">
+ <Progress value={(doneCount / total) * 100} aria-label="Steps done" className="h-1.5" />
+ </div>
+ <ul className="m-0 flex list-none flex-col p-0">
+ {rows.map((row) => (
+ <li key={row.id}>
+ <Step row={row} />
+ </li>
+ ))}
+ </ul>
+ {allDone && (
+ <div className="px-2 pt-1 pb-1 text-center">
+ <ActionButton intent="run" onClick={hide}>
+ <Check aria-hidden className="size-4" />
+ Done
+ </ActionButton>
+ </div>
+ )}
+ </section>
+ );
+}
+
+export default GetStartedChecklist;
diff --git a/client/src/features/home/onboarding/WelcomeGuide.tsx b/client/src/features/home/onboarding/WelcomeGuide.tsx
new file mode 100644
index 00000000..85f79e28
--- /dev/null
+++ b/client/src/features/home/onboarding/WelcomeGuide.tsx
@@ -0,0 +1,148 @@
+/**
+ * The Welcome guide (onboarding handoff A): three steps over Home, Welcome,
+ * Connect an AI model and Your first hire, in the Settings dialog's shape
+ * (left nav, the page, a footer bar).
+ *
+ * It opens by itself the first time Home shows for an owner who has not
+ * finished it, and again from the header's Guide button or Settings > Help
+ * (useOnboarding). The nav reaches any step already visited, and Connect
+ * always. A step is ticked once passed; Connect is ticked as soon as any AI
+ * model is connected. Skip for now, the close button, Esc and a click
+ * outside finish the guide; the last step finishes it by creating a setup.
+ * Esc first closes what is open above the page: a disconnect confirmation
+ * (its own layer), then a provider's page.
+ */
+
+import { useId, useLayoutEffect, useRef } from 'react';
+import { ArrowLeft, ArrowRight, CircleCheck, KeyRound, Sparkles, UserPlus, X, type LucideIcon } from 'lucide-react';
+import { Tabs as TabsPrimitive } from 'radix-ui';
+import { OcLogo } from '@/components/brand/Logo';
+import { staggerSettings } from '@/components/catalog/stagger';
+import { ActionButton } from '@/components/ui/action-button';
+import { Button } from '@/components/ui/button';
+import Modal from '@/components/ui/Modal';
+import { cn } from '@/lib/utils';
+import { useConnectors } from '../data/connectors';
+import { GUIDE_STEPS, useHomeStore, type GuideStep } from '../state/homeStore';
+import { NAV_ITEM } from '../ui/nav';
+import { MicroLabel } from '../ui/primitives';
+import { ConnectStep } from './steps/ConnectStep';
+import { FirstHireStep } from './steps/FirstHireStep';
+import { WelcomeStep } from './steps/WelcomeStep';
+import { useOnboarding } from './useOnboarding';
+
+const NAV: Record<GuideStep, { title: string; icon: LucideIcon }> = {
+ welcome: { title: 'Welcome', icon: Sparkles },
+ connect: { title: 'Connect an AI model', icon: KeyRound },
+ 'first-hire': { title: 'Your first hire', icon: UserPlus },
+};
+
+export function WelcomeGuide() {
+ const guide = useOnboarding();
+ const { hasAi } = useConnectors();
+ const setProvider = useHomeStore((s) => s.setGuideProvider);
+ const navLabelId = useId();
+ const bodyRef = useRef<HTMLDivElement>(null);
+ const { open, step, index, furthest, provider } = guide;
+
+ // The page's blocks rise in when the guide opens or the step changes.
+ useLayoutEffect(() => {
+ if (open) staggerSettings(bodyRef.current);
+ }, [open, step]);
+
+ // A provider's page carries its own way back.
+ const onPage = step === 'connect' && provider !== null;
+ const showNext = !onPage && (step === 'welcome' || (step === 'connect' && hasAi));
+ const showLater = !onPage && step === 'connect' && !hasAi;
+
+ return (
+ <Modal
+ isOpen={open}
+ onClose={guide.skip}
+ onEscapeKeyDown={(event) => {
+ if (!onPage) return;
+ event.preventDefault();
+ setProvider(null);
+ }}
+ title="Welcome guide"
+ hideHeader
+ motion="spring"
+ scrollableBody={false}
+ maxWidth="min(var(--w-guide), calc(100vw - 3rem))"
+ maxHeight="min(var(--h-guide), calc(100vh - 3rem))"
+ className="rounded-panel bg-bg-panel shadow-dialog"
+ >
+ <TabsPrimitive.Root
+ orientation="vertical"
+ value={step}
+ onValueChange={(next) => guide.goTo(next as GuideStep)}
+ className="flex h-full min-h-0"
+ >
+ <div className="flex w-(--w-settings-nav) shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-border-default px-3 py-4">
+ <MicroLabel className="px-2.5 pt-3.5 pb-1.5">
+ <span id={navLabelId}>Get started</span>
+ </MicroLabel>
+ <TabsPrimitive.List aria-labelledby={navLabelId} className="flex flex-col gap-0.5">
+ {GUIDE_STEPS.map((id, i) => {
+ const { title, icon } = NAV[id];
+ const done = i < index || (id === 'connect' && hasAi);
+ const Icon = done && i !== index ? CircleCheck : icon;
+ return (
+ <TabsPrimitive.Trigger key={id} value={id} disabled={i > furthest && id !== 'connect'} className={NAV_ITEM}>
+ <Icon aria-hidden strokeWidth={1.75} className={cn('size-4.25', done && 'text-action-run-ink')} />
+ {title}
+ </TabsPrimitive.Trigger>
+ );
+ })}
+ </TabsPrimitive.List>
+ <div className="mt-auto px-2.5 pt-3.5">
+ <OcLogo size="settings" wordmark={false} />
+ </div>
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div ref={bodyRef} className="min-h-0 flex-1 overflow-y-auto">
+ <TabsPrimitive.Content value="welcome" className="outline-none">
+ <WelcomeStep />
+ </TabsPrimitive.Content>
+ <TabsPrimitive.Content value="connect" className="outline-none">
+ <ConnectStep onFinish={guide.complete} />
+ </TabsPrimitive.Content>
+ <TabsPrimitive.Content value="first-hire" className="outline-none">
+ <FirstHireStep onDone={guide.complete} onNeedsModel={() => guide.goTo('connect')} />
+ </TabsPrimitive.Content>
+ </div>
+ <div className="flex items-center gap-2 border-t border-border-default bg-bg-panel px-6 py-3.5">
+ <Button variant="quiet" onClick={guide.skip} className="h-8 px-2.5">
+ Skip for now
+ </Button>
+ <span className="ml-auto font-mono text-2xs text-fg-faint">
+ {index + 1} / {GUIDE_STEPS.length}
+ </span>
+ {guide.back && !onPage && (
+ <Button variant="quiet" onClick={guide.back} className="h-8 gap-1.5 border-border-strong px-3 font-semibold text-fg-default">
+ <ArrowLeft aria-hidden />
+ Back
+ </Button>
+ )}
+ {showNext && guide.next && (
+ <ActionButton intent="tools" onClick={guide.next}>
+ Next
+ <ArrowRight aria-hidden className="size-4" />
+ </ActionButton>
+ )}
+ {showLater && guide.next && (
+ <Button variant="quiet" onClick={guide.next} className="h-8 px-3 font-semibold">
+ I’ll do this later
+ </Button>
+ )}
+ </div>
+ </div>
+ </TabsPrimitive.Root>
+ <Button variant="quiet" size="icon" onClick={guide.skip} aria-label="Close guide" className="absolute top-3.5 right-3.5 z-10">
+ <X />
+ </Button>
+ </Modal>
+ );
+}
+
+export default WelcomeGuide;
diff --git a/client/src/features/home/onboarding/getStartedItems.ts b/client/src/features/home/onboarding/getStartedItems.ts
new file mode 100644
index 00000000..d1f54d65
--- /dev/null
+++ b/client/src/features/home/onboarding/getStartedItems.ts
@@ -0,0 +1,22 @@
+/**
+ * The Get started checklist's steps, in order (onboarding handoff D). What
+ * each says under its label depends on the team, so useGetStarted writes it.
+ */
+
+import type { LucideIcon } from 'lucide-react';
+import { KeyRound, MessageCircle, ShieldCheck, UserPlus } from 'lucide-react';
+
+export type GetStartedItemId = 'connect-ai' | 'hire' | 'say-hello' | 'approve-draft';
+
+export interface GetStartedItemDef {
+ id: GetStartedItemId;
+ label: string;
+ icon: LucideIcon;
+}
+
+export const GET_STARTED_ITEMS: readonly GetStartedItemDef[] = [
+ { id: 'connect-ai', label: 'Connect an AI model', icon: KeyRound },
+ { id: 'hire', label: 'Hire your first employee', icon: UserPlus },
+ { id: 'say-hello', label: 'Say hello', icon: MessageCircle },
+ { id: 'approve-draft', label: 'Approve a first draft', icon: ShieldCheck },
+];
diff --git a/client/src/features/home/onboarding/steps/ConnectStep.tsx b/client/src/features/home/onboarding/steps/ConnectStep.tsx
new file mode 100644
index 00000000..68bfb699
--- /dev/null
+++ b/client/src/features/home/onboarding/steps/ConnectStep.tsx
@@ -0,0 +1,95 @@
+/**
+ * Guide step 2, Connect an AI model (onboarding handoff A2): the shared
+ * credentials browser, cut to AI models. Every AI provider shows (no
+ * "Show all" cap, so models that run on this computer are not hidden),
+ * Yours counts AI models only, and there is no category filter.
+ *
+ * Connect and Manage open the provider's page in place of the list
+ * (ProviderPage, the same page the credentials dialog shows). The list stays
+ * mounted underneath, hidden, so a card that turns connected still glows
+ * and reports it: then a pill says so, and the step returns to the list
+ * after a connect (Manage stays open). When the last step's job is waiting
+ * for a model, connecting one finishes the guide and sends it. Back returns
+ * focus to the card it came from.
+ */
+
+import { useEffect, useMemo, useRef } from 'react';
+import { CredentialsBrowser, type CredentialsBrowserCopy } from '@/components/credentials/CredentialsBrowser';
+import { ProviderPage } from '@/components/credentials/ProviderPage';
+import { isConnected, useCredentialsCatalogue } from '../../data/connectors';
+import { useJobComposer } from '../../genui';
+import { useHomeStore } from '../../state/homeStore';
+import { pillToast } from '../../ui/pillToast';
+
+const AI_COPY = (connected: boolean): CredentialsBrowserCopy => ({
+ title: connected ? 'You’re connected' : 'Connect an AI model',
+ searchPlaceholder: 'Search AI models',
+ listLabel: 'AI models to show',
+ discoverTitle: 'AI models',
+ yoursEmpty: { title: 'No AI models connected yet', detail: 'Connect one so your employees can think.' },
+});
+
+export function ConnectStep({ onFinish }: { onFinish: () => void }) {
+ const catalogue = useCredentialsCatalogue();
+ const providers = useMemo(() => catalogue.providers.filter((provider) => provider.consumer_category === 'ai'), [catalogue.providers]);
+ const view = { ...catalogue, providers, categories: [] };
+ const connected = providers.some(isConnected);
+ const selection = useHomeStore((s) => s.guide.provider);
+ const setProvider = useHomeStore((s) => s.setGuideProvider);
+ const job = useJobComposer();
+
+ // Back on the list: focus the card the page was opened from.
+ const shown = useRef<string | null>(null);
+ useEffect(() => {
+ if (selection) {
+ shown.current = selection.id;
+ return;
+ }
+ const id = shown.current;
+ shown.current = null;
+ if (id) document.querySelector<HTMLElement>(`[data-catalog-item="${id}"] button`)?.focus();
+ }, [selection]);
+
+ const onItemAdded = (id: string) => {
+ const name = providers.find((provider) => provider.id === id)?.name ?? 'Your AI model';
+ pillToast(`${name} is connected`);
+ const { guide } = useHomeStore.getState();
+ if (guide.pendingDraft) {
+ onFinish();
+ useHomeStore.getState().showHire();
+ void job.submit();
+ return;
+ }
+ if (guide.provider?.id === id && guide.provider.intent === 'connect') setProvider(null);
+ };
+
+ return (
+ <>
+ <div hidden={selection !== null}>
+ <CredentialsBrowser
+ catalogue={view}
+ onConnect={(id, intent = 'connect') => setProvider({ id, intent })}
+ copy={AI_COPY(connected)}
+ variant="embedded"
+ discoverLimit={null}
+ onItemAdded={onItemAdded}
+ />
+ </div>
+ {selection && (
+ <div className="px-3 pb-8">
+ <ProviderPage
+ view={view}
+ selection={selection}
+ backLabel="All AI models"
+ onBack={() => setProvider(null)}
+ visible
+ showHeading
+ autoFocusBack
+ />
+ </div>
+ )}
+ </>
+ );
+}
+
+export default ConnectStep;
diff --git a/client/src/features/home/onboarding/steps/FirstHireStep.tsx b/client/src/features/home/onboarding/steps/FirstHireStep.tsx
new file mode 100644
index 00000000..1b5cad94
--- /dev/null
+++ b/client/src/features/home/onboarding/steps/FirstHireStep.tsx
@@ -0,0 +1,82 @@
+/**
+ * Guide step 3, Your first hire (onboarding handoff A3, trimmed by R1): the
+ * starter chips and the same composer as Home, bound to the same draft.
+ * "Create their setup" finishes the guide, shows the hire view and sends
+ * the job; the setup then writes itself under Home's composer. Without an
+ * AI model nothing is sent: a notice and the button lead to step 2, and the
+ * job written so far waits there; connecting a model sends it
+ * (`pendingDraft`, ConnectStep).
+ */
+
+import { ActionButton } from '@/components/ui/action-button';
+import { useConnectors } from '../../data/connectors';
+import { useJobComposer } from '../../genui';
+import { Composer } from '../../hire/Composer';
+import { TemplateChips } from '../../hire/TemplateChips';
+import { HIRE_TEMPLATES } from '../../hire/templates';
+import { useHomeStore } from '../../state/homeStore';
+
+export function FirstHireStep({ onDone, onNeedsModel }: { onDone: () => void; onNeedsModel: () => void }) {
+ const job = useJobComposer();
+ const { connectedApps, hasAi, isLoading } = useConnectors();
+ const openSettings = useHomeStore((s) => s.openSettings);
+ const needsAi = !isLoading && !hasAi;
+ const picked = HIRE_TEMPLATES.find((template) => template.job === job.value.trim()) ?? null;
+ const apps = connectedApps.map((provider) => ({ id: provider.id, name: provider.name, icon_ref: provider.icon_ref }));
+
+ // Off to Connect; the job waits when there is one.
+ const toConnect = () => {
+ useHomeStore.getState().setGuidePendingDraft(job.value.trim() !== '');
+ onNeedsModel();
+ };
+
+ const create = () => {
+ if (needsAi) {
+ toConnect();
+ return;
+ }
+ onDone();
+ useHomeStore.getState().showHire();
+ void job.submit();
+ };
+
+ return (
+ <div className="flex flex-col gap-4.5 px-8 pt-6.5 pb-8">
+ <h2 data-stagger className="m-0 pr-10 text-lg font-semibold tracking-[-0.02em] text-fg-default">
+ Who should we hire first?
+ </h2>
+ <div data-stagger>
+ <TemplateChips picked={picked} onPick={(template) => job.pick(template.job)} disabled={job.working} className="justify-start" />
+ </div>
+ <div data-stagger>
+ <Composer
+ value={job.value}
+ onChange={job.onChange}
+ onSubmit={create}
+ refining={false}
+ onStopRefining={() => {}}
+ working={job.working}
+ apps={apps}
+ onOpenApps={() => openSettings('connectors')}
+ idleLabel="Create their setup"
+ flat
+ maxLength={2000}
+ />
+ </div>
+ {needsAi && (
+ <div
+ data-stagger
+ className="flex flex-wrap items-center gap-3 rounded-card border border-node-trigger-border bg-node-trigger-soft px-3.5 py-3"
+ >
+ <span aria-hidden className="size-2 shrink-0 rounded-full bg-node-trigger" />
+ <span className="min-w-50 flex-1 text-sm text-fg-muted">Connect an AI model first.</span>
+ <ActionButton intent="run" onClick={toConnect}>
+ Connect an AI model
+ </ActionButton>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default FirstHireStep;
diff --git a/client/src/features/home/onboarding/steps/WelcomeDemo.tsx b/client/src/features/home/onboarding/steps/WelcomeDemo.tsx
new file mode 100644
index 00000000..19d989b0
--- /dev/null
+++ b/client/src/features/home/onboarding/steps/WelcomeDemo.tsx
@@ -0,0 +1,251 @@
+/**
+ * The Welcome step's demo (onboarding handoff A1): three beats on the left,
+ * and on the right a stage drawing the one playing, a small version of what
+ * the owner will see. Describe the job (the composer), Check and hire (the
+ * setup card, as R2 draws it), Talk to them (a reply and a draft waiting
+ * for the owner).
+ *
+ * It plays on its own clock, one tick every TICK_MS: the job types itself a
+ * character a tick and Create pops when it is written, then the setup and
+ * the conversation rise in, each beat for BEAT_TICKS[beat] ticks, round and
+ * round while the Welcome step shows (it unmounts with the step). A bar
+ * under the playing beat fills as it plays, and clicking a beat starts it.
+ * Under reduced motion there is no clock: the conversation shows, still,
+ * and a click shows another beat.
+ *
+ * The stage is decoration (`aria-hidden`), made of token-classed spans,
+ * never real controls; the beats are the buttons.
+ */
+
+import { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { ArrowRight } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { RISE, animate, rise, stagger } from '@/lib/motion';
+import { useReducedMotion } from '@/lib/useReducedMotion';
+import { cn } from '@/lib/utils';
+import { AVATAR_CLASS, STATUS_PILL_CLASS } from '../../data/presentation';
+import { MicroLabel } from '../../ui/primitives';
+
+/** What the demo's owner types. */
+const DEMO_JOB = 'Answer WhatsApp messages and take bookings';
+
+const BEATS = [{ title: 'Describe the job' }, { title: 'Check and hire' }, { title: 'Talk to them' }] as const;
+
+/** One tick of the demo's clock, ms. */
+const TICK_MS = 80;
+/** How long each beat plays, in ticks: the job typed then a pause, the
+ * setup, the conversation. */
+const BEAT_TICKS = [DEMO_JOB.length + 16, 48, 56] as const;
+
+/** Where the demo is: the beat playing and how far into it. */
+interface Clock {
+ beat: number;
+ tick: number;
+}
+
+function nextTick({ beat, tick }: Clock): Clock {
+ return tick + 1 < BEAT_TICKS[beat] ? { beat, tick: tick + 1 } : { beat: (beat + 1) % BEATS.length, tick: 0 };
+}
+
+const ROUTINE = [
+ { label: 'When', text: 'A customer messages you', dot: 'bg-node-trigger', ink: 'text-node-trigger-ink' },
+ { label: 'They', text: 'Answer kindly and briefly', dot: 'bg-node-agent', ink: 'text-node-agent-ink' },
+ { label: 'Then', text: 'Note bookings for you', dot: 'bg-node-workflow', ink: 'text-node-workflow-ink' },
+] as const;
+
+const STAGE_CARD = 'flex w-full max-w-75 flex-col border border-border-default bg-bg-panel shadow-float';
+
+/** A small invert pill, like the composer's Create and the setup card's Hire. */
+function MiniPill({ label }: { label: string }) {
+ return (
+ <span className="inline-flex h-7 items-center gap-1 rounded-pill bg-fg-default px-3 text-xs font-semibold whitespace-nowrap text-bg-app">
+ {label}
+ <ArrowRight className="size-3.5" strokeWidth={2.25} />
+ </span>
+ );
+}
+
+/** A stage card rising in as its beat begins. */
+function useRiseIn<T extends HTMLElement>() {
+ const ref = useRef<T>(null);
+ useLayoutEffect(() => {
+ rise(ref.current);
+ }, []);
+ return ref;
+}
+
+/** The job typed so far; Create pops once it is all written. */
+function MiniComposer({ typed }: { typed: string }) {
+ const ref = useRiseIn<HTMLDivElement>();
+ const pillRef = useRef<HTMLSpanElement>(null);
+ const written = typed.length === DEMO_JOB.length;
+ useLayoutEffect(() => {
+ if (written) {
+ animate(pillRef.current, [{ opacity: 0.35, transform: 'scale(0.94)' }, { opacity: 1, transform: 'none' }], {
+ duration: 'chip-pop',
+ easing: 'overshoot',
+ });
+ }
+ }, [written]);
+ return (
+ <div ref={ref} className={cn(STAGE_CARD, 'gap-3 rounded-draft pt-3 pr-3 pb-2.5 pl-3.5')}>
+ <p className="m-0 min-h-10.5 text-row leading-normal text-fg-default">
+ {typed}
+ <span className="opencompany-caret-blink ml-px inline-block h-3.75 w-0.5 translate-y-0.5 bg-fg-default" />
+ </p>
+ <div className="flex items-center gap-2">
+ <span className="inline-flex h-6.5 items-center rounded-pill border border-border-default px-2.5 text-xs whitespace-nowrap text-fg-muted">
+ 0 apps
+ </span>
+ <span ref={pillRef} className={cn('ml-auto', !written && 'scale-94 opacity-35')}>
+ <MiniPill label="Create" />
+ </span>
+ </div>
+ </div>
+ );
+}
+
+function MiniSetup() {
+ const ref = useRiseIn<HTMLDivElement>();
+ const rowsRef = useRef<HTMLDivElement>(null);
+ const hireRef = useRef<HTMLSpanElement>(null);
+ useLayoutEffect(() => {
+ const rows = rowsRef.current?.querySelectorAll('[data-demo-row]');
+ if (rows) stagger(rows, RISE, { base: 150, step: 150, duration: 'follow-in', easing: 'spring' });
+ rise(hireRef.current, { delay: 650, duration: 'follow-in' });
+ }, []);
+ return (
+ <div ref={ref} className={cn(STAGE_CARD, 'gap-3 rounded-panel p-3.5')}>
+ <div className="flex items-center gap-2.5">
+ <span className={cn('grid size-8.5 shrink-0 place-items-center rounded-full border-2 text-base font-semibold', AVATAR_CLASS.agent)}>
+ M
+ </span>
+ <span className="flex min-w-0 flex-col">
+ <span className="text-base font-semibold text-fg-default">Maya</span>
+ <span className="truncate text-xs text-fg-muted">Receptionist · WhatsApp</span>
+ </span>
+ </div>
+ <div ref={rowsRef} className="relative flex flex-col gap-1.5">
+ <span className="absolute top-2 bottom-2 left-0.75 w-px bg-border-default" />
+ {ROUTINE.map((row) => (
+ <div key={row.label} data-demo-row className="relative grid grid-cols-[8px_40px_minmax(0,1fr)] items-center gap-2 text-meta">
+ <span className={cn('size-1.75 rounded-full ring-3 ring-bg-panel', row.dot)} />
+ <span className={cn('font-mono text-2xs tracking-label uppercase', row.ink)}>{row.label}</span>
+ <span className="truncate text-fg-default">{row.text}</span>
+ </div>
+ ))}
+ </div>
+ <div className="flex items-center gap-2 border-t border-border-default pt-2.5">
+ <span className="inline-flex h-4 w-7 shrink-0 items-center justify-end rounded-pill border border-action-run-border bg-action-run-hover px-0.5">
+ <span className="size-2.75 rounded-full bg-action-run-ink" />
+ </span>
+ <span className="flex-1 text-xs text-fg-muted">Ask before sending</span>
+ <span ref={hireRef}>
+ <MiniPill label="Hire Maya" />
+ </span>
+ </div>
+ </div>
+ );
+}
+
+function MiniTalk({ name }: { name: string }) {
+ const ref = useRiseIn<HTMLDivElement>();
+ const replyRef = useRef<HTMLDivElement>(null);
+ const draftRef = useRef<HTMLDivElement>(null);
+ useLayoutEffect(() => {
+ rise(replyRef.current, { delay: 450, duration: 'follow-in' });
+ rise(draftRef.current, { delay: 950 });
+ }, []);
+ return (
+ <div ref={ref} className="flex w-full max-w-75 flex-col gap-2.5">
+ <span className="self-end rounded-card rounded-br-sm bg-bg-active px-3 py-2 text-sm text-fg-default">Hi Maya!</span>
+ <div ref={replyRef} className="grid grid-cols-[26px_minmax(0,1fr)] gap-2.25">
+ <span className={cn('grid size-6.5 place-items-center rounded-full border text-2xs font-semibold', AVATAR_CLASS.agent)}>M</span>
+ <span className="pt-0.75 text-sm leading-normal text-fg-default">
+ Hi{name ? ` ${name}` : ''}! Here’s a reply for Priya. Nothing goes out until you say so.
+ </span>
+ </div>
+ <div ref={draftRef} className="ml-8.75 flex flex-col rounded-card border border-border-default bg-bg-elevated shadow-float">
+ <div className="flex items-center gap-1.5 border-b border-border-default px-2.5 py-2">
+ <MicroLabel>WhatsApp</MicroLabel>
+ <span className="text-xs text-fg-muted">to Priya</span>
+ <span className={cn('ml-auto inline-flex h-4.5 items-center rounded-pill border px-1.75 text-2xs font-medium whitespace-nowrap', STATUS_PILL_CLASS.waiting)}>
+ Needs you
+ </span>
+ </div>
+ <p className="m-0 px-2.5 py-2 text-xs leading-normal text-fg-default">We have a free slot on Thursday at 10:30. Shall I note it down?</p>
+ <div className="flex justify-end gap-1.5 border-t border-border-default px-2.5 py-2">
+ <span className="inline-flex h-6 items-center rounded-md border border-border-strong px-2.25 text-2xs font-semibold text-fg-default">
+ Discard
+ </span>
+ <span className="inline-flex h-6 items-center rounded-md border border-action-run-border bg-action-run-soft px-2.5 text-2xs font-semibold text-action-run-ink">
+ Send
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function WelcomeDemo({ name }: { name: string }) {
+ const reduced = useReducedMotion();
+ const [clock, setClock] = useState<Clock>(() => (reduced ? { beat: 2, tick: 0 } : { beat: 0, tick: 0 }));
+ useEffect(() => {
+ if (reduced) return;
+ const timer = window.setInterval(() => setClock(nextTick), TICK_MS);
+ return () => window.clearInterval(timer);
+ }, [reduced]);
+ const { beat, tick } = clock;
+ // Still, the job shows written.
+ const typed = reduced ? DEMO_JOB : DEMO_JOB.slice(0, tick);
+ return (
+ <div data-stagger className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.15fr)] gap-4.5">
+ <div className="flex flex-col gap-1.5">
+ {BEATS.map((b, i) => {
+ const active = i === beat;
+ return (
+ <Button
+ key={b.title}
+ variant="quiet"
+ aria-current={active ? 'step' : undefined}
+ onClick={() => setClock({ beat: i, tick: 0 })}
+ className={cn(
+ 'relative grid h-auto grid-cols-[26px_minmax(0,1fr)] items-start justify-normal gap-3 overflow-hidden rounded-card border px-3.5 py-3.25 text-left whitespace-normal hover:bg-bg-elevated',
+ active ? 'border-border-default bg-bg-elevated shadow-card' : 'border-transparent',
+ )}
+ >
+ <span
+ className={cn(
+ 'grid size-6.5 place-items-center rounded-full border font-mono text-2xs font-semibold transition-colors duration-(--dur-slow)',
+ active ? 'border-fg-default bg-fg-default text-bg-app' : i < beat ? 'border-fg-default text-fg-default' : 'border-border-default text-fg-muted',
+ )}
+ >
+ {i + 1}
+ </span>
+ <span className={cn('pt-0.75 text-base font-semibold transition-colors duration-(--dur-slow)', active ? 'text-fg-default' : 'text-fg-muted')}>
+ {b.title}
+ </span>
+ {active && !reduced && (
+ // How far the beat has played: the clock's own value.
+ <span
+ data-beat-progress
+ aria-hidden
+ className="absolute inset-x-0 bottom-0 h-0.5 origin-left bg-fg-default opacity-70 transition-transform ease-linear"
+ style={{ transform: `scaleX(${tick / BEAT_TICKS[i]})`, transitionDuration: `${TICK_MS}ms` }}
+ />
+ )}
+ </Button>
+ );
+ })}
+ </div>
+ <div
+ aria-hidden
+ className="home-welcome-stage relative grid min-h-68 place-items-center overflow-hidden rounded-panel border border-border-default p-5.5"
+ >
+ {beat === 0 ? <MiniComposer typed={typed} /> : beat === 1 ? <MiniSetup /> : <MiniTalk name={name} />}
+ </div>
+ </div>
+ );
+}
+
+export default WelcomeDemo;
diff --git a/client/src/features/home/onboarding/steps/WelcomeStep.tsx b/client/src/features/home/onboarding/steps/WelcomeStep.tsx
new file mode 100644
index 00000000..e27cd3ef
--- /dev/null
+++ b/client/src/features/home/onboarding/steps/WelcomeStep.tsx
@@ -0,0 +1,26 @@
+/**
+ * Guide step 1 (onboarding handoff A1, trimmed by R1): who the guide is for,
+ * one line on what OpenCompany does, and the three-beat demo.
+ */
+
+import { callName, useOwnerSettings } from '../../data/profile';
+import { MicroLabel } from '../../ui/primitives';
+import { WelcomeDemo } from './WelcomeDemo';
+
+export function WelcomeStep() {
+ const { data: settings } = useOwnerSettings();
+ const name = callName(settings);
+ return (
+ <div className="flex flex-col gap-6 px-8 pt-7.5 pb-6.5">
+ <div data-stagger className="flex flex-col gap-2.5 pr-10">
+ <MicroLabel className="text-node-agent-ink">{name ? `Welcome, ${name}` : 'Welcome'}</MicroLabel>
+ <h2 className="m-0 text-headline leading-hero font-semibold tracking-hero text-balance text-fg-default">
+ Your AI team, hired in plain words.
+ </h2>
+ </div>
+ <WelcomeDemo name={name} />
+ </div>
+ );
+}
+
+export default WelcomeStep;
diff --git a/client/src/features/home/onboarding/useGetStarted.ts b/client/src/features/home/onboarding/useGetStarted.ts
new file mode 100644
index 00000000..48583fe0
--- /dev/null
+++ b/client/src/features/home/onboarding/useGetStarted.ts
@@ -0,0 +1,120 @@
+/**
+ * The Get started checklist's state (onboarding handoff D), from what Home
+ * already knows:
+ *
+ * - Connect an AI model: one is connected now.
+ * - Hire your first employee: someone on the team was hired.
+ * - Say hello: the owner has written to their first hire. Latched in the
+ * owner's settings (`getting_started_said_hello`), since New conversation
+ * or a restart empties the thread.
+ * - Approve a first draft: the owner sent a draft an employee held for them
+ * (`approval_lifecycle` decided as approved, heard while Home is open).
+ * Latched (`getting_started_approved_draft`).
+ *
+ * Each latch is written once: the saved flag guards it. The card shows once
+ * the Welcome guide is finished, until the owner hides it (Settings > Help
+ * shows it again).
+ */
+
+import { useEffect } from 'react';
+import type { LucideIcon } from 'lucide-react';
+import { useWebSocketActions } from '@/contexts/WebSocketContext';
+import { useChatThread } from '@/features/chat';
+import { useSaveUserSettingsMutationCore } from '@/hooks/useUserSettingsQuery';
+import { isConnected, useConnectors } from '../data/connectors';
+import { useEmployeesQuery } from '../data/employees';
+import { useOwnerSettings } from '../data/profile';
+import type { EmployeeSummary } from '../data/schemas';
+import { useHomeStore } from '../state/homeStore';
+import { GET_STARTED_ITEMS, type GetStartedItemId } from './getStartedItems';
+
+const SAID_HELLO = 'getting_started_said_hello';
+const APPROVED_DRAFT = 'getting_started_approved_draft';
+
+export interface GetStartedRow {
+ id: GetStartedItemId;
+ label: string;
+ icon: LucideIcon;
+ /** Under the label: what to do, or what was done. */
+ sub: string;
+ done: boolean;
+ /** Where a click on a step not done yet takes the owner. */
+ act?: () => void;
+}
+
+/** The employee hired first. */
+function firstHire(team: readonly EmployeeSummary[]): EmployeeSummary | null {
+ let first: EmployeeSummary | null = null;
+ for (const employee of team) {
+ if (employee.derived || !employee.hired_at) continue;
+ if (!first || Date.parse(employee.hired_at) < Date.parse(first.hired_at ?? '')) first = employee;
+ }
+ return first;
+}
+
+export function useGetStarted() {
+ const { data: settings, isSuccess } = useOwnerSettings();
+ const { sendRequest, addEventListener } = useWebSocketActions();
+ const { mutate: save } = useSaveUserSettingsMutationCore(sendRequest);
+ const { providers, hasAi } = useConnectors();
+ const team = useEmployeesQuery().data;
+ const first = firstHire(team ?? []);
+
+ const saidHello = Boolean(settings?.[SAID_HELLO]);
+ const approved = Boolean(settings?.[APPROVED_DRAFT]);
+ // Their first hire's conversation, read only until the owner has written to them.
+ const thread = useChatThread(saidHello ? null : (first?.workflow_id ?? null), 'all');
+ const wroteToFirst = Boolean(thread.data?.messages.some((message) => message.role === 'user'));
+
+ useEffect(() => {
+ if (isSuccess && wroteToFirst && !saidHello) save({ [SAID_HELLO]: true });
+ }, [isSuccess, wroteToFirst, saidHello, save]);
+
+ useEffect(() => {
+ if (!isSuccess || approved) return;
+ return addEventListener('approval_lifecycle', (event) => {
+ if (event?.type === 'com.opencompany.approval.decided' && event?.data?.status === 'approved') save({ [APPROVED_DRAFT]: true });
+ });
+ }, [isSuccess, approved, addEventListener, save]);
+
+ const ai = providers.find((provider) => provider.consumer_category === 'ai' && isConnected(provider));
+ const waiting = (team ?? []).find((employee) => employee.pending_approvals > 0) ?? first;
+ const home = useHomeStore.getState;
+ const state: Record<GetStartedItemId, Omit<GetStartedRow, 'id' | 'label' | 'icon'>> = {
+ 'connect-ai': {
+ done: hasAi,
+ sub: ai ? `${ai.name} is connected` : 'OpenAI, Anthropic, Gemini or a local model',
+ act: () => home().openGuide('connect'),
+ },
+ hire: {
+ done: first !== null,
+ sub: first ? `${first.name}, ${first.role}` : 'Describe a job or pick a starter',
+ act: () => home().showHire({ focus: true }),
+ },
+ 'say-hello': {
+ done: saidHello || wroteToFirst,
+ sub: first ? `Send ${first.name} a message` : 'Send your first hire a message',
+ act: first ? () => home().showEmployee(first.workflow_id) : undefined,
+ },
+ 'approve-draft': {
+ done: approved,
+ sub: 'They ask before sending anything',
+ act: waiting ? () => home().showEmployee(waiting.workflow_id) : undefined,
+ },
+ };
+ const rows: GetStartedRow[] = GET_STARTED_ITEMS.map((item) => ({ ...item, ...state[item.id] }));
+
+ return {
+ visible: isSuccess && Boolean(settings?.onboarding_completed) && !settings?.getting_started_dismissed,
+ rows,
+ doneCount: rows.filter((row) => row.done).length,
+ dismiss: () => save({ getting_started_dismissed: true }),
+ };
+}
+
+/** Settings > Help: show the hidden checklist again. */
+export function useShowGetStarted(): () => void {
+ const { sendRequest } = useWebSocketActions();
+ const { mutate: save } = useSaveUserSettingsMutationCore(sendRequest);
+ return () => save({ getting_started_dismissed: false });
+}
diff --git a/client/src/features/home/onboarding/useOnboarding.ts b/client/src/features/home/onboarding/useOnboarding.ts
new file mode 100644
index 00000000..fd38d575
--- /dev/null
+++ b/client/src/features/home/onboarding/useOnboarding.ts
@@ -0,0 +1,67 @@
+/**
+ * The Welcome guide's moves and saved progress.
+ *
+ * Whether the guide is open, and at which step, lives in homeStore
+ * (`guide`): the header's Guide button and Settings > Help open it
+ * directly, and since nothing counts replays, a remount (a mode switch
+ * re-keys the screens) never reopens it. This hook adds the saved side:
+ * once per session it opens the guide for an owner who has not finished it
+ * (`onboarding_completed`, at their saved `onboarding_step`), and it saves
+ * the step on every move. Skip, the close button, Esc and a click outside
+ * finish the guide at the step reached; "Create their setup" finishes it.
+ * A replay never marks it unfinished.
+ *
+ * Mount it once (WelcomeGuide). It reads the settings through the stable
+ * actions context, so Home never re-renders on a WebSocket message.
+ */
+
+import { useCallback, useEffect } from 'react';
+import { useWebSocketActions } from '@/contexts/WebSocketContext';
+import { useSaveUserSettingsMutationCore } from '@/hooks/useUserSettingsQuery';
+import { useOwnerSettings } from '../data/profile';
+import { GUIDE_STEPS, useHomeStore, type GuideStep } from '../state/homeStore';
+
+export function useOnboarding() {
+ const guide = useHomeStore((s) => s.guide);
+ const { data: settings, isSuccess } = useOwnerSettings();
+ const { sendRequest } = useWebSocketActions();
+ const { mutate: save } = useSaveUserSettingsMutationCore(sendRequest);
+
+ useEffect(() => {
+ if (isSuccess && settings) useHomeStore.getState().checkGuide(settings);
+ }, [isSuccess, settings]);
+
+ const goTo = useCallback(
+ (step: GuideStep) => {
+ useHomeStore.getState().goToGuideStep(step);
+ save({ onboarding_step: GUIDE_STEPS.indexOf(step) });
+ },
+ [save],
+ );
+
+ const finish = useCallback(
+ (step: number) => {
+ useHomeStore.getState().closeGuide();
+ save({ onboarding_completed: true, onboarding_step: step });
+ },
+ [save],
+ );
+
+ const index = GUIDE_STEPS.indexOf(guide.step);
+ const nextStep: GuideStep | undefined = GUIDE_STEPS[index + 1];
+ const prevStep: GuideStep | undefined = GUIDE_STEPS[index - 1];
+
+ return {
+ ...guide,
+ index,
+ goTo,
+ /** Undefined on the last step. */
+ next: nextStep ? () => goTo(nextStep) : undefined,
+ /** Undefined on the first step. */
+ back: prevStep ? () => goTo(prevStep) : undefined,
+ /** Skip for now, the close button, Esc: done, at the step reached. */
+ skip: () => finish(index),
+ /** The guide's end: the owner asked for their first setup. */
+ complete: () => finish(GUIDE_STEPS.length),
+ };
+}
diff --git a/client/src/features/home/orb/OrbSlot.tsx b/client/src/features/home/orb/OrbSlot.tsx
index aec1dcb4..c3d23580 100644
--- a/client/src/features/home/orb/OrbSlot.tsx
+++ b/client/src/features/home/orb/OrbSlot.tsx
@@ -1,17 +1,20 @@
/**
- * Where the orb sits on the hire and employee views (design handoff "Orb").
- * The slot reserves the orb's square and the orb, drawn behind the content,
- * glides into it. Where the orb cannot run, the slot shows the static mark.
+ * Where the orb sits: the hire and employee views, the Connecting screen
+ * and sign-in. The slot reserves the orb's square and the orb, drawn behind
+ * the content, glides into it; the newest slot mounted is the one it fills
+ * (orb.ts). Where the orb cannot run, the slot shows the static mark.
*/
import { useLayoutEffect, useRef } from 'react';
import { OcMark } from '@/components/brand/Logo';
import { cn } from '@/lib/utils';
-import { orbState, useOrbFallback } from './orb';
+import { popOrbSlot, pushOrbSlot, useOrbFallback } from './orb';
const SLOT_SIZE = {
hire: 'size-(--size-orb-hire)',
employee: 'size-(--size-orb-employee)',
+ connecting: 'size-(--size-orb-connecting)',
+ login: 'size-(--size-orb-login)',
} as const;
export function OrbSlot({ size }: { size: keyof typeof SLOT_SIZE }) {
@@ -20,10 +23,9 @@ export function OrbSlot({ size }: { size: keyof typeof SLOT_SIZE }) {
useLayoutEffect(() => {
const element = ref.current;
- orbState.slot = element;
- return () => {
- if (orbState.slot === element) orbState.slot = null;
- };
+ if (!element) return;
+ pushOrbSlot(element);
+ return () => popOrbSlot(element);
}, []);
return (
diff --git a/client/src/features/home/orb/OrbStage.tsx b/client/src/features/home/orb/OrbStage.tsx
index 01eee1e4..b853599e 100644
--- a/client/src/features/home/orb/OrbStage.tsx
+++ b/client/src/features/home/orb/OrbStage.tsx
@@ -1,12 +1,20 @@
/**
- * The orb's canvas host (design handoff orb/ORB.md): fills Home's main area
- * below the header, behind the content, and never takes pointer events.
+ * The orb's canvas host: behind the content, never taking pointer events.
+ * `home` fills Home's main area below the header; `screen` fills the whole
+ * window (the Connecting and sign-in screens). A stage mounted over another
+ * borrows the orb until it unmounts (orb.ts).
*/
import { useLayoutEffect, useRef } from 'react';
+import { cn } from '@/lib/utils';
import { mountOrb, unmountOrb } from './orb';
-export function OrbStage() {
+const FILL = {
+ home: 'absolute inset-x-0 top-(--h-home-header) bottom-0',
+ screen: 'fixed inset-0',
+} as const;
+
+export function OrbStage({ fill = 'home' }: { fill?: keyof typeof FILL }) {
const ref = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const element = ref.current;
@@ -14,13 +22,7 @@ export function OrbStage() {
mountOrb(element);
return () => unmountOrb(element);
}, []);
- return (
- <div
- ref={ref}
- aria-hidden
- className="pointer-events-none absolute inset-x-0 top-(--h-home-header) bottom-0 z-0 overflow-hidden"
- />
- );
+ return <div ref={ref} aria-hidden className={cn('pointer-events-none z-0 overflow-hidden', FILL[fill])} />;
}
export default OrbStage;
diff --git a/client/src/features/home/orb/__tests__/orb.test.ts b/client/src/features/home/orb/__tests__/orb.test.ts
new file mode 100644
index 00000000..694d51b3
--- /dev/null
+++ b/client/src/features/home/orb/__tests__/orb.test.ts
@@ -0,0 +1,166 @@
+/**
+ * The orb's lifecycle (orb.ts): stages and slots are stacks, so a screen
+ * mounted over another borrows the orb and hands it back; the engine loads
+ * once; a failed engine load shows the mark until the next stage tries
+ * again, while no WebGL, reduced motion and a lost context hold for good.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, renderHook } from '@testing-library/react';
+
+const engine = { attach: vi.fn(), detach: vi.fn(), dispose: vi.fn() };
+const createOrbEngine = vi.fn((onLost: () => void) => {
+ lose = onLost;
+ return engine;
+});
+let lose: () => void = () => {};
+
+vi.mock('../orbEngine', () => ({ createOrbEngine: (onLost: () => void) => createOrbEngine(onLost) }));
+
+import { setReducedMotion } from '@/test/waapi';
+import { mountOrb, orbState, popOrbSlot, pushOrbSlot, resetOrbForTests, unmountOrb, useOrbFallback } from '../orb';
+
+const element = () => document.createElement('div');
+
+/** Let the engine's chunk "load". */
+async function loaded() {
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+let restoreMotion: () => void = () => {};
+let getContext: ReturnType<typeof vi.spyOn>;
+
+beforeEach(() => {
+ resetOrbForTests();
+ engine.attach.mockClear();
+ engine.detach.mockClear();
+ engine.dispose.mockClear();
+ createOrbEngine.mockClear();
+ getContext = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({} as RenderingContext);
+});
+
+afterEach(() => {
+ restoreMotion();
+ restoreMotion = () => {};
+ getContext.mockRestore();
+ resetOrbForTests();
+});
+
+describe('slots', () => {
+ it('fill the newest slot, and the one under it again when it goes', () => {
+ const home = element();
+ const connecting = element();
+ pushOrbSlot(home);
+ pushOrbSlot(connecting);
+ expect(orbState.slot).toBe(connecting);
+ popOrbSlot(connecting);
+ expect(orbState.slot).toBe(home);
+ popOrbSlot(home);
+ expect(orbState.slot).toBeNull();
+ });
+
+ it('keep the newest slot when an older one goes first', () => {
+ const home = element();
+ const connecting = element();
+ pushOrbSlot(home);
+ pushOrbSlot(connecting);
+ popOrbSlot(home);
+ expect(orbState.slot).toBe(connecting);
+ });
+});
+
+describe('stages', () => {
+ it('load the engine once, and hand the orb back to the stage underneath', async () => {
+ const home = element();
+ const overlay = element();
+ mountOrb(home);
+ await loaded();
+ expect(createOrbEngine).toHaveBeenCalledTimes(1);
+ expect(engine.attach).toHaveBeenLastCalledWith(home);
+
+ mountOrb(overlay);
+ expect(engine.attach).toHaveBeenLastCalledWith(overlay);
+ unmountOrb(overlay);
+ expect(engine.detach).toHaveBeenCalledTimes(1);
+ expect(engine.attach).toHaveBeenLastCalledWith(home);
+ expect(createOrbEngine).toHaveBeenCalledTimes(1);
+ });
+
+ it('leave the orb where it is when a stage underneath goes', async () => {
+ const home = element();
+ const overlay = element();
+ mountOrb(home);
+ await loaded();
+ mountOrb(overlay);
+ unmountOrb(home);
+ expect(engine.detach).not.toHaveBeenCalled();
+ expect(engine.attach).toHaveBeenLastCalledWith(overlay);
+ });
+
+ it('attach to the newest stage once a slow engine loads', async () => {
+ const home = element();
+ const overlay = element();
+ mountOrb(home);
+ mountOrb(overlay);
+ await loaded();
+ expect(createOrbEngine).toHaveBeenCalledTimes(1);
+ expect(engine.attach).toHaveBeenCalledTimes(1);
+ expect(engine.attach).toHaveBeenLastCalledWith(overlay);
+ });
+});
+
+describe('the static mark', () => {
+ it('shows while the engine failed to load, and the next stage tries again', async () => {
+ const { result } = renderHook(() => useOrbFallback());
+ createOrbEngine.mockImplementationOnce(() => {
+ throw new Error('the chunk did not load');
+ });
+ const first = element();
+ mountOrb(first);
+ await loaded();
+ expect(result.current).toBe(true);
+
+ unmountOrb(first);
+ mountOrb(element());
+ await loaded();
+ expect(createOrbEngine).toHaveBeenCalledTimes(2);
+ expect(result.current).toBe(false);
+ });
+
+ it('holds without WebGL, and nothing tries again', async () => {
+ getContext.mockReturnValue(null);
+ const { result } = renderHook(() => useOrbFallback());
+ mountOrb(element());
+ await loaded();
+ expect(result.current).toBe(true);
+ getContext.mockReturnValue({} as RenderingContext);
+ mountOrb(element());
+ await loaded();
+ expect(createOrbEngine).not.toHaveBeenCalled();
+ expect(result.current).toBe(true);
+ });
+
+ it('holds under reduced motion', async () => {
+ restoreMotion = setReducedMotion(true);
+ const { result } = renderHook(() => useOrbFallback());
+ mountOrb(element());
+ await loaded();
+ expect(createOrbEngine).not.toHaveBeenCalled();
+ expect(result.current).toBe(true);
+ });
+
+ it('holds after the WebGL context is lost', async () => {
+ const { result } = renderHook(() => useOrbFallback());
+ mountOrb(element());
+ await loaded();
+ act(() => lose());
+ expect(engine.dispose).toHaveBeenCalledTimes(1);
+ expect(result.current).toBe(true);
+ mountOrb(element());
+ await loaded();
+ expect(createOrbEngine).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/features/home/orb/orb.ts b/client/src/features/home/orb/orb.ts
index 32cf7882..b3a68849 100644
--- a/client/src/features/home/orb/orb.ts
+++ b/client/src/features/home/orb/orb.ts
@@ -1,17 +1,26 @@
/**
- * Home's 3D orb (design handoff orb/ORB.md): what the engine reads each
- * frame (the slot to fill, the energy target, a spike), and its lifecycle.
- * three.js loads only when the orb first runs (orbEngine, its own chunk).
- * Leaving Home keeps the engine for the next visit; the app shell disposes
- * it. Without WebGL, under reduced motion, or after a lost WebGL context,
- * slots show the static mark instead.
+ * The 3D orb (design handoff orb, onboarding handoff R3): what the engine
+ * reads each frame (the slot to fill, the energy target, a spike, whether it
+ * waits for the server), and its lifecycle. three.js loads only when the orb
+ * first runs (orbEngine, its own chunk).
+ *
+ * Stages (OrbStage, the canvas host) and slots (OrbSlot, where the orb
+ * glides) are stacks: a screen mounted over another, such as Connecting
+ * over Home, borrows the orb while it shows and hands it back when it goes.
+ * Leaving every stage keeps the engine for the next one; the app disposes
+ * it (App.tsx).
+ *
+ * Slots show the static mark instead when the orb cannot run. No WebGL,
+ * reduced motion and a lost WebGL context hold for the session; an engine
+ * chunk that failed to load shows the mark until the next stage mounts,
+ * which tries again.
*/
import { useSyncExternalStore } from 'react';
import { prefersReducedMotion } from '@/lib/useReducedMotion';
/** The prototype's energy levels and event bursts. */
-export const ENERGY = { idle: 0.15, focus: 0.35, typing: 0.55, generating: 1 } as const;
+export const ENERGY = { idle: 0.15, focus: 0.35, typing: 0.55, generating: 1, waiting: 0.22 } as const;
export const SPIKE = {
hire: 1,
connect: 0.7,
@@ -23,6 +32,9 @@ export const SPIKE = {
draftReady: 0.8,
draftFailed: 0.4,
profileSaved: 0.7,
+ /** The server answered again (Connecting). */
+ connected: 1,
+ signedIn: 1,
} as const;
/** Read by the engine every frame; the engine decays `spike` itself. */
@@ -30,6 +42,8 @@ export const orbState = {
slot: null as HTMLElement | null,
target: ENERGY.idle as number,
spike: 0,
+ /** The server can't be reached: the orb slows, breathes and searches. */
+ waiting: false,
};
export function setEnergyTarget(target: number): void {
@@ -40,18 +54,34 @@ export function spikeOrb(amount: number): void {
orbState.spike = Math.max(orbState.spike, amount);
}
+export function setOrbWaiting(waiting: boolean): void {
+ orbState.waiting = waiting;
+}
+
interface OrbEngine {
attach(host: HTMLElement): void;
detach(): void;
dispose(): void;
}
+type Fallback = 'none' | 'missing' | 'latched';
+
let engine: OrbEngine | null = null;
let loading = false;
-let host: HTMLElement | null = null;
-let fallback = false;
+let fallback: Fallback = 'none';
+const hosts: HTMLElement[] = [];
+const slots: HTMLElement[] = [];
const listeners = new Set<() => void>();
+function top<T>(stack: readonly T[]): T | null {
+ return stack.length > 0 ? stack[stack.length - 1] : null;
+}
+
+function remove<T>(stack: T[], item: T): void {
+ const at = stack.lastIndexOf(item);
+ if (at !== -1) stack.splice(at, 1);
+}
+
function canRun(): boolean {
if (prefersReducedMotion()) return false;
try {
@@ -62,21 +92,23 @@ function canRun(): boolean {
}
}
-function showFallback(): void {
- fallback = true;
+function setFallback(next: Fallback): void {
+ if (fallback === next) return;
+ fallback = next;
listeners.forEach((listener) => listener());
}
-/** The stage mounted: draw the orb into it (loading it the first time). */
-export function mountOrb(element: HTMLElement): void {
- host = element;
+/** Draw the orb into the top stage, loading the engine the first time. */
+function show(): void {
+ const host = top(hosts);
+ if (!host) return;
if (engine) {
- engine.attach(element);
+ engine.attach(host);
return;
}
- if (loading || fallback) return;
+ if (loading || fallback === 'latched') return;
if (!canRun()) {
- showFallback();
+ setFallback('latched');
return;
}
loading = true;
@@ -86,26 +118,48 @@ export function mountOrb(element: HTMLElement): void {
engine = createOrbEngine(() => {
engine?.dispose();
engine = null;
- showFallback();
+ setFallback('latched');
});
- if (host) engine.attach(host);
+ setFallback('none');
+ show();
})
.catch(() => {
loading = false;
- showFallback();
+ setFallback('missing');
});
}
+/** A stage mounted: it hosts the orb until it unmounts. */
+export function mountOrb(element: HTMLElement): void {
+ hosts.push(element);
+ show();
+}
+
+/** A stage unmounted: the one under it, if any, gets the orb back. */
export function unmountOrb(element: HTMLElement): void {
- if (host !== element) return;
- host = null;
+ const wasTop = top(hosts) === element;
+ remove(hosts, element);
+ if (!wasTop) return;
engine?.detach();
+ show();
+}
+
+/** A slot mounted: the orb glides to it until it unmounts. */
+export function pushOrbSlot(element: HTMLElement): void {
+ slots.push(element);
+ orbState.slot = element;
+}
+
+export function popOrbSlot(element: HTMLElement): void {
+ remove(slots, element);
+ orbState.slot = top(slots);
}
export function disposeOrb(): void {
engine?.dispose();
engine = null;
- host = null;
+ hosts.length = 0;
+ slots.length = 0;
orbState.slot = null;
}
@@ -116,7 +170,7 @@ export function useOrbFallback(): boolean {
listeners.add(listener);
return () => listeners.delete(listener);
},
- () => fallback,
+ () => fallback !== 'none',
() => false,
);
}
@@ -125,7 +179,8 @@ export function useOrbFallback(): boolean {
export function resetOrbForTests(): void {
disposeOrb();
loading = false;
- fallback = false;
+ fallback = 'none';
orbState.target = ENERGY.idle;
orbState.spike = 0;
+ orbState.waiting = false;
}
diff --git a/client/src/features/home/orb/orbEngine.ts b/client/src/features/home/orb/orbEngine.ts
index 1604d9a4..5c57a7d5 100644
--- a/client/src/features/home/orb/orbEngine.ts
+++ b/client/src/features/home/orb/orbEngine.ts
@@ -1,7 +1,8 @@
/**
* The 3D orb's scene and frame loop: a port of the design prototype's
- * `initScene` (design_handoff_opencompany_home, reference/OpenCompany
- * Home.dc.html; spec in orb/ORB.md). Loaded only through orb.ts.
+ * `initScene` (the Home handoff's reference page), with the onboarding
+ * handoff's waiting mode and sizing fixes (its oc-orb.js). Loaded only
+ * through orb.ts.
*
* Its shapes are the logo's mark in 3D (brand/geometry.ts): the C, a ring
* open on one side, around the core, and the council, three heads each
@@ -9,6 +10,16 @@
* council turns more slowly the same way (heads first), and a line from the
* core to each head carries a packet. It keeps its own colours.
*
+ * While the server can't be reached (`orbState.waiting`) it eases into a
+ * waiting mode over about a second: slower, a double heartbeat in the core,
+ * the council breathing out and back in turn, one searching ping per line,
+ * a little dimmer. It eases back the same way.
+ *
+ * The host is measured every frame and the drawing buffer follows it;
+ * nothing is drawn until the host has a size, so a first 0x0 measure never
+ * leaves a 1x1 buffer. Frames stop while the page is hidden or the window
+ * is blurred (lib/pageActivity).
+ *
* Changes from the prototype's three r149 for current three:
* - colour management off and sRGB output, so colours read as authored;
* - lights are physically based now: intensities x PI, and the point
@@ -50,8 +61,9 @@ import {
Vector3,
WebGLRenderer,
} from 'three';
+import { pageActivity } from '@/lib/pageActivity';
import { prefersReducedMotion } from '@/lib/useReducedMotion';
-import { orbState } from './orb';
+import { ENERGY, orbState } from './orb';
ColorManagement.enabled = false;
@@ -71,6 +83,11 @@ const HEAD_D = 1.916;
* head, and rounds off over its first 4 degrees. */
const CRESCENT = { from: (16 * PI) / 180, to: (37 * PI) / 180, dome: 4 / 21, r0: 1.83, dr: 0.28, thick: 0.26 };
+/** Waiting: the heartbeat's period (s), and how far a member breathes out
+ * (a share of its distance from the core). */
+const BEAT_S = 1.8;
+const BREATH = 0.11;
+
/** The C's open end: a flat disc across the tube at `angle`, facing out of it. */
function ringCap(angle: number, facing: 1 | -1): BufferGeometry {
const out = new Vector3(Math.sin(angle), -Math.cos(angle), 0).multiplyScalar(facing);
@@ -224,7 +241,8 @@ export function createOrbEngine(onLost: () => void) {
orb.add(coreGlow, ringGlow);
// The council: a head and its crescent every 120 degrees from the top, one
- // material each. The lines and packets sit beside it in the tilted plane.
+ // material each, grouped so a member can breathe out as one. The lines and
+ // packets sit beside it in the tilted plane.
const council = new Group();
tilt.add(council);
const members = [0xff79c6, 0xf1fa8c, 0x50fa7b].map((col, i) => {
@@ -234,7 +252,9 @@ export function createOrbEngine(onLost: () => void) {
head.position.set(Math.cos(angle) * HEAD_D, Math.sin(angle) * HEAD_D, 0);
const halo = glow(col, 1.2, 0.5);
head.add(halo);
- council.add(head, new Mesh(crescentGeometry(angle), mat));
+ const member = new Group();
+ member.add(head, new Mesh(crescentGeometry(angle), mat));
+ council.add(member);
const lg = new BufferGeometry();
lg.setAttribute('position', new BufferAttribute(new Float32Array(33 * 3), 3));
const line = new Line(lg, new LineBasicMaterial({ color: 0x6272a4, transparent: true, opacity: 0.7 }));
@@ -242,7 +262,7 @@ export function createOrbEngine(onLost: () => void) {
tilt.add(line, pk);
const cd = new Color(col);
const cl = new Color([0x060607, 0x0e0f12][i % 2]);
- return { angle, mat, halo, line, pk, cd, cl, off: Math.random() };
+ return { angle, member, mat, halo, line, pk, cd, cl, off: Math.random() };
});
const N = 900;
@@ -285,20 +305,21 @@ export function createOrbEngine(onLost: () => void) {
p2: new Color(0x8be9fd),
};
const bez = new QuadraticBezierCurve3(new Vector3(), new Vector3(), new Vector3());
+ const ping = new Vector3();
const vh = 2 * 9 * Math.tan((17.5 * PI) / 180);
let host: HTMLElement | null = null;
- let size = { w: 1, h: 1 };
- const resize = () => {
- if (!host) return;
- const w = host.clientWidth || 1;
- const h = host.clientHeight || 1;
+ /** The host's size in CSS pixels; null until it has one. */
+ let size: { w: number; h: number } | null = null;
+ const measure = (element: HTMLElement) => {
+ const w = element.clientWidth;
+ const h = element.clientHeight;
+ if (w <= 0 || h <= 0 || (size && size.w === w && size.h === h)) return;
R.setSize(w, h, false);
cam.aspect = w / h;
cam.updateProjectionMatrix();
size = { w, h };
};
- const ro = new ResizeObserver(resize);
let mx = 0;
let my = 0;
const onMove = (e: PointerEvent) => {
@@ -310,6 +331,8 @@ export function createOrbEngine(onLost: () => void) {
let last = 0;
let t = 0;
let energy = orbState.target;
+ /** How far into the waiting mode, 0..1. */
+ let wf = orbState.waiting ? 1 : 0;
let placed = false;
let rx = 0;
let ry = 0;
@@ -321,10 +344,13 @@ export function createOrbEngine(onLost: () => void) {
const loop = (now: number) => {
raf = requestAnimationFrame(loop);
if (!host) return;
+ measure(host);
+ if (!size) return;
const dt = Math.min((now - last) / 1000, 0.05);
last = now;
const mot = prefersReducedMotion() ? 0.15 : 1;
- energy += (orbState.target - energy) * Math.min(1, dt * 3);
+ wf += ((orbState.waiting ? 1 : 0) - wf) * Math.min(1, dt * 1.6);
+ energy += (orbState.target * (1 - wf) + ENERGY.waiting * wf - energy) * Math.min(1, dt * 3);
orbState.spike = Math.max(0, orbState.spike - dt * 0.6);
const e = Math.max(energy, orbState.spike);
t += dt * mot * (0.4 + e * 1.8);
@@ -355,29 +381,43 @@ export function createOrbEngine(onLost: () => void) {
rx += (my * 0.25 - rx) * k;
ry += (mx * 0.4 - ry) * k;
orb.rotation.set(rx, ry, 0);
- tilt.rotation.x = 0.3 + Math.sin(t * 0.5) * 0.18;
+ tilt.rotation.x = 0.3 + Math.sin(t * 0.5) * 0.18 + wf * Math.sin(now * 0.0007) * 0.12;
tilt.rotation.y = Math.cos(t * 0.4) * 0.22;
- ring.rotation.z += dt * mot * (0.25 + e * 2.4);
- council.rotation.z += dt * mot * (0.12 + e * 0.5);
- core.scale.setScalar(1 + Math.sin(now * 0.004 * (1 + e * 2)) * 0.04 * (1 + e * 3));
- coreGlow.material.opacity = 0.25 + e * 0.5;
- coreGlow.scale.setScalar(2 + e * 1.6);
+ ring.rotation.z += dt * mot * (0.25 + e * 2.4) * (1 - 0.45 * wf);
+ council.rotation.z += dt * mot * (0.12 + e * 0.5) * (1 - 0.3 * wf);
+
+ // The core pulses with the energy; waiting, a double heartbeat instead.
+ const beatT = (now * 0.001) % BEAT_S;
+ const beat = Math.exp(-((beatT - 0.1) ** 2) / 0.004) + 0.6 * Math.exp(-((beatT - 0.38) ** 2) / 0.004);
+ const pulse = 1 + Math.sin(now * 0.004 * (1 + e * 2)) * 0.04 * (1 + e * 3);
+ core.scale.setScalar(pulse * (1 - wf) + (1 + beat * 0.09) * wf);
+ coreGlow.material.opacity = (0.25 + e * 0.5) * (1 - wf) + (0.22 + beat * 0.45) * wf;
+ coreGlow.scale.setScalar((2 + e * 1.6) * (1 - wf) + (2 + beat * 1.4) * wf);
ringGlow.material.opacity = 0.08 + e * 0.18;
- members.forEach((n) => {
+ members.forEach((n, i) => {
+ // Waiting, each member breathes out and back, in turn.
+ const breath = wf * BREATH * Math.max(0, Math.sin(now * 0.0014 - (i * 2 * PI) / 3));
+ n.member.position.set(Math.cos(n.angle) * HEAD_D * breath, Math.sin(n.angle) * HEAD_D * breath, 0);
const a = n.angle + council.rotation.z;
- const p = bez.v2.set(Math.cos(a) * HEAD_D, Math.sin(a) * HEAD_D, 0);
+ const d = HEAD_D * (1 + breath);
+ const p = bez.v2.set(Math.cos(a) * d, Math.sin(a) * d, 0);
bez.v1.set(p.x * 0.5 - p.y * 0.25, p.y * 0.5 + p.x * 0.25, 0.6);
const arr = n.line.geometry.attributes.position.array as Float32Array;
bez.getPoints(32).forEach((v, j) => arr.set([v.x, v.y, v.z], j * 3));
n.line.geometry.attributes.position.needsUpdate = true;
- n.line.material.opacity = 0.45 + e * 0.45;
+ n.line.material.opacity = (0.45 + e * 0.45) * (1 - wf) + (0.18 + 0.12 * Math.sin(now * 0.003 + i)) * wf;
+ // Packets stream from the core; waiting, one searching ping goes out
+ // and fades. The two blend, so nothing jumps on the way in or out.
+ const search = (now * 0.00045 + i / 3) % 1;
+ const out = Math.min(1, search / 0.55);
bez.getPoint((t * 0.9 + n.off) % 1, n.pk.position);
- n.pk.material.opacity = 0.3 + e * 0.7;
+ n.pk.position.lerp(bez.getPoint(out, ping), wf);
+ n.pk.material.opacity = (0.3 + e * 0.7) * (1 - wf) + (search < 0.55 ? Math.sin(PI * out) * 0.9 : 0) * wf;
});
// Light theme: glossy piano-black, blended over ~0.3 s.
const light = !document.documentElement.classList.contains('dark');
- ptBase += ((light ? 0.85 : 0.8) - ptBase) * k;
+ ptBase += ((light ? 0.85 : 0.8) * (1 - 0.35 * wf) - ptBase) * k;
pts.rotation.y += dt * 0.02 * mot * (1 + e * 3);
pts.rotation.x = rx * 0.3;
lf += ((light ? 1 : 0) - lf) * Math.min(1, dt * 3.2);
@@ -415,11 +455,11 @@ export function createOrbEngine(onLost: () => void) {
ringMat.roughness = 0.18 - 0.08 * lf;
coreMat.roughness = 0.3 - 0.2 * lf;
members.forEach((n) => {
- n.mat.emissiveIntensity = 0.35 * (1 - lf);
+ n.mat.emissiveIntensity = 0.35 * (1 - lf) * (1 - 0.4 * wf);
n.mat.roughness = 0.25 - 0.15 * lf;
- n.halo.material.opacity = 0.5 - 0.35 * lf;
+ n.halo.material.opacity = (0.5 - 0.35 * lf) * (1 - 0.5 * wf);
});
- R.toneMappingExposure = 1.1 - 0.2 * lf;
+ R.toneMappingExposure = (1.1 - 0.2 * lf) * (1 - 0.12 * wf);
amb.intensity = (0.35 - 0.2 * lf) * PI;
key.intensity = (1.1 + 1.4 * lf) * PI;
rim.intensity = 2.2 * lf * PI;
@@ -450,30 +490,38 @@ export function createOrbEngine(onLost: () => void) {
cancelAnimationFrame(raf);
raf = 0;
};
+ /** Frames run while there is a host and someone can see the page. */
+ const run = () => {
+ if (!host || !pageActivity.isActive()) {
+ stop();
+ return;
+ }
+ if (!raf) {
+ last = performance.now();
+ raf = requestAnimationFrame(loop);
+ }
+ };
+ const unsubscribe = pageActivity.subscribe(run);
return {
attach(element: HTMLElement) {
host = element;
element.appendChild(R.domElement);
- ro.disconnect();
- ro.observe(element);
- resize();
+ size = null;
placed = false;
window.addEventListener('pointermove', onMove, { passive: true });
- if (!raf) {
- last = performance.now();
- raf = requestAnimationFrame(loop);
- }
+ run();
},
detach() {
stop();
- ro.disconnect();
window.removeEventListener('pointermove', onMove);
R.domElement.remove();
host = null;
+ size = null;
},
dispose() {
this.detach();
+ unsubscribe();
R.domElement.removeEventListener('webglcontextlost', lost);
scene.traverse((object) => {
const mesh = object as Mesh;
diff --git a/client/src/features/home/settings/HelpTab.tsx b/client/src/features/home/settings/HelpTab.tsx
new file mode 100644
index 00000000..b0ae5d45
--- /dev/null
+++ b/client/src/features/home/settings/HelpTab.tsx
@@ -0,0 +1,52 @@
+/**
+ * Settings > Help: the way back to the Welcome guide, and to the Get
+ * started checklist once it is hidden.
+ */
+
+import { Button } from '@/components/ui/button';
+import { useShowGetStarted } from '../onboarding/useGetStarted';
+import { useHomeStore } from '../state/homeStore';
+import { SettingRow } from './SettingRow';
+
+const ROW_BUTTON = 'h-8 border-border-strong px-3 text-sm font-semibold text-fg-default';
+
+export function HelpTab({ onDone }: { onDone: () => void }) {
+ const openGuide = useHomeStore((s) => s.openGuide);
+ const showGetStarted = useShowGetStarted();
+ return (
+ <div className="flex max-w-170 flex-col gap-5 px-8 pt-7 pb-8">
+ <div data-stagger className="flex flex-col gap-1 pr-9">
+ <h2 className="text-lg font-semibold tracking-[-0.01em] text-fg-default">Help</h2>
+ <p className="text-sm text-pretty text-fg-muted">Find your way around OpenCompany again.</p>
+ </div>
+ <div data-stagger className="flex flex-col">
+ <SettingRow title="Welcome guide" detail="Connect an AI model and hire your first employee, step by step.">
+ <Button
+ variant="quiet"
+ onClick={() => {
+ onDone();
+ openGuide('welcome');
+ }}
+ className={ROW_BUTTON}
+ >
+ Replay
+ </Button>
+ </SettingRow>
+ <SettingRow title="Get started checklist" detail="Your first steps, ticked off as you go, in the corner of Home." last>
+ <Button
+ variant="quiet"
+ onClick={() => {
+ onDone();
+ showGetStarted();
+ }}
+ className={ROW_BUTTON}
+ >
+ Show
+ </Button>
+ </SettingRow>
+ </div>
+ </div>
+ );
+}
+
+export default HelpTab;
diff --git a/client/src/features/home/settings/HomeSettings.tsx b/client/src/features/home/settings/HomeSettings.tsx
index bb4952ba..00778fcf 100644
--- a/client/src/features/home/settings/HomeSettings.tsx
+++ b/client/src/features/home/settings/HomeSettings.tsx
@@ -8,7 +8,7 @@
*/
import { useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
-import { CircleUserRound, CreditCard, Grid2x2Plus, Plug, Star, X, type LucideIcon } from 'lucide-react';
+import { CircleHelp, CircleUserRound, CreditCard, Grid2x2Plus, Plug, Star, X, type LucideIcon } from 'lucide-react';
import { Tabs as TabsPrimitive } from 'radix-ui';
import { OcLogo } from '@/components/brand/Logo';
import { Button } from '@/components/ui/button';
@@ -16,17 +16,16 @@ import { CredentialsBrowser } from '@/components/credentials/CredentialsBrowser'
import Modal from '@/components/ui/Modal';
import type { CredentialsIntent } from '@/stores/shellDialogsStore';
import { useHomeStore, type SettingsTab } from '../state/homeStore';
+import { NAV_ITEM } from '../ui/nav';
import { MicroLabel, SearchField } from '../ui/primitives';
import { BillingTab } from './BillingTab';
+import { HelpTab } from './HelpTab';
import { PluginsTab } from './PluginsTab';
import { ProfileTab } from './ProfileTab';
import { SkillsTab } from './SkillsTab';
import { AccessTab } from './AccessTab';
import { staggerSettings } from './stagger';
-const NAV_ITEM =
- 'flex h-9 w-full items-center gap-2.5 rounded-lg px-2.5 text-left text-row font-medium text-fg-muted outline-none transition-colors hover:bg-bg-hover hover:text-fg-default focus-visible:ring-3 focus-visible:ring-ring/50 data-[state=active]:bg-bg-hover data-[state=active]:text-fg-default';
-
interface PageContext {
close: () => void;
onConnect: (providerId: string, intent?: CredentialsIntent) => void;
@@ -67,6 +66,14 @@ const PAGES: Page[] = [
keywords: 'plan invoices usage',
render: () => <BillingTab />,
},
+ {
+ tab: 'help',
+ group: 'settings',
+ label: 'Help',
+ icon: CircleHelp,
+ keywords: 'guide welcome tour replay checklist get started',
+ render: ({ close }) => <HelpTab onDone={close} />,
+ },
{
tab: 'skills',
group: 'customize',
diff --git a/client/src/features/home/settings/ProfileTab.tsx b/client/src/features/home/settings/ProfileTab.tsx
index dfe3654e..02d607ee 100644
--- a/client/src/features/home/settings/ProfileTab.tsx
+++ b/client/src/features/home/settings/ProfileTab.tsx
@@ -5,7 +5,7 @@
* trims and bounds them again on save.
*/
-import { useEffect, useRef, useState, type ReactNode } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { ActionButton } from '@/components/ui/action-button';
@@ -28,33 +28,12 @@ import {
import { SPIKE, spikeOrb } from '../orb/orb';
import { Avatar } from '../ui/primitives';
import { pillToast } from '../ui/pillToast';
+import { SettingRow } from './SettingRow';
// The fields sit on the app surface at the design's size (the primitives
// would tint them in dark and shrink the text to 13px from md up).
const FIELD_INPUT = 'h-9.5 rounded-lg bg-bg-app px-3 text-base font-normal md:text-base dark:bg-bg-app';
-function SettingRow({
- title,
- detail,
- children,
- last = false,
-}: {
- title: string;
- detail: string;
- children: ReactNode;
- last?: boolean;
-}) {
- return (
- <div className={`flex items-center gap-4 border-t border-border-default py-3.5 ${last ? 'border-b' : ''}`}>
- <div className="flex flex-1 flex-col gap-0.75">
- <span className="text-base font-medium text-fg-default">{title}</span>
- <span className="text-meta text-fg-muted">{detail}</span>
- </div>
- {children}
- </div>
- );
-}
-
export function ProfileTab({ onDone }: { onDone: () => void }) {
const { data: settings } = useOwnerSettings();
const { saveProfile, isPending } = useSaveProfile();
diff --git a/client/src/features/home/settings/SettingRow.tsx b/client/src/features/home/settings/SettingRow.tsx
new file mode 100644
index 00000000..49af5941
--- /dev/null
+++ b/client/src/features/home/settings/SettingRow.tsx
@@ -0,0 +1,29 @@
+/** One labelled row of a Settings page: title and detail, its control on the
+ * right (Profile's switches, Help's replay). */
+
+import type { ReactNode } from 'react';
+import { cn } from '@/lib/utils';
+
+export function SettingRow({
+ title,
+ detail,
+ children,
+ last = false,
+}: {
+ title: string;
+ detail: string;
+ children: ReactNode;
+ last?: boolean;
+}) {
+ return (
+ <div className={cn('flex items-center gap-4 border-t border-border-default py-3.5', last && 'border-b')}>
+ <div className="flex flex-1 flex-col gap-0.75">
+ <span className="text-base font-medium text-fg-default">{title}</span>
+ <span className="text-meta text-fg-muted">{detail}</span>
+ </div>
+ {children}
+ </div>
+ );
+}
+
+export default SettingRow;
diff --git a/client/src/features/home/sidebar/HomeSidebar.tsx b/client/src/features/home/sidebar/HomeSidebar.tsx
index eb7bd8d4..36748b52 100644
--- a/client/src/features/home/sidebar/HomeSidebar.tsx
+++ b/client/src/features/home/sidebar/HomeSidebar.tsx
@@ -23,6 +23,7 @@ import { Skeleton } from '@/components/ui/skeleton';
import { animate } from '@/lib/motion';
import { cn } from '@/lib/utils';
import { useEmployeesQuery } from '../data/employees';
+import { useAnswering } from '../data/liveTask';
import { presentEmployee } from '../data/presentation';
import { useOwnerSettings } from '../data/profile';
import type { EmployeeSummary } from '../data/schemas';
@@ -36,8 +37,9 @@ function EmployeeRow({ employee, selected }: { employee: EmployeeSummary; select
const showEmployee = useHomeStore((s) => s.showEmployee);
const glow = useHomeStore((s) => (s.glow?.workflowId === employee.workflow_id ? s.glow.nonce : 0));
const pending = useWorkflowControlPending(employee.workflow_id);
+ const answering = useAnswering(employee);
const ref = useRef<HTMLButtonElement>(null);
- const view = presentEmployee(employee, pending);
+ const view = presentEmployee(employee, pending, answering);
const deleteWorkflow = useAppStore((s) => s.deleteWorkflow);
const [confirming, setConfirming] = useState(false);
const [deleting, setDeleting] = useState(false);
diff --git a/client/src/features/home/state/homeStore.ts b/client/src/features/home/state/homeStore.ts
index 3603719a..852ae3a4 100644
--- a/client/src/features/home/state/homeStore.ts
+++ b/client/src/features/home/state/homeStore.ts
@@ -1,19 +1,38 @@
/**
* Normal mode's UI state: which view is showing, the sidebar, the Settings
- * dialog, the Workspace dock, and
+ * dialog, the Workspace dock, the Welcome guide, and
* the one-shot signals the hire choreography fires (a sidebar row's glow,
- * the logo pulse, what a hire could not set up as asked). Server data lives
- * in TanStack Query (features/home/data), never here.
+ * the logo pulse, what a hire could not set up as asked, a new hire's first
+ * day). Server data lives in TanStack Query (features/home/data), never here.
*/
import { z } from 'zod';
import { create } from 'zustand';
import type { CanvasFocus } from '@/lib/canvasBoard';
-import { useShellDialogsStore } from '@/stores/shellDialogsStore';
+import { useShellDialogsStore, type CredentialsIntent } from '@/stores/shellDialogsStore';
import { SPIKE, spikeOrb } from '../orb/orb';
export type HomeView = { kind: 'hire' } | { kind: 'employee'; workflowId: string };
-export type SettingsTab = 'profile' | 'billing' | 'skills' | 'connectors' | 'plugins' | 'access';
+export type SettingsTab = 'profile' | 'billing' | 'skills' | 'connectors' | 'plugins' | 'access' | 'help';
+
+/** The Welcome guide's steps, in order. The saved `onboarding_step` is an
+ * index into this list. */
+export const GUIDE_STEPS = ['welcome', 'connect', 'first-hire'] as const;
+export type GuideStep = (typeof GUIDE_STEPS)[number];
+
+export interface GuideState {
+ open: boolean;
+ step: GuideStep;
+ /** The furthest step visited; the nav reaches any step up to it. */
+ furthest: number;
+ /** The first-launch check ran this session (checkGuide). */
+ checked: boolean;
+ /** The provider page the Connect step shows in place of the list. */
+ provider: { id: string; intent: CredentialsIntent } | null;
+ /** The last step's job waits for an AI model: connecting one finishes
+ * the guide and sends it. */
+ pendingDraft: boolean;
+}
// View ids, not node types: the Canvas tab is 'board' so no id reads as the
// `canvas` node type (tests/test_frontend_no_node_type_copies.py).
@@ -62,6 +81,15 @@ export interface WorkspaceFocus extends CanvasFocus {
canvasNodeId: string;
}
+/** A hire made in this session, from the hire until their first
+ * conversation begins (employee/FirstDay). A reload ends it. */
+export interface FirstDay {
+ /** The hire started them itself (nothing was missing). */
+ started: boolean;
+ /** Blocks in the workflow the hire built; null when the reply did not say. */
+ nodeCount: number | null;
+}
+
/** What a hire could not set up as asked (a tool left out while they ask
* first, a skill an employee cannot be given), shown on the new
* employee's page until the owner dismisses it or moves on. */
@@ -106,6 +134,10 @@ interface HomeState {
/** A Canvas item to show (a reply's document card); the nonce lets the
* same one be asked for again. */
workspaceFocus: WorkspaceFocus | null;
+ /** The Welcome guide (onboarding/WelcomeGuide). */
+ guide: GuideState;
+ /** New hires on their first day, by workflow id. */
+ firstDays: Record<string, FirstDay>;
showHire: (options?: { focus?: boolean }) => void;
showEmployee: (workflowId: string) => void;
@@ -129,8 +161,24 @@ interface HomeState {
/** Open the Workspace on the Canvas tab, at an item and version of an
* employee's board. */
openCanvasItem: (target: { workflowId: string; canvasNodeId: string; itemId: string; version?: number | null }) => void;
+ /** Open the Welcome guide at a step (the header's Guide button, Settings
+ * > Help, the first-launch check). */
+ openGuide: (step?: GuideStep) => void;
+ closeGuide: () => void;
+ goToGuideStep: (step: GuideStep) => void;
+ /** Show a provider's page in the Connect step (null: back to the list). */
+ setGuideProvider: (provider: GuideState['provider']) => void;
+ setGuidePendingDraft: (pending: boolean) => void;
+ /** Once per session: open the guide for an owner who has not finished it,
+ * at the step they left. A completed owner never sees it unasked. */
+ checkGuide: (settings: { onboarding_completed?: unknown; onboarding_step?: unknown }) => void;
+ beginFirstDay: (workflowId: string, firstDay: FirstDay) => void;
+ /** Their first conversation began, or they are gone. */
+ endFirstDay: (workflowId: string) => void;
}
+const stepIndex = (step: GuideStep) => GUIDE_STEPS.indexOf(step);
+
const workspace = loadWorkspacePrefs();
export const useHomeStore = create<HomeState>((set, get) => ({
@@ -149,6 +197,8 @@ export const useHomeStore = create<HomeState>((set, get) => ({
workspaceWide: false,
workspaceFor: null,
workspaceFocus: null,
+ guide: { open: false, step: 'welcome', furthest: 0, checked: false, provider: null, pendingDraft: false },
+ firstDays: {},
showHire: (options) =>
set((state) => ({
@@ -216,4 +266,44 @@ export const useHomeStore = create<HomeState>((set, get) => ({
}));
saveWorkspacePrefs(get());
},
+ openGuide: (step = 'welcome') =>
+ set((state) => ({
+ guide: {
+ ...state.guide,
+ open: true,
+ step,
+ furthest: Math.max(state.guide.furthest, stepIndex(step)),
+ provider: null,
+ pendingDraft: false,
+ },
+ })),
+ // The step and any provider page stay, so the dialog does not change page
+ // while it closes; a job waiting for a model is not carried past it.
+ closeGuide: () => set((state) => ({ guide: { ...state.guide, open: false, pendingDraft: false } })),
+ goToGuideStep: (step) =>
+ set((state) => ({
+ guide: { ...state.guide, step, furthest: Math.max(state.guide.furthest, stepIndex(step)), provider: null },
+ })),
+ setGuideProvider: (provider) => set((state) => ({ guide: { ...state.guide, provider } })),
+ setGuidePendingDraft: (pendingDraft) => set((state) => ({ guide: { ...state.guide, pendingDraft } })),
+ checkGuide: (settings) => {
+ if (get().guide.checked) return;
+ const saved = settings.onboarding_step;
+ const step = (typeof saved === 'number' && GUIDE_STEPS[saved]) || 'welcome';
+ if (settings.onboarding_completed) {
+ set((state) => ({ guide: { ...state.guide, checked: true } }));
+ return;
+ }
+ set((state) => ({
+ guide: { ...state.guide, open: true, step, furthest: Math.max(state.guide.furthest, stepIndex(step)), checked: true },
+ }));
+ },
+ beginFirstDay: (workflowId, firstDay) => set((state) => ({ firstDays: { ...state.firstDays, [workflowId]: firstDay } })),
+ endFirstDay: (workflowId) =>
+ set((state) => {
+ if (!(workflowId in state.firstDays)) return state;
+ const firstDays = { ...state.firstDays };
+ delete firstDays[workflowId];
+ return { firstDays };
+ }),
}));
diff --git a/client/src/features/home/ui/nav.ts b/client/src/features/home/ui/nav.ts
new file mode 100644
index 00000000..44ee3ffe
--- /dev/null
+++ b/client/src/features/home/ui/nav.ts
@@ -0,0 +1,7 @@
+/**
+ * A row of a Home dialog's left nav (Settings, the Welcome guide). Used on a
+ * Radix Tabs trigger, so the open page reads from `data-state`; a step the
+ * guide cannot reach yet is a disabled trigger.
+ */
+export const NAV_ITEM =
+ 'flex h-9 w-full items-center gap-2.5 rounded-lg px-2.5 text-left text-row font-medium text-fg-muted outline-none transition-colors hover:bg-bg-hover hover:text-fg-default focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none data-[state=active]:bg-bg-hover data-[state=active]:text-fg-default';
diff --git a/client/src/features/home/ui/primitives.tsx b/client/src/features/home/ui/primitives.tsx
index 9cc107fd..90c9a2b0 100644
--- a/client/src/features/home/ui/primitives.tsx
+++ b/client/src/features/home/ui/primitives.tsx
@@ -18,7 +18,11 @@ import type { ColorRole } from '../data/schemas';
const AVATAR_SIZE = {
sm: 'size-7.5 text-xs',
md: 'size-8 text-sm',
+ /** 48px: the identity row of a new employee's setup card. */
+ card: 'size-12 border-2 text-lg',
lg: 'size-14 border-2 text-title',
+ /** 72px: a new hire arriving on their page. */
+ xl: 'size-18 border-2 text-headline',
} as const;
export function Avatar({
diff --git a/client/src/features/home/ui/routine.tsx b/client/src/features/home/ui/routine.tsx
new file mode 100644
index 00000000..39d2f113
--- /dev/null
+++ b/client/src/features/home/ui/routine.tsx
@@ -0,0 +1,73 @@
+/**
+ * A routine as a timeline (onboarding handoff R2): a thin rule down the left
+ * and one row per step, its role dot on the rule with a halo the colour of
+ * the card, a mono label in the role's ink (WHEN / THEY / USING / THEN),
+ * then the step on one line, its title and " · detail" in the muted colour.
+ * A row may end in an action (the setup card's "Change" on the When row).
+ *
+ * `md` is the setup card's size, `sm` a new hire's first day.
+ */
+
+import type { ReactNode, Ref } from 'react';
+import { cn } from '@/lib/utils';
+import type { ColorRole } from '../data/schemas';
+
+export type RoutineRole = Extract<ColorRole, 'trigger' | 'agent' | 'tool' | 'workflow'>;
+
+const LABEL: Record<RoutineRole, string> = { trigger: 'When', agent: 'They', tool: 'Using', workflow: 'Then' };
+
+// Tailwind scans these literals.
+const DOT: Record<RoutineRole, string> = {
+ trigger: 'bg-node-trigger',
+ agent: 'bg-node-agent',
+ tool: 'bg-node-tool',
+ workflow: 'bg-node-workflow',
+};
+
+const INK: Record<RoutineRole, string> = {
+ trigger: 'text-node-trigger-ink',
+ agent: 'text-node-agent-ink',
+ tool: 'text-node-tool-ink',
+ workflow: 'text-node-workflow-ink',
+};
+
+const SIZE = {
+ md: { row: 'min-h-9', dot: 'size-2.25', text: 'text-base' },
+ sm: { row: 'min-h-8', dot: 'size-2', text: 'text-row' },
+} as const;
+
+export function RoutineTimeline({ children, className, ref }: { children: ReactNode; className?: string; ref?: Ref<HTMLDivElement> }) {
+ return (
+ <div ref={ref} className={cn('relative flex flex-col', className)}>
+ <span aria-hidden className="absolute top-3.5 bottom-3.5 left-1.25 w-px bg-border-default" />
+ {children}
+ </div>
+ );
+}
+
+export function RoutineRow({
+ role,
+ title,
+ detail,
+ action,
+ size = 'md',
+}: {
+ role: RoutineRole;
+ title: string;
+ detail?: string;
+ action?: ReactNode;
+ size?: keyof typeof SIZE;
+}) {
+ const s = SIZE[size];
+ return (
+ <div data-routine-row className={cn('relative grid grid-cols-[12px_52px_minmax(0,1fr)_auto] items-center gap-2.5', s.row)}>
+ <span aria-hidden className={cn('justify-self-center rounded-full ring-3 ring-bg-panel', s.dot, DOT[role])} />
+ <span className={cn('font-mono text-2xs font-medium tracking-label uppercase', INK[role])}>{LABEL[role]}</span>
+ <span className={cn('truncate leading-snug', s.text)}>
+ <span className="text-fg-default">{title}</span>
+ {detail && <span className="text-fg-muted"> · {detail}</span>}
+ </span>
+ {action ?? <span />}
+ </div>
+ );
+}
diff --git a/client/src/hooks/__tests__/useGetStarted.test.ts b/client/src/hooks/__tests__/useGetStarted.test.ts
deleted file mode 100644
index f12c951a..00000000
--- a/client/src/hooks/__tests__/useGetStarted.test.ts
+++ /dev/null
@@ -1,298 +0,0 @@
-/**
- * Tests for useGetStarted — the Get Started checklist state hook.
- *
- * Locks the contract:
- * - visible = settings query success && onboarding_completed && !dismissed
- * - completion per item = persisted latch field || live signal
- * - newly-true live signals persist a one-way latch via saveSettings.mutate,
- * guarded by the settings flag (no re-write when already latched)
- * - build-workflow excludes the three seeded example workflow names
- * - try-theme compares against the theme captured on first render
- * - dismiss()/restore() write getting_started_dismissed true/false
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { renderHook, act } from '@testing-library/react';
-
-// --- controllable mock state -------------------------------------------------
-// Factories below return closures that read these at call time (safe under
-// vi.mock hoisting — the values are only dereferenced during render).
-
-const settingsState: {
- data: Record<string, any> | undefined;
- isSuccess: boolean;
-} = { data: undefined, isSuccess: false };
-
-const saveMutate = vi.fn();
-
-vi.mock('../useUserSettingsQuery', () => ({
- useUserSettingsQuery: () => ({
- data: settingsState.data,
- isSuccess: settingsState.isSuccess,
- }),
- useSaveUserSettingsMutation: () => ({ mutate: saveMutate }),
-}));
-
-const catalogueState = { storedCount: 0 };
-vi.mock('../useCatalogueQuery', () => ({
- useStoredProviderCount: () => catalogueState.storedCount,
-}));
-
-const chatState = {
- messages: [] as Array<{ role: 'user' | 'assistant'; text: string }>,
- reads: [] as Array<[string | null, string]>,
-};
-// Full-module replace — importActual+spread is broken under React 19 (see
-// CredentialsModal.test.tsx for the canonical note).
-vi.mock('../../features/chat', () => ({
- useChatThread: (sessionId: string | null, scope: string) => {
- chatState.reads.push([sessionId, scope]);
- return { data: { messages: chatState.messages } };
- },
-}));
-
-const themeState = { theme: 'dark' };
-vi.mock('../../contexts/ThemeContext', () => ({
- useTheme: () => ({ theme: themeState.theme }),
-}));
-
-import { useGetStarted } from '../useGetStarted';
-import { useAppStore, type WorkflowData } from '../../store/useAppStore';
-import type { GetStartedItemId } from '../../components/onboarding/getStartedItems';
-
-// --- helpers -----------------------------------------------------------------
-
-const makeWorkflow = (name: string, nodeCount = 1): WorkflowData => ({
- id: 'wf-1',
- name,
- slug: '',
- nodes: Array.from({ length: nodeCount }, (_, i) => ({
- id: `n${i}`,
- type: 'aiAgent',
- position: { x: 0, y: 0 },
- data: {},
- })) as WorkflowData['nodes'],
- edges: [],
- createdAt: new Date(),
- lastModified: new Date(),
-});
-
-const completedSettings = (extra: Record<string, any> = {}) => ({
- onboarding_completed: true,
- ...extra,
-});
-
-function itemCompleted(
- result: { current: ReturnType<typeof useGetStarted> },
- id: GetStartedItemId,
-): boolean {
- const item = result.current.items.find((i) => i.id === id);
- expect(item).toBeDefined();
- return item!.completed;
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
- settingsState.data = completedSettings();
- settingsState.isSuccess = true;
- catalogueState.storedCount = 0;
- chatState.messages = [];
- chatState.reads = [];
- themeState.theme = 'dark';
- useAppStore.setState({ currentWorkflow: null, hasUnsavedChanges: false });
-});
-
-// --- visibility --------------------------------------------------------------
-
-describe('useGetStarted visibility', () => {
- it('is hidden when getting_started_dismissed is set', () => {
- settingsState.data = completedSettings({ getting_started_dismissed: true });
- const { result } = renderHook(() => useGetStarted());
- expect(result.current.visible).toBe(false);
- });
-
- it('is hidden when onboarding is not completed', () => {
- settingsState.data = { onboarding_completed: false };
- const { result } = renderHook(() => useGetStarted());
- expect(result.current.visible).toBe(false);
- });
-
- it('is hidden while the settings query is pending, and persists no latches', () => {
- settingsState.data = undefined;
- settingsState.isSuccess = false;
- catalogueState.storedCount = 3; // live signal true, but query not settled
- const { result } = renderHook(() => useGetStarted());
- expect(result.current.visible).toBe(false);
- expect(saveMutate).not.toHaveBeenCalled();
- });
-
- it('is visible for completed-onboarding, non-dismissed settings', () => {
- const { result } = renderHook(() => useGetStarted());
- expect(result.current.visible).toBe(true);
- });
-});
-
-// --- baseline ----------------------------------------------------------------
-
-describe('useGetStarted baseline', () => {
- it('endows fresh settings with only the setup item completed (1 of 5)', () => {
- const { result } = renderHook(() => useGetStarted());
- expect(result.current.totalCount).toBe(5);
- expect(result.current.completedCount).toBe(1);
- expect(itemCompleted(result, 'setup')).toBe(true);
- expect(itemCompleted(result, 'add-key')).toBe(false);
- expect(itemCompleted(result, 'chat-example')).toBe(false);
- expect(itemCompleted(result, 'build-workflow')).toBe(false);
- expect(itemCompleted(result, 'try-theme')).toBe(false);
- expect(saveMutate).not.toHaveBeenCalled();
- });
-});
-
-// --- add-key -----------------------------------------------------------------
-
-describe('useGetStarted add-key', () => {
- it('completes when a provider credential is stored and persists the latch', () => {
- catalogueState.storedCount = 2;
- const { result } = renderHook(() => useGetStarted());
- expect(itemCompleted(result, 'add-key')).toBe(true);
- expect(result.current.completedCount).toBe(2); // setup + add-key
- expect(saveMutate).toHaveBeenCalledWith({ getting_started_added_key: true });
- expect(saveMutate).toHaveBeenCalledTimes(1);
- });
-
- it('does not re-persist when the latch flag is already set', () => {
- settingsState.data = completedSettings({ getting_started_added_key: true });
- catalogueState.storedCount = 2;
- const { result } = renderHook(() => useGetStarted());
- expect(itemCompleted(result, 'add-key')).toBe(true);
- expect(saveMutate).not.toHaveBeenCalled();
- });
-});
-
-// --- chat-example ------------------------------------------------------------
-
-describe('useGetStarted chat-example', () => {
- it('stays incomplete with only user messages', () => {
- chatState.messages = [{ role: 'user', text: 'hi' }];
- const { result } = renderHook(() => useGetStarted());
- expect(itemCompleted(result, 'chat-example')).toBe(false);
- expect(saveMutate).not.toHaveBeenCalled();
- });
-
- it("reads the open workflow's live thread", () => {
- renderHook(() => useGetStarted());
- expect(chatState.reads.at(-1)).toEqual(['default', 'live']);
- useAppStore.setState({ currentWorkflow: makeWorkflow('My Automation') });
- renderHook(() => useGetStarted());
- expect(chatState.reads.at(-1)).toEqual(['wf-1', 'live']);
- });
-
- it('completes on an assistant message and persists the latch', () => {
- chatState.messages = [
- { role: 'user', text: 'hi' },
- { role: 'assistant', text: 'hello!' },
- ];
- const { result } = renderHook(() => useGetStarted());
- expect(itemCompleted(result, 'chat-example')).toBe(true);
- expect(saveMutate).toHaveBeenCalledWith({ getting_started_ran_example: true });
- });
-});
-
-// --- build-workflow ----------------------------------------------------------
-
-describe('useGetStarted build-workflow', () => {
- it('completes for a saved, non-example workflow with nodes', () => {
- useAppStore.setState({
- currentWorkflow: makeWorkflow('My Automation', 2),
- hasUnsavedChanges: false,
- });
- const { result } = renderHook(() => useGetStarted());
- expect(itemCompleted(result, 'build-workflow')).toBe(true);
- expect(saveMutate).toHaveBeenCalledWith({ getting_started_built_workflow: true });
- });
-
- it('does NOT complete via live signal for a seeded example workflow name', () => {
- useAppStore.setState({
- currentWorkflow: makeWorkflow('AI Assistant', 3),
- hasUnsavedChanges: false,
- });
- const { result } = renderHook(() => useGetStarted());
- expect(itemCompleted(result, 'build-workflow')).toBe(false);
- expect(saveMutate).not.toHaveBeenCalledWith({ getting_started_built_workflow: true });
- });
-
- it('does not complete while the workflow has unsaved changes', () => {
- useAppStore.setState({
- currentWorkflow: makeWorkflow('My Automation', 2),
- hasUnsavedChanges: true,
- });
- const { result } = renderHook(() => useGetStarted());
- expect(itemCompleted(result, 'build-workflow')).toBe(false);
- });
-
- it('does not complete for an empty (node-less) workflow', () => {
- useAppStore.setState({
- currentWorkflow: makeWorkflow('My Automation', 0),
- hasUnsavedChanges: false,
- });
- const { result } = renderHook(() => useGetStarted());
- expect(itemCompleted(result, 'build-workflow')).toBe(false);
- });
-});
-
-// --- try-theme ---------------------------------------------------------------
-
-describe('useGetStarted try-theme', () => {
- it('stays incomplete while the theme matches the initial theme', () => {
- const { result, rerender } = renderHook(() => useGetStarted());
- expect(itemCompleted(result, 'try-theme')).toBe(false);
- rerender();
- expect(itemCompleted(result, 'try-theme')).toBe(false);
- expect(saveMutate).not.toHaveBeenCalled();
- });
-
- it('completes when the theme changes from the initial one and persists the latch', () => {
- const { result, rerender } = renderHook(() => useGetStarted());
- expect(itemCompleted(result, 'try-theme')).toBe(false);
-
- themeState.theme = 'cyber';
- rerender();
-
- expect(itemCompleted(result, 'try-theme')).toBe(true);
- expect(saveMutate).toHaveBeenCalledWith({ getting_started_tried_theme: true });
- });
-});
-
-// --- one-way latch -----------------------------------------------------------
-
-describe('useGetStarted one-way latch', () => {
- it('keeps an item completed via the latch even when the live signal is false', () => {
- settingsState.data = completedSettings({
- getting_started_tried_theme: true,
- getting_started_added_key: true,
- });
- // All live signals false: no stored providers, no chat, same theme.
- const { result } = renderHook(() => useGetStarted());
- expect(itemCompleted(result, 'try-theme')).toBe(true);
- expect(itemCompleted(result, 'add-key')).toBe(true);
- expect(result.current.completedCount).toBe(3); // setup + the two latches
- expect(saveMutate).not.toHaveBeenCalled();
- });
-});
-
-// --- dismiss / restore -------------------------------------------------------
-
-describe('useGetStarted dismiss/restore', () => {
- it('dismiss() persists getting_started_dismissed: true', () => {
- const { result } = renderHook(() => useGetStarted());
- act(() => result.current.dismiss());
- expect(saveMutate).toHaveBeenCalledWith({ getting_started_dismissed: true });
- });
-
- it('restore() persists getting_started_dismissed: false', () => {
- settingsState.data = completedSettings({ getting_started_dismissed: true });
- const { result } = renderHook(() => useGetStarted());
- act(() => result.current.restore());
- expect(saveMutate).toHaveBeenCalledWith({ getting_started_dismissed: false });
- });
-});
diff --git a/client/src/hooks/__tests__/useOnboarding.steps.test.ts b/client/src/hooks/__tests__/useOnboarding.steps.test.ts
deleted file mode 100644
index 9d3910f5..00000000
--- a/client/src/hooks/__tests__/useOnboarding.steps.test.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * useOnboarding step-hydration tests.
- *
- * Locks in the persisted-step validation contract: on hydration the hook
- * keeps `onboarding_step` only when `0 <= step < totalSteps`; anything
- * out of range (the old 5-step wizard persisted step 4, the new wizard
- * has 4 steps) resets to 0 so a replay never starts past the end.
- * Also locks the visibility gate on `onboarding_completed`.
- *
- * useUserSettingsQuery / useSaveUserSettingsMutation are module-mocked
- * (full replace) so no WebSocket / TanStack plumbing is exercised.
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { renderHook } from '@testing-library/react';
-import { wrapperWithProviders } from '../../test/providers';
-
-// --- Mocks (declared BEFORE importing the hook -- vi.mock is hoisted) -------
-
-interface SettingsQueryState {
- isSuccess: boolean;
- isError: boolean;
- data: Record<string, unknown> | undefined;
- error: Error | null;
-}
-
-let settingsQueryState: SettingsQueryState;
-const mutateMock = vi.fn();
-
-vi.mock('../useUserSettingsQuery', () => ({
- useUserSettingsQuery: () => settingsQueryState,
- useSaveUserSettingsMutation: () => ({ mutate: mutateMock }),
-}));
-
-import { useOnboarding } from '../useOnboarding';
-
-const TOTAL_STEPS = 4;
-
-const renderOnboarding = () =>
- renderHook(() => useOnboarding(undefined, TOTAL_STEPS), {
- wrapper: wrapperWithProviders(),
- });
-
-beforeEach(() => {
- mutateMock.mockClear();
- settingsQueryState = {
- isSuccess: true,
- isError: false,
- data: {},
- error: null,
- };
-});
-
-// --- Tests ------------------------------------------------------------------
-
-describe('useOnboarding persisted-step hydration', () => {
- it('resets an out-of-range persisted step (old 5-step wizard) to 0 and stays visible', () => {
- settingsQueryState.data = { onboarding_step: 4, onboarding_completed: false };
- const { result } = renderOnboarding();
-
- expect(result.current.currentStep).toBe(0);
- expect(result.current.isVisible).toBe(true);
- expect(result.current.isCompleted).toBe(false);
- expect(result.current.hasChecked).toBe(true);
- expect(result.current.isLoading).toBe(false);
- });
-
- it('keeps an in-range persisted step', () => {
- settingsQueryState.data = { onboarding_step: 2, onboarding_completed: false };
- const { result } = renderOnboarding();
-
- expect(result.current.currentStep).toBe(2);
- expect(result.current.isVisible).toBe(true);
- });
-
- it('resets a negative persisted step to 0', () => {
- settingsQueryState.data = { onboarding_step: -1, onboarding_completed: false };
- const { result } = renderOnboarding();
-
- expect(result.current.currentStep).toBe(0);
- expect(result.current.isVisible).toBe(true);
- });
-
- it('stays hidden when onboarding is already completed', () => {
- settingsQueryState.data = { onboarding_step: 1, onboarding_completed: true };
- const { result } = renderOnboarding();
-
- expect(result.current.isVisible).toBe(false);
- expect(result.current.isCompleted).toBe(true);
- expect(result.current.hasChecked).toBe(true);
- expect(result.current.isLoading).toBe(false);
- });
-});
diff --git a/client/src/hooks/useGetStarted.ts b/client/src/hooks/useGetStarted.ts
deleted file mode 100644
index eda72740..00000000
--- a/client/src/hooks/useGetStarted.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-/**
- * Get Started checklist state.
- *
- * Each item's completion is `persisted latch || live signal`. Latches are
- * one-way booleans in `user_settings` (written once via the shared settings
- * mutation, guarded by the flag itself) so completion survives the live
- * signal disappearing later (key deleted, chat cleared, theme reverted).
- */
-
-import { useEffect, useRef } from 'react';
-import { useUserSettingsQuery, useSaveUserSettingsMutation } from './useUserSettingsQuery';
-import { useStoredProviderCount } from './useCatalogueQuery';
-import { useChatThread } from '../features/chat';
-import { useTheme } from '../contexts/ThemeContext';
-import { useAppStore } from '../store/useAppStore';
-import {
- GET_STARTED_ITEMS,
- EXAMPLE_WORKFLOW_NAMES,
- type GetStartedItemId,
-} from '../components/onboarding/getStartedItems';
-
-const LATCH_FIELDS: Partial<Record<GetStartedItemId, string>> = {
- 'add-key': 'getting_started_added_key',
- 'chat-example': 'getting_started_ran_example',
- 'build-workflow': 'getting_started_built_workflow',
- 'try-theme': 'getting_started_tried_theme',
-};
-
-export interface GetStartedItemState {
- id: GetStartedItemId;
- completed: boolean;
-}
-
-export interface GetStartedState {
- visible: boolean;
- items: GetStartedItemState[];
- completedCount: number;
- totalCount: number;
- dismiss: () => void;
- restore: () => void;
-}
-
-export function useGetStarted(): GetStartedState {
- const settingsQuery = useUserSettingsQuery();
- const saveSettings = useSaveUserSettingsMutation();
- const settings = settingsQuery.data;
-
- // Live signals.
- const storedProviderCount = useStoredProviderCount();
- // The open workflow's chat, the thread the console's Chat pane shows.
- const chatSessionId = useAppStore((s) => s.currentWorkflow?.id || 'default');
- const chatMessages = useChatThread(chatSessionId, 'live').data?.messages ?? [];
- const { theme } = useTheme();
- const initialThemeRef = useRef(theme);
- const currentWorkflowName = useAppStore((s) => s.currentWorkflow?.name);
- const currentWorkflowNodeCount = useAppStore((s) => s.currentWorkflow?.nodes.length ?? 0);
- const hasUnsavedChanges = useAppStore((s) => s.hasUnsavedChanges);
-
- const liveSignals: Partial<Record<GetStartedItemId, boolean>> = {
- 'add-key': storedProviderCount > 0,
- 'chat-example': chatMessages.some((m) => m.role === 'assistant'),
- 'build-workflow':
- !hasUnsavedChanges &&
- currentWorkflowNodeCount > 0 &&
- currentWorkflowName !== undefined &&
- !EXAMPLE_WORKFLOW_NAMES.some(
- (example) => example.toLowerCase() === currentWorkflowName.toLowerCase(),
- ),
- 'try-theme': theme !== initialThemeRef.current,
- };
-
- const completedById = Object.fromEntries(
- GET_STARTED_ITEMS.map((item) => {
- const latchField = LATCH_FIELDS[item.id];
- const latched = latchField ? Boolean(settings?.[latchField]) : true;
- return [item.id, latched || Boolean(liveSignals[item.id])];
- }),
- ) as Record<GetStartedItemId, boolean>;
-
- // Persist newly-true live signals as one-way latches.
- const { mutate: saveMutate } = saveSettings;
- useEffect(() => {
- if (!settingsQuery.isSuccess) return;
- for (const [itemId, field] of Object.entries(LATCH_FIELDS)) {
- if (liveSignals[itemId as GetStartedItemId] && !settings?.[field]) {
- saveMutate({ [field]: true });
- }
- }
- // The settings flag is the dedup guard once the mutation settles
- // (onSuccess patches the query cache). Renders before settlement may
- // re-send the same boolean patch — harmless, the write is idempotent.
- });
-
- const items = GET_STARTED_ITEMS.map((item) => ({
- id: item.id,
- completed: completedById[item.id],
- }));
- const completedCount = items.filter((item) => item.completed).length;
-
- return {
- visible:
- settingsQuery.isSuccess &&
- Boolean(settings?.onboarding_completed) &&
- !settings?.getting_started_dismissed,
- items,
- completedCount,
- totalCount: items.length,
- dismiss: () => saveMutate({ getting_started_dismissed: true }),
- restore: () => saveMutate({ getting_started_dismissed: false }),
- };
-}
diff --git a/client/src/hooks/useOnboarding.ts b/client/src/hooks/useOnboarding.ts
deleted file mode 100644
index fd7d93c5..00000000
--- a/client/src/hooks/useOnboarding.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import { useState, useCallback, useEffect } from 'react';
-import {
- useUserSettingsQuery,
- useSaveUserSettingsMutation,
-} from './useUserSettingsQuery';
-
-export interface OnboardingState {
- isVisible: boolean;
- currentStep: number;
- isCompleted: boolean;
- isLoading: boolean;
- hasChecked: boolean;
-}
-
-const DEFAULT_TOTAL_STEPS = 4;
-
-/**
- * Onboarding wizard state hook.
- *
- * @param reopenTrigger - bump from SettingsPanel to replay the wizard.
- * @param totalSteps - number of steps the wizard will render. Caller
- * owns the step list (`STEPS.length` in OnboardingWizard); the hook
- * uses this only to detect last-step completion. The default matches
- * the shipped wizard so a caller that omits it still completes.
- */
-export const useOnboarding = (
- reopenTrigger?: number,
- totalSteps: number = DEFAULT_TOTAL_STEPS,
-) => {
- const settingsQuery = useUserSettingsQuery();
- const saveSettings = useSaveUserSettingsMutation();
- const [state, setState] = useState<OnboardingState>({
- isVisible: false,
- currentStep: 0,
- isCompleted: false,
- isLoading: true,
- hasChecked: false,
- });
-
- // Hydrate UI state from query result.
- useEffect(() => {
- if (!settingsQuery.isSuccess) return;
- const settings = settingsQuery.data;
- const completed = settings?.onboarding_completed ?? false;
- const storedStep = settings?.onboarding_step ?? 0;
- const step = storedStep >= 0 && storedStep < totalSteps ? storedStep : 0;
- setState((prev) => ({
- ...prev,
- // Only flip visibility on first hydration; later renders shouldn't
- // re-open the wizard if the user manually closed it.
- isVisible: prev.hasChecked ? prev.isVisible : !completed,
- currentStep: prev.hasChecked ? prev.currentStep : step,
- isCompleted: completed,
- isLoading: false,
- hasChecked: true,
- }));
- }, [settingsQuery.isSuccess, settingsQuery.data, totalSteps]);
-
- // Surface query errors as a non-blocking "checked" state so the app
- // continues even if the WS round-trip failed.
- useEffect(() => {
- if (settingsQuery.isError) {
- console.error('[Onboarding] Failed to check status:', settingsQuery.error);
- setState((prev) => ({ ...prev, isLoading: false, hasChecked: true }));
- }
- }, [settingsQuery.isError, settingsQuery.error]);
-
- // Replay trigger from SettingsPanel.
- useEffect(() => {
- if (reopenTrigger && reopenTrigger > 0) {
- setState((prev) => ({
- ...prev,
- isVisible: true,
- currentStep: 0,
- isCompleted: false,
- }));
- }
- }, [reopenTrigger]);
-
- const saveProgress = useCallback(
- (step: number, completed: boolean) => {
- saveSettings.mutate({
- onboarding_step: step,
- onboarding_completed: completed,
- });
- },
- [saveSettings],
- );
-
- const nextStep = useCallback(() => {
- setState((prev) => {
- const next = prev.currentStep + 1;
- if (next >= totalSteps) {
- saveProgress(totalSteps, true);
- return { ...prev, currentStep: next, isCompleted: true, isVisible: false };
- }
- saveProgress(next, false);
- return { ...prev, currentStep: next };
- });
- }, [saveProgress, totalSteps]);
-
- const prevStep = useCallback(() => {
- setState((prev) => {
- const next = Math.max(0, prev.currentStep - 1);
- saveProgress(next, false);
- return { ...prev, currentStep: next };
- });
- }, [saveProgress]);
-
- const skip = useCallback(() => {
- saveProgress(state.currentStep, true);
- setState((prev) => ({ ...prev, isVisible: false, isCompleted: true }));
- }, [saveProgress, state.currentStep]);
-
- const complete = useCallback(() => {
- saveProgress(totalSteps, true);
- setState((prev) => ({ ...prev, isVisible: false, isCompleted: true }));
- }, [saveProgress, totalSteps]);
-
- return {
- ...state,
- totalSteps,
- nextStep,
- prevStep,
- skip,
- complete,
- };
-};
diff --git a/client/src/index.css b/client/src/index.css
index 1fca27fd..25b89801 100644
--- a/client/src/index.css
+++ b/client/src/index.css
@@ -245,6 +245,7 @@
--text-row: var(--text-row);
--text-lead: var(--text-lead);
--text-title: var(--text-title);
+ --text-headline: var(--text-headline);
--text-hero: var(--text-hero);
--radius-row: var(--radius-row);
@@ -257,6 +258,9 @@
--shadow-popover: var(--shadow-popover);
--shadow-dialog: var(--shadow-dialog);
--shadow-dock: var(--shadow-dock);
+ --shadow-pip: var(--shadow-pip);
+ /* The green "Connected" glow (light.css, dark.css), held while it shows. */
+ --shadow-glow-connect: var(--glow-connect);
/* Design-system elevation steps (base.css, dark.css), used by the chat. */
--shadow-card: var(--shadow-card);
--shadow-card-hover: var(--shadow-card-hover);
@@ -286,6 +290,10 @@
--color-status-waiting-fill: var(--status-waiting-fill);
--color-status-waiting-border: var(--status-waiting-border);
+ /* Error surfaces (themes/base.css) -> bg-danger-soft, border-danger-border */
+ --color-danger-soft: var(--danger-soft);
+ --color-danger-border: var(--danger-border);
+
--ease-spring: var(--ease-spring);
--ease-overshoot: var(--ease-overshoot);
--ease-reveal: var(--ease-reveal);
@@ -470,6 +478,19 @@ html {
}
}
+/* ============================================================================
+ * Welcome guide (Home onboarding): the demo stage. Two soft washes over the
+ * app surface, the agent fill from the top right and the model tint from
+ * the bottom left (design handoff A1).
+ * ============================================================================ */
+
+.home-welcome-stage {
+ background:
+ radial-gradient(110% 80% at 100% 0%, var(--node-agent-fill), transparent 60%),
+ radial-gradient(100% 80% at 0% 100%, var(--node-model-soft), transparent 65%),
+ var(--bg-app);
+}
+
/* ============================================================================
* Theme switch (ThemeContext.setTheme with `reveal`).
*
diff --git a/client/src/lib/__tests__/motion.test.ts b/client/src/lib/__tests__/motion.test.ts
index 1dff3d8f..2a7ff514 100644
--- a/client/src/lib/__tests__/motion.test.ts
+++ b/client/src/lib/__tests__/motion.test.ts
@@ -12,6 +12,9 @@ import {
loop,
motionSuppressed,
parseDuration,
+ rise,
+ RISE,
+ shake,
stagger,
STAGGER_FALLBACK,
staggerStep,
@@ -173,6 +176,55 @@ describe('animate', () => {
});
});
+describe('rise and shake', () => {
+ let waapi: ReturnType<typeof installWaapiStub>;
+ let restoreMotion: () => void;
+
+ beforeEach(() => {
+ waapi = installWaapiStub();
+ restoreMotion = setReducedMotion(false);
+ pageActivity.set(true);
+ });
+
+ afterEach(() => {
+ waapi.restore();
+ restoreMotion();
+ pageActivity.set(true);
+ invalidateMotionTokens();
+ });
+
+ it('rises on the spring curve over card-in, and takes overrides', () => {
+ const el = document.createElement('div');
+ rise(el);
+ expect(waapi.calls[0].keyframes).toBe(RISE);
+ expect(waapi.calls[0].options).toMatchObject({ duration: 700, easing: 'cubic-bezier(0.16, 1, 0.3, 1)' });
+ rise(el, { duration: 'intro', delay: 80 });
+ expect(waapi.calls[1].options).toMatchObject({ duration: 720, delay: 80 });
+ });
+
+ it('shakes -6, 5, -3, 2 px with each swing eased and the run linear', () => {
+ shake(document.createElement('div'));
+ const { keyframes, options } = waapi.calls[0];
+ expect((keyframes as Keyframe[]).map((k) => k.transform)).toEqual([
+ 'translateX(0px)',
+ 'translateX(-6px)',
+ 'translateX(5px)',
+ 'translateX(-3px)',
+ 'translateX(2px)',
+ 'translateX(0px)',
+ ]);
+ expect((keyframes as Keyframe[])[1].easing).toBe('cubic-bezier(0.36, 0.07, 0.19, 0.97)');
+ expect(options).toMatchObject({ duration: 420, easing: 'linear' });
+ });
+
+ it('lands at once under reduced motion', () => {
+ restoreMotion();
+ restoreMotion = setReducedMotion(true);
+ shake(document.createElement('div'));
+ expect(waapi.calls[0].options).toMatchObject({ duration: 1, delay: 0 });
+ });
+});
+
describe('finished', () => {
let waapi: ReturnType<typeof installWaapiStub>;
diff --git a/client/src/lib/motion.ts b/client/src/lib/motion.ts
index 6628b11f..8a5b1a05 100644
--- a/client/src/lib/motion.ts
+++ b/client/src/lib/motion.ts
@@ -24,7 +24,7 @@
import { pageActivity } from './pageActivity';
import { prefersReducedMotion } from './useReducedMotion';
-export type EaseName = 'default' | 'emphasis' | 'spring' | 'overshoot' | 'reveal';
+export type EaseName = 'default' | 'emphasis' | 'spring' | 'overshoot' | 'reveal' | 'shake';
export type DurName =
| 'fast'
@@ -50,6 +50,7 @@ export type DurName =
| 'glow'
| 'pip-loop'
| 'switch'
+ | 'shake'
| 'chat-rise'
| 'genui-enter'
| 'follow-in'
@@ -67,6 +68,7 @@ const EASE_FALLBACK: Record<EaseName, string> = {
spring: 'cubic-bezier(0.16, 1, 0.3, 1)',
overshoot: 'cubic-bezier(0.34, 1.56, 0.64, 1)',
reveal: 'cubic-bezier(0.65, 0, 0.35, 1)',
+ shake: 'cubic-bezier(0.36, 0.07, 0.19, 0.97)',
};
/** Mirrors the `--dur-*` values in themes/base.css; a test reads that file
@@ -95,6 +97,7 @@ export const DUR_FALLBACK: Record<DurName, number> = {
glow: 1400,
'pip-loop': 1600,
switch: 280,
+ shake: 420,
'chat-rise': 560,
'genui-enter': 420,
'follow-in': 460,
@@ -238,6 +241,27 @@ export function stagger(
return started;
}
+/** Home's entrance (onboarding handoff `rise`): up from 16px below, from
+ * .98 and a 4px blur. Use with `animate` / `stagger`, or through `rise`. */
+export const RISE: Keyframe[] = [
+ { opacity: 0, transform: 'translateY(16px) scale(0.98)', filter: 'blur(4px)' },
+ { opacity: 1, transform: 'none', filter: 'none' },
+];
+
+/** One element rising in on the spring curve; `card-in` unless told otherwise. */
+export function rise(el: Element | null | undefined, options: MotionOptions = {}): Animation | null {
+ return animate(el, RISE, { duration: 'card-in', easing: 'spring', ...options });
+}
+
+/** A short sideways shake (a rejected sign-in). Each swing is eased, as a
+ * CSS keyframe animation would be, so the whole run is linear. It starts
+ * over on every call and lands at once under reduced motion. */
+export function shake(el: Element | null | undefined): Animation | null {
+ const swing = ease('shake');
+ const keyframes: Keyframe[] = [0, -6, 5, -3, 2, 0].map((x) => ({ transform: `translateX(${x}px)`, easing: swing }));
+ return animate(el, keyframes, { duration: 'shake', easing: 'linear' });
+}
+
/** Resolves when the animation ends, is cancelled, or overruns its own
* timing by a small margin (so a throttled background tab never hangs a
* choreography waiting on it). Never rejects. */
diff --git a/client/src/lib/utils.ts b/client/src/lib/utils.ts
index 000226e6..a338fc15 100644
--- a/client/src/lib/utils.ts
+++ b/client/src/lib/utils.ts
@@ -13,9 +13,9 @@ import { extendTailwindMerge } from "tailwind-merge"
const twMerge = extendTailwindMerge({
extend: {
theme: {
- text: ["meta", "row", "lead", "title", "hero"],
+ text: ["meta", "row", "lead", "title", "headline", "hero"],
radius: ["pill", "row", "card", "panel", "draft", "composer"],
- shadow: ["float", "popover", "dialog", "dock", "card", "card-hover", "modal"],
+ shadow: ["float", "popover", "dialog", "dock", "pip", "glow-connect", "card", "card-hover", "modal"],
ease: ["spring", "overshoot", "reveal", "default", "emphasis"],
tracking: ["label", "hero", "wordmark"],
leading: ["hero"],
diff --git a/client/src/store/__tests__/appStore.test.ts b/client/src/store/__tests__/appStore.test.ts
new file mode 100644
index 00000000..b47e685a
--- /dev/null
+++ b/client/src/store/__tests__/appStore.test.ts
@@ -0,0 +1,154 @@
+/**
+ * Tests for useAppStore.requestChatFocus and the authoritative graph a
+ * save hands back.
+ *
+ * - requestChatFocus bumps a monotonic counter the console's Chat pane
+ * watches (components/__tests__/ConsolePanel.focus.test.tsx).
+ * - A save's response replaces the edit buffer with the server's
+ * normalized graph and reconciles the selection.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// --- mocks (hoisted; closures dereference the spies at call time) -----------
+
+const getAllWorkflowsMock = vi.fn();
+const getWorkflowMock = vi.fn();
+const saveWorkflowMock = vi.fn();
+const deleteWorkflowMock = vi.fn();
+
+vi.mock('../../services/workflowApi', () => ({
+ workflowApi: {
+ getAllWorkflows: (...args: unknown[]) => getAllWorkflowsMock(...args),
+ getWorkflow: (...args: unknown[]) => getWorkflowMock(...args),
+ saveWorkflow: (...args: unknown[]) => saveWorkflowMock(...args),
+ deleteWorkflow: (...args: unknown[]) => deleteWorkflowMock(...args),
+ },
+}));
+
+const toastInfoMock = vi.fn();
+const toastErrorMock = vi.fn();
+vi.mock('sonner', () => ({
+ toast: {
+ info: (...args: unknown[]) => toastInfoMock(...args),
+ error: (...args: unknown[]) => toastErrorMock(...args),
+ success: vi.fn(),
+ message: vi.fn(),
+ warning: vi.fn(),
+ },
+}));
+
+import { useAppStore } from '../useAppStore';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ useAppStore.setState({
+ currentWorkflow: null,
+ hasUnsavedChanges: false,
+ selectedNode: null,
+ consolePanelVisible: false,
+ chatFocusRequest: 0,
+ });
+});
+
+// ---------------------------------------------------------------------------
+
+describe('useAppStore.requestChatFocus', () => {
+ it('increments the monotonic chatFocusRequest counter', () => {
+ expect(useAppStore.getState().chatFocusRequest).toBe(0);
+ useAppStore.getState().requestChatFocus();
+ expect(useAppStore.getState().chatFocusRequest).toBe(1);
+ useAppStore.getState().requestChatFocus();
+ expect(useAppStore.getState().chatFocusRequest).toBe(2);
+ });
+});
+
+describe('useAppStore authoritative normalized graph handoff', () => {
+ it('replaces the edit buffer with save response data and reconciles selection', async () => {
+ const draftAgent = {
+ id: 'draft-agent',
+ type: 'aiAgent',
+ data: { label: 'Agent' },
+ position: { x: 100, y: 100 },
+ };
+ useAppStore.setState({
+ currentWorkflow: {
+ id: 'wf-1',
+ name: 'Context flow',
+ slug: 'Context_flow_1',
+ nodes: [draftAgent],
+ edges: [],
+ createdAt: new Date(),
+ lastModified: new Date(),
+ },
+ selectedNode: draftAgent,
+ hasUnsavedChanges: true,
+ });
+ const normalizedAgent = { ...draftAgent, id: 'wf-1:aiAgent:1' };
+ const contextNode = {
+ id: 'wf-1:context:1',
+ type: 'context',
+ data: { systemManaged: true },
+ position: { x: -120, y: 100 },
+ };
+ const contextEdge = {
+ id: 'wf-1:edge:context:1',
+ source: contextNode.id,
+ target: normalizedAgent.id,
+ sourceHandle: 'output-context',
+ targetHandle: 'input-context',
+ };
+ saveWorkflowMock.mockResolvedValue({
+ success: true,
+ id: 'wf-1',
+ slug: 'Context_flow_1',
+ nodeIdAliases: { 'draft-agent': normalizedAgent.id },
+ data: {
+ graphVersion: 2,
+ nodes: [normalizedAgent, contextNode],
+ edges: [contextEdge],
+ },
+ });
+
+ await useAppStore.getState().saveWorkflow();
+
+ const state = useAppStore.getState();
+ expect(state.currentWorkflow?.nodes).toEqual([normalizedAgent, contextNode]);
+ expect(state.currentWorkflow?.edges).toEqual([contextEdge]);
+ expect(state.selectedNode).toEqual(normalizedAgent);
+ expect(state.hasUnsavedChanges).toBe(false);
+ });
+
+ it('uses aliases only as a compatibility fallback when save data is absent', async () => {
+ const draftAgent = {
+ id: 'draft-agent',
+ type: 'aiAgent',
+ data: {},
+ position: { x: 0, y: 0 },
+ };
+ useAppStore.setState({
+ currentWorkflow: {
+ id: 'wf-1',
+ name: 'Legacy save',
+ slug: '',
+ nodes: [draftAgent],
+ edges: [],
+ createdAt: new Date(),
+ lastModified: new Date(),
+ },
+ selectedNode: draftAgent,
+ });
+ saveWorkflowMock.mockResolvedValue({
+ success: true,
+ id: 'wf-1',
+ nodeIdAliases: { 'draft-agent': 'wf-1:aiAgent:1' },
+ });
+
+ await useAppStore.getState().saveWorkflow();
+
+ expect(useAppStore.getState().currentWorkflow?.nodes[0].id).toBe(
+ 'wf-1:aiAgent:1',
+ );
+ expect(useAppStore.getState().selectedNode?.id).toBe('wf-1:aiAgent:1');
+ });
+});
diff --git a/client/src/store/__tests__/openExampleAndChat.test.ts b/client/src/store/__tests__/openExampleAndChat.test.ts
deleted file mode 100644
index 8be53529..00000000
--- a/client/src/store/__tests__/openExampleAndChat.test.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-/**
- * Tests for useAppStore.openExampleAndChat + requestChatFocus.
- *
- * Locks the onboarding handoff contract:
- * - case-insensitive name lookup against workflowApi.getAllWorkflows()
- * - hit: loads the workflow (workflowApi.getWorkflow), reveals the console
- * panel, bumps chatFocusRequest, returns the loaded workflow
- * - miss: toast.info, returns null, state untouched
- * - load failure (getWorkflow -> null): toast.error, returns null,
- * state untouched
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-// --- mocks (hoisted; closures dereference the spies at call time) -----------
-
-const getAllWorkflowsMock = vi.fn();
-const getWorkflowMock = vi.fn();
-const saveWorkflowMock = vi.fn();
-const deleteWorkflowMock = vi.fn();
-
-vi.mock('../../services/workflowApi', () => ({
- workflowApi: {
- getAllWorkflows: (...args: unknown[]) => getAllWorkflowsMock(...args),
- getWorkflow: (...args: unknown[]) => getWorkflowMock(...args),
- saveWorkflow: (...args: unknown[]) => saveWorkflowMock(...args),
- deleteWorkflow: (...args: unknown[]) => deleteWorkflowMock(...args),
- },
-}));
-
-const toastInfoMock = vi.fn();
-const toastErrorMock = vi.fn();
-vi.mock('sonner', () => ({
- toast: {
- info: (...args: unknown[]) => toastInfoMock(...args),
- error: (...args: unknown[]) => toastErrorMock(...args),
- success: vi.fn(),
- message: vi.fn(),
- warning: vi.fn(),
- },
-}));
-
-import { useAppStore } from '../useAppStore';
-
-// --- fixtures ----------------------------------------------------------------
-
-const summary = (id: string, name: string) => ({
- id,
- name,
- slug: `${name.replace(/\s+/g, '_')}_1`,
- nodeCount: 1,
- createdAt: '2026-01-01T00:00:00Z',
- lastModified: '2026-01-02T00:00:00Z',
-});
-
-// Shape of workflowApi.getWorkflow's resolved value (services/workflowApi.ts
-// WorkflowData): { id, name, slug, data: { nodes, edges }, createdAt,
-// lastModified }.
-const workflowRecord = (id: string, name: string) => ({
- id,
- name,
- slug: `${name.replace(/\s+/g, '_')}_1`,
- data: { nodes: [], edges: [] },
- createdAt: '2026-01-01T00:00:00Z',
- lastModified: '2026-01-02T00:00:00Z',
-});
-
-beforeEach(() => {
- vi.clearAllMocks();
- useAppStore.setState({
- currentWorkflow: null,
- hasUnsavedChanges: false,
- selectedNode: null,
- consolePanelVisible: false,
- chatFocusRequest: 0,
- });
-});
-
-// ---------------------------------------------------------------------------
-
-describe('useAppStore.requestChatFocus', () => {
- it('increments the monotonic chatFocusRequest counter', () => {
- expect(useAppStore.getState().chatFocusRequest).toBe(0);
- useAppStore.getState().requestChatFocus();
- expect(useAppStore.getState().chatFocusRequest).toBe(1);
- useAppStore.getState().requestChatFocus();
- expect(useAppStore.getState().chatFocusRequest).toBe(2);
- });
-});
-
-describe('useAppStore.openExampleAndChat', () => {
- it('finds the workflow case-insensitively, loads it, opens the console, and requests chat focus', async () => {
- getAllWorkflowsMock.mockResolvedValue([
- summary('wf-other', 'Other Flow'),
- summary('wf-1', 'AI Assistant'),
- ]);
- getWorkflowMock.mockResolvedValue(workflowRecord('wf-1', 'AI Assistant'));
-
- const result = await useAppStore.getState().openExampleAndChat('ai assistant');
-
- // Load path went through workflowApi.getWorkflow with the matched id.
- expect(getWorkflowMock).toHaveBeenCalledTimes(1);
- expect(getWorkflowMock).toHaveBeenCalledWith('wf-1');
-
- // Returns the loaded workflow.
- expect(result).not.toBeNull();
- expect(result!.id).toBe('wf-1');
- expect(result!.name).toBe('AI Assistant');
-
- const state = useAppStore.getState();
- expect(state.currentWorkflow?.id).toBe('wf-1');
- expect(state.currentWorkflow?.name).toBe('AI Assistant');
- expect(state.hasUnsavedChanges).toBe(false);
- expect(state.consolePanelVisible).toBe(true);
- expect(state.chatFocusRequest).toBe(1);
-
- expect(toastInfoMock).not.toHaveBeenCalled();
- expect(toastErrorMock).not.toHaveBeenCalled();
- });
-
- it('toasts info and leaves state untouched when no workflow matches the name', async () => {
- getAllWorkflowsMock.mockResolvedValue([summary('wf-other', 'Other Flow')]);
-
- const result = await useAppStore.getState().openExampleAndChat('AI Assistant');
-
- expect(result).toBeNull();
- expect(toastInfoMock).toHaveBeenCalledTimes(1);
- expect(getWorkflowMock).not.toHaveBeenCalled();
-
- const state = useAppStore.getState();
- expect(state.currentWorkflow).toBeNull();
- expect(state.consolePanelVisible).toBe(false);
- expect(state.chatFocusRequest).toBe(0);
- expect(toastErrorMock).not.toHaveBeenCalled();
- });
-
- it('toasts error and returns null when the workflow fails to load', async () => {
- getAllWorkflowsMock.mockResolvedValue([summary('wf-1', 'AI Assistant')]);
- getWorkflowMock.mockResolvedValue(null); // loadWorkflow leaves the store untouched
-
- const result = await useAppStore.getState().openExampleAndChat('AI Assistant');
-
- expect(result).toBeNull();
- expect(getWorkflowMock).toHaveBeenCalledWith('wf-1');
- expect(toastErrorMock).toHaveBeenCalledTimes(1);
- expect(toastInfoMock).not.toHaveBeenCalled();
-
- const state = useAppStore.getState();
- expect(state.currentWorkflow).toBeNull();
- expect(state.consolePanelVisible).toBe(false);
- expect(state.chatFocusRequest).toBe(0);
- });
-
- it('does not treat a different open workflow as the load target (id verification)', async () => {
- // A previously open workflow stays current when the load fails; the id
- // check must compare against the TARGET id, not merely non-null.
- useAppStore.setState({
- currentWorkflow: {
- id: 'wf-prev',
- name: 'Previous',
- slug: '',
- nodes: [],
- edges: [],
- createdAt: new Date(),
- lastModified: new Date(),
- },
- });
- getAllWorkflowsMock.mockResolvedValue([summary('wf-1', 'AI Assistant')]);
- getWorkflowMock.mockResolvedValue(null);
-
- const result = await useAppStore.getState().openExampleAndChat('AI Assistant');
-
- expect(result).toBeNull();
- expect(toastErrorMock).toHaveBeenCalledTimes(1);
- const state = useAppStore.getState();
- expect(state.currentWorkflow?.id).toBe('wf-prev');
- expect(state.consolePanelVisible).toBe(false);
- expect(state.chatFocusRequest).toBe(0);
- });
-});
-
-describe('useAppStore authoritative normalized graph handoff', () => {
- it('replaces the edit buffer with save response data and reconciles selection', async () => {
- const draftAgent = {
- id: 'draft-agent',
- type: 'aiAgent',
- data: { label: 'Agent' },
- position: { x: 100, y: 100 },
- };
- useAppStore.setState({
- currentWorkflow: {
- id: 'wf-1',
- name: 'Context flow',
- slug: 'Context_flow_1',
- nodes: [draftAgent],
- edges: [],
- createdAt: new Date(),
- lastModified: new Date(),
- },
- selectedNode: draftAgent,
- hasUnsavedChanges: true,
- });
- const normalizedAgent = { ...draftAgent, id: 'wf-1:aiAgent:1' };
- const contextNode = {
- id: 'wf-1:context:1',
- type: 'context',
- data: { systemManaged: true },
- position: { x: -120, y: 100 },
- };
- const contextEdge = {
- id: 'wf-1:edge:context:1',
- source: contextNode.id,
- target: normalizedAgent.id,
- sourceHandle: 'output-context',
- targetHandle: 'input-context',
- };
- saveWorkflowMock.mockResolvedValue({
- success: true,
- id: 'wf-1',
- slug: 'Context_flow_1',
- nodeIdAliases: { 'draft-agent': normalizedAgent.id },
- data: {
- graphVersion: 2,
- nodes: [normalizedAgent, contextNode],
- edges: [contextEdge],
- },
- });
-
- await useAppStore.getState().saveWorkflow();
-
- const state = useAppStore.getState();
- expect(state.currentWorkflow?.nodes).toEqual([normalizedAgent, contextNode]);
- expect(state.currentWorkflow?.edges).toEqual([contextEdge]);
- expect(state.selectedNode).toEqual(normalizedAgent);
- expect(state.hasUnsavedChanges).toBe(false);
- });
-
- it('uses aliases only as a compatibility fallback when save data is absent', async () => {
- const draftAgent = {
- id: 'draft-agent',
- type: 'aiAgent',
- data: {},
- position: { x: 0, y: 0 },
- };
- useAppStore.setState({
- currentWorkflow: {
- id: 'wf-1',
- name: 'Legacy save',
- slug: '',
- nodes: [draftAgent],
- edges: [],
- createdAt: new Date(),
- lastModified: new Date(),
- },
- selectedNode: draftAgent,
- });
- saveWorkflowMock.mockResolvedValue({
- success: true,
- id: 'wf-1',
- nodeIdAliases: { 'draft-agent': 'wf-1:aiAgent:1' },
- });
-
- await useAppStore.getState().saveWorkflow();
-
- expect(useAppStore.getState().currentWorkflow?.nodes[0].id).toBe(
- 'wf-1:aiAgent:1',
- );
- expect(useAppStore.getState().selectedNode?.id).toBe('wf-1:aiAgent:1');
- });
-});
diff --git a/client/src/store/useAppStore.ts b/client/src/store/useAppStore.ts
index 5dfc4128..7449e61d 100644
--- a/client/src/store/useAppStore.ts
+++ b/client/src/store/useAppStore.ts
@@ -125,10 +125,6 @@ interface AppStore {
setConsolePanelVisible: (visible: boolean) => void;
toggleConsolePanelVisible: () => void;
requestChatFocus: () => void;
- /** Open a workflow by display name, reveal the console panel, and focus
- * the chat input. Used by the onboarding finish handoff and the Get
- * Started checklist. Returns the loaded workflow, or null if not found. */
- openExampleAndChat: (name: string) => Promise<WorkflowData | null>;
applyUIDefaults: (defaults: { sidebarDefaultOpen?: boolean; componentPaletteDefaultOpen?: boolean; consolePanelDefaultOpen?: boolean }) => void;
// Per-workflow UI state actions (n8n pattern)
@@ -581,26 +577,6 @@ export const useAppStore = create<AppStore>((set, get) => ({
set((state) => ({ chatFocusRequest: state.chatFocusRequest + 1 }));
},
- openExampleAndChat: async (name) => {
- const workflows = await workflowApi.getAllWorkflows();
- const target = workflows.find((w) => w.name.toLowerCase() === name.toLowerCase());
- if (!target) {
- toast.info(`The "${name}" example was not found. Open any workflow from the sidebar to chat with it.`);
- return null;
- }
-
- await get().loadWorkflow(target.id);
- const loaded = get().currentWorkflow;
- if (loaded?.id !== target.id) {
- toast.error(`Could not open "${name}". Try opening it from the sidebar.`);
- return null;
- }
-
- get().setConsolePanelVisible(true);
- get().requestChatFocus();
- return loaded;
- },
-
applyUIDefaults: (defaults) => {
const updates: Partial<{ sidebarVisible: boolean; componentPaletteVisible: boolean; consolePanelVisible: boolean }> = {};
diff --git a/client/src/stores/shellDialogsStore.ts b/client/src/stores/shellDialogsStore.ts
index 1dacc1e2..d5b1494d 100644
--- a/client/src/stores/shellDialogsStore.ts
+++ b/client/src/stores/shellDialogsStore.ts
@@ -21,13 +21,10 @@ interface ShellDialogsState {
credentialsOptions: CredentialsOptions & { intent: CredentialsIntent };
/** Repeated opens are navigation requests, even when their target matches. */
credentialsRequestId: number;
- /** Increments to ask the (editor-only) onboarding wizard to reopen. */
- onboardingReplay: number;
openSettings: () => void;
closeSettings: () => void;
openCredentials: (options?: CredentialsOptions) => void;
closeCredentials: () => void;
- replayOnboarding: () => void;
}
export const useShellDialogsStore = create<ShellDialogsState>((set) => ({
@@ -35,7 +32,6 @@ export const useShellDialogsStore = create<ShellDialogsState>((set) => ({
credentialsOpen: false,
credentialsOptions: { intent: 'manage' },
credentialsRequestId: 0,
- onboardingReplay: 0,
openSettings: () => set({ settingsOpen: true }),
closeSettings: () => set({ settingsOpen: false }),
openCredentials: (options) => set((state) => ({
@@ -44,5 +40,4 @@ export const useShellDialogsStore = create<ShellDialogsState>((set) => ({
credentialsRequestId: state.credentialsRequestId + 1,
})),
closeCredentials: () => set({ credentialsOpen: false }),
- replayOnboarding: () => set((state) => ({ settingsOpen: false, onboardingReplay: state.onboardingReplay + 1 })),
}));
diff --git a/client/src/themes/animations.css b/client/src/themes/animations.css
index 03376dde..4788fc54 100644
--- a/client/src/themes/animations.css
+++ b/client/src/themes/animations.css
@@ -261,10 +261,20 @@
animation: opencompany-draw var(--dur-check-draw, 420ms) var(--ease-spring) both;
}
+/* ============================================================================
+ * Onboarding (design handoff onboarding, 2026-10-08).
+ * ========================================================================== */
+
+/* A hard on/off blink: the typing caret in the Welcome guide's demo. */
+@keyframes opencompany-blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
+.opencompany-caret-blink { animation: opencompany-blink var(--dur-caret, 1000ms) steps(1) infinite; }
+/* The slower ring spinner: a new employee starting up. */
+.opencompany-spinner-slow { animation: spin var(--dur-live-ring, 1200ms) linear infinite; }
+
@media (prefers-reduced-motion: reduce) {
.opencompany-pulse, .opencompany-crt, .opencompany-scanline::after,
.opencompany-trigger-armed, .opencompany-trigger-fire, .opencompany-bolt, .opencompany-pip-pulse,
.opencompany-spinner, .opencompany-live-ring, .opencompany-shimmer, .opencompany-shimmer-slot,
.opencompany-shimmer-text, .opencompany-caret, .opencompany-dots > *, .opencompany-grow,
- .opencompany-draw { animation: none !important; }
+ .opencompany-draw, .opencompany-caret-blink, .opencompany-spinner-slow { animation: none !important; }
}
diff --git a/client/src/themes/base.css b/client/src/themes/base.css
index 58483891..52ab2cfe 100644
--- a/client/src/themes/base.css
+++ b/client/src/themes/base.css
@@ -126,6 +126,7 @@
--ease-spring: cubic-bezier(0.16, 1, 0.3, 1); /* entrances, panels */
--ease-overshoot: cubic-bezier(0.34, 1.56, 0.64, 1); /* pops (logo, nodes) */
--ease-reveal: cubic-bezier(0.65, 0, 0.35, 1); /* theme wipe */
+ --ease-shake: cubic-bezier(0.36, 0.07, 0.19, 0.97); /* each swing of a shake */
--dur-intro: 720ms;
--dur-card-in: 700ms;
--dur-view-swap: 520ms;
@@ -146,6 +147,7 @@
--dur-glow: 1400ms;
--dur-pip-loop: 1600ms;
--dur-switch: 280ms; /* switch knob travel */
+ --dur-shake: 420ms; /* a rejected sign-in shakes its card */
--stagger-intro: 80ms;
--stagger-settings: 30ms;
--blur-scrim: 6px; /* backdrop blur behind Home dialogs */
@@ -164,6 +166,7 @@
--text-row: 13.5px;
--text-lead: 15px;
--text-title: 22px;
+ --text-headline: 28px; /* onboarding headings: the guide's welcome, a new hire's arrival */
--text-hero: 36px;
--tracking-hero: -0.025em;
--leading-hero: 1.15;
@@ -177,9 +180,13 @@
--w-employee-card: 620px;
--size-orb-hire: min(230px, 26vh);
--size-orb-employee: min(96px, 14vh); /* small: the conversation has the page */
+ --size-orb-connecting: min(300px, 36vh); /* waiting for the server */
+ --size-orb-login: min(150px, 20vh); /* above the sign-in card */
--w-settings: 1040px;
--h-settings: 760px;
--w-settings-nav: 224px;
+ --w-guide: 940px; /* the Welcome guide dialog */
+ --h-guide: 620px;
/* ── Chat (Home Talk and Dev's console Chat pane share it) — design
* handoff design_handoff_opencompany_home/chat (2026-10-03). Loop
@@ -231,6 +238,8 @@
--status-waiting-ink: var(--node-workflow-ink);
--status-waiting-fill: color-mix(in srgb, var(--status-waiting-dot) var(--tint-status-fill), transparent);
--status-waiting-border: color-mix(in srgb, var(--status-waiting-dot) var(--tint-status-border), transparent);
+ /* A status dot's glow: colour the dot with text-status-*-dot and bg-current. */
+ --shadow-pip: 0 0 8px currentColor;
/* Sound (read by JS in a future phase) */
--sound-pack: none;
@@ -286,6 +295,8 @@
--success-soft: color-mix(in srgb, var(--success) var(--tint-semantic-soft), transparent);
--warning-soft: color-mix(in srgb, var(--warning) var(--tint-semantic-soft), transparent);
--danger-soft: color-mix(in srgb, var(--destructive) var(--tint-semantic-soft), transparent);
+ /* The outline of an error on a Home surface (the sign-in card's alert). */
+ --danger-border: color-mix(in srgb, var(--destructive) var(--tint-status-border), transparent);
}
/* ============================================================================
diff --git a/docs-internal/chat_protocol.md b/docs-internal/chat_protocol.md
index ab5dd63f..64e84114 100644
--- a/docs-internal/chat_protocol.md
+++ b/docs-internal/chat_protocol.md
@@ -434,9 +434,11 @@ continuation: Resume does not explicitly rerun completed tools to reconstruct th
`client/src/features/chat/` is the shared chat; only its `index.ts` is public (an ESLint rule keeps the rest
private, tests excepted). Hosts give it a `ChatHost` (`host.ts`): the session and scope, who answers, whether the
-message box sends now, waits for Resume or is closed, and what sits around the conversation (notices, a top slot, a
-slot after the thread, a footnote, how to tell the owner something). Home's employee page (`EmployeeChat`) and the
-editor's console pane (`ConsoleChat`, compact, scope `live`) are the two hosts.
+message box sends now, waits for Resume, shows but takes nothing yet (`wait`, with the host's `placeholder`: a new
+hire still starting) or is closed, and what sits around the conversation (notices, a top slot, a slot after the
+thread, an empty state, greetings that fill the box in place of the suggested commands, a footnote, how to tell the
+owner something). Home's employee page (`EmployeeChat`) and the editor's console pane (`ConsoleChat`, compact, scope
+`live`) are the two hosts.
- **Run events** reach `stores/chatRunStore.ts` through one `case 'chat_run_event'` in `WebSocketContext.tsx`.
`lib/agui/events.ts` checks each frame (source, type prefix, `subject`, `id` = `<run id>:<seq>`, scope fields) and
diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.md
index 963e6df2..d8014359 100644
--- a/docs-internal/frontend_architecture.md
+++ b/docs-internal/frontend_architecture.md
@@ -147,11 +147,6 @@ client/src/
│ │ ├── InputSection.tsx # Connected node outputs
│ │ └── MasterSkillEditor.tsx # Skill enable/disable + instructions editor
│ │
-│ ├── onboarding/
-│ │ ├── OnboardingWizard.tsx # Custom step indicator (no antd Steps)
-│ │ ├── GetStartedChecklist.tsx # Post-wizard checklist
-│ │ └── steps/ # WelcomeStep / HowItWorksStep / ConnectAIStep / TryItStep
-│ │
│ ├── icons/ # AI provider icons (SVG data URIs)
│ ├── brand/Logo.tsx # OcMark / OcLogo (inline SVG in the text colour, intro + pulse)
│ ├── brand/geometry.ts # Mark + wordmark paths; the favicon, desktop icon and media/brand/ SVGs embed MARK_PATH
@@ -175,7 +170,6 @@ client/src/
│ ├── useApiKeys.ts # WS-based API key CRUD
│ ├── useApiKeyValidation.ts # Provider-specific validation helpers
│ ├── useComponentPalette.ts / useDragAndDrop.ts / useDragWorkspaceFile.ts
-│ ├── useOnboarding.ts # Reads via useUserSettingsQuery; writes via mutation
│ ├── useParameterPanel.ts # Thin orchestrator over useNodeParamsQuery + save mutation
│ ├── useWhatsApp.ts # WS-based WhatsApp ops (Android ops go via useWebSocket directly)
│ ├── useUserSkills.ts / useFolderSkills.ts # Skill library + skill-folder queries (Home Skills, Master Skill editor)
@@ -424,7 +418,7 @@ components/credentials/CredentialsModal.tsx (one AppShell host)
**Anchor cache contracts at the prefix root via `setQueryDefaults`, not per-call options.** `PersistQueryClientProvider` hydrates entries from localStorage with the QueryClient's *default* options, so per-call `staleTime: FOREVER` does not stop `gcTime: 5min` eviction on hydration. Every persisted prefix must have a matching `queryClient.setQueryDefaults(['<prefix>'], { staleTime: FOREVER, gcTime: FOREVER })` declaration in [client/src/lib/queryClient.ts](../client/src/lib/queryClient.ts). The persisted set is `['nodeSpec']`, `['nodeGroups']`; both carry `setQueryDefaults`. `['skillContent']` and `['credentialValues']` carry `setQueryDefaults` for in-memory longevity only and are intentionally absent from the persistor whitelist. The persistor whitelist in [client/src/lib/queryPersist.ts](../client/src/lib/queryPersist.ts) must mirror it; a string in the whitelist that doesn't match a real query key (the prior `'pluginCatalogue'` typo) is silently dead. `credentialCatalogue` is intentionally NOT in either list — it has its own `idb-keyval` warm-start. `credentialValues` keeps `gcTime: FOREVER` for the in-memory cache so the credentials form survives idle, but it is intentionally NOT persisted (OWASP — see "Persistence layers" above).
**Component rules:**
-- Normal and Dev use the same connector cards and provider dialogs. `openCredentials({ providerId?, categoryId?, intent? })` defaults to management; guided connection intent closes on a selected provider's disconnected-to-connected transition. Connected cards expose Manage and Disconnect. All entry points use the app-level host, including Home's AI setup action.
+- Normal and Dev use the same connector cards and provider dialogs. `openCredentials({ providerId?, categoryId?, intent? })` defaults to management; guided connection intent closes on a selected provider's disconnected-to-connected transition. Connected cards expose Manage and Disconnect. Every entry point uses the app-level host, including Home's AI setup action, except the Welcome guide's Connect step: it renders the same provider page ([components/credentials/ProviderPage.tsx](../client/src/components/credentials/ProviderPage.tsx), which the host shows as its second layer) in place of its list, with its own heading, and returns to the list when the model connects.
- The host derives `showTechnicalSections` from effective `useShellMode()` (including the Home-disabled fallback). Provider defaults, usage and rate limits mount only in Dev. Required authentication fields, callback URLs and setup help remain available in both modes; normal-mode saves never clear advanced values.
- The shared catalogue waits for credential-category visibility before mounting a provider form, including direct targets. Missing or disabled targets show an unavailable state. The credential panel is keyed by provider ID, never mode: switching mode preserves connection drafts, while switching providers resets transient errors and secret reveal state.
- `PanelRenderer` lazy-loads each panel type so the initial JS payload doesn't grow linearly with provider count.
diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.md
index 5771e430..805fd3d9 100644
--- a/docs-internal/normal_mode.md
+++ b/docs-internal/normal_mode.md
@@ -64,24 +64,41 @@ is the reference.
| Folder | Contents |
|---|---|
-| `HomeShell.tsx` | Sidebar, header, the current view (hire or one employee), the Workspace dock, Settings, the connect dialog, the guided Connect an AI model dialog, the orb's stage, and under an employee's page a line saying whether they ask first |
-| `sidebar/`, `header/` | The team list, New employee, the profile row; the view title, the Workspace pill, the mode toggle (on an employee's page, Dev opens their workflow) and the theme button |
+| `HomeShell.tsx` | Sidebar, header, the current view (hire or one employee), the Workspace dock, Settings, the Welcome guide, the Get started checklist, the connect dialog, the orb's stage, and under an employee's page a line saying whether they ask first |
+| `sidebar/`, `header/` | The team list, New employee, the profile row; the view title, the Guide pill (opens the Welcome guide), the Workspace pill, the mode toggle (on an employee's page, Dev opens their workflow) and the theme button |
+| `onboarding/` | The Welcome guide: three steps (Welcome, Connect an AI model, Your first hire) that open on first launch and again from Guide or Settings > Help; then the Get started checklist in the corner (connect a model, hire, say hello, approve a first draft) until it is hidden ([onboarding.md](./onboarding.md)) |
| `hire/` | The hero, the composer, the template chips, the hire notice (`HireNotice.tsx`), and the starter bundles (`starters.json`), which the chips and Settings > Plugins both read |
| `genui/` | The setup draft under the composer, and the hire itself, from a setup or a starter (below) |
| `employee/` | One employee's page, which is the conversation with them (`EmployeeChat` over the shared chat, Talk below); the header names them. What to act on shows only while there is something to do: the drafts waiting for the owner after the conversation, and above the message box their main action while they can't read messages (Resume, Start, or connect what is missing; `useEmployeeControl`, `PrimaryActionButton`) or Help in browser while they wait there. The conversation's Stop controls its run's owning generation; the Workspace header offers generation Stop and Resume too |
-| `connectAI/` | The guided Connect an AI model dialog (below) |
| `workspace/` | The Workspace dock (below), its header pill, and its Canvas tab, which loads in its own chunk |
-| `settings/` | Settings pages (Profile, Billing, Skills, Connectors, Plugins). Catalog primitives live in `components/catalog`; Connectors embeds the shared `components/credentials/CredentialsBrowser`. Provider dialogs belong to AppShell. |
+| `settings/` | Settings pages (App access, Profile, Billing, Help, Skills, Connectors, Plugins). Catalog primitives live in `components/catalog`; Connectors embeds the shared `components/credentials/CredentialsBrowser`. Provider dialogs belong to AppShell. |
| `approvals/` | The drafts query, the decide mutation (optimistic), the approval broadcast listener |
| `data/` | zod-parsed queries for employees, connectors and the profile; `employeeCache.ts`, the team's query keys and `removeEmployee` (shared with the app store's delete); `talk.ts`, Turn on Talk, Apply and the retry note (the thread itself is the shared chat's); `presentation.ts` maps server state to pills, actions and the message box's mode without deriving new rules |
| `orb/` | The 3D orb (below) |
| `ui/` | Small shared pieces (avatar, status dot and pill, app mark), the pill toast, and `useAutoGrow` (the composer's and the message box's growing text area) |
-| `state/homeStore.ts` | UI state only: the view, the sidebar, Settings, the Connect an AI model dialog, the last hire's notice, the Workspace dock, one-shot glow and pulse signals |
+| `state/homeStore.ts` | UI state only: the view, the sidebar, Settings, the Welcome guide (`guide`), new hires' first days (`firstDays`), the last hire's notice, the Workspace dock, one-shot glow and pulse signals; `openConnectAI` opens the app's credentials dialog on the AI category |
-Status comes from the server: an employee summary is `working`, `ready`,
-`paused` or `attention` (an automatic pause, see below). The `paused` summary
-is displayed as **Stopped**; durable control transitions display
-**Stopping…** or **Resuming…** even after the local request has ended. A pending draft
+Status comes from the server: an employee summary is `working` (control
+`starting`, `running` or `resuming`), `ready` (never started, or reset),
+`paused` or `attention` (an automatic pause, see below). The pill
+(`presentEmployee` in `data/presentation.ts`, first match wins):
+
+| State | Pill |
+|---|---|
+| a draft waits, or the browser waits for the owner | **Needs you** |
+| Start pressed, or control `starting` / `resuming` | **Starting…** / **Resuming…** (cyan) |
+| `working` and answering | **Working** (green, the pip pulses) |
+| `working`, idle | **Ready** (cyan) |
+| `ready` | **Not started** (grey) |
+| `paused` / `attention` | **Stopped** / **Needs attention** |
+
+"Answering" is live, not from the summary: one of the employee's
+`watch_node_ids`, or their Talk agent (`talk.agent_node_id`), is `executing`
+in the node status store (`useAnswering` in `data/liveTask.ts`). The hire
+view's "N working now" counts the same way (`useAnsweringCount`). The
+Workspace header keeps its own **Live** pill for a running employee. Durable
+control transitions display **Stopping…** or **Resuming…** on the main button
+even after the local request has ended. A pending draft
shows as "Needs you". So does a browser waiting for the owner: when an agent
calls `request_user`, the summary's `browser_request` (`{node_id, reason,
since}`, never the agent's message, since summaries reach every socket) is
@@ -143,21 +160,36 @@ side, around the core, and three heads each trailing a crescent that tapers
along the ring. The ring spins, the heads turn more slowly the same way, and a
line from the core to each head carries a packet.
[orb/orb.ts](../client/src/features/home/orb/orb.ts) holds what the engine
-reads each frame (the slot to fill, an energy target, a spike) and its
-lifecycle: leaving Home keeps the renderer, the app shell disposes it.
-`OrbStage` is the canvas host below the header; each view's `OrbSlot` reserves
-the square the orb glides into (`--size-orb-hire`, `--size-orb-employee`:
-large on the hire view, small on an employee's page, where the conversation
-needs the room). The composer sets the energy target (focused, holding text, a
-setup being written). These spike it: a hire, a theme or mode switch, a
-connect, a task change, opening Settings or the Workspace, a setup arriving or
-failing, and saving the profile (`SPIKE` in orb.ts). The logo itself is one
+reads each frame (the slot to fill, an energy target, a spike, whether it
+waits for the server) and its lifecycle: leaving Home keeps the renderer, and
+the app (`App.tsx`, above the sign-in gate, so signing out never frees an orb
+the sign-in screen has taken) disposes it. `OrbStage` is the canvas host
+(`fill="home"` below Home's header, `fill="screen"` the whole window for the
+Connecting and sign-in screens); each view's `OrbSlot` reserves the square the
+orb glides into (`--size-orb-hire`, `--size-orb-employee`, and
+`--size-orb-connecting` / `--size-orb-login`: large on the hire view, small on
+an employee's page, where the conversation needs the room). Stages and slots
+are stacks: a screen mounted over another (Connecting over Home) borrows the
+orb and hands it back when it goes. The composer sets the energy target
+(focused, holding text, a setup being written). These spike it: a hire, a theme
+or mode switch, a connect, a task change, opening Settings or the Workspace, a
+setup arriving or failing, saving the profile, the server answering again and
+signing in (`SPIKE` in orb.ts). While the server can't be reached
+(`setOrbWaiting`) it eases into a waiting mode (onboarding handoff R3): slower,
+a double heartbeat in the core, the heads breathing out and back in turn
+(each head and its crescent are one group), one searching ping per line,
+slightly dimmer, blended in and out over about a second with no jump. The
+engine measures its host every frame, draws nothing until the host has a size,
+and stops its frames while the page is hidden or the window blurred
+(`lib/pageActivity`). The logo itself is one
colour; in dark the orb keeps colours of its own (a purple-to-cyan ring; pink,
yellow and green heads) with white particles and packets; in light it is
glossy piano-black under a white rim light. Its glows and particles blend
additively in dark and normally in light (additive glow vanishes on white),
fading through zero at the midpoint of a theme change. Without WebGL, under
-reduced motion, or after a lost WebGL context, the slot shows the static mark.
+reduced motion, or after a lost WebGL context, the slot shows the static mark
+for the session; when the engine's chunk fails to load it shows the mark until
+the next stage mounts and tries again (`orb/__tests__/orb.test.ts`).
## The Workspace
@@ -169,8 +201,8 @@ Help in browser), else the first on the team.
- **Header**: the avatar, "{Name}’s workspace", the live task line when
there is one (`useLiveTask`, else the summary's task), and a pill: Live
- while the employee works, otherwise their status (Ready, Stopped, Needs
- attention, Needs you). Then their main action (Stop, Resume, Start, or
+ while the employee runs, otherwise their status (Not started, Starting…,
+ Stopped, Needs attention, Needs you). Then their main action (Stop, Resume, Start, or
connect what is missing), and Expand and Close. Stop shows Stopping while
admitted work drains; the header follows authoritative generation control
instead of treating a completed browser request as a completed Stop.
@@ -257,9 +289,9 @@ fixed component catalogue (`registry.ts`, `views.tsx`, `HireScreen.tsx`,
loaded lazily so json-render stays out of Home's first chunk). The normaliser
still reads the older shape a model may write (a Toggle's `value`, a
Button's `action` / `actionParams` props), keeps the root a vertical stack,
-enforces a tree, guarantees one Hire button, one change button, the "Ask me
-before sending anything" toggle (on by default) and one `Schedule` (below),
-caps sizes, and drops what json-render does not guard: any path through
+enforces a tree, lays the screen out as the setup card (below), guarantees one
+Hire button, one change button and the "Ask me before sending anything" toggle
+(on by default), caps sizes, and drops what json-render does not guard: any path through
`__proto__`, `constructor` or `prototype`, and `watch`, `repeat`, `slots`,
`$computed` and an action's `confirm`. That glue is shared with the chat's
generated replies in [lib/jsonRender/](../client/src/lib/jsonRender/)
@@ -273,19 +305,43 @@ parsed the same way on both sides. Only what `genui/index.ts` exports
(`HireDraftPanel`, `useHireComposer`, `useStarterHire`, `DraftMessagePreview`)
leaves the folder: ESLint refuses imports of its internal modules.
-**When they work.** Every screen shows one `Schedule` after the routine. The
-normaliser inserts it (the catalogue marks it `inserted`, so the model is
-never offered it) and binds it to `/trigger` (`state_paths.trigger`). It starts
-as the Hire button's `trigger`, else a new message in the app the routine's
-first "When" step names, else the owner messaging them, snapped to what the
-server builds: a known kind, a frequency, a time from `trigger.times` (the
-builder's `SCHEDULE_TIMES`; `test_genui_catalog_sync.py` holds them equal), and
-a weekday or day of the month. It reads as one sentence ("Every weekday at
-08:00"). Edit offers the owner messaging them, a schedule,
-or a new message in any app whose `can_trigger` is true; a change rewrites the
-routine's "When" step, and the hire payload reads `/trigger` before the
-button's params. `views.tsx` labels the routine "Their routine" and its steps
-in plain words (When, They, Using, Then).
+**The card** (onboarding handoff R2). Whatever the model wrote, the
+normaliser lays the screen out one way and names the places in
+`NormalizedSpec.layout`: the first `AgentCard` is the identity row (avatar,
+name, "role · apps", the description in two lines, no status), then the
+routine (the first `Plan`, else the `Schedule`), then everything else in the
+order written, then the footer strip's two: the ask-first toggle, taken out of
+whatever card held it, and a row of the change button (secondary) and the Hire
+button (primary). Further agent cards and Plans are dropped. `HireScreen`
+draws each place with its own `Renderer` over the same spec under one
+`JSONUIProvider`, so they share state and handlers and the reveal still runs
+element by element: the identity row with Discard beside it, the body, the
+suggested team (the panel's children), then the footer strip, which bleeds to
+the card's edges on `bg-bg-app` and gives its controls their own look
+(`HireSpecContext.inFooter`): "Ask before sending" beside a compact switch,
+"Change something" as a quiet pill and "Hire {name} →" as the inverted pill.
+The model's other rules, choices and inputs stay in view in compact cards, so
+nothing is hired unseen. The panel's header (NEW EMPLOYEE, the job, Discard)
+shows only while the setup is written or after it failed, or for a screen with
+no agent card, and the model's one-line introduction is not shown.
+
+**When they work.** The routine says it in its When row. With a `Plan`, the
+normaliser binds the plan's `trigger` to `/trigger` (`state_paths.trigger`)
+and drops any `Schedule`; without one it inserts a single `Schedule` (the
+catalogue marks it `inserted`, so the model is never offered it) bound there,
+drawn as a routine of that one row. `/trigger` starts as the Hire button's
+`trigger`, else a new message in the app the routine's first "When" step
+names, else the owner messaging them, snapped to what the server builds: a
+known kind, a frequency, a time from `trigger.times` (the builder's
+`SCHEDULE_TIMES`; `test_genui_catalog_sync.py` holds them equal), and a weekday
+or day of the month. The routine is a timeline
+([ui/routine.tsx](../client/src/features/home/ui/routine.tsx): a rule down
+the left, each step's dot on it, its role in mono as WHEN / THEY / USING /
+THEN), and a routine with no "When" step still starts with one. The When row
+ends in **Change**, which opens the editor under it: the owner messaging them,
+a schedule, or a new message in any app whose `can_trigger` is true. A change
+rewrites the When row as one sentence ("Every weekday at 08:00"), and the hire
+payload reads `/trigger` before the button's params.
### 2. Hire
@@ -351,15 +407,25 @@ the client's `HIRE_PAYLOAD_KEYS` must match, locked by
5. records on the row the apps the graph actually uses (`built.app_ids`), so
an app the hire named but left out never shows as one to connect;
summaries read apps off the graph the same way;
-6. answers `{employee, started, missing_apps, needs_ai, unsupported_apps, warnings, idempotent}`
- and, when every app is connected and an AI model exists, starts the
- employee in the background. Errors: `invalid_request`, `too_large`,
- `conflict`, `busy`, `not_allowed`, `build_failed`, `save_failed`.
+6. answers `{employee, started, missing_apps, needs_ai, unsupported_apps,
+ node_count, warnings, idempotent, request_id, activation_state,
+ readiness_issue}` and, when every app is connected and an AI model exists,
+ starts the employee in the background
+ ([activation.py](../server/services/employees/activation.py), which also
+ retries a held start every ten seconds, so connecting what was missing
+ starts them). `node_count` is the saved graph's size, read from the saved
+ workflow so a replay of the same key says the same. The summary's
+ `activation_state` says how that start went (`saved` until it is tried,
+ then `blocked`, `running` or `failed`; null for a workflow built in the
+ editor), and a change to it is broadcast at once, since a start that is
+ held or fails before Start made a control row changes nothing else the
+ page hears about. Errors: `invalid_request`, `too_large`, `conflict`,
+ `busy`, `not_allowed`, `build_failed`, `save_failed`.
On the client ([genui/useHire.ts](../client/src/features/home/genui/useHire.ts))
-every successful hire lands on the new employee's page, with a glow in the
-sidebar and a toast; the team list is then read back from the server rather
-than taking the summary the hire answered with. The response's `warnings` show there once as the hire
+every successful hire lands on the new employee's page, on their first day
+(below), with a glow in the sidebar and a toast; the team list is then read
+back from the server rather than taking the summary the hire answered with. The response's `warnings` show there once as the hire
notice ("A few notes on {Name}'s setup", `hire/HireNotice.tsx`), until the
owner dismisses it or opens another view; `needs_ai` opens Connect an AI
model; every error code has plain words (`busy`: they are still being set
@@ -421,12 +487,18 @@ that way and fails when one loses an app it names or the way it starts.
`homeStore.openConnectAI()` delegates to the shared app-level credentials
host with `{ categoryId: 'ai', intent: 'connect' }`. The connector browser
-starts on AI with beginner guidance; selecting a provider opens the same
-connection form used in Dev. Featured providers retain the key-page links
-and hints from `components/onboarding/aiProviderLinks.ts`. Successful guided
-connection closes the flow; Manage stays open after saving. These actions
-serve setup's `no_ai_provider`, hire/start's `needs_ai`, and the employee's
-Connect an AI model action.
+starts on AI; selecting a provider opens the same connection form used in
+Dev (`components/credentials/ProviderPage.tsx`). Featured providers keep the
+key-page links and hints from `components/credentials/aiProviderLinks.ts`.
+Successful guided connection closes the flow; Manage stays open after
+saving. These actions serve setup's `no_ai_provider`, hire/start's
+`needs_ai`, and the employee's Connect an AI model action.
+
+The Welcome guide's step 2 is the other way in ([onboarding.md](./onboarding.md)):
+the same browser cut to AI models, with the provider page shown in place of
+the list. A pill says "{Provider} is connected" and the step returns to the
+list; when step 3's job was waiting for a model, connecting one finishes the
+guide and sends it.
## Talk
@@ -469,6 +541,27 @@ header draws its border. Turn on Talk and Apply are in
sending and drafts belong to the chat (wire and client rules in
[chat_protocol.md](./chat_protocol.md#client)).
+- **A new hire's first day** ([employee/FirstDay.tsx](../client/src/features/home/employee/FirstDay.tsx),
+ onboarding handoff C): a hire made in this session (`homeStore.firstDays`,
+ set by `welcomeHire` from the response's `started` and `node_count`) shows
+ this in place of the empty conversation until the first message, and then
+ never again (a Reset that empties the thread later does not bring it back;
+ a reload or deleting them ends it too). Their avatar turns a ring while
+ they start, then glows once with a ready pip; "{Name} joined your team".
+ The start-up card's rows follow what happened, never timers: Setup saved
+ and "Workflow built · N blocks" (the hire did both), then "{Name} is
+ running" once the control state is `running`, and "Ready to talk" once
+ they run with Talk on (`firstDayPhase` in `presentation.ts`: starting while
+ the control state is starting, or never started by a hire that started
+ them and whose `activation_state` is neither `blocked` nor `failed`). A
+ start that did not go ahead ends the card with why (`firstDayNote`:
+ "WhatsApp isn't connected yet.", "Connect an AI model first.", "{Name}
+ couldn't start.") and their main action, so the line above the box does
+ not say it again. "What {Name} does" lists their routine from the hire's
+ `plan` (`get_employee`), on the timeline the setup card uses. While they
+ start, the box shows but takes nothing ("{Name} is starting…", the host's
+ `wait`); once they can read messages, two greetings under the card put
+ their words in it. The small orb stays above.
- **The thread** is `get_chat_messages` with `all_generations: true` (the
newest 200 messages): the conversation since the employee last started,
since a Reset clears it (see [Turn on Talk and Apply](#turn-on-talk-and-apply)).
@@ -546,6 +639,8 @@ sending and drafts belong to the chat (wire and client rules in
- *start* (never started, ready, resetting, failed): no box; a line says
they can't read messages, beside their main action (Start, Start again,
or what they are missing), which the Workspace header offers too.
+ - *wait* (a new hire still starting, on their first day): the box shows,
+ disabled, saying "{Name} is starting…".
- While the agent waits for the owner in the browser, the server's line
for it ("Needs you to sign in to a site in the browser") sits above the
box beside Help in browser; after a run of failures paused them, why.
@@ -747,8 +842,8 @@ across the whole team) is always complete.
A 1040x760 dialog ([settings/HomeSettings.tsx](../client/src/features/home/settings/HomeSettings.tsx))
with a 224px nav. One `PAGES` list drives the nav and the panels. The pages
-are grouped under *Settings* (Profile, Billing) and *Customize* (Skills,
-Connectors, Plugins), and the nav's search matches each page's label and
+are grouped under *Settings* (App access, Profile, Billing, Help) and
+*Customize* (Skills, Connectors, Plugins), and the nav's search matches each page's label and
keywords, dropping a group with no match. Opening Settings on a category
(`openSettings('connectors', 'ai')`) only sets where the page starts:
changing page clears it.
@@ -761,6 +856,9 @@ changing page clears it.
- **Billing**: usage only. It shows the tasks done this month
(`get_employee_usage`) and the number of employees in the sidebar. A count
that can't be read shows a dash, never a zero.
+- **Help**: Welcome guide · Replay, which closes Settings and opens the guide
+ at its first step, and Get started checklist · Show, which brings the
+ hidden checklist back ([onboarding.md](./onboarding.md)).
- **Skills**: the owner's library, which is the user-skills table. Each row is
on (`is_active`) or off for employees hired from now on.
- *Discover* lists the built-in `server/skills/employee/` folder. These are
@@ -828,12 +926,12 @@ WebSocket requests (snake_case; failures come back as `success: false` with an
| Type | Payload | Response |
|---|---|---|
-| `list_employees` | `{}` | `{employees}`; each summary's `canvas_node_id` is its Canvas board: the one it was hired with, else the graph's first Canvas node, else null. `browser_request` is a browser waiting for the owner (`{node_id, reason, since}`), else null. `talk` is `{state: "on" \| "off" \| "unsupported", agent_node_id}` (the agent that answers the owner; not in `watch_node_ids`). `task` is `{label, text}`, or null when the page already says it (a running employee with Talk on whose only work is the owner's messages). `asks_first` is the hire's "ask me first" rule (built in Dev mode: whether it has an approval gate). `pending_changes` is true when the saved graph's structure differs from the live generation's snapshot. `photo_url` is the photo the owner gave them (the workspace file route, versioned), else null |
+| `list_employees` | `{}` | `{employees}`; each summary's `canvas_node_id` is its Canvas board: the one it was hired with, else the graph's first Canvas node, else null. `browser_request` is a browser waiting for the owner (`{node_id, reason, since}`), else null. `talk` is `{state: "on" \| "off" \| "unsupported", agent_node_id}` (the agent that answers the owner; not in `watch_node_ids`). `task` is `{label, text}`, or null when the page already says it (a running employee with Talk on whose only work is the owner's messages). `asks_first` is the hire's "ask me first" rule (built in Dev mode: whether it has an approval gate). `pending_changes` is true when the saved graph's structure differs from the live generation's snapshot. `photo_url` is the photo the owner gave them (the workspace file route, versioned), else null. `activation_state` is how the hire's own start went (`saved`, `blocked`, `running` or `failed`), null for a workflow built in the editor |
| `get_employee` | `{workflow_id}` | the summary plus `description`, `job`, `plan`, `rules`, `choices`, `trigger_text`, `last_run`, `latest_report` |
| `get_employee_usage` | `{}` | `{tasks_this_month}` (successful runs since the 1st, owner's timezone, whole team) |
| `generate_employee_setup` | `{job, refine?, history?, draft_token}` | `{draft_token, reply, provider, model, usage, retried, finish_reason, apps}`; `apps` maps each app the reply mentions to its AppRef plus `can_trigger` |
| `cancel_employee_setup` | `{draft_token}` | `{cancelled}` |
-| `hire_employee` | `HireEmployeeRequest` | `{employee, started, missing_apps, needs_ai, unsupported_apps, warnings, idempotent}`; errors include `busy` while the same key's first attempt is still building |
+| `hire_employee` | `HireEmployeeRequest` | `{employee, started, missing_apps, needs_ai, unsupported_apps, node_count, warnings, idempotent, request_id, activation_state, readiness_issue}`: `node_count` is the saved graph's size; `activation_state` is `starting` or `blocked` (a replay of the same key: the stored one), `readiness_issue` why a team cannot start yet; errors include `busy` while the same key's first attempt is still building |
| `start_employee` | `{workflow_id, expected_revision, idempotency_key}` | as `start_workflow` |
| `pause_workflow` / `resume_workflow` | `{workflow_id, expected_revision, idempotency_key}` | Generation control snapshot: `state`, `revision`, root and execution identities, capabilities and `execution_control_version`; acknowledged `paused` means admitted work drained for version 1. Transitional status is reconciled after a timeout |
| `enable_employee_talk` | `{workflow_id, idempotency_key}` | `{employee}`. Errors: `invalid_request`, `not_found`, `unsupported`, `conflict` (a start, pause, resume or reset is under way, or the graph changed meanwhile), `restart_failed`; the last three carry `employee` too |
@@ -853,7 +951,7 @@ every frame but `workflow_ops_apply` carries the whole envelope:
| Wire key | Type | Notes |
|---|---|---|
-| `employee_lifecycle` | `com.opencompany.employee.{hired,updated,removed}` | Subject is the workflow id; `updated` is coalesced to one per second per employee, except control changes and browser control changes (each agent step, and the wait for the owner), which go out at once. Home refetches on `hired` and `updated` rather than taking the summary the event carries, which can already be out of date; `removed` drops the employee |
+| `employee_lifecycle` | `com.opencompany.employee.{hired,updated,removed}` | Subject is the workflow id; `updated` is coalesced to one per second per employee, except control changes, browser control changes (each agent step, and the wait for the owner) and a change in how a hire's own start went (`activation_state`), which go out at once. Home refetches on `hired` and `updated` rather than taking the summary the event carries, which can already be out of date; `removed` drops the employee |
| `approval_lifecycle` | `com.opencompany.approval.{requested,decided,expired,cancelled}` | Identity only, never the message or the recipient |
| `workflow_lifecycle` | gains `created` and `deleted` stages | So open editors refresh their workflow lists. `deleted` also makes every tab forget the workflow and its employee (`forgetWorkflow`, see [Deleting an employee](#deleting-an-employee)) |
| `chat.updated` | `com.opencompany.chat.updated` | Sent after every chat insert and clear (`services/chat_thread.py`), and when a chat run ends. Data `{workflow_id, session_id, role}`, identity only: `role` is null for a clear or a run's end, `workflow_id` null for session `"default"`. Home's thread and the editor's chat pane refetch |
@@ -884,7 +982,8 @@ history). Talk and growing a saved employee: `tests/services/employees/`
`tests/services/test_workflow_context_archive_outbox.py` (a late save or read
cannot re-create a deleted workflow). Client:
`features/home/**/__tests__` (including `employeeChat.test.tsx`,
-`homeHeader.test.tsx`, `connectAI.test.tsx`), `features/chat/__tests__` (the
+`homeHeader.test.tsx`, `connectAI.test.ts`, `welcomeGuide.test.tsx`,
+`employee/__tests__/FirstDay.test.tsx`), `features/chat/__tests__` (the
shared chat: turns, drafts, the pane against a fake server),
`stores/__tests__/chatRunStore.test.ts`, `lib/agui/__tests__`, `app/__tests__`,
`contexts/__tests__/themePrePaint.test.ts`,
diff --git a/docs-internal/onboarding.md b/docs-internal/onboarding.md
index fbfbdec3..9d4a0b0d 100644
--- a/docs-internal/onboarding.md
+++ b/docs-internal/onboarding.md
@@ -1,324 +1,132 @@
-# Onboarding Service
+# Onboarding
## Overview
-The onboarding service provides a four-step welcome wizard that appears after a user's first launch: what OpenCompany is, how the canvas works, connecting an AI provider, and trying the shipped AI Assistant example. It is database-backed, skippable, resumable, and replayable from Settings. The wizard is part of the workflow editor (`Dashboard.tsx`), so with Normal mode on it first appears when Dev mode opens; Normal mode's first screen is Home itself ([normal_mode.md](./normal_mode.md)). A separate, dismissable **Get Started checklist** (`GetStartedChecklist.tsx`) sits in the corner of the canvas after the wizard and tracks five first-session milestones.
+Onboarding is the **Welcome guide** on Home (Normal mode, [normal_mode.md](./normal_mode.md)): three steps, Welcome, Connect an AI model and Your first hire, in a dialog shaped like Home's Settings (a left nav, the page, a footer bar). It opens by itself the first time Home shows for an owner who has not finished it, and again from the header's **Guide** button or **Settings → Help → Welcome guide · Replay**. Progress is saved on the user settings row (`onboarding_completed`, `onboarding_step`), so it resumes where the owner left it, and skipping finishes it.
-The frontend is **fully shadcn/ui + Tailwind** — antd was removed from `client/src/`. The wizard composes the project's `Modal` primitive, shadcn `Button` / `ActionButton` / `Card` / `Badge` / `Alert` / `Skeleton`, and `lucide-react` icons. The step progress indicator is a hand-rolled `<ol>` driven by node-role tokens (no antd `Steps`).
+The guide replaced the editor's four-step wizard (it taught blocks and the Start button, and only appeared once Dev mode opened). The design is the onboarding handoff of 2026-10-08 (`design_handoff_onboarding/`, untracked; its README's revisions R1 and R2 trim the copy).
-## Architecture
+Once the guide is finished, a dismissable **Get started checklist** sits in Home's bottom-right corner and ticks off four first steps (see below). The editor has neither.
-```
-┌────────────────────────────────────────────────────────────────┐
-│ Dashboard.tsx │
-│ ┌────────────────────────────────────────────────────────┐ │
-│ │ OnboardingWizard.tsx │ │
-│ │ ┌────────────────────────────────────────────────┐ │ │
-│ │ │ useOnboarding(reopenTrigger, STEPS.length) │ │ │
-│ │ │ - Reads onboarding_completed/step via │ │ │
-│ │ │ useUserSettingsQuery (TanStack Query, WS) │ │ │
-│ │ │ - Manages step navigation + persistence │ │ │
-│ │ └───────────────┬────────────────────────────────┘ │ │
-│ │ │ │ │
-│ │ STEPS array (single source of truth in wizard): │ │
-│ │ ┌─────────┬──────────────┬─────────────────┬────────┐ │ │
-│ │ │Step 0 │Step 1 │Step 2 │Step 3 │ │ │
-│ │ │Welcome │How it works │Connect your AI │Try it │ │ │
-│ │ └─────────┴──────────────┴─────────────────┴────────┘ │ │
-│ │ │ │
-│ │ Modal (project primitive, Radix-backed) │ │
-│ │ + <ol> progress stepper (Tailwind + role tokens) │ │
-│ └────────────────────────────────────────────────────────┘ │
-│ │
-│ SettingsPanel.tsx → "Replay Welcome Guide" button │
-│ └── onReplayOnboarding → increments reopenTrigger │
-└────────────────────────────────────────────────────────────────┘
- │ │
- │ WebSocket (via TanStack Q) │ WebSocket
- ▼ ▼
-┌──────────────────────────────────────────────────────────────┐
-│ server/services/settings/handlers.py │
-│ - get_user_settings → returns onboarding_completed, step │
-│ - save_user_settings → persists onboarding_completed, step │
-│ │
-│ server/core/database.py │
-│ - _migrate_user_settings() adds columns + marks existing │
-│ users (examples_loaded=1) as onboarding_completed=1 │
-│ │
-│ server/models/database.py │
-│ - UserSettings.onboarding_completed: bool │
-│ - UserSettings.onboarding_step: int │
-└──────────────────────────────────────────────────────────────┘
-```
-
-## Database Schema
-
-### UserSettings Fields
-
-| Field | Type | Default | Description |
-|-------|------|---------|-------------|
-| `onboarding_completed` | `bool` | `False` | Whether onboarding was completed or skipped |
-| `onboarding_step` | `int` | `0` | Last completed step (for resuming mid-wizard) |
-
-### Migration
-
-In `server/core/database.py` `_migrate_user_settings()`:
-
-```python
-if "onboarding_completed" not in columns:
- await conn.execute(text(
- "ALTER TABLE user_settings ADD COLUMN onboarding_completed BOOLEAN DEFAULT 0"
- ))
- # Existing users (examples_loaded=1) skip onboarding
- await conn.execute(text(
- "UPDATE user_settings SET onboarding_completed = 1 WHERE examples_loaded = 1"
- ))
+## Files
-if "onboarding_step" not in columns:
- await conn.execute(text(
- "ALTER TABLE user_settings ADD COLUMN onboarding_step INTEGER DEFAULT 0"
- ))
+```
+client/src/features/home/
+├── onboarding/
+│ ├── WelcomeGuide.tsx # the dialog: nav, the three steps, the footer bar
+│ ├── useOnboarding.ts # saved progress + moves (goTo / next / back / skip / complete)
+│ ├── GetStartedChecklist.tsx # the corner card and its folded pill
+│ ├── useGetStarted.ts # the four steps' state, the two latches, useShowGetStarted
+│ ├── getStartedItems.ts # the steps, in order
+│ └── steps/
+│ ├── WelcomeStep.tsx # eyebrow with the owner's call name, the headline, the demo
+│ ├── WelcomeDemo.tsx # three beats and a stage drawing the picked one
+│ ├── ConnectStep.tsx # the shared CredentialsBrowser, cut to AI models
+│ └── FirstHireStep.tsx # starter chips + Home's composer, bound to the same draft
+├── header/GuideButton.tsx # the header's Guide pill
+├── settings/HelpTab.tsx # Settings > Help: Replay the guide, Show the checklist
+└── state/homeStore.ts # `guide` state: open, step, furthest, checked
```
-**Existing user handling**: The migration marks all rows with `examples_loaded=1` as `onboarding_completed=1`, so returning users never see the wizard.
+`HomeShell.tsx` mounts `WelcomeGuide` and `GetStartedChecklist` beside `HomeSettings`.
-## Frontend File Structure
+## State
-```
-client/src/
-├── components/
-│ └── onboarding/
-│ ├── OnboardingWizard.tsx # Wizard modal orchestrator + STEPS SSOT + <ol> stepper
-│ ├── GetStartedChecklist.tsx # Post-wizard corner checklist (collapsible, dismissable)
-│ ├── getStartedItems.ts # The five checklist milestones + EXAMPLE_WORKFLOW_NAMES
-│ ├── aiProviderLinks.ts # FEATURED_AI_PROVIDERS: hint + key-page URL per provider id
-│ ├── nodeRoleClasses.ts # Shared role→Tailwind-token map for step cards
-│ ├── steps/
-│ │ ├── WelcomeStep.tsx # Step 0: what OpenCompany is, 2×2 feature grid
-│ │ ├── HowItWorksStep.tsx # Step 1: blocks, agents, chat; Normal/Dev switch
-│ │ ├── ConnectAIStep.tsx # Step 2: provider tiles from the live catalogue
-│ │ └── TryItStep.tsx # Step 3: three-step recipe for the AI Assistant example
-│ └── __tests__/ # ConnectAIStep, GetStartedChecklist, HowItWorksStep, OnboardingWizard
-└── hooks/
- ├── useOnboarding.ts # Wizard state + TanStack-Query persistence
- └── useGetStarted.ts # Checklist state (which milestones are done, dismissed)
-```
+The open state and the step live in `homeStore` (`guide: { open, step, furthest, checked, provider, pendingDraft }`, steps `GUIDE_STEPS = ['welcome', 'connect', 'first-hire']`; `provider` is the page step 2 shows in place of its list, `pendingDraft` a step-3 job waiting for a model), so every entry point opens the guide directly (`openGuide(step)`, which clears both) and nothing counts replays. That is what keeps a remount from reopening it: a mode switch re-keys the screens, and the old wizard's replay counter reopened the wizard on every remount after one replay.
-## Components
-
-### useOnboarding Hook
-
-**Location**: `client/src/hooks/useOnboarding.ts`
-
-Custom hook managing the full onboarding lifecycle. Persistence rides the **TanStack Query** server-state layer (`useUserSettingsQuery` / `useSaveUserSettingsMutation` from `useUserSettingsQuery.ts`), which are themselves WebSocket-backed (`get_user_settings` / `save_user_settings`). The hook does NOT call WebSocket handlers directly.
-
-```typescript
-export const useOnboarding = (
- reopenTrigger?: number,
- totalSteps: number = DEFAULT_TOTAL_STEPS, // 4; the wizard passes STEPS.length
-) => {
- // Returns (spread of OnboardingState + actions):
- // - isVisible: boolean - Whether wizard should render
- // - currentStep: number - Active step index (0..totalSteps-1)
- // - isCompleted: boolean - Whether already completed/skipped
- // - isLoading: boolean - Settings query in progress
- // - hasChecked: boolean - Initial hydration done
- // - totalSteps: number - Echoed back from the param
- // - nextStep(): void - Advance (completes + persists when next >= totalSteps)
- // - prevStep(): void - Go back one step (clamped at 0)
- // - skip(): void - Skip: persist current step, completed=true, hide
- // - complete(): void - Persist totalSteps, completed=true, hide
-};
-```
+`useOnboarding()` (mounted once, in `WelcomeGuide`) adds the saved side:
-**Key behaviors**:
-- `totalSteps` is a **parameter**. The wizard owns the step list and passes `STEPS.length`, so the hook never hardcodes the count — it uses `totalSteps` only to detect last-step completion in `nextStep`. The default only matters if a caller omits it; it matches the shipped wizard.
-- Hydrates UI state from `settingsQuery.data` on `isSuccess`: reads `onboarding_completed` / `onboarding_step`. Visibility flips only on first hydration (`prev.hasChecked ? prev.isVisible : !completed`) so a user-closed wizard does not re-open on later query refetches.
-- Each navigation (`nextStep` / `prevStep` / `skip` / `complete`) calls `saveSettings.mutate({ onboarding_step, onboarding_completed })` to persist progress.
-- Query errors surface as a non-blocking "checked" state (`isLoading=false, hasChecked=true`) so the app continues even if the round-trip failed.
-- `reopenTrigger` prop change (when `> 0`) resets state and reopens the wizard from step 0.
-
-### OnboardingWizard
-
-**Location**: `client/src/components/onboarding/OnboardingWizard.tsx`
-
-**Props**:
-| Prop | Type | Description |
-|------|------|-------------|
-| `onOpenCredentials` | `() => void` | Opens CredentialsModal (passed from Dashboard) |
-| `reopenTrigger` | `number?` | Incrementing counter triggers wizard reopen |
-| `onFinish` | `() => void?` | Called after the last step's button completes the wizard; the Dashboard opens the AI Assistant example and focuses chat. Never called on skip or modal close. |
-
-**`STEPS` is the single source of truth.** The wizard declares a module-scope `STEPS` array of `{ title, render }` entries. Its `.length` feeds the hook's `totalSteps`, the progress indicator renders one node per entry, and the active step's `render` is dispatched by index. Adding a step is a one-line edit to this array.
-
-```typescript
-const STEPS = [
- { title: 'Welcome', render: () => <WelcomeStep /> },
- { title: 'How it works', render: () => <HowItWorksStep /> },
- { title: 'Connect your AI', render: ({ onOpenCredentials }) => <ConnectAIStep onOpenCredentials={onOpenCredentials} /> },
- { title: 'Try it', render: () => <TryItStep /> },
-];
-```
-
-**UI Structure** (all shadcn/Tailwind, no antd):
-- Project `Modal` primitive with `maxWidth="95vw"`, `maxHeight="95vh"`, titled "Welcome Guide"; `onClose` is wired to `skip`.
-- Progress indicator: a hand-rolled `<ol>` of step pills. Each pill is a rounded number/`Check` (lucide) badge with one of three statuses — `completed` (filled `bg-primary text-primary-foreground`), `active` (`border-primary text-primary`), `upcoming` (`border-border text-muted-foreground`) — joined by a connector `<div>` (`bg-primary` once passed, else `bg-border`). No antd `Steps`.
-- Step content rendered via `STEPS[safeIndex].render({ onOpenCredentials })` inside a scrollable `max-h-[calc(95vh-200px)]` container.
-- Footer: shadcn `Button variant="ghost"` "Skip for now" (left) | `Button variant="outline"` "Back" (shown when `currentStep > 0`) + an `ActionButton` on the right.
-- The right-side primary button uses **`ActionButton` intents**, not raw colour hex: `<ActionButton intent="tools">` for "Next" (with `ArrowRight`), `<ActionButton intent="run">` for the final "Open AI Assistant" (with `MessageCircle`), which calls `complete()` and then `onFinish`.
-- Only renders when `isVisible && hasChecked && !isLoading`.
+- **First launch.** When the settings query first succeeds it calls `checkGuide(settings)`, which runs once per session (`checked`). For an owner whose `onboarding_completed` is false it opens the guide at `GUIDE_STEPS[onboarding_step]`, or at Welcome when that index is not a step (rows saved by the old four-step wizard can hold 2 or 3). A finished owner never sees it unasked.
+- **Moves.** `goTo(step)` (the nav, Next, Back, "I'll do this later") saves `{ onboarding_step }`.
+- **Finishing.** `skip()` (Skip for now, the close button, Esc, a click outside) saves `{ onboarding_completed: true, onboarding_step: <step reached> }`; `complete()` (the last step's Create) saves `onboarding_step: 3`. A replay never writes `onboarding_completed: false`.
-### Node-role token map
+It reads and writes the settings through `useOwnerSettings` / `useSaveUserSettingsMutationCore` with the stable `useWebSocketActions()`, so Home never re-renders on a WebSocket message.
-**Location**: `client/src/components/onboarding/nodeRoleClasses.ts`
+Existing owners keep skipping: the server's migration marked every row with `examples_loaded = 1` as `onboarding_completed = 1` when the columns were added (`server/core/database.py` `_migrate_user_settings`).
-`NODE_ROLE_CLASSES` maps a `NodeRole` (`model | skill | agent | workflow | trigger`) to the matching `--node-X` triplet (`{ card: 'bg-node-X-soft border-node-X-border', text: 'text-node-X' }`). Every step keys its card surfaces off this so the cards track every theme with **no opacity arithmetic at the call site**.
+## The dialog
-### Step Components
+`WelcomeGuide` uses the shared `Modal` the way `HomeSettings` does (`hideHeader`, `motion="spring"`, `scrollableBody={false}`, `rounded-panel bg-bg-panel shadow-dialog`), at `min(var(--w-guide), 100vw - 3rem)` by `min(var(--h-guide), 100vh - 3rem)` (940 by 620).
-All steps are shadcn/Tailwind compositions using `lucide-react` icons. No antd, no `@ant-design/icons`. The copy is deliberately non-technical (blocks, agents, chat), not node-type vocabulary.
+- **Nav** (`w-(--w-settings-nav)`): the "Get started" label, then one Radix Tabs trigger per step (`NAV_ITEM` from `features/home/ui/nav.ts`, shared with Settings), with Sparkles / KeyRound / UserPlus. A step is ticked (`CircleCheck` in `action-run-ink`) once passed; Connect is ticked as soon as any AI model is connected. The nav reaches the steps already visited (`furthest`) and always Connect; the others are disabled triggers. The Open Council mark sits at the foot.
+- **Footer**: Skip for now, the mono "n / 3", Back (hidden on Welcome), then Next (`ActionButton intent="tools"`) on Welcome and on Connect once a model is connected, or "I'll do this later" on Connect without one. The last step has no footer button: its composer's own Create is the action.
+- Inactive steps unmount (Radix Tabs), and each step's blocks rise in with the Settings stagger (`staggerSettings`).
-| Step | Component | Heading | Purpose | Notable data sources |
-|------|-----------|---------|---------|----------------------|
-| 0 | `WelcomeStep` | Build your own AI team | Platform intro + 2×2 feature grid (agents, drag-and-drop, bring your AI, local and private) | static; `Card` / `CardContent`, role-token cards |
-| 1 | `HowItWorksStep` | See how it works | Three ideas: snap blocks together, agents do the thinking, chat to make it go; explains the Normal / Dev toolbar switch | `useNodeGroups()` — the Normal-mode group labels render live as `Badge`s |
-| 2 | `ConnectAIStep` | Connect your AI (or "You're connected") | Featured provider tiles with "Get a key" links, the remaining AI providers as chips, and the Connect / Manage button | `useCatalogueQuery()` for name, icon and `stored` state; `FEATURED_AI_PROVIDERS` for hint + key URL |
-| 3 | `TryItStep` | Say hello to your first agent | Three-step recipe (open AI Assistant, press Start, say hello) plus "more to explore" cards for Claude Assistant and AI Employee | static |
+### Step 1, Welcome
-**ConnectAIStep** takes an `onOpenCredentials` prop so it links to the existing CredentialsModal without duplicating key input. Everything about a provider except its marketing hint and key-page URL comes from the live credential catalogue: `FEATURED_AI_PROVIDERS` (`aiProviderLinks.ts`) lists only `{ id, hint, keyUrl }` for openai, anthropic and gemini, and the step joins that to `useCatalogueQuery().providers` filtered to `category === 'ai'`. Providers not featured render as a chip row with a note that Ollama and LM Studio run locally. While the catalogue loads it shows three `Skeleton` tiles; once any AI provider is `stored` the heading, button label and closing `Alert` all switch to the connected variant.
+The eyebrow says "Welcome, {call name}" (`callName` from the profile; "Welcome" without one) in the agent ink, over "Your AI team, hired in plain words." (`text-headline`). The demo beside it has three beats, each a button: Describe the job (a small composer with the job typed in), Check and hire (the setup card as the R2 design draws it: identity, a WHEN / THEY / THEN routine, "Ask before sending" and Hire), and Talk to them (the owner's "Hi Maya!", the reply, and a WhatsApp draft that "Needs you"). The stage (`.home-welcome-stage`, two washes of `--node-agent-fill` and `--node-model-soft` over `--bg-app`) is decoration (`aria-hidden`), drawn with token classes, never real controls. It plays by itself on an 80 ms clock (`TICK_MS`): the job types itself a character a tick and Create pops when it is written, a pause, then the setup (its rows rising one by one, then Hire), then the conversation (the reply, then the draft), each beat for its `BEAT_TICKS`, round again; a bar under the playing beat fills as it plays (an inline `scaleX` of the clock), and clicking a beat starts it. It runs only while the step shows, since inactive steps unmount. Under reduced motion there is no clock: the conversation shows, still, with no bar, and a click shows another beat.
-**HowItWorksStep** reads `useNodeGroups()` and renders the labels of every group whose `visibility` is `normal` or `all`, so the "Normal shows just the AI blocks" sentence stays true as groups are added.
+### Step 2, Connect an AI model
-### Get Started checklist
+The shared `CredentialsBrowser` (the same as Settings > Connectors), handed a catalogue cut to `consumer_category === 'ai'` with no categories, so Yours counts AI models only and there is no category filter. It runs with `variant="embedded"` (a smaller title and search box), `discoverLimit={null}` (every AI model, so the ones that run on this computer are not behind "Show all") and AI copy: "Connect an AI model" ("You're connected" once one is), "Search AI models", "AI models", and "No AI models connected yet".
-**Location**: `client/src/components/onboarding/GetStartedChecklist.tsx`, state in `client/src/hooks/useGetStarted.ts`, items in `getStartedItems.ts`.
+Connect and Manage open the provider's page **in place of the list** (`components/credentials/ProviderPage.tsx`, the page the credentials dialog shows as its second layer, here with its own "Connect {name}" heading and focus on "All AI models"). The footer's Back and Next step aside while it shows; "All AI models" and Esc return to the list, focusing the card it came from (a disconnect confirmation, its own layer, closes first on Esc). The list stays mounted underneath, hidden, so a card that turns connected still glows and reports it through `onItemAdded`: a pill says "{Provider} is connected" and, after a connect, the step returns to the list (Manage stays open).
-A fixed-position card (bottom right, above the console) that appears after the wizard and tracks five milestones: workspace set up (auto-complete), add an AI key, chat with the AI Assistant, build your own workflow (told apart from editing a shipped example via `EXAMPLE_WORKFLOW_NAMES`), and try a theme. Rows flagged `actionable` take a click handler from the Dashboard through the `actions` prop. It collapses to a pill and can be dismissed; dismissal is reversible from Settings → Help.
+**A job waiting for a model.** On step 3 without a model, Create (or the notice's button) goes to step 2 with `guide.pendingDraft` set when the box holds a job. Connecting a model then finishes the guide, shows the hire view and sends the job. Closing the guide drops the flag. This is the guide's own path; a draft Home already sent that failed with `no_ai_provider` is still re-sent by `useHireComposer` once a model is connected anywhere.
-## Integration Points
+### Step 3, Your first hire
-### Dashboard.tsx
+"Who should we hire first?", the starter chips (left-aligned, without Hire now) and Home's `Composer` (`flat`, `idleLabel="Create their setup"`), bound through genui's `useJobComposer()`: the same draft as Home's composer, without the effects `useHireComposer` runs (they stay mounted once, in the hire view), and picking a starter takes no focus from Home. Create finishes the guide, shows the hire view and sends the job; the setup then writes itself under Home's composer. Without an AI model it sends nothing: a pink notice, "Connect an AI model first.", and its button (or Create) lead to step 2, where the job waits (above).
-```typescript
-// State for replay trigger
-const [onboardingReopenTrigger, setOnboardingReopenTrigger] = React.useState(0);
+## Get started checklist
-// SettingsPanel gets replay callback
-<SettingsPanel
- onReplayOnboarding={() => {
- setSettingsOpen(false);
- setOnboardingReopenTrigger(prev => prev + 1);
- }}
-/>
+**Location**: `features/home/onboarding/GetStartedChecklist.tsx`, state in `useGetStarted.ts`, steps in `getStartedItems.ts` (onboarding handoff D).
-// OnboardingWizard rendered after CredentialsModal
-<OnboardingWizard
- onOpenCredentials={() => setCredentialsOpen(true)}
- reopenTrigger={onboardingReopenTrigger}
- onFinish={openAiAssistantAndFocusChat}
-/>
-```
+A card fixed in Home's bottom-right corner (`w-80`, `shadow-popover`), shown once `onboarding_completed` is true and until `getting_started_dismissed`, and never while the Welcome guide is open. Four steps, each ticking itself:
-### SettingsPanel.tsx
+| Step | Done when | Under the label | A click |
+|------|-----------|-----------------|---------|
+| Connect an AI model | an AI model is connected now (`useConnectors().hasAi`) | "OpenAI, Anthropic, Gemini or a local model", then "{Provider} is connected" | the guide at Connect |
+| Hire your first employee | someone on the team was hired (not `derived`) | "Describe a job or pick a starter", then "{Name}, {role}" | the hire view, composer focused |
+| Say hello | latched: the owner has written to their first hire (the one hired earliest) | "Send {Name} a message" | their page |
+| Approve a first draft | latched: an `approval_lifecycle` `decided` event with status `approved` arrived while Home was open | "They ask before sending anything" | the page of whoever has a draft waiting, else the first hire |
-`SettingsPanel` takes an `onReplayOnboarding?: () => void` prop. The Help section renders a shadcn `Button variant="default"` "Replay Welcome Guide" (lucide `HelpCircle` icon, `disabled` when the callback is absent) that fires `onReplayOnboarding`.
+The two latches are `UserSettings.getting_started_said_hello` and `getting_started_approved_draft`, written once each (the saved flag is the guard), since New conversation or a restart empties the thread and an approval is an event. The first hire's conversation is read only until Say hello is latched. The card folds to a "Get started · n/4" pill; hiding it says "Get started hidden. Reopen it from Settings → Help.", and Settings → Help → Get started checklist · Show brings it back (`useShowGetStarted`). The four earlier latch columns (`getting_started_added_key`, `_ran_example`, `_built_workflow`, `_tried_theme`, from the editor's checklist) are no longer read.
-## WebSocket Handlers
+## WebSocket handlers
-No new handlers were needed. The onboarding system reuses the generic user-settings handlers (registered from `server/services/settings/handlers.py`), accessed through the TanStack Query user-settings layer:
+No onboarding-specific handlers. Progress rides the user settings handlers (`server/services/settings/handlers.py`) through the TanStack Query layer:
| Handler | Usage |
|---------|-------|
-| `get_user_settings` | Check `onboarding_completed` and `onboarding_step` on hydration |
-| `save_user_settings` | Persist step progress on each navigation, skip, or complete |
-
-## Lifecycle
-
-### First Launch (New User)
-
-1. User opens app, WebSocket connects
-2. `useOnboarding` reads `useUserSettingsQuery` -- no settings exist yet
-3. `onboarding_completed` defaults to `false`, `onboarding_step` defaults to `0`
-4. Wizard opens at step 0
-5. User navigates steps -- each transition saves via the save mutation (`save_user_settings`)
-6. On "Open AI Assistant" or "Skip for now", `onboarding_completed` set to `true`; only the former also fires `onFinish`
-7. Wizard closes, does not reappear on refresh
-
-### Existing User (Database Migration)
-
-1. Server starts, `_migrate_user_settings()` runs
-2. Adds `onboarding_completed` column, sets to `1` where `examples_loaded = 1`
-3. User opens app, `useOnboarding` checks -- sees `onboarding_completed = true`
-4. Wizard does not appear
-
-### Resume Mid-Wizard
-
-1. User advances to step 2, closes browser
-2. `onboarding_step = 2` was saved on last navigation
-3. User reopens app, `useOnboarding` reads `step = 2, completed = false`
-4. Wizard opens at step 2
-
-### Replay from Settings
-
-1. User opens Settings, clicks "Replay Welcome Guide"
-2. `onReplayOnboarding()` callback fires:
- - Closes SettingsPanel
- - Increments `onboardingReopenTrigger`
-3. `useOnboarding` detects the trigger change (`> 0`):
- - Sets `isVisible = true, currentStep = 0, isCompleted = false`
-4. Wizard opens from step 0
-
-## Edge Cases
-
-| Scenario | Behavior |
-|----------|----------|
-| Auth disabled (`VITE_AUTH_ENABLED=false`) | Works unchanged -- reads from `user_id="default"` |
-| Settings query not resolved yet | `isLoading=true` prevents render until `hasChecked` |
-| Settings query errors | Non-blocking: `isLoading=false, hasChecked=true`, app continues |
-| Browser closed mid-wizard | `onboarding_step` saved on each transition, resumes from last step |
-| Multiple tabs | Completing in one tab doesn't update others until query refetch |
-| Replay from Settings | Resets local state and reopens wizard from step 0 |
-| Fresh database (no workflow.db) | Onboarding appears after first settings query resolves |
-| Credential catalogue still loading on step 2 | `Skeleton` tiles; the Connect button is always available |
-
-## Verification Checklist
-
-1. **Fresh database**: Delete `~/.opencompany/workflow.db` (or the configured DB), start server -- wizard appears
-2. **Step navigation**: Click through all 4 steps -- the `<ol>` stepper updates, Back/Next work
-3. **Skip**: Click "Skip for now" -- wizard closes, doesn't reappear on refresh
-4. **Resume**: Advance to step 2, close browser, reopen -- wizard resumes at step 2
-5. **Complete**: Finish via "Open AI Assistant" -- wizard doesn't reappear, the AI Assistant example opens with chat focused
-6. **Connect step**: Click "Connect your AI account" -- CredentialsModal opens; after saving a key, the step re-renders as connected
-7. **Existing user migration**: With existing `workflow.db` where `examples_loaded=1` -- onboarding does NOT appear
-8. **Theme support**: Switch themes -- role-token cards adapt correctly
-9. **Replay**: Open Settings, click "Replay Welcome Guide" -- wizard reopens from step 0
-10. **Tests**: `bun run --filter react-flow-client test` runs the four `onboarding/__tests__/` suites; `bun run typecheck` (root gate, TypeScript 7) passes clean
-
-## Key Files
+| `get_user_settings` | `onboarding_completed` and `onboarding_step` for the first-launch check; the checklist's `getting_started_*` flags |
+| `save_user_settings` | the step on every move; `onboarding_completed` on skip and complete; the checklist's latches and `getting_started_dismissed` |
+
+## Edge cases
+
+| Scenario | Behaviour |
+|----------|-----------|
+| Settings query not resolved yet | The guide stays closed until it resolves |
+| Settings query fails | The guide stays closed; the Guide button still opens it |
+| A mode switch or remount | Does not reopen it: `checked` holds for the session |
+| Saved step from the old wizard (2 or 3) | 2 opens Your first hire; 3 or more opens Welcome |
+| Multiple tabs | Finishing in one tab does not close it in another until that one reloads |
+| `VITE_NORMAL_MODE=false` | There is no Home, so no guide |
+| Auth disabled | Works unchanged: the settings row is the anonymous owner's |
+
+## Tests
+
+- `features/home/__tests__/welcomeGuide.test.tsx`: opens at the saved step, Welcome for an out-of-range step, never for a finished owner, no reopen on remount; the nav's reachability; Next saves the step; Connect lists every AI model and no apps, "I'll do this later", "You're connected"; the provider page in place of the list, Back and Esc (focus returns to the card), the pill and the return to the list on connect; closing saves the step reached; the last step finishes and sends, or sends nothing without a model until one is connected, which finishes the guide.
+- `features/home/__tests__/welcomeDemo.test.tsx` (fake timers): the job typed a character a tick, the beats in turn and round again, a click starting a beat, reduced motion holding the conversation with no bar.
+- `features/home/__tests__/guideStore.test.ts`: `checkGuide`, `openGuide`, `goToGuideStep`, `closeGuide`, the provider page and the waiting job.
+- `components/__tests__/CredentialsModal.test.tsx`: the dialog around the same `ProviderPage`.
+- `features/home/genui/__tests__/useHireComposer.test.tsx`: `useJobComposer` (no focus taken, a new job only, no dialog of its own).
+- `composer.test.tsx` (`flat`, the idle label, chips without Hire now), `catalogLayout.test.tsx` (no cap, the list label), `homeHeader.test.tsx` (Guide), `homeSettings.test.tsx` (Help → Replay).
+- `features/home/__tests__/getStarted.test.tsx`: shown once the guide is finished and never over it, each step's click, what is done now, each latch written once (and not for a discarded draft), the folded pill, hiding with its toast.
+- Server: `tests/test_user_settings_contract.py` and `tests/services/test_getting_started_settings.py` (the latch columns, their migration and the getter).
+
+## Key files
| File | Description |
|------|-------------|
-| `client/src/hooks/useOnboarding.ts` | Wizard state hook; persists via TanStack-Query user-settings layer |
-| `client/src/hooks/useGetStarted.ts` | Get Started checklist state |
-| `client/src/hooks/useUserSettingsQuery.ts` | `useUserSettingsQuery` / `useSaveUserSettingsMutation` (WS-backed) |
-| `client/src/components/onboarding/OnboardingWizard.tsx` | Main wizard modal: `STEPS` SSOT + `<ol>` stepper + ActionButton footer |
-| `client/src/components/onboarding/GetStartedChecklist.tsx` | Post-wizard milestone checklist |
-| `client/src/components/onboarding/getStartedItems.ts` | Checklist items + `EXAMPLE_WORKFLOW_NAMES` |
-| `client/src/components/onboarding/aiProviderLinks.ts` | `FEATURED_AI_PROVIDERS` hints and key-page URLs |
-| `client/src/components/onboarding/nodeRoleClasses.ts` | `NODE_ROLE_CLASSES` role→token map for step cards |
-| `client/src/components/onboarding/steps/WelcomeStep.tsx` | Step 0: what OpenCompany is |
-| `client/src/components/onboarding/steps/HowItWorksStep.tsx` | Step 1: blocks, agents, chat, Normal/Dev switch |
-| `client/src/components/onboarding/steps/ConnectAIStep.tsx` | Step 2: provider tiles from the catalogue + Credentials link |
-| `client/src/components/onboarding/steps/TryItStep.tsx` | Step 3: AI Assistant recipe |
-| `client/src/Dashboard.tsx` | Integration: renders wizard + checklist, passes replay trigger and `onFinish` |
-| `client/src/components/ui/SettingsPanel.tsx` | "Replay Welcome Guide" button in Help section |
-| `server/models/database.py` | `UserSettings.onboarding_completed`, `onboarding_step` fields |
-| `server/core/database.py` | Migration + CRUD for onboarding fields |
-
-## Adding New Steps
-
-To add a new onboarding step:
-
-1. Create `client/src/components/onboarding/steps/NewStep.tsx` composing shadcn primitives + Tailwind tokens + lucide icons (use `NODE_ROLE_CLASSES` for tinted cards). Do NOT introduce antd. Prefer live data (`useCatalogueQuery`, `useNodeGroups`) over hardcoded lists, as steps 1 and 2 do.
-2. Add a `{ title, render }` entry to the `STEPS` array in `OnboardingWizard.tsx`. Its `.length` automatically updates the hook's `totalSteps` and the progress stepper — no separate count to maintain. If the new step is last, the "Open AI Assistant" button and `onFinish` move to it automatically.
-3. No backend changes needed (step index is just a number).
+| `client/src/features/home/onboarding/WelcomeGuide.tsx` | The dialog |
+| `client/src/features/home/onboarding/useOnboarding.ts` | First-launch check and saved progress |
+| `client/src/features/home/state/homeStore.ts` | `guide` state, `GUIDE_STEPS` |
+| `client/src/components/credentials/CredentialsBrowser.tsx` | `copy`, `variant`, `discoverLimit`, `onItemAdded` |
+| `client/src/components/credentials/ProviderPage.tsx` | One provider's page, shared by the guide and the credentials dialog |
+| `client/src/components/credentials/aiProviderLinks.ts` | "Get a key from …" links for the featured AI providers |
+| `client/src/components/catalog/CatalogLayout.tsx` | `variant`, `discoverLimit`, `listLabel` |
+| `client/src/features/home/genui/useHireComposer.ts` | `useJobComposer` |
+| `client/src/features/home/onboarding/useGetStarted.ts` | The checklist's steps and latches |
+| `server/models/database.py` | `UserSettings.onboarding_completed`, `onboarding_step`, the `getting_started_*` flags |
+| `server/core/database.py` | The migration that marks existing owners finished |
diff --git a/docs-internal/theme_system.md b/docs-internal/theme_system.md
index 3e3dbbfe..cbd77c7c 100644
--- a/docs-internal/theme_system.md
+++ b/docs-internal/theme_system.md
@@ -133,26 +133,40 @@ Normal mode ([normal_mode.md](./normal_mode.md)) adds its own steps, all in
`index.css` where a Tailwind utility needs them (the layout and duration
tokens are used directly, as `w-(--w-home-sidebar)` or `duration-(--dur-slow)`):
-- **Motion**: `--ease-spring | overshoot | reveal` and the choreography
+- **Motion**: `--ease-spring | overshoot | reveal | shake` and the choreography
durations (`--dur-intro`, `--dur-view-swap`, `--dur-panel-in/-out`,
`--dur-toast-in/-hold/-out`, `--dur-mode-in/-out`, `--dur-theme-reveal`,
`--dur-glow`, `--dur-pip-loop`, `--dur-dock-in` for the Workspace dock,
- …). Web Animations read them through
+ `--dur-shake`, …). Web Animations read them through
[lib/motion.ts](../client/src/lib/motion.ts), whose fallbacks mirror
- base.css.
+ base.css. It also holds the onboarding presets: `RISE` / `rise(el)` (up from
+ 16px, scale .98, a 4px blur, `card-in` on the spring curve) and `shake(el)`
+ (-6, 5, -3, 2px, each swing on `--ease-shake`). The CSS loops beside them in
+ `animations.css` are `.opencompany-caret-blink` (a hard on/off caret) and
+ `.opencompany-spinner-slow` (the `--dur-live-ring` pace), drawn as a ring by
+ `components/ui/ring-spinner.tsx`; both stop under reduced motion.
- **Radii**: `--radius-row | card | panel | draft | composer`, multiples of each
theme's `--radius-lg`, so square themes stay square. The Tailwind
`rounded-sm/md/lg/xl` utilities do not follow themes: `index.css` computes
them from `--radius`, which no theme overrides, so they are 4/6/8/12px
everywhere. `rounded-pill`, these Home radii and CSS reading
`var(--radius-*)` directly do follow the theme.
-- **Type and layout**: `--text-meta | row | lead | title | hero` (with
- `--tracking-hero`, `--leading-hero`), and the Home layout constants
- (`--w-home-sidebar`, `--h-home-header`, `--w-composer`, the orb slot sizes,
- the Settings dialog size).
+- **Type and layout**: `--text-meta | row | lead | title | headline | hero` (with
+ `--tracking-hero`, `--leading-hero`; `headline` is 28px, the onboarding
+ headings), and the Home layout constants (`--w-home-sidebar`,
+ `--h-home-header`, `--w-composer`, the orb slot sizes `--size-orb-hire |
+ employee | connecting | login`, the Settings and Welcome guide dialog sizes
+ `--w-settings`/`--h-settings` and `--w-guide`/`--h-guide`). The guide's demo
+ stage is the `.home-welcome-stage` class in `index.css` (two washes of
+ `--node-agent-fill` and `--node-model-soft` over `--bg-app`).
- **Status**: `--status-{working,ready,paused,attention,waiting}-{dot,fill,border,ink}`
for the employee pills and dots. The dot is the raw role colour; light.css
- keeps the paused dot at the design's mid grey.
+ keeps the paused dot at the design's mid grey. `--shadow-pip`
+ (`shadow-pip`) is a dot's glow in its own colour: give the dot a
+ `text-status-*-dot` colour and `bg-current`.
+- **Errors**: `--danger-soft` (15%) and `--danger-border` (45%) tint
+ `--destructive` for an error on a Home surface (`bg-danger-soft`,
+ `border-danger-border`).
- **Per family** (light.css / dark.css): `--shadow-float | popover | dialog |
dock` (`dock` is the Workspace's left shadow when it lies over the page),
the node-role `-fill / -edge / -hover / -ink` variants, and Home's glows:
@@ -282,7 +296,7 @@ the surrounding chrome. Every other surface uses Tailwind + tokens. New themes c
### Done
- **`--node-pulse-color` contract** — executing-node glow color is independent of `--node-color` (the plugin accent). Each decorated skin overrides `--node-pulse-color` to its highest-contrast accent (light/dark deliberately keep the base.css `var(--info)` fallback) (Cyber neon cyan, Surveillance REC red, Renaissance ultramarine `--lapis-bright`, Atomic turquoise, etc.) so the glow stays visible against any canvas background. Defined in [base.css](../client/src/themes/base.css) at `:root`, overridden in each per-theme file. The executing keyframes (`node-pulse` + per-theme `cyber-pulse-exec` / `surv-pulse-exec` / `ren-pulse-exec`) and the per-theme `--pulse-keyframe` / `--pulse-duration` / `--pulse-timing` tokens live in [animations.css](../client/src/themes/animations.css); base.css's `.sq-node[data-executing] .sq-node-box` / `.react-flow__node.executing .{sq-node-box,node}` rule reads `var(--pulse-keyframe, node-pulse)`, so a theme picks its pulse by overriding ONE token (Cyber → `cyber-pulse-exec`, Surveillance → `surv-pulse-exec`, Renaissance → `ren-pulse-exec`) — no high-specificity per-theme animation rule. `node-pulse` is a triple-layer expanding box-shadow (12px ring + 32px mid halo + 56px outer halo) consuming `var(--node-pulse-color)` + the shared `--tint-pulse-*` alphas. Trigger nodes use a separate continuous `.opencompany-trigger-armed` "listening" heartbeat (`trigger-listening` keyframe) while waiting, plus `.opencompany-bolt` on the ⚡ badge — distinct from the one-shot execution pulse. **Never animate `opacity` on whole-node selectors** — it fades the node icon + content, not just the glow.
-- **`data-page-hidden` animation pause** — `usePageActivitySync()` ([app/usePageActivitySync.ts](../client/src/app/usePageActivitySync.ts)), mounted once in [AppShell.tsx](../client/src/app/AppShell.tsx)'s `ShellEffects` so it covers both screens, listens to `visibilitychange` plus window `blur` / `focus` and toggles `data-page-hidden` on `<html>`; [base.css](../client/src/themes/base.css) declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important; }`. Without this, paused CSS keyframes accumulate frames in the compositor queue while the tab is hidden; on tab return all 50+ executing nodes' triple-layer pulses + Cyber's full-viewport `cyber-flicker` / `cyber-roll` resume simultaneously, stalling the GPU compositor 100-200ms and blocking input dispatch (first-click-feels-frozen pattern). The unpause is deferred two `requestAnimationFrame` ticks so input dispatch wins the frame before composite resumes.
+- **`data-page-hidden` animation pause** — `usePageActivitySync()` ([app/usePageActivitySync.ts](../client/src/app/usePageActivitySync.ts)), mounted once in [App.tsx](../client/src/App.tsx), above the sign-in gate, so it covers every screen (sign-in and Connecting included), listens to `visibilitychange` plus window `blur` / `focus` and toggles `data-page-hidden` on `<html>`; [base.css](../client/src/themes/base.css) declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important; }`. Without this, paused CSS keyframes accumulate frames in the compositor queue while the tab is hidden; on tab return all 50+ executing nodes' triple-layer pulses + Cyber's full-viewport `cyber-flicker` / `cyber-roll` resume simultaneously, stalling the GPU compositor 100-200ms and blocking input dispatch (first-click-feels-frozen pattern). The unpause is deferred two `requestAnimationFrame` ticks so input dispatch wins the frame before composite resumes.
- **Parameter panel theme contract** — MasterSkillEditor, OutputPanel, MiddleSection, ParameterPanel removed `useAppTheme()`. Every surface renders against Tailwind tokens + new-contract CSS custom props. Section headers carry the display-typography triplet (`font-display tracking-[var(--type-tracking-display)] [text-transform:var(--type-uppercase)] text-fg-default`); action buttons use `<ActionButton intent="run|stop|save|config|tools">`; backgrounds use `bg-bg-elevated` / `bg-bg-panel` / `bg-bg-input` from the surface tier table above. EditableNodeLabel emits both `sq-node-label` and `node-label` classNames so per-theme typography rules fire under either topology. Per-theme scrollbar webkit rules (`::-webkit-scrollbar-thumb` etc.) declared in all 12 themes — gold (Renaissance), square-cornered (Atomic / Edo / Greek / Wasteland / Plague), metallic (Steampunk), phosphor (Rot), neon (Cyber), REC-red (Surveillance), shadcn neutral (Light / Dark).
- **Canvas-node class topology alignment** (W26) — TriggerNode, StartNode, ToolkitNode migrated from `.node` (rectangular spec-card) topology to `.sq-node` / `.sq-node-box` (square-icon node) topology so per-theme decorations (Steampunk brass rivets, Edo hanko seal, Surveillance REC LED, Renaissance gold emblem) reach them. Status pips, gear buttons, and React Flow handles on every node component now carry `.sq-node-pip` / `.sq-node-gear` / `.sq-node-handle.in/.out` (square nodes) or `.node-pip` / `.node-gear` / `.node-handle.in/.out` (rectangular nodes — AIAgentNode, TeamMonitorNode; the former `GenericNode` was retired with the spec-driven canvas). Pip background is data-driven via `data-status="idle | executing | waiting | success | error"` — base.css picks the colour from shadcn semantic tokens; per-theme files override. Inline JS-computed `backgroundColor` / `border` / `animation` on these elements stripped — CSS owns visuals. Cyber's `.node-trigger` rule extended to dual-target both rectangular and square topologies (`.sq-node.node-trigger .sq-node-box`). Orphan `.node-output` rule removed. EditableNodeLabel now emits both `sq-node-label` and `node-label` classNames so per-theme typography rules fire. StartNode reads `nodeColor` from `definition?.defaults?.color` instead of hardcoded `theme.dracula.cyan`; the NodeSpec adapter never fills that field, so it resolves to `var(--node-workflow)`.
- **Audio fix** (W20) — `--sound-pack: chime` typo in `light.css` + `dark.css` was silently falling through to `'none'` (`chime` not in the engine's pack registry), making sound silent for the most-used themes. Renamed `light` → `parchment`, `dark` → `terminal`. Added `Sounds.unlock()` exported from [lib/sound.ts](../client/src/lib/sound.ts) plus a one-shot `pointerdown / keydown / touchstart` capture-phase listener in `useSoundSync()` ([hooks/useSound.ts](../client/src/hooks/useSound.ts)) so the AudioContext resumes on the user's first gesture (Chrome / Safari autoplay policy compliance).